Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Problem generating exponentiation operator with unary operator applied to base #74

Closed
stonegray opened this issue Jul 19, 2019 · 1 comment
Labels

Comments

@stonegray
Copy link

I believe I've found an error in how code is generated when a UnaryExpression is used as the base in an ExponentiationExpression:

(-2)**4

From MDN:

In JavaScript, it is impossible to write an ambiguous exponentiation expression, i.e. you cannot put a unary operator (+/-/~/!/delete/void/typeof) immediately before the base number.

I am using the following AST. I believe this is the correct AST to produce the desired outpput as acorn, cherow, and meriyah all produce the same output for this code. I was not able to test in esprima or espree as this code crashes them.

{
    "type": "Program",
    "sourceType": "script",
    "body": [
        {
            "type": "ExpressionStatement",
            "expression": {
                "type": "BinaryExpression",
                "left": {
                    "type": "UnaryExpression",
                    "operator": "+",
                    "argument": {
                        "type": "Literal",
                        "value": 2
                    },
                    "prefix": true
                },
                "right": {
                    "type": "Literal",
                    "value": 4
                },
                "operator": "**"
            }
        }
    ]
}

Expected behavior

Code should be generated with parentheses around the base when a unary operator is applied.

astring.generate(acorn.parse('(+2)**4'))

// Expected Output:
(+2)**4;

Actual behavior

No parentheses are added, leading to invalid code that throws an error when executed.

astring.generate(acorn.parse('(+2)**4'))

// Observed Output:
+2**4;

Error:

+2**4
^^^^

SyntaxError: Unary operator used immediately before exponentiation expression. Parenthesis must be used to disambiguate operator precedence

See also: jquery/esprima#1981

@davidbonnet
Copy link
Owner

Thanks @stonegray for reporting this. It is fixed v1.4.1.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants