Node Location
By default, Esprima parser produces an abstract syntax tree. For some uses cases, this abstract syntax tree is not sufficient. For instance, having the location information of each node is necessary in a few cases of static analysis, e.g. to give a meaningful feedback to the user.
To have each node carries some additional properties indicating its location, the parser must be invoked by specifying the flags, range
or loc
or both of them, in the parsing configuration.
Setting the range
flag to true adds a new property, range
, to each node. It is an array of two elements, each indicating the zero-based index of the starting and end location (exclusive) of the node. A simple example follows:
- $ node
- > var esprima = require('esprima')
- > esprima.parse('answer = 42', { range: true })
- Program {
- type: 'Program',
- body:
- [ ExpressionStatement {
- type: 'ExpressionStatement',
- expression: [Object],
- range: [Object] } ],
- sourceType: 'script',
- range: [ 0, 11 ] }
The top-level Program node has the range [0, 11]. This indicates that the program starts from the zeroth character and finishes before the 11th character.
A subsequent example to inspect the numeric literal 42 on the right side of the assignment:
- $ node
- > var esprima = require('esprima')
- > var program = esprima.parse('answer = 42', { range: true })
- > program.body[0].expression.right
- Literal { type: 'Literal', value: 42, raw: '42', range: [ 9, 11 ] }
In the above example, the location of the Literal node is determined to be [9, 11]. In other words, the ninth and the tenth characters (the eleventh is excluded) of the source correspond to the numeric literal 42
.
Setting the loc
flag to true adds a new property, loc
, to each node. It is a object that contains the line number and column number of the starting and end location (exclusive) of the node. It is illustrated in this example:
- $ node
- > var esprima = require('esprima')
- > esprima.parse('answer = 42', { loc: true })
- Program {
- type: 'Program',
- body:
- [ ExpressionStatement {
- type: 'ExpressionStatement',
- expression: [Object],
- loc: [Object] } ],
- sourceType: 'script',
- loc: { start: { line: 1, column: 0 }, end: { line: 1, column: 11 } } }
Note that the line number is one-based while the column number is zero-based.
It is possible to set both range
and loc
to true, thereby giving each token the most complete location information.