Skip to content

Nodes positions

Ioan CHIRIAC edited this page Feb 12, 2016 · 1 revision

This option enables the ability to locate each AST node into the document.

In order to not change the plain AST structure, a position structure will surround each node.

// original AST structure (without any location) :
['program', [
   ['sys', 'echo', [['string', 'Hello World']]]
]]

// And the result with locations :
['program', [
  ['position',  
    [1, 0, 0],        // start position : line, column, offset
    [1, 20, 20],      // end position : same as start
    ['sys', 'echo', [ // node contents
      ['position',
        [1, 5, 5],
        [1, 20, 20],
        ['string', 'Hello World']      
      ]
    ]]
  ]
]]

I've chose to surround the AST node VS to change informations into the node itself, in order to make more easy the nodes visitors algorithms and to make the positions nodes optionnals.

The position structure is like any AST nodes :

  • offset 0 : start array
    • offset 0 : line (first line starts at 1)
    • offset 1 : column (first column starts at 0)
    • offset 2 : offset - the char position into the string
  • offset 1 : end array (same structure as start)
  • offset 2 : the node itself

Enable this options

By default the positions are disabled to avoid extra information when not needed. To enable them :

var reader = require('php-parser');

// setting a flag on all request :
reader.parser.locations = true;
reader.parseEval('echo "azerty";');

// or setting it only for the current parsing :
reader.parseEval('echo "azerty";', {
   parser: {
     locations: true
   }
});
You can’t perform that action at this time.