JavaScript example: Fix handling of elided elements in array literals

JavaScript allows one to skip (elide) elements in array literals. It
also allows a trailing comma, which doesn't imply an element elision.

For example, an array literal:

  [,,,]

contains three elided elements (one before each comma) and a trailing
comma.

Example JavaScript parser handled elided elements incorrectly and just
threw them away. This commit fixes this behvior and inserts |null| in
the AST for each elided element. This is in line with how SpiderMonkey's
JavaScript parser (the |Reflect.parse| API), Esprima and Acorn behave.

Based on a patch by @fpirsch:

  https://github.com/dmajda/pegjs/pull/177
redux
David Majda 11 years ago
parent d71bca46a1
commit f3d392bd1c

@ -475,32 +475,45 @@ PrimaryExpression
/ "(" __ expression:Expression __ ")" { return expression; } / "(" __ expression:Expression __ ")" { return expression; }
ArrayLiteral ArrayLiteral
= "[" __ (Elision __)? "]" { = "[" __ elision:(Elision __)? "]" {
return { return {
type: "ArrayLiteral", type: "ArrayLiteral",
elements: [] elements: elision !== "" ? elision[0] : []
}; };
} }
/ "[" __ elements:ElementList __ ("," __ (Elision __)?)? "]" { / "[" __ elements:ElementList __ elision:("," __ (Elision __)?)? "]" {
return { return {
type: "ArrayLiteral", type: "ArrayLiteral",
elements: elements elements: elements.concat(elision !== "" && elision[2] !== "" ? elision[2][0] : [])
}; };
} }
ElementList ElementList
= (Elision __)? = head:(
head:AssignmentExpression elision:(Elision __)? element:AssignmentExpression {
tail:(__ "," __ (Elision __)? AssignmentExpression)* { return (elision !== "" ? elision[0] : []).concat(element);
var result = [head]; }
)
tail:(
__ "," __ elision:(Elision __)? element:AssignmentExpression {
return (elision !== "" ? elision[0] : []).concat(element);
}
)* {
var result = head;
for (var i = 0; i < tail.length; i++) { for (var i = 0; i < tail.length; i++) {
result.push(tail[i][4]); result = result.concat(tail[i]);
} }
return result; return result;
} }
Elision Elision
= "," (__ ",")* = "," elision:(__ ",")* {
var result = [null];
for (var i = 0; i < elision.length; i++) {
result.push(null);
}
return result;
}
ObjectLiteral ObjectLiteral
= "{" __ properties:(PropertyNameAndValueList __ ("," __)?)? "}" { = "{" __ properties:(PropertyNameAndValueList __ ("," __)?)? "}" {

Loading…
Cancel
Save