shapesecurity / shift-parser-js

ECMAScript parser that produces a Shift format AST
http://shift-ast.org/parser.html
Apache License 2.0
245 stars 28 forks source link

line number information is not serialized #451

Open nashid opened 2 years ago

nashid commented 2 years ago

Should show line number information.

Test case:

let {parseScriptWithLocation, parseModuleWithLocation} = require("shift-parser");
let {tree, locations, comments} = parseScriptWithLocation("2 + 3 /* = 5 */");
console.log(JSON.stringify(locations))

Output = {}

Expected: Can show locations Actual: Shows empty array {}

bakkot commented 2 years ago

That's because it's a WeakMap. That's how WeakMaps work. What are you expecting?

nashid commented 2 years ago

I need to serialize the location information. For each AST node, I need to determine the start and end line number.

bakkot commented 2 years ago

You can just stick the location information on the nodes, if you want:

let { tree, locations } = parseScriptWithLocation(`whatever`);
function addLocationInformation(node) {
  node.loc = locations.get(node);
  for (let field of Object.values(node)) {
    if (Array.isArray(field)) {
      field.forEach(addLocationInformation);
    } else if (typeof field === 'object' && field !== null) {
      addLocationInformation(field);
    }
  }
}
addLocationInformation(tree);

console.log(JSON.stringify(tree));