fstirlitz / luaparse

A Lua parser written in JavaScript
https://fstirlitz.github.io/luaparse/
MIT License
459 stars 91 forks source link

variable with negative Integer/Number gives UnaryExpression #51

Closed Bizarrus closed 7 years ago

Bizarrus commented 7 years ago

Sample Line:

priority = -1

Currently fixing with follwing:

switch(content.type) {
    // Default numbers
    case 'NumericLiteral':
        value = parseInt(content.value, 10);
    break;

    case 'UnaryExpression':
        /* Fix parsing error for negative numbers */
        if(content.operator == '-') {
            value = -parseInt(content.argument.value, 10);
        }
    break;
}
fstirlitz commented 7 years ago

Latest git master returns this for your example:

    {
      "type": "AssignmentStatement",
      "variables": [
        {
          "type": "Identifier",
          "name": "priority"
        }
      ],
      "init": [
        {
          "type": "UnaryExpression",
          "operator": "-",
          "argument": {
            "type": "NumericLiteral",
            "value": 1,
            "raw": "1"
          }
        }
      ]
    }

It seems like a valid interpretation to me, even if a bit silly. I'm not sure if Lua considers -1 a single token or not, but either way it is read, the expression evaluates to the same value.

Your 'fix' doesn't check that the underlying operand is a NumericLiteral; it'll crash on -x. And why call parseInt on a value that is not a string?

oxyc commented 7 years ago

Lua does the same:

If I recall the bison/flex grammars I looked at as well as esprima/acorn does this too.