rspivak / slimit

SlimIt - a JavaScript minifier/parser in Python
MIT License
550 stars 94 forks source link

how can i get the line number of the node in ast tree? #111

Closed LoRexxar closed 5 years ago

LoRexxar commented 5 years ago

how can i get the line number from node in ast tree?

metatoaster commented 5 years ago

slimit does not make use of line tracking of the lexer thus the tokens it yields would not contain this type of information, and that the node types themselves don't really track this information at all, so what you want (getting the line number) cannot be done with this library.

I do have a fork of this library (calmjs.parse pypi/pip, GitHub) that reworked a large number of the relevant internals (along with fixing bugs) that enabled this feature in the lexer and added relevant fields to the nodes, such that what you wish to achieve may be done.

Given this JavaScript source:

var main = function(greet) {
    var hello = "hello " + greet;
    return hello;
};
console.log(main('world'));

Let's look at a brief example on the usage of that library and getting to nodes and their attributes (which are further nodes), and access the line number (and column number):

>>> from calmjs.parse import es5
>>> # source = '''a multi-line string of the above JS source'''
>>> program = es5(source)
>>> print(repr(program))
<ES5Program @1:1 ?children=[
  <VarStatement @1:1 ?children=[
    <VarDecl @1:5 identifier=<Identifier ...>, initializer=<FuncExpr ...>>
  ]>,
  <ExprStatement @5:1 expr=<FunctionCall @5:1 args=<Arguments ...>, identifier=<DotAccessor ...>>>
]>
>>> print(program.children()[1].expr.args)
(main('world'))
>>> print(program.children()[1].expr.args.lineno)
5
>>> print(program.children()[1].expr.args.colno)
12
LoRexxar commented 5 years ago

Thank you for your help, i got it