How to simplify JavaScript/ECMAScript array literal production?

元气小坏坏 提交于 2019-12-13 17:44:27

问题


I currently implementing a JavaScript/ECMAScript 5.1 parser with JavaCC and have problems with the ArrayLiteral production.

ArrayLiteral :
    [ Elision_opt ]
    [ ElementList ]
    [ ElementList , Elision_opt ]

ElementList :
    Elision_opt AssignmentExpression
    ElementList , Elision_opt AssignmentExpression

Elision :
    ,
    Elision ,

I have three questions, I'll ask them one by one.


I have tried to simplify/to rewrite the ArrayLiteral production depicted above and finally arrived to the following production (pseudo-grammar):

ArrayLiteral:
    "[" ("," | AssignmentExpression ",") * AssignmentExpression ? "]"

My first question: is this rewriting correct?

Two other quetsions:

  • LOOKAHEADs for the JavaScript/ECMAScript array literal production
  • How to implement a negative LOOKAHEAD check for a token in JavaCC?

回答1:


Yes, that correctly captures the grammar presented.

However, a better rewrite would be:

"[" AssignmentExpression ? ( "," AssignmentExpression ? ) * "]"

because the rewriting in the OP is not LL(1) -- you cannot distinguish the possibilities without reading the entire AssignmentExpression -- whereas with this one you can figure out which alternative to use simply by looking at the first token.



来源:https://stackoverflow.com/questions/26908490/how-to-simplify-javascript-ecmascript-array-literal-production

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!