简体   繁体   中英

How to simplify JavaScript/ECMAScript array literal production?

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM