Literal assignment in ECMAScript 2017 Specification
https://softwareengineering.stackexchange.com/questions/367808
-
30-01-2021 - |
Question
I am trying to build a derivation tree for the program
x = 42
using the specification for ECMAScript 2017. I see that there there is an AssignmentExpression
which has the production rule:
LeftHandExpression = AssignmentExpression
however, I don't see any rule that allows an AssignmentExpression
to be a literal.
Maybe I am looking in the wrong place, but AssignmentExpression
seems to be the only reasonable choice.
The production rule for AssignmentExpression
is here: https://www.ecma-international.org/ecma-262/8.0/index.html#prod-AssignmentExpression
Solution
The ECMAScript grammar is very complex. It encodes operator precedence explicitly through various grammar rules. This means that a grammar rule doesn't just match that specific operator, but also all expressions that have higher precedence than this operator. Typically, this will be the first alternative.
The derivation from AssignmentExpression
to Literal
is this, with sometimes misleading names for the rules:
- AssignmentExpression (12.15)
- ConditionalExpression (12.14)
- LogicalORExpression (12.13)
- LogicalANDExpression (12.13)
- BitwiseORExpression (12.12)
- BitwiseXORExpression (12.12)
- BitwiseANDExpression (12.12)
- EqualityExpression (12.11)
- RelationalExpression (12.10)
- ShiftExpression (12.9)
- AdditiveExpression (12.8)
- MultiplicativeExpression (12.7)
- ExponentiationExpression (12.6)
- UnaryExpression (12.5)
- UpdateExpression (12.4)
- LeftHandSideExpression (12.3)
- NewExpression (12.3)
- MemberExpression (12.3)
- PrimaryExpression (12.2)
- Literal (12.2.4)
Traversing these grammar rules can sometimes be confusing because the grammar allows weird syntax like "foo" += 3
. However, the specification contains a set of static semantics that decide whether a given syntax represents a valid assignment target. So not all LeftHandSideExpressions are allowed on the left hand side of an assignment!
OTHER TIPS
I don't find the 2017 spec right now, but the 2019 spec clearly has some more alternatives in the AssignmentExpression rule, one of which ultimately produces via a pretty long path of production rules Literal, as expected. I can't imagine that the 2017 version is much different in that respect.
Update: upon further search I found https://msdn.microsoft.com/en-us/library/mt828938(v=vs.85).aspx which cites only parts of the spec. If you look at that instead of an official spec, you don't see the full production rule...