Skip to content

Commit

Permalink
Fix parsing error in exponent expressions with unary left-hand sides (#…
Browse files Browse the repository at this point in the history
…201)

* Fix parsing error in exponent expressions with unary left-hand sides.

Esprima (correctly) rejects expressions like -1**2. - jquery/esprima#2070
However, expressions like (-1)**2 are valid but still rejected.
This commit fixes this issue by identifying when the left operand
is parenthesized.

Fixes jquery/esprima#1981

* add test for unary left side
  • Loading branch information
jogibear9988 authored Nov 2, 2021
1 parent 399986f commit b7a1ed0
Show file tree
Hide file tree
Showing 3 changed files with 121 additions and 4 deletions.
12 changes: 8 additions & 4 deletions src/Esprima/JavascriptParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1861,10 +1861,14 @@ private Expression ParseUnaryExpression()

private Expression ParseExponentiationExpression()
{
var startToken = _lookahead;

var expr = InheritCoverGrammar(parseUnaryExpression);
if (expr.Type != Nodes.UnaryExpression && Match("**"))
var startToken = _lookahead;

var isLeftParenthesized = this.Match("(");
var expr = InheritCoverGrammar(parseUnaryExpression);

var exponentAllowed = expr.Type != Nodes.UnaryExpression || isLeftParenthesized;

if (exponentAllowed && Match("**"))
{
NextToken();
_context.IsAssignmentTarget = false;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
(+2)**4;
112 changes: 112 additions & 0 deletions test/Esprima.Tests/Fixtures/invalid-syntax/unary_left_side.tree.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
{
"type": "Program",
"body": [
{
"type": "ExpressionStatement",
"expression": {
"type": "BinaryExpression",
"operator": "**",
"left": {
"type": "UnaryExpression",
"operator": "+",
"argument": {
"type": "Literal",
"value": 2,
"raw": "2",
"range": [
2,
3
],
"loc": {
"start": {
"line": 1,
"column": 2
},
"end": {
"line": 1,
"column": 3
}
}
},
"prefix": true,
"range": [
1,
3
],
"loc": {
"start": {
"line": 1,
"column": 1
},
"end": {
"line": 1,
"column": 3
}
}
},
"right": {
"type": "Literal",
"value": 4,
"raw": "4",
"range": [
6,
7
],
"loc": {
"start": {
"line": 1,
"column": 6
},
"end": {
"line": 1,
"column": 7
}
}
},
"range": [
0,
7
],
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 7
}
}
},
"range": [
0,
8
],
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 8
}
}
}
],
"sourceType": "script",
"range": [
0,
8
],
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 8
}
}
}

0 comments on commit b7a1ed0

Please sign in to comment.