ConsenSysMesh / solidity-parser

Solidity Parser in Javascript
138 stars 54 forks source link

Add range property #3

Closed duaraghav8 closed 8 years ago

duaraghav8 commented 8 years ago

Could you please add the range feature to the parser? The range is a property every Node in the AST possesses whose value is an array of 2 integers:

range [0] denotes the position of the starting character of the complete piece of code responsible for the particular node in question

range [1] denotes the position of its ending character.

So for eg- if my solidity code looks like:

contract Voting {
  struct Voter {
    bool hasVoted;
  }
}

The AST created by Solidity Parser looks like:

{
  "type": "Program",
  "body": [
    {
      "type": "ContractStatement",
      "name": "Voting",
      "is": [],
      "body": [
        {
          "type": "StructDeclaration",
          "body": [
            {
              "type": "DeclarativeExpression",
              "name": "hasVoted",
              "literal": {
                "type": "Type",
                "literal": "bool",
                "members": [],
                "array_parts": []
              },
              "is_constant": false,
              "is_public": false,
              "is_memory": false
            }
          ]
        }
      ]
    }
  ]
}

If we had the range feature, then node for hasVoted property would look like:

{
  "type": "DeclarativeExpression",
  "name": "hasVoted",
  "literal": {
    "type": "Type",
    "literal": "bool",
    "members": [],
    "array_parts": []
  },
  "is_constant": false,
  "is_public": false,
  "is_memory": false,
  "range": [39, 52]
}

39 is the position of 'b' and 52 of ';' in bool hasVoted; (the code responsible for the "hasVoted" node)

I'm requesting this feature because it makes it possible for us to obtain the code for a node. Eg - If I have the full source code inside variable sourceCode, I can get the particular code responsible for declaring & defining hasVoted like:

sourceCode.slice (node.range [0], node.range [1])

and it returns bool hasVoted;

espree provides a similar range property, if you'd like to see an example

npm install --save espree

let espree = require ('espree'),
    sourceCode = 'var x = 100;\nx = 200;'

let AST = espree.parse (sourceCode, {range: true});

console.log (JSON.stringify (AST, null, 2));
tcoulter commented 8 years ago

Fixed in #4