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:

  1. $ node
  2. > var esprima = require('esprima')
  3. > esprima.parse('answer = 42', { range: true })
  4. Program {
  5. type: 'Program',
  6. body:
  7. [ ExpressionStatement {
  8. type: 'ExpressionStatement',
  9. expression: [Object],
  10. range: [Object] } ],
  11. sourceType: 'script',
  12. 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:

  1. $ node
  2. > var esprima = require('esprima')
  3. > var program = esprima.parse('answer = 42', { range: true })
  4. > program.body[0].expression.right
  5. 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:

  1. $ node
  2. > var esprima = require('esprima')
  3. > esprima.parse('answer = 42', { loc: true })
  4. Program {
  5. type: 'Program',
  6. body:
  7. [ ExpressionStatement {
  8. type: 'ExpressionStatement',
  9. expression: [Object],
  10. loc: [Object] } ],
  11. sourceType: 'script',
  12. 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.