Merge pull request +11450 from c9/eslint

update eslint
smf-sdk
Lennart Kats 2016-01-08 13:10:17 +01:00
commit a4a15ed24d
6 zmienionych plików z 343 dodań i 232 usunięć

Wyświetl plik

@ -25,10 +25,6 @@ var _tokentype = _dereq_("./tokentype");
var _state = _dereq_("./state"); var _state = _dereq_("./state");
var _identifier = _dereq_("./identifier");
var _util = _dereq_("./util");
var pp = _state.Parser.prototype; var pp = _state.Parser.prototype;
// Check if property name clashes with already added. // Check if property name clashes with already added.
@ -38,8 +34,7 @@ var pp = _state.Parser.prototype;
pp.checkPropClash = function (prop, propHash) { pp.checkPropClash = function (prop, propHash) {
if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) return; if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) return;
var key = prop.key, var key = prop.key;var name = undefined;
name = undefined;
switch (key.type) { switch (key.type) {
case "Identifier": case "Identifier":
name = key.name;break; name = key.name;break;
@ -49,6 +44,7 @@ pp.checkPropClash = function (prop, propHash) {
return; return;
} }
var kind = prop.kind; var kind = prop.kind;
if (this.options.ecmaVersion >= 6) { if (this.options.ecmaVersion >= 6) {
if (name === "__proto__" && kind === "init") { if (name === "__proto__" && kind === "init") {
if (propHash.proto) this.raise(key.start, "Redefinition of __proto__ property"); if (propHash.proto) this.raise(key.start, "Redefinition of __proto__ property");
@ -56,9 +52,9 @@ pp.checkPropClash = function (prop, propHash) {
} }
return; return;
} }
var other = undefined; name = "$" + name;
if (_util.has(propHash, name)) { var other = propHash[name];
other = propHash[name]; if (other) {
var isGetSet = kind !== "init"; var isGetSet = kind !== "init";
if ((this.strict || isGetSet) && other[kind] || !(isGetSet ^ other.init)) this.raise(key.start, "Redefinition of property"); if ((this.strict || isGetSet) && other[kind] || !(isGetSet ^ other.init)) this.raise(key.start, "Redefinition of property");
} else { } else {
@ -86,14 +82,14 @@ pp.checkPropClash = function (prop, propHash) {
// and object pattern might appear (so it's possible to raise // and object pattern might appear (so it's possible to raise
// delayed syntax error at correct position). // delayed syntax error at correct position).
pp.parseExpression = function (noIn, refShorthandDefaultPos) { pp.parseExpression = function (noIn, refDestructuringErrors) {
var startPos = this.start, var startPos = this.start,
startLoc = this.startLoc; startLoc = this.startLoc;
var expr = this.parseMaybeAssign(noIn, refShorthandDefaultPos); var expr = this.parseMaybeAssign(noIn, refDestructuringErrors);
if (this.type === _tokentype.types.comma) { if (this.type === _tokentype.types.comma) {
var node = this.startNodeAt(startPos, startLoc); var node = this.startNodeAt(startPos, startLoc);
node.expressions = [expr]; node.expressions = [expr];
while (this.eat(_tokentype.types.comma)) node.expressions.push(this.parseMaybeAssign(noIn, refShorthandDefaultPos)); while (this.eat(_tokentype.types.comma)) node.expressions.push(this.parseMaybeAssign(noIn, refDestructuringErrors));
return this.finishNode(node, "SequenceExpression"); return this.finishNode(node, "SequenceExpression");
} }
return expr; return expr;
@ -102,43 +98,42 @@ pp.parseExpression = function (noIn, refShorthandDefaultPos) {
// Parse an assignment expression. This includes applications of // Parse an assignment expression. This includes applications of
// operators like `+=`. // operators like `+=`.
pp.parseMaybeAssign = function (noIn, refShorthandDefaultPos, afterLeftParse) { pp.parseMaybeAssign = function (noIn, refDestructuringErrors, afterLeftParse) {
if (this.type == _tokentype.types._yield && this.inGenerator) return this.parseYield(); if (this.type == _tokentype.types._yield && this.inGenerator) return this.parseYield();
var failOnShorthandAssign = undefined; var validateDestructuring = false;
if (!refShorthandDefaultPos) { if (!refDestructuringErrors) {
refShorthandDefaultPos = { start: 0 }; refDestructuringErrors = { shorthandAssign: 0, trailingComma: 0 };
failOnShorthandAssign = true; validateDestructuring = true;
} else {
failOnShorthandAssign = false;
} }
var startPos = this.start, var startPos = this.start,
startLoc = this.startLoc; startLoc = this.startLoc;
if (this.type == _tokentype.types.parenL || this.type == _tokentype.types.name) this.potentialArrowAt = this.start; if (this.type == _tokentype.types.parenL || this.type == _tokentype.types.name) this.potentialArrowAt = this.start;
var left = this.parseMaybeConditional(noIn, refShorthandDefaultPos); var left = this.parseMaybeConditional(noIn, refDestructuringErrors);
if (afterLeftParse) left = afterLeftParse.call(this, left, startPos, startLoc); if (afterLeftParse) left = afterLeftParse.call(this, left, startPos, startLoc);
if (this.type.isAssign) { if (this.type.isAssign) {
if (validateDestructuring) this.checkPatternErrors(refDestructuringErrors, true);
var node = this.startNodeAt(startPos, startLoc); var node = this.startNodeAt(startPos, startLoc);
node.operator = this.value; node.operator = this.value;
node.left = this.type === _tokentype.types.eq ? this.toAssignable(left) : left; node.left = this.type === _tokentype.types.eq ? this.toAssignable(left) : left;
refShorthandDefaultPos.start = 0; // reset because shorthand default was used correctly refDestructuringErrors.shorthandAssign = 0; // reset because shorthand default was used correctly
this.checkLVal(left); this.checkLVal(left);
this.next(); this.next();
node.right = this.parseMaybeAssign(noIn); node.right = this.parseMaybeAssign(noIn);
return this.finishNode(node, "AssignmentExpression"); return this.finishNode(node, "AssignmentExpression");
} else if (failOnShorthandAssign && refShorthandDefaultPos.start) { } else {
this.unexpected(refShorthandDefaultPos.start); if (validateDestructuring) this.checkExpressionErrors(refDestructuringErrors, true);
} }
return left; return left;
}; };
// Parse a ternary conditional (`?:`) operator. // Parse a ternary conditional (`?:`) operator.
pp.parseMaybeConditional = function (noIn, refShorthandDefaultPos) { pp.parseMaybeConditional = function (noIn, refDestructuringErrors) {
var startPos = this.start, var startPos = this.start,
startLoc = this.startLoc; startLoc = this.startLoc;
var expr = this.parseExprOps(noIn, refShorthandDefaultPos); var expr = this.parseExprOps(noIn, refDestructuringErrors);
if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr; if (this.checkExpressionErrors(refDestructuringErrors)) return expr;
if (this.eat(_tokentype.types.question)) { if (this.eat(_tokentype.types.question)) {
var node = this.startNodeAt(startPos, startLoc); var node = this.startNodeAt(startPos, startLoc);
node.test = expr; node.test = expr;
@ -152,11 +147,11 @@ pp.parseMaybeConditional = function (noIn, refShorthandDefaultPos) {
// Start the precedence parser. // Start the precedence parser.
pp.parseExprOps = function (noIn, refShorthandDefaultPos) { pp.parseExprOps = function (noIn, refDestructuringErrors) {
var startPos = this.start, var startPos = this.start,
startLoc = this.startLoc; startLoc = this.startLoc;
var expr = this.parseMaybeUnary(refShorthandDefaultPos); var expr = this.parseMaybeUnary(refDestructuringErrors);
if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr; if (this.checkExpressionErrors(refDestructuringErrors)) return expr;
return this.parseExprOp(expr, startPos, startLoc, -1, noIn); return this.parseExprOp(expr, startPos, startLoc, -1, noIn);
}; };
@ -187,7 +182,7 @@ pp.parseExprOp = function (left, leftStartPos, leftStartLoc, minPrec, noIn) {
// Parse unary operators, both prefix and postfix. // Parse unary operators, both prefix and postfix.
pp.parseMaybeUnary = function (refShorthandDefaultPos) { pp.parseMaybeUnary = function (refDestructuringErrors) {
if (this.type.prefix) { if (this.type.prefix) {
var node = this.startNode(), var node = this.startNode(),
update = this.type === _tokentype.types.incDec; update = this.type === _tokentype.types.incDec;
@ -195,14 +190,14 @@ pp.parseMaybeUnary = function (refShorthandDefaultPos) {
node.prefix = true; node.prefix = true;
this.next(); this.next();
node.argument = this.parseMaybeUnary(); node.argument = this.parseMaybeUnary();
if (refShorthandDefaultPos && refShorthandDefaultPos.start) this.unexpected(refShorthandDefaultPos.start); this.checkExpressionErrors(refDestructuringErrors, true);
if (update) this.checkLVal(node.argument);else if (this.strict && node.operator === "delete" && node.argument.type === "Identifier") this.raise(node.start, "Deleting local variable in strict mode"); if (update) this.checkLVal(node.argument);else if (this.strict && node.operator === "delete" && node.argument.type === "Identifier") this.raise(node.start, "Deleting local variable in strict mode");
return this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); return this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
} }
var startPos = this.start, var startPos = this.start,
startLoc = this.startLoc; startLoc = this.startLoc;
var expr = this.parseExprSubscripts(refShorthandDefaultPos); var expr = this.parseExprSubscripts(refDestructuringErrors);
if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr; if (this.checkExpressionErrors(refDestructuringErrors)) return expr;
while (this.type.postfix && !this.canInsertSemicolon()) { while (this.type.postfix && !this.canInsertSemicolon()) {
var node = this.startNodeAt(startPos, startLoc); var node = this.startNodeAt(startPos, startLoc);
node.operator = this.value; node.operator = this.value;
@ -217,11 +212,12 @@ pp.parseMaybeUnary = function (refShorthandDefaultPos) {
// Parse call, dot, and `[]`-subscript expressions. // Parse call, dot, and `[]`-subscript expressions.
pp.parseExprSubscripts = function (refShorthandDefaultPos) { pp.parseExprSubscripts = function (refDestructuringErrors) {
var startPos = this.start, var startPos = this.start,
startLoc = this.startLoc; startLoc = this.startLoc;
var expr = this.parseExprAtom(refShorthandDefaultPos); var expr = this.parseExprAtom(refDestructuringErrors);
if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr; var skipArrowSubscripts = expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")";
if (this.checkExpressionErrors(refDestructuringErrors) || skipArrowSubscripts) return expr;
return this.parseSubscripts(expr, startPos, startLoc); return this.parseSubscripts(expr, startPos, startLoc);
}; };
@ -261,7 +257,7 @@ pp.parseSubscripts = function (base, startPos, startLoc, noCalls) {
// `new`, or an expression wrapped in punctuation like `()`, `[]`, // `new`, or an expression wrapped in punctuation like `()`, `[]`,
// or `{}`. // or `{}`.
pp.parseExprAtom = function (refShorthandDefaultPos) { pp.parseExprAtom = function (refDestructuringErrors) {
var node = undefined, var node = undefined,
canBeArrow = this.potentialArrowAt == this.start; canBeArrow = this.potentialArrowAt == this.start;
switch (this.type) { switch (this.type) {
@ -277,6 +273,18 @@ pp.parseExprAtom = function (refShorthandDefaultPos) {
if (this.inGenerator) this.unexpected(); if (this.inGenerator) this.unexpected();
case _tokentype.types.name: case _tokentype.types.name:
// quick hack to allow async and await
if (this.value == "async" && /^[ \t]+function\b/.test(this.input.slice(this.end))) {
node = this.startNode();
this.next();
return this.parseExprAtom(refDestructuringErrors);
}
if (this.value == "await" && /^[ \t]+[\w\x1f-\uffff]/.test(this.input.slice(this.end))) {
node = this.startNode();
this.next();
return this.parseExprAtom(refDestructuringErrors);
}
var startPos = this.start, var startPos = this.start,
startLoc = this.startLoc; startLoc = this.startLoc;
var id = this.parseIdent(this.type !== _tokentype.types.name); var id = this.parseIdent(this.type !== _tokentype.types.name);
@ -309,11 +317,11 @@ pp.parseExprAtom = function (refShorthandDefaultPos) {
if (this.options.ecmaVersion >= 7 && this.type === _tokentype.types._for) { if (this.options.ecmaVersion >= 7 && this.type === _tokentype.types._for) {
return this.parseComprehension(node, false); return this.parseComprehension(node, false);
} }
node.elements = this.parseExprList(_tokentype.types.bracketR, true, true, refShorthandDefaultPos); node.elements = this.parseExprList(_tokentype.types.bracketR, true, true, refDestructuringErrors);
return this.finishNode(node, "ArrayExpression"); return this.finishNode(node, "ArrayExpression");
case _tokentype.types.braceL: case _tokentype.types.braceL:
return this.parseObj(false, refShorthandDefaultPos); return this.parseObj(false, refDestructuringErrors);
case _tokentype.types._function: case _tokentype.types._function:
node = this.startNode(); node = this.startNode();
@ -364,7 +372,7 @@ pp.parseParenAndDistinguishExpression = function (canBeArrow) {
innerStartLoc = this.startLoc; innerStartLoc = this.startLoc;
var exprList = [], var exprList = [],
first = true; first = true;
var refShorthandDefaultPos = { start: 0 }, var refDestructuringErrors = { shorthandAssign: 0, trailingComma: 0 },
spreadStart = undefined, spreadStart = undefined,
innerParenStart = undefined; innerParenStart = undefined;
while (this.type !== _tokentype.types.parenR) { while (this.type !== _tokentype.types.parenR) {
@ -377,7 +385,7 @@ pp.parseParenAndDistinguishExpression = function (canBeArrow) {
if (this.type === _tokentype.types.parenL && !innerParenStart) { if (this.type === _tokentype.types.parenL && !innerParenStart) {
innerParenStart = this.start; innerParenStart = this.start;
} }
exprList.push(this.parseMaybeAssign(false, refShorthandDefaultPos, this.parseParenItem)); exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
} }
} }
var innerEndPos = this.start, var innerEndPos = this.start,
@ -385,13 +393,14 @@ pp.parseParenAndDistinguishExpression = function (canBeArrow) {
this.expect(_tokentype.types.parenR); this.expect(_tokentype.types.parenR);
if (canBeArrow && !this.canInsertSemicolon() && this.eat(_tokentype.types.arrow)) { if (canBeArrow && !this.canInsertSemicolon() && this.eat(_tokentype.types.arrow)) {
this.checkPatternErrors(refDestructuringErrors, true);
if (innerParenStart) this.unexpected(innerParenStart); if (innerParenStart) this.unexpected(innerParenStart);
return this.parseParenArrowList(startPos, startLoc, exprList); return this.parseParenArrowList(startPos, startLoc, exprList);
} }
if (!exprList.length) this.unexpected(this.lastTokStart); if (!exprList.length) this.unexpected(this.lastTokStart);
if (spreadStart) this.unexpected(spreadStart); if (spreadStart) this.unexpected(spreadStart);
if (refShorthandDefaultPos.start) this.unexpected(refShorthandDefaultPos.start); this.checkExpressionErrors(refDestructuringErrors, true);
if (exprList.length > 1) { if (exprList.length > 1) {
val = this.startNodeAt(innerStartPos, innerStartLoc); val = this.startNodeAt(innerStartPos, innerStartLoc);
@ -421,9 +430,11 @@ pp.parseParenArrowList = function (startPos, startLoc, exprList) {
return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList); return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList);
}; };
// New's precedence is slightly tricky. It must allow its argument // New's precedence is slightly tricky. It must allow its argument to
// to be a `[]` or dot subscript expression, but not a call — at // be a `[]` or dot subscript expression, but not a call — at least,
// least, not without wrapping it in parentheses. Thus, it uses the // not without wrapping it in parentheses. Thus, it uses the noCalls
// argument to parseSubscripts to prevent it from consuming the
// argument list.
var empty = []; var empty = [];
@ -434,6 +445,7 @@ pp.parseNew = function () {
node.meta = meta; node.meta = meta;
node.property = this.parseIdent(true); node.property = this.parseIdent(true);
if (node.property.name !== "target") this.raise(node.property.start, "The only valid meta property for new is new.target"); if (node.property.name !== "target") this.raise(node.property.start, "The only valid meta property for new is new.target");
if (!this.inFunction) this.raise(node.start, "new.target can only be used in functions");
return this.finishNode(node, "MetaProperty"); return this.finishNode(node, "MetaProperty");
} }
var startPos = this.start, var startPos = this.start,
@ -474,7 +486,7 @@ pp.parseTemplate = function () {
// Parse an object literal or binding pattern. // Parse an object literal or binding pattern.
pp.parseObj = function (isPattern, refShorthandDefaultPos) { pp.parseObj = function (isPattern, refDestructuringErrors) {
var node = this.startNode(), var node = this.startNode(),
first = true, first = true,
propHash = {}; propHash = {};
@ -493,23 +505,23 @@ pp.parseObj = function (isPattern, refShorthandDefaultPos) {
if (this.options.ecmaVersion >= 6) { if (this.options.ecmaVersion >= 6) {
prop.method = false; prop.method = false;
prop.shorthand = false; prop.shorthand = false;
if (isPattern || refShorthandDefaultPos) { if (isPattern || refDestructuringErrors) {
startPos = this.start; startPos = this.start;
startLoc = this.startLoc; startLoc = this.startLoc;
} }
if (!isPattern) isGenerator = this.eat(_tokentype.types.star); if (!isPattern) isGenerator = this.eat(_tokentype.types.star);
} }
this.parsePropertyName(prop); this.parsePropertyName(prop);
this.parsePropertyValue(prop, isPattern, isGenerator, startPos, startLoc, refShorthandDefaultPos); this.parsePropertyValue(prop, isPattern, isGenerator, startPos, startLoc, refDestructuringErrors);
this.checkPropClash(prop, propHash); this.checkPropClash(prop, propHash);
node.properties.push(this.finishNode(prop, "Property")); node.properties.push(this.finishNode(prop, "Property"));
} }
return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression"); return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression");
}; };
pp.parsePropertyValue = function (prop, isPattern, isGenerator, startPos, startLoc, refShorthandDefaultPos) { pp.parsePropertyValue = function (prop, isPattern, isGenerator, startPos, startLoc, refDestructuringErrors) {
if (this.eat(_tokentype.types.colon)) { if (this.eat(_tokentype.types.colon)) {
prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refShorthandDefaultPos); prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
prop.kind = "init"; prop.kind = "init";
} else if (this.options.ecmaVersion >= 6 && this.type === _tokentype.types.parenL) { } else if (this.options.ecmaVersion >= 6 && this.type === _tokentype.types.parenL) {
if (isPattern) this.unexpected(); if (isPattern) this.unexpected();
@ -526,13 +538,14 @@ pp.parsePropertyValue = function (prop, isPattern, isGenerator, startPos, startL
var start = prop.value.start; var start = prop.value.start;
if (prop.kind === "get") this.raise(start, "getter should have no params");else this.raise(start, "setter should have exactly one param"); if (prop.kind === "get") this.raise(start, "getter should have no params");else this.raise(start, "setter should have exactly one param");
} }
if (prop.kind === "set" && prop.value.params[0].type === "RestElement") this.raise(prop.value.params[0].start, "Setter cannot use rest params");
} else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
prop.kind = "init"; prop.kind = "init";
if (isPattern) { if (isPattern) {
if (this.isKeyword(prop.key.name) || this.strict && (_identifier.reservedWords.strictBind(prop.key.name) || _identifier.reservedWords.strict(prop.key.name)) || !this.options.allowReserved && this.isReservedWord(prop.key.name)) this.raise(prop.key.start, "Binding " + prop.key.name); if (this.keywords.test(prop.key.name) || (this.strict ? this.reservedWordsStrictBind : this.reservedWords).test(prop.key.name)) this.raise(prop.key.start, "Binding " + prop.key.name);
prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key); prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
} else if (this.type === _tokentype.types.eq && refShorthandDefaultPos) { } else if (this.type === _tokentype.types.eq && refDestructuringErrors) {
if (!refShorthandDefaultPos.start) refShorthandDefaultPos.start = this.start; if (!refDestructuringErrors.shorthandAssign) refDestructuringErrors.shorthandAssign = this.start;
prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key); prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
} else { } else {
prop.value = prop.key; prop.value = prop.key;
@ -572,10 +585,7 @@ pp.parseMethod = function (isGenerator) {
this.initFunction(node); this.initFunction(node);
this.expect(_tokentype.types.parenL); this.expect(_tokentype.types.parenL);
node.params = this.parseBindingList(_tokentype.types.parenR, false, false); node.params = this.parseBindingList(_tokentype.types.parenR, false, false);
var allowExpressionBody = undefined; if (this.options.ecmaVersion >= 6) node.generator = isGenerator;
if (this.options.ecmaVersion >= 6) {
node.generator = isGenerator;
}
this.parseFunctionBody(node, false); this.parseFunctionBody(node, false);
return this.finishNode(node, "FunctionExpression"); return this.finishNode(node, "FunctionExpression");
}; };
@ -591,8 +601,8 @@ pp.parseArrowExpression = function (node, params) {
// Parse function body and check parameters. // Parse function body and check parameters.
pp.parseFunctionBody = function (node, allowExpression) { pp.parseFunctionBody = function (node, isArrowFunction) {
var isExpression = allowExpression && this.type !== _tokentype.types.braceL; var isExpression = isArrowFunction && this.type !== _tokentype.types.braceL;
if (isExpression) { if (isExpression) {
node.body = this.parseMaybeAssign(); node.body = this.parseMaybeAssign();
@ -613,13 +623,23 @@ pp.parseFunctionBody = function (node, allowExpression) {
// are not repeated, and it does not try to bind the words `eval` // are not repeated, and it does not try to bind the words `eval`
// or `arguments`. // or `arguments`.
if (this.strict || !isExpression && node.body.body.length && this.isUseStrict(node.body.body[0])) { if (this.strict || !isExpression && node.body.body.length && this.isUseStrict(node.body.body[0])) {
var nameHash = {}, var oldStrict = this.strict;
oldStrict = this.strict;
this.strict = true; this.strict = true;
if (node.id) this.checkLVal(node.id, true); if (node.id) this.checkLVal(node.id, true);
for (var i = 0; i < node.params.length; i++) { this.checkParams(node);
this.checkLVal(node.params[i], true, nameHash); this.strict = oldStrict;
}this.strict = oldStrict; } else if (isArrowFunction) {
this.checkParams(node);
}
};
// Checks function params for various disallowed patterns such as using "eval"
// or "arguments" and duplicate parameters.
pp.checkParams = function (node) {
var nameHash = {};
for (var i = 0; i < node.params.length; i++) {
this.checkLVal(node.params[i], true, nameHash);
} }
}; };
@ -629,17 +649,20 @@ pp.parseFunctionBody = function (node, allowExpression) {
// nothing in between them to be parsed as `null` (which is needed // nothing in between them to be parsed as `null` (which is needed
// for array literals). // for array literals).
pp.parseExprList = function (close, allowTrailingComma, allowEmpty, refShorthandDefaultPos) { pp.parseExprList = function (close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
var elts = [], var elts = [],
first = true; first = true;
while (!this.eat(close)) { while (!this.eat(close)) {
if (!first) { if (!first) {
this.expect(_tokentype.types.comma); this.expect(_tokentype.types.comma);
if (this.type === close && refDestructuringErrors && !refDestructuringErrors.trailingComma) {
refDestructuringErrors.trailingComma = this.lastTokStart;
}
if (allowTrailingComma && this.afterTrailingComma(close)) break; if (allowTrailingComma && this.afterTrailingComma(close)) break;
} else first = false; } else first = false;
var elt = undefined; var elt = undefined;
if (allowEmpty && this.type === _tokentype.types.comma) elt = null;else if (this.type === _tokentype.types.ellipsis) elt = this.parseSpread(refShorthandDefaultPos);else elt = this.parseMaybeAssign(false, refShorthandDefaultPos); if (allowEmpty && this.type === _tokentype.types.comma) elt = null;else if (this.type === _tokentype.types.ellipsis) elt = this.parseSpread(refDestructuringErrors);else elt = this.parseMaybeAssign(false, refDestructuringErrors);
elts.push(elt); elts.push(elt);
} }
return elts; return elts;
@ -653,7 +676,7 @@ pp.parseIdent = function (liberal) {
var node = this.startNode(); var node = this.startNode();
if (liberal && this.options.allowReserved == "never") liberal = false; if (liberal && this.options.allowReserved == "never") liberal = false;
if (this.type === _tokentype.types.name) { if (this.type === _tokentype.types.name) {
if (!liberal && (!this.options.allowReserved && this.isReservedWord(this.value) || this.strict && _identifier.reservedWords.strict(this.value) && (this.options.ecmaVersion >= 6 || this.input.slice(this.start, this.end).indexOf("\\") == -1))) this.raise(this.start, "The keyword '" + this.value + "' is reserved"); if (!liberal && (this.strict ? this.reservedWordsStrict : this.reservedWords).test(this.value) && (this.options.ecmaVersion >= 6 || this.input.slice(this.start, this.end).indexOf("\\") == -1)) this.raise(this.start, "The keyword '" + this.value + "' is reserved");
node.name = this.value; node.name = this.value;
} else if (liberal && this.type.keyword) { } else if (liberal && this.type.keyword) {
node.name = this.type.keyword; node.name = this.type.keyword;
@ -701,7 +724,7 @@ pp.parseComprehension = function (node, isGenerator) {
return this.finishNode(node, "ComprehensionExpression"); return this.finishNode(node, "ComprehensionExpression");
}; };
},{"./identifier":"/src\\identifier.js","./state":"/src\\state.js","./tokentype":"/src\\tokentype.js","./util":"/src\\util.js"}],"/src\\identifier.js":[function(_dereq_,module,exports){ },{"./state":"/src\\state.js","./tokentype":"/src\\tokentype.js"}],"/src\\identifier.js":[function(_dereq_,module,exports){
// This is a trick taken from Esprima. It turns out that, on // This is a trick taken from Esprima. It turns out that, on
// non-Chrome browsers, to check whether a string is in a set, a // non-Chrome browsers, to check whether a string is in a set, a
// predicate containing a big ugly `switch` statement is faster than // predicate containing a big ugly `switch` statement is faster than
@ -711,36 +734,19 @@ pp.parseComprehension = function (node, isGenerator) {
// //
// It starts by sorting the words by length. // It starts by sorting the words by length.
// Reserved word lists for various dialects of the language
"use strict"; "use strict";
exports.__esModule = true; exports.__esModule = true;
exports.isIdentifierStart = isIdentifierStart; exports.isIdentifierStart = isIdentifierStart;
exports.isIdentifierChar = isIdentifierChar; exports.isIdentifierChar = isIdentifierChar;
// Removed to create an eval-free library
// Reserved word lists for various dialects of the language
var reservedWords = { var reservedWords = {
3: function anonymous(str 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
/**/) { 5: "class enum extends super const export import",
switch(str.length){case 6:switch(str){case "double":case "export":case "import":case "native":case "public":case "static":case "throws":return true}return false;case 4:switch(str){case "byte":case "char":case "enum":case "goto":case "long":return true}return false;case 5:switch(str){case "class":case "final":case "float":case "short":case "super":return true}return false;case 7:switch(str){case "boolean":case "extends":case "package":case "private":return true}return false;case 9:switch(str){case "interface":case "protected":case "transient":return true}return false;case 8:switch(str){case "abstract":case "volatile":return true}return false;case 10:return str === "implements";case 3:return str === "int";case 12:return str === "synchronized";} 6: "enum",
}, strict: "implements interface let package private protected public static yield",
5: function anonymous(str strictBind: "eval arguments"
/**/) {
switch(str.length){case 5:switch(str){case "class":case "super":case "const":return true}return false;case 6:switch(str){case "export":case "import":return true}return false;case 4:return str === "enum";case 7:return str === "extends";}
},
6: function anonymous(str
/**/) {
switch(str){case "enum":case "await":return true}return false;
},
strict: function anonymous(str
/**/) {
switch(str.length){case 9:switch(str){case "interface":case "protected":return true}return false;case 7:switch(str){case "package":case "private":return true}return false;case 6:switch(str){case "public":case "static":return true}return false;case 10:return str === "implements";case 3:return str === "let";case 5:return str === "yield";}
},
strictBind: function anonymous(str
/**/) {
switch(str){case "eval":case "arguments":return true}return false;
}
}; };
exports.reservedWords = reservedWords; exports.reservedWords = reservedWords;
@ -749,14 +755,8 @@ exports.reservedWords = reservedWords;
var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"; var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
var keywords = { var keywords = {
5: function anonymous(str 5: ecma5AndLessKeywords,
/**/) { 6: ecma5AndLessKeywords + " let const class extends export import yield super"
switch(str.length){case 4:switch(str){case "case":case "else":case "with":case "null":case "true":case "void":case "this":return true}return false;case 5:switch(str){case "break":case "catch":case "throw":case "while":case "false":return true}return false;case 3:switch(str){case "for":case "try":case "var":case "new":return true}return false;case 6:switch(str){case "return":case "switch":case "typeof":case "delete":return true}return false;case 8:switch(str){case "continue":case "debugger":case "function":return true}return false;case 2:switch(str){case "do":case "if":case "in":return true}return false;case 7:switch(str){case "default":case "finally":return true}return false;case 10:return str === "instanceof";}
},
6: function anonymous(str
/**/) {
switch(str.length){case 5:switch(str){case "break":case "catch":case "throw":case "while":case "false":case "const":case "class":case "yield":case "super":return true}return false;case 4:switch(str){case "case":case "else":case "with":case "null":case "true":case "void":case "this":return true}return false;case 6:switch(str){case "return":case "switch":case "typeof":case "delete":case "export":case "import":return true}return false;case 3:switch(str){case "for":case "try":case "var":case "new":case "let":return true}return false;case 8:switch(str){case "continue":case "debugger":case "function":return true}return false;case 7:switch(str){case "default":case "finally":case "extends":return true}return false;case 2:switch(str){case "do":case "if":case "in":return true}return false;case 10:return str === "instanceof";}
}
}; };
exports.keywords = keywords; exports.keywords = keywords;
@ -793,11 +793,11 @@ function isIdentifierChar(code, astral) {
// Git repositories for Acorn are available at // Git repositories for Acorn are available at
// //
// http://marijnhaverbeke.nl/git/acorn // http://marijnhaverbeke.nl/git/acorn
// https://github.com/marijnh/acorn.git // https://github.com/ternjs/acorn.git
// //
// Please use the [github bug tracker][ghbt] to report issues. // Please use the [github bug tracker][ghbt] to report issues.
// //
// [ghbt]: https://github.com/marijnh/acorn/issues // [ghbt]: https://github.com/ternjs/acorn/issues
// //
// This file defines the main parser interface. The library also comes // This file defines the main parser interface. The library also comes
// with a [error-tolerant parser][dammit] and an // with a [error-tolerant parser][dammit] and an
@ -815,8 +815,6 @@ exports.tokenizer = tokenizer;
var _state = _dereq_("./state"); var _state = _dereq_("./state");
var _options = _dereq_("./options");
_dereq_("./parseutil"); _dereq_("./parseutil");
_dereq_("./statement"); _dereq_("./statement");
@ -829,6 +827,9 @@ _dereq_("./location");
exports.Parser = _state.Parser; exports.Parser = _state.Parser;
exports.plugins = _state.plugins; exports.plugins = _state.plugins;
var _options = _dereq_("./options");
exports.defaultOptions = _options.defaultOptions; exports.defaultOptions = _options.defaultOptions;
var _locutil = _dereq_("./locutil"); var _locutil = _dereq_("./locutil");
@ -865,7 +866,7 @@ var _whitespace = _dereq_("./whitespace");
exports.isNewLine = _whitespace.isNewLine; exports.isNewLine = _whitespace.isNewLine;
exports.lineBreak = _whitespace.lineBreak; exports.lineBreak = _whitespace.lineBreak;
exports.lineBreakG = _whitespace.lineBreakG; exports.lineBreakG = _whitespace.lineBreakG;
var version = "2.1.1"; var version = "2.7.0";
exports.version = version; exports.version = version;
// The main exported interface (under `self.acorn` when in the // The main exported interface (under `self.acorn` when in the
@ -890,7 +891,7 @@ function parseExpressionAt(input, pos, options) {
} }
// Acorn is organized as a tokenizer and a recursive-descent parser. // Acorn is organized as a tokenizer and a recursive-descent parser.
// The `tokenize` export provides an interface to the tokenizer. // The `tokenizer` export provides an interface to the tokenizer.
function tokenizer(input, options) { function tokenizer(input, options) {
return new _state.Parser(options, input); return new _state.Parser(options, input);
@ -940,7 +941,7 @@ var _whitespace = _dereq_("./whitespace");
var Position = (function () { var Position = (function () {
function Position(line, col) { function Position(line, col) {
_classCallCheck(this, Position);
this.line = line; this.line = line;
this.column = col; this.column = col;
@ -956,7 +957,7 @@ var Position = (function () {
exports.Position = Position; exports.Position = Position;
var SourceLocation = function SourceLocation(p, start, end) { var SourceLocation = function SourceLocation(p, start, end) {
_classCallCheck(this, SourceLocation);
this.start = start; this.start = start;
this.end = end; this.end = end;
@ -991,8 +992,6 @@ var _tokentype = _dereq_("./tokentype");
var _state = _dereq_("./state"); var _state = _dereq_("./state");
var _identifier = _dereq_("./identifier");
var _util = _dereq_("./util"); var _util = _dereq_("./util");
var pp = _state.Parser.prototype; var pp = _state.Parser.prototype;
@ -1006,7 +1005,6 @@ pp.toAssignable = function (node, isBinding) {
case "Identifier": case "Identifier":
case "ObjectPattern": case "ObjectPattern":
case "ArrayPattern": case "ArrayPattern":
case "AssignmentPattern":
break; break;
case "ObjectExpression": case "ObjectExpression":
@ -1026,10 +1024,16 @@ pp.toAssignable = function (node, isBinding) {
case "AssignmentExpression": case "AssignmentExpression":
if (node.operator === "=") { if (node.operator === "=") {
node.type = "AssignmentPattern"; node.type = "AssignmentPattern";
delete node.operator; delete node.operator
// falls through to AssignmentPattern
;
} else { } else {
this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); this.raise(node.left.end, "Only '=' operator can be used for specifying default value.");
break;
} }
case "AssignmentPattern":
if (node.right.type === "YieldExpression") this.raise(node.right.start, "Yield expression cannot be a default value");
break; break;
case "ParenthesizedExpression": case "ParenthesizedExpression":
@ -1061,6 +1065,8 @@ pp.toAssignableList = function (exprList, isBinding) {
if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern") this.unexpected(arg.start); if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern") this.unexpected(arg.start);
--end; --end;
} }
if (isBinding && last.type === "RestElement" && last.argument.type !== "Identifier") this.unexpected(last.argument.start);
} }
for (var i = 0; i < end; i++) { for (var i = 0; i < end; i++) {
var elt = exprList[i]; var elt = exprList[i];
@ -1071,17 +1077,20 @@ pp.toAssignableList = function (exprList, isBinding) {
// Parses spread element. // Parses spread element.
pp.parseSpread = function (refShorthandDefaultPos) { pp.parseSpread = function (refDestructuringErrors) {
var node = this.startNode(); var node = this.startNode();
this.next(); this.next();
node.argument = this.parseMaybeAssign(refShorthandDefaultPos); node.argument = this.parseMaybeAssign(refDestructuringErrors);
return this.finishNode(node, "SpreadElement"); return this.finishNode(node, "SpreadElement");
}; };
pp.parseRest = function () { pp.parseRest = function (allowNonIdent) {
var node = this.startNode(); var node = this.startNode();
this.next(); this.next();
node.argument = this.type === _tokentype.types.name || this.type === _tokentype.types.bracketL ? this.parseBindingAtom() : this.unexpected();
// RestElement inside of a function parameter must be an identifier
if (allowNonIdent) node.argument = this.type === _tokentype.types.name ? this.parseIdent() : this.unexpected();else node.argument = this.type === _tokentype.types.name || this.type === _tokentype.types.bracketL ? this.parseBindingAtom() : this.unexpected();
return this.finishNode(node, "RestElement"); return this.finishNode(node, "RestElement");
}; };
@ -1107,7 +1116,7 @@ pp.parseBindingAtom = function () {
} }
}; };
pp.parseBindingList = function (close, allowEmpty, allowTrailingComma) { pp.parseBindingList = function (close, allowEmpty, allowTrailingComma, allowNonIdent) {
var elts = [], var elts = [],
first = true; first = true;
while (!this.eat(close)) { while (!this.eat(close)) {
@ -1117,7 +1126,7 @@ pp.parseBindingList = function (close, allowEmpty, allowTrailingComma) {
} else if (allowTrailingComma && this.afterTrailingComma(close)) { } else if (allowTrailingComma && this.afterTrailingComma(close)) {
break; break;
} else if (this.type === _tokentype.types.ellipsis) { } else if (this.type === _tokentype.types.ellipsis) {
var rest = this.parseRest(); var rest = this.parseRest(allowNonIdent);
this.parseBindingListItem(rest); this.parseBindingListItem(rest);
elts.push(rest); elts.push(rest);
this.expect(close); this.expect(close);
@ -1139,9 +1148,8 @@ pp.parseBindingListItem = function (param) {
pp.parseMaybeDefault = function (startPos, startLoc, left) { pp.parseMaybeDefault = function (startPos, startLoc, left) {
left = left || this.parseBindingAtom(); left = left || this.parseBindingAtom();
if (!this.eat(_tokentype.types.eq)) return left; if (this.options.ecmaVersion < 6 || !this.eat(_tokentype.types.eq)) return left;
var node = this.startNodeAt(startPos, startLoc); var node = this.startNodeAt(startPos, startLoc);
node.operator = "=";
node.left = left; node.left = left;
node.right = this.parseMaybeAssign(); node.right = this.parseMaybeAssign();
return this.finishNode(node, "AssignmentPattern"); return this.finishNode(node, "AssignmentPattern");
@ -1153,9 +1161,9 @@ pp.parseMaybeDefault = function (startPos, startLoc, left) {
pp.checkLVal = function (expr, isBinding, checkClashes) { pp.checkLVal = function (expr, isBinding, checkClashes) {
switch (expr.type) { switch (expr.type) {
case "Identifier": case "Identifier":
if (this.strict && (_identifier.reservedWords.strictBind(expr.name) || _identifier.reservedWords.strict(expr.name))) this.raise(expr.start, (isBinding ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); if (this.strict && this.reservedWordsStrictBind.test(expr.name)) this.raise(expr.start, (isBinding ? "Binding " : "Assigning to ") + expr.name + " in strict mode");
if (checkClashes) { if (checkClashes) {
if (_util.has(checkClashes, expr.name)) this.raise(expr.start, "Argument name clash in strict mode"); if (_util.has(checkClashes, expr.name)) this.raise(expr.start, "Argument name clash");
checkClashes[expr.name] = true; checkClashes[expr.name] = true;
} }
break; break;
@ -1193,7 +1201,7 @@ pp.checkLVal = function (expr, isBinding, checkClashes) {
} }
}; };
},{"./identifier":"/src\\identifier.js","./state":"/src\\state.js","./tokentype":"/src\\tokentype.js","./util":"/src\\util.js"}],"/src\\node.js":[function(_dereq_,module,exports){ },{"./state":"/src\\state.js","./tokentype":"/src\\tokentype.js","./util":"/src\\util.js"}],"/src\\node.js":[function(_dereq_,module,exports){
"use strict"; "use strict";
exports.__esModule = true; exports.__esModule = true;
@ -1205,7 +1213,7 @@ var _state = _dereq_("./state");
var _locutil = _dereq_("./locutil"); var _locutil = _dereq_("./locutil");
var Node = function Node(parser, pos, loc) { var Node = function Node(parser, pos, loc) {
_classCallCheck(this, Node);
this.type = ""; this.type = "";
this.start = pos; this.start = pos;
@ -1279,11 +1287,11 @@ var defaultOptions = {
// `onTrailingComma` is similar to `onInsertedSemicolon`, but for // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
// trailing commas. // trailing commas.
onTrailingComma: null, onTrailingComma: null,
// By default, reserved words are not enforced. Disable // By default, reserved words are only enforced if ecmaVersion >= 5.
// `allowReserved` to enforce them. When this option has the // Set `allowReserved` to a boolean value to explicitly turn this on
// value "never", reserved words and keywords can also not be // an off. When this option has the value "never", reserved words
// used as property names. // and keywords can also not be used as property names.
allowReserved: true, allowReserved: null,
// When enabled, a return at the top level is not considered an // When enabled, a return at the top level is not considered an
// error. // error.
allowReturnOutsideFunction: false, allowReturnOutsideFunction: false,
@ -1300,9 +1308,9 @@ var defaultOptions = {
locations: true, locations: true,
// A function can be passed as `onToken` option, which will // A function can be passed as `onToken` option, which will
// cause Acorn to call that function with object in the same // cause Acorn to call that function with object in the same
// format as tokenize() returns. Note that you are not // format as tokens returned from `tokenizer().getToken()`. Note
// allowed to call the parser from the callback—that will // that you are not allowed to call the parser from the
// corrupt its internal state. // callback—that will corrupt its internal state.
onToken: null, onToken: null,
// A function can be passed as `onComment` option, which will // A function can be passed as `onComment` option, which will
// cause Acorn to call that function with `(block, text, start, // cause Acorn to call that function with `(block, text, start,
@ -1349,7 +1357,9 @@ function getOptions(opts) {
var options = {}; var options = {};
for (var opt in defaultOptions) { for (var opt in defaultOptions) {
options[opt] = opts && _util.has(opts, opt) ? opts[opt] : defaultOptions[opt]; options[opt] = opts && _util.has(opts, opt) ? opts[opt] : defaultOptions[opt];
}if (_util.isArray(options.onToken)) { }if (options.allowReserved == null) options.allowReserved = options.ecmaVersion < 5;
if (_util.isArray(options.onToken)) {
(function () { (function () {
var tokens = options.onToken; var tokens = options.onToken;
options.onToken = function (token) { options.onToken = function (token) {
@ -1466,6 +1476,18 @@ pp.unexpected = function (pos) {
this.raise(pos != null ? pos : this.start, "Unexpected token"); this.raise(pos != null ? pos : this.start, "Unexpected token");
}; };
pp.checkPatternErrors = function (refDestructuringErrors, andThrow) {
var pos = refDestructuringErrors && refDestructuringErrors.trailingComma;
if (!andThrow) return !!pos;
if (pos) this.raise(pos, "Trailing comma is not permitted in destructuring patterns");
};
pp.checkExpressionErrors = function (refDestructuringErrors, andThrow) {
var pos = refDestructuringErrors && refDestructuringErrors.shorthandAssign;
if (!andThrow) return !!pos;
if (pos) this.raise(pos, "Shorthand property assignments are valid only in destructuring patterns");
};
},{"./state":"/src\\state.js","./tokentype":"/src\\tokentype.js","./whitespace":"/src\\whitespace.js"}],"/src\\state.js":[function(_dereq_,module,exports){ },{"./state":"/src\\state.js","./tokentype":"/src\\tokentype.js","./whitespace":"/src\\whitespace.js"}],"/src\\state.js":[function(_dereq_,module,exports){
"use strict"; "use strict";
@ -1485,19 +1507,31 @@ var _options = _dereq_("./options");
var plugins = {}; var plugins = {};
exports.plugins = plugins; exports.plugins = plugins;
function keywordRegexp(words) {
return new RegExp("^(" + words.replace(/ /g, "|") + ")$");
}
var Parser = (function () { var Parser = (function () {
function Parser(options, input, startPos) { function Parser(options, input, startPos) {
_classCallCheck(this, Parser);
this.options = _options.getOptions(options);
this.sourceFile = this.options.sourceFile; this.options = options = _options.getOptions(options);
this.isKeyword = _identifier.keywords[this.options.ecmaVersion >= 6 ? 6 : 5]; this.sourceFile = options.sourceFile;
this.isReservedWord = _identifier.reservedWords[this.options.ecmaVersion]; this.keywords = keywordRegexp(_identifier.keywords[options.ecmaVersion >= 6 ? 6 : 5]);
var reserved = options.allowReserved ? "" : _identifier.reservedWords[options.ecmaVersion] + (options.sourceType == "module" ? " await" : "");
this.reservedWords = keywordRegexp(reserved);
var reservedStrict = (reserved ? reserved + " " : "") + _identifier.reservedWords.strict;
this.reservedWordsStrict = keywordRegexp(reservedStrict);
this.reservedWordsStrictBind = keywordRegexp(reservedStrict + " " + _identifier.reservedWords.strictBind);
this.input = String(input); this.input = String(input);
// Used to signal to callers of `readWord1` whether the word
// contained any escape sequences. This is needed because words with
// escape sequences must not be interpreted as keywords.
this.containsEsc = false;
// Load plugins // Load plugins
this.loadPlugins(this.options.plugins); this.loadPlugins(options.plugins);
// Set up token state // Set up token state
@ -1533,7 +1567,7 @@ var Parser = (function () {
this.exprAllowed = true; this.exprAllowed = true;
// Figure out if it's a module code. // Figure out if it's a module code.
this.strict = this.inModule = this.options.sourceType === "module"; this.strict = this.inModule = options.sourceType === "module";
// Used to signify the start of a potential arrow function // Used to signify the start of a potential arrow function
this.potentialArrowAt = -1; this.potentialArrowAt = -1;
@ -1544,9 +1578,19 @@ var Parser = (function () {
this.labels = []; this.labels = [];
// If enabled, skip leading hashbang line. // If enabled, skip leading hashbang line.
if (this.pos === 0 && this.options.allowHashBang && this.input.slice(0, 2) === "#!") this.skipLineComment(2); if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") this.skipLineComment(2);
} }
// DEPRECATED Kept for backwards compatibility until 3.0 in case a plugin uses them
Parser.prototype.isKeyword = function isKeyword(word) {
return this.keywords.test(word);
};
Parser.prototype.isReservedWord = function isReservedWord(word) {
return this.reservedWords.test(word);
};
Parser.prototype.extend = function extend(name, f) { Parser.prototype.extend = function extend(name, f) {
this[name] = f(this[name]); this[name] = f(this[name]);
}; };
@ -1665,7 +1709,7 @@ pp.parseStatement = function (declaration, topLevel) {
case _tokentype.types._import: case _tokentype.types._import:
if (!this.options.allowImportExportEverywhere) { if (!this.options.allowImportExportEverywhere) {
if (!topLevel) this.raise(this.start, "'import' and 'export' may only appear at the top level"); if (!topLevel) this.raise(this.start, "'import' and 'export' may only appear at the top level");
if (!this.inModule) this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); // if (!this.inModule) this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'");
} }
return starttype === _tokentype.types._import ? this.parseImport(node) : this.parseExport(node); return starttype === _tokentype.types._import ? this.parseImport(node) : this.parseExport(node);
@ -1741,14 +1785,15 @@ pp.parseForStatement = function (node) {
if ((this.type === _tokentype.types._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) && _init.declarations.length === 1 && !(varKind !== _tokentype.types._var && _init.declarations[0].init)) return this.parseForIn(node, _init); if ((this.type === _tokentype.types._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) && _init.declarations.length === 1 && !(varKind !== _tokentype.types._var && _init.declarations[0].init)) return this.parseForIn(node, _init);
return this.parseFor(node, _init); return this.parseFor(node, _init);
} }
var refShorthandDefaultPos = { start: 0 }; var refDestructuringErrors = { shorthandAssign: 0, trailingComma: 0 };
var init = this.parseExpression(true, refShorthandDefaultPos); var init = this.parseExpression(true, refDestructuringErrors);
if (this.type === _tokentype.types._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) { if (this.type === _tokentype.types._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) {
this.checkPatternErrors(refDestructuringErrors, true);
this.toAssignable(init); this.toAssignable(init);
this.checkLVal(init); this.checkLVal(init);
return this.parseForIn(node, init); return this.parseForIn(node, init);
} else if (refShorthandDefaultPos.start) { } else {
this.unexpected(refShorthandDefaultPos.start); this.checkExpressionErrors(refDestructuringErrors, true);
} }
return this.parseFor(node, init); return this.parseFor(node, init);
}; };
@ -1840,11 +1885,9 @@ pp.parseTryStatement = function (node) {
clause.param = this.parseBindingAtom(); clause.param = this.parseBindingAtom();
this.checkLVal(clause.param, true); this.checkLVal(clause.param, true);
this.expect(_tokentype.types.parenR); this.expect(_tokentype.types.parenR);
clause.guard = null;
clause.body = this.parseBlock(); clause.body = this.parseBlock();
node.handler = this.finishNode(clause, "CatchClause"); node.handler = this.finishNode(clause, "CatchClause");
} }
node.guardedHandlers = empty;
node.finalizer = this.eat(_tokentype.types._finally) ? this.parseBlock() : null; node.finalizer = this.eat(_tokentype.types._finally) ? this.parseBlock() : null;
if (!node.handler && !node.finalizer) this.raise(node.start, "Missing catch or finally clause"); if (!node.handler && !node.finalizer) this.raise(node.start, "Missing catch or finally clause");
return this.finishNode(node, "TryStatement"); return this.finishNode(node, "TryStatement");
@ -1998,7 +2041,7 @@ pp.parseFunction = function (node, isStatement, allowExpressionBody) {
pp.parseFunctionParams = function (node) { pp.parseFunctionParams = function (node) {
this.expect(_tokentype.types.parenL); this.expect(_tokentype.types.parenL);
node.params = this.parseBindingList(_tokentype.types.parenR, false, false); node.params = this.parseBindingList(_tokentype.types.parenR, false, false, true);
}; };
// Parse a class declaration or literal (depending on the // Parse a class declaration or literal (depending on the
@ -2049,6 +2092,7 @@ pp.parseClass = function (node, isStatement) {
var start = method.value.start; var start = method.value.start;
if (method.kind === "get") this.raise(start, "getter should have no params");else this.raise(start, "setter should have exactly one param"); if (method.kind === "get") this.raise(start, "getter should have no params");else this.raise(start, "setter should have exactly one param");
} }
if (method.kind === "set" && method.value.params[0].type === "RestElement") this.raise(method.value.params[0].start, "Setter cannot use rest params");
} }
} }
node.body = this.finishNode(classBody, "ClassBody"); node.body = this.finishNode(classBody, "ClassBody");
@ -2105,6 +2149,13 @@ pp.parseExport = function (node) {
if (this.eatContextual("from")) { if (this.eatContextual("from")) {
node.source = this.type === _tokentype.types.string ? this.parseExprAtom() : this.unexpected(); node.source = this.type === _tokentype.types.string ? this.parseExprAtom() : this.unexpected();
} else { } else {
// check for keywords used as local names
for (var i = 0; i < node.specifiers.length; i++) {
if (this.keywords.test(node.specifiers[i].local.name) || this.reservedWords.test(node.specifiers[i].local.name)) {
this.unexpected(node.specifiers[i].local.start);
}
}
node.source = null; node.source = null;
} }
this.semicolon(); this.semicolon();
@ -2145,7 +2196,6 @@ pp.parseImport = function (node) {
if (this.type === _tokentype.types.string) { if (this.type === _tokentype.types.string) {
node.specifiers = empty; node.specifiers = empty;
node.source = this.parseExprAtom(); node.source = this.parseExprAtom();
node.kind = "";
} else { } else {
node.specifiers = this.parseImportSpecifiers(); node.specifiers = this.parseImportSpecifiers();
this.expectContextual("from"); this.expectContextual("from");
@ -2186,7 +2236,13 @@ pp.parseImportSpecifiers = function () {
var node = this.startNode(); var node = this.startNode();
node.imported = this.parseIdent(true); node.imported = this.parseIdent(true);
node.local = this.eatContextual("as") ? this.parseIdent() : node.imported; if (this.eatContextual("as")) {
node.local = this.parseIdent();
} else {
node.local = node.imported;
if (this.isKeyword(node.local.name)) this.unexpected(node.local.start);
if (this.reservedWordsStrict.test(node.local.name)) this.raise(node.local.start, "The keyword '" + node.local.name + "' is reserved");
}
this.checkLVal(node.local, true); this.checkLVal(node.local, true);
nodes.push(this.finishNode(node, "ImportSpecifier")); nodes.push(this.finishNode(node, "ImportSpecifier"));
} }
@ -2211,7 +2267,7 @@ var _tokentype = _dereq_("./tokentype");
var _whitespace = _dereq_("./whitespace"); var _whitespace = _dereq_("./whitespace");
var TokContext = function TokContext(token, isExpr, preserveSpace, override) { var TokContext = function TokContext(token, isExpr, preserveSpace, override) {
_classCallCheck(this, TokContext);
this.token = token; this.token = token;
this.isExpr = !!isExpr; this.isExpr = !!isExpr;
@ -2326,7 +2382,7 @@ var _whitespace = _dereq_("./whitespace");
// used for the onToken callback and the external tokenizer. // used for the onToken callback and the external tokenizer.
var Token = function Token(p) { var Token = function Token(p) {
_classCallCheck(this, Token);
this.type = p.type; this.type = p.type;
this.value = p.value; this.value = p.value;
@ -2720,13 +2776,13 @@ pp.finishOp = function (type, size) {
// Parse a regular expression. Some context-awareness is necessary, // Parse a regular expression. Some context-awareness is necessary,
// since a '/' inside a '[]' set does not end the expression. // since a '/' inside a '[]' set does not end the expression.
function tryCreateRegexp(src, flags, throwErrorAt) { function tryCreateRegexp(src, flags, throwErrorAt, parser) {
try { try {
return new RegExp(src, flags); return new RegExp(src, flags);
} catch (e) { } catch (e) {
if (throwErrorAt !== undefined) { if (throwErrorAt !== undefined) {
if (e instanceof SyntaxError) this.raise(throwErrorAt, "Error parsing regular expression: " + e.message); if (e instanceof SyntaxError) parser.raise(throwErrorAt, "Error parsing regular expression: " + e.message);
this.raise(e); throw e;
} }
} }
} }
@ -2756,8 +2812,8 @@ pp.readRegexp = function () {
var mods = this.readWord1(); var mods = this.readWord1();
var tmp = content; var tmp = content;
if (mods) { if (mods) {
var validFlags = /^[gmsiy]*$/; var validFlags = /^[gim]*$/;
if (this.options.ecmaVersion >= 6) validFlags = /^[gmsiyu]*$/; if (this.options.ecmaVersion >= 6) validFlags = /^[gimuy]*$/;
if (!validFlags.test(mods)) this.raise(start, "Invalid regular expression flag"); if (!validFlags.test(mods)) this.raise(start, "Invalid regular expression flag");
if (mods.indexOf("u") >= 0 && !regexpUnicodeSupport) { if (mods.indexOf("u") >= 0 && !regexpUnicodeSupport) {
// Replace each astral symbol and every Unicode escape sequence that // Replace each astral symbol and every Unicode escape sequence that
@ -2768,7 +2824,7 @@ pp.readRegexp = function () {
// negatives in unlikely scenarios. For example, `[\u{61}-b]` is a // negatives in unlikely scenarios. For example, `[\u{61}-b]` is a
// perfectly valid pattern that is equivalent to `[a-b]`, but it would // perfectly valid pattern that is equivalent to `[a-b]`, but it would
// be replaced by `[x-b]` which throws an error. // be replaced by `[x-b]` which throws an error.
tmp = tmp.replace(/\\u\{([0-9a-fA-F]+)\}/g, function (match, code, offset) { tmp = tmp.replace(/\\u\{([0-9a-fA-F]+)\}/g, function (_match, code, offset) {
code = Number("0x" + code); code = Number("0x" + code);
if (code > 0x10FFFF) _this.raise(start + offset + 3, "Code point out of bounds"); if (code > 0x10FFFF) _this.raise(start + offset + 3, "Code point out of bounds");
return "x"; return "x";
@ -2781,7 +2837,7 @@ pp.readRegexp = function () {
// Rhino's regular expression parser is flaky and throws uncatchable exceptions, // Rhino's regular expression parser is flaky and throws uncatchable exceptions,
// so don't do detection if we are running under Rhino // so don't do detection if we are running under Rhino
if (!isRhino) { if (!isRhino) {
tryCreateRegexp(tmp, undefined, start); tryCreateRegexp(tmp, undefined, start, this);
// Get a regular expression object for this pattern-flag pair, or `null` in // Get a regular expression object for this pattern-flag pair, or `null` in
// case the current environment doesn't support the flags it uses. // case the current environment doesn't support the flags it uses.
value = tryCreateRegexp(content, mods); value = tryCreateRegexp(content, mods);
@ -2985,7 +3041,7 @@ pp.readEscapedChar = function (inTemplate) {
octalStr = octalStr.slice(0, -1); octalStr = octalStr.slice(0, -1);
octal = parseInt(octalStr, 8); octal = parseInt(octalStr, 8);
} }
if (octal > 0 && (this.strict || inTemplate)) { if (octalStr !== "0" && (this.strict || inTemplate)) {
this.raise(this.pos - 2, "Octal literal in strict mode"); this.raise(this.pos - 2, "Octal literal in strict mode");
} }
this.pos += octalStr.length - 1; this.pos += octalStr.length - 1;
@ -3004,20 +3060,14 @@ pp.readHexChar = function (len) {
return n; return n;
}; };
// Used to signal to callers of `readWord1` whether the word // Read an identifier, and return it as a string. Sets `this.containsEsc`
// contained any escape sequences. This is needed because words with
// escape sequences must not be interpreted as keywords.
var containsEsc;
// Read an identifier, and return it as a string. Sets `containsEsc`
// to whether the word contained a '\u' escape. // to whether the word contained a '\u' escape.
// //
// Incrementally adds only escaped chars, adding other chunks as-is // Incrementally adds only escaped chars, adding other chunks as-is
// as a micro-optimization. // as a micro-optimization.
pp.readWord1 = function () { pp.readWord1 = function () {
containsEsc = false; this.containsEsc = false;
var word = "", var word = "",
first = true, first = true,
chunkStart = this.pos; chunkStart = this.pos;
@ -3028,7 +3078,7 @@ pp.readWord1 = function () {
this.pos += ch <= 0xffff ? 1 : 2; this.pos += ch <= 0xffff ? 1 : 2;
} else if (ch === 92) { } else if (ch === 92) {
// "\" // "\"
containsEsc = true; this.containsEsc = true;
word += this.input.slice(chunkStart, this.pos); word += this.input.slice(chunkStart, this.pos);
var escStart = this.pos; var escStart = this.pos;
if (this.input.charCodeAt(++this.pos) != 117) // "u" if (this.input.charCodeAt(++this.pos) != 117) // "u"
@ -3052,7 +3102,7 @@ pp.readWord1 = function () {
pp.readWord = function () { pp.readWord = function () {
var word = this.readWord1(); var word = this.readWord1();
var type = _tokentype.types.name; var type = _tokentype.types.name;
if ((this.options.ecmaVersion >= 6 || !containsEsc) && this.isKeyword(word)) type = _tokentype.keywords[word]; if ((this.options.ecmaVersion >= 6 || !this.containsEsc) && this.keywords.test(word)) type = _tokentype.keywords[word];
return this.finishToken(type, word); return this.finishToken(type, word);
}; };
@ -3071,6 +3121,11 @@ pp.readWord = function () {
// be followed by an expression (thus, a slash after them would be a // be followed by an expression (thus, a slash after them would be a
// regular expression). // regular expression).
// //
// The `startsExpr` property is used to check if the token ends a
// `yield` expression. It is set on all token types that either can
// directly start an expression (like a quotation mark) or can
// continue an expression (like the body of a string).
//
// `isLoop` marks a keyword as starting a loop, which is important // `isLoop` marks a keyword as starting a loop, which is important
// to know when parsing a label, in order to allow or disallow // to know when parsing a label, in order to allow or disallow
// continue jumps to that label. // continue jumps to that label.
@ -3084,7 +3139,6 @@ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Cons
var TokenType = function TokenType(label) { var TokenType = function TokenType(label) {
var conf = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var conf = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
_classCallCheck(this, TokenType);
this.label = label; this.label = label;
this.keyword = conf.keyword; this.keyword = conf.keyword;
@ -3183,7 +3237,7 @@ kw("catch");
kw("continue"); kw("continue");
kw("debugger"); kw("debugger");
kw("default", beforeExpr); kw("default", beforeExpr);
kw("do", { isLoop: true }); kw("do", { isLoop: true, beforeExpr: true });
kw("else", beforeExpr); kw("else", beforeExpr);
kw("finally"); kw("finally");
kw("for", { isLoop: true }); kw("for", { isLoop: true });
@ -3255,5 +3309,4 @@ exports.nonASCIIwhitespace = nonASCIIwhitespace;
},{}]},{},["/src\\index.js"])("/src\\index.js") },{}]},{},["/src\\index.js"])("/src\\index.js")
}); });
});
})

Wyświetl plik

@ -1,8 +1,9 @@
define(["require", "exports", "module", "./acorn"], function(require, exports, module) { define(["require", "exports", "module", "./acorn"], function(require, exports, module) {
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}(g.acorn || (g.acorn = {})).loose = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({"/src\\index.js":[function(_dereq_,module,exports){ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}(g.acorn || (g.acorn = {})).loose = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({"/src\\index.js":[function(_dereq_,module,exports){
"use strict"; "use strict";
module.exports = typeof acorn != "undefined" ? acorn : _dereq_("./acorn"); module.exports = typeof acorn != 'undefined' ? acorn : require("./acorn");
},{}],"/src\\loose\\expression.js":[function(_dereq_,module,exports){ },{}],"/src\\loose\\expression.js":[function(_dereq_,module,exports){
"use strict"; "use strict";
@ -15,26 +16,17 @@ var _ = _dereq_("..");
var lp = _state.LooseParser.prototype; var lp = _state.LooseParser.prototype;
lp.checkLVal = function (expr, binding) { lp.checkLVal = function (expr) {
if (!expr) return expr; if (!expr) return expr;
switch (expr.type) { switch (expr.type) {
case "Identifier": case "Identifier":
return expr;
case "MemberExpression": case "MemberExpression":
return binding ? this.dummyIdent() : expr; return expr;
case "ParenthesizedExpression": case "ParenthesizedExpression":
expr.expression = this.checkLVal(expr.expression, binding); expr.expression = this.checkLVal(expr.expression);
return expr; return expr;
// FIXME recursively check contents
case "ObjectPattern":
case "ArrayPattern":
case "RestElement":
case "AssignmentPattern":
if (this.options.ecmaVersion >= 6) return expr;
default: default:
return this.dummyIdent(); return this.dummyIdent();
} }
@ -200,6 +192,17 @@ lp.parseExprAtom = function () {
return this.finishNode(node, type); return this.finishNode(node, type);
case _.tokTypes.name: case _.tokTypes.name:
// quick hack to allow async and await
if (this.tok.value == "async" && /^[ \t]+function\b/.test(this.input.slice(this.tok.end))) {
node = this.startNode();
this.next();
return this.parseExprAtom();
}
if (this.tok.value == "await" && /^[ \t]+[\w\x1f-\uffff]/.test(this.input.slice(this.tok.end))) {
node = this.startNode();
this.next();
return this.parseExprAtom();
}
var start = this.storeCurrentPos(); var start = this.storeCurrentPos();
var id = this.parseIdent(); var id = this.parseIdent();
return this.eat(_.tokTypes.arrow) ? this.parseArrowExpression(this.startNodeAt(start), [id]) : id; return this.eat(_.tokTypes.arrow) ? this.parseArrowExpression(this.startNodeAt(start), [id]) : id;
@ -440,32 +443,29 @@ lp.initFunction = function (node) {
// if possible. // if possible.
lp.toAssignable = function (node, binding) { lp.toAssignable = function (node, binding) {
if (this.options.ecmaVersion >= 6 && node) { if (!node || node.type == "Identifier" || node.type == "MemberExpression" && !binding) {} else if (node.type == "ParenthesizedExpression") {
switch (node.type) { node.expression = this.toAssignable(node.expression, binding);
case "ObjectExpression": } else if (this.options.ecmaVersion < 6) {
node.type = "ObjectPattern"; return this.dummyIdent();
var props = node.properties; } else if (node.type == "ObjectExpression") {
for (var i = 0; i < props.length; i++) { node.type = "ObjectPattern";
this.toAssignable(props[i].value, binding); var props = node.properties;
}break; for (var i = 0; i < props.length; i++) {
props[i].value = this.toAssignable(props[i].value, binding);
case "ArrayExpression":
node.type = "ArrayPattern";
this.toAssignableList(node.elements, binding);
break;
case "SpreadElement":
node.type = "RestElement";
node.argument = this.toAssignable(node.argument, binding);
break;
case "AssignmentExpression":
node.type = "AssignmentPattern";
delete node.operator;
break;
} }
} else if (node.type == "ArrayExpression") {
node.type = "ArrayPattern";
this.toAssignableList(node.elements, binding);
} else if (node.type == "SpreadElement") {
node.type = "RestElement";
node.argument = this.toAssignable(node.argument, binding);
} else if (node.type == "AssignmentExpression") {
node.type = "AssignmentPattern";
delete node.operator;
} else {
return this.dummyIdent();
} }
return this.checkLVal(node, binding); return node;
}; };
lp.toAssignableList = function (exprList, binding) { lp.toAssignableList = function (exprList, binding) {
@ -527,6 +527,8 @@ lp.parseExprList = function (close, allowEmpty) {
return elts; return elts;
}; };
// Okay
},{"..":"/src\\index.js","./parseutil":"/src\\loose\\parseutil.js","./state":"/src\\loose\\state.js"}],"/src\\loose\\index.js":[function(_dereq_,module,exports){ },{"..":"/src\\index.js","./parseutil":"/src\\loose\\parseutil.js","./state":"/src\\loose\\state.js"}],"/src\\loose\\index.js":[function(_dereq_,module,exports){
// Acorn: Loose parser // Acorn: Loose parser
// //
@ -579,6 +581,7 @@ _dereq_("./statement");
_dereq_("./expression"); _dereq_("./expression");
exports.LooseParser = _state.LooseParser; exports.LooseParser = _state.LooseParser;
exports.pluginsLoose = _state.pluginsLoose;
acorn.defaultOptions.tabSize = 4; acorn.defaultOptions.tabSize = 4;
@ -590,6 +593,7 @@ function parse_dammit(input, options) {
acorn.parse_dammit = parse_dammit; acorn.parse_dammit = parse_dammit;
acorn.LooseParser = _state.LooseParser; acorn.LooseParser = _state.LooseParser;
acorn.pluginsLoose = _state.pluginsLoose;
},{"..":"/src\\index.js","./expression":"/src\\loose\\expression.js","./state":"/src\\loose\\state.js","./statement":"/src\\loose\\statement.js","./tokenize":"/src\\loose\\tokenize.js"}],"/src\\loose\\parseutil.js":[function(_dereq_,module,exports){ },{"..":"/src\\index.js","./expression":"/src\\loose\\expression.js","./state":"/src\\loose\\state.js","./statement":"/src\\loose\\statement.js","./tokenize":"/src\\loose\\tokenize.js"}],"/src\\loose\\parseutil.js":[function(_dereq_,module,exports){
"use strict"; "use strict";
@ -610,9 +614,14 @@ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Cons
var _ = _dereq_(".."); var _ = _dereq_("..");
// Registered plugins
var pluginsLoose = {};
exports.pluginsLoose = pluginsLoose;
var LooseParser = (function () { var LooseParser = (function () {
function LooseParser(input, options) { function LooseParser(input, options) {
_classCallCheck(this, LooseParser);
this.toks = _.tokenizer(input, options); this.toks = _.tokenizer(input, options);
this.options = this.toks.options; this.options = this.toks.options;
@ -627,6 +636,9 @@ var LooseParser = (function () {
this.curIndent = 0; this.curIndent = 0;
this.curLineStart = 0; this.curLineStart = 0;
this.nextLineStart = this.lineEnd(this.curLineStart) + 1; this.nextLineStart = this.lineEnd(this.curLineStart) + 1;
// Load plugins
this.options.pluginsLoose = options.pluginsLoose || {};
this.loadPlugins(this.options.pluginsLoose);
} }
LooseParser.prototype.startNode = function startNode() { LooseParser.prototype.startNode = function startNode() {
@ -653,10 +665,26 @@ var LooseParser = (function () {
return node; return node;
}; };
LooseParser.prototype.dummyIdent = function dummyIdent() { LooseParser.prototype.dummyNode = function dummyNode(type) {
var dummy = this.startNode(); var dummy = this.startNode();
dummy.type = type;
dummy.end = dummy.start;
if (this.options.locations) dummy.loc.end = dummy.loc.start;
if (this.options.ranges) dummy.range[1] = dummy.start;
this.last = { type: _.tokTypes.name, start: dummy.start, end: dummy.start, loc: dummy.loc };
return dummy;
};
LooseParser.prototype.dummyIdent = function dummyIdent() {
var dummy = this.dummyNode("Identifier");
dummy.name = "✖"; dummy.name = "✖";
return this.finishNode(dummy, "Identifier"); return dummy;
};
LooseParser.prototype.dummyString = function dummyString() {
var dummy = this.dummyNode("Literal");
dummy.value = dummy.raw = "✖";
return dummy;
}; };
LooseParser.prototype.eat = function eat(type) { LooseParser.prototype.eat = function eat(type) {
@ -732,6 +760,18 @@ var LooseParser = (function () {
return true; return true;
}; };
LooseParser.prototype.extend = function extend(name, f) {
this[name] = f(this[name]);
};
LooseParser.prototype.loadPlugins = function loadPlugins(pluginConfigs) {
for (var _name in pluginConfigs) {
var plugin = pluginsLoose[_name];
if (!plugin) throw new Error("Plugin '" + _name + "' not found");
plugin(this, pluginConfigs[_name]);
}
};
return LooseParser; return LooseParser;
})(); })();
@ -870,7 +910,6 @@ lp.parseStatement = function () {
this.expect(_.tokTypes.parenL); this.expect(_.tokTypes.parenL);
clause.param = this.toAssignable(this.parseExprAtom(), true); clause.param = this.toAssignable(this.parseExprAtom(), true);
this.expect(_.tokTypes.parenR); this.expect(_.tokTypes.parenR);
clause.guard = null;
clause.body = this.parseBlock(); clause.body = this.parseBlock();
node.handler = this.finishNode(clause, "CatchClause"); node.handler = this.finishNode(clause, "CatchClause");
} }
@ -1104,7 +1143,7 @@ lp.parseImport = function () {
this.eat(_.tokTypes.comma); this.eat(_.tokTypes.comma);
} }
node.specifiers = this.parseImportSpecifierList(); node.specifiers = this.parseImportSpecifierList();
node.source = this.eatContextual("from") ? this.parseExprAtom() : null; node.source = this.eatContextual("from") && this.tok.type == _.tokTypes.string ? this.parseExprAtom() : this.dummyString();
if (elt) node.specifiers.unshift(elt); if (elt) node.specifiers.unshift(elt);
} }
this.semicolon(); this.semicolon();
@ -1128,7 +1167,7 @@ lp.parseImportSpecifierList = function () {
while (!this.closes(_.tokTypes.braceR, indent + (this.curLineStart <= continuedLine ? 1 : 0), line)) { while (!this.closes(_.tokTypes.braceR, indent + (this.curLineStart <= continuedLine ? 1 : 0), line)) {
var elt = this.startNode(); var elt = this.startNode();
if (this.eat(_.tokTypes.star)) { if (this.eat(_.tokTypes.star)) {
if (this.eatContextual("as")) elt.local = this.parseIdent(); elt.local = this.eatContextual("as") ? this.parseIdent() : this.dummyIdent();
this.finishNode(elt, "ImportNamespaceSpecifier"); this.finishNode(elt, "ImportNamespaceSpecifier");
} else { } else {
if (this.isContextual("from")) break; if (this.isContextual("from")) break;
@ -1276,5 +1315,4 @@ lp.lookAhead = function (n) {
},{"..":"/src\\index.js","./state":"/src\\loose\\state.js"}]},{},["/src\\loose\\index.js"])("/src\\loose\\index.js") },{"..":"/src\\index.js","./state":"/src\\loose\\state.js"}]},{},["/src\\loose\\index.js"])("/src\\loose\\index.js")
}); });
});
})

Wyświetl plik

@ -1,4 +1,5 @@
define(["require", "exports", "module", "./acorn"], function(require, exports, module) { define(["require", "exports", "module", "./acorn"], function(require, exports, module) {
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}(g.acorn || (g.acorn = {})).walk = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({"/src\\walk\\index.js":[function(_dereq_,module,exports){ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}(g.acorn || (g.acorn = {})).walk = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({"/src\\walk\\index.js":[function(_dereq_,module,exports){
// AST walker module for Mozilla Parser API compatible trees // AST walker module for Mozilla Parser API compatible trees
@ -79,7 +80,7 @@ function makeTest(test) {
} }
var Found = function Found(node, state) { var Found = function Found(node, state) {
_classCallCheck(this, Found);
this.node = node;this.state = state; this.node = node;this.state = state;
}; };
@ -95,7 +96,7 @@ function findNodeAt(node, start, end, test, base, state) {
;(function c(node, st, override) { ;(function c(node, st, override) {
var type = override || node.type; var type = override || node.type;
if ((start == null || node.start <= start) && (end == null || node.end >= end)) base[type](node, st, c); if ((start == null || node.start <= start) && (end == null || node.end >= end)) base[type](node, st, c);
if (test(type, node) && (start == null || node.start == start) && (end == null || node.end == end)) throw new Found(node, st); if ((start == null || node.start == start) && (end == null || node.end == end) && test(type, node)) throw new Found(node, st);
})(node, state); })(node, state);
} catch (e) { } catch (e) {
if (e instanceof Found) return e; if (e instanceof Found) return e;
@ -247,20 +248,28 @@ base.FunctionDeclaration = function (node, st, c) {
}; };
base.VariableDeclaration = function (node, st, c) { base.VariableDeclaration = function (node, st, c) {
for (var i = 0; i < node.declarations.length; ++i) { for (var i = 0; i < node.declarations.length; ++i) {
var decl = node.declarations[i]; c(node.declarations[i], st);
c(decl.id, st, "Pattern");
if (decl.init) c(decl.init, st, "Expression");
} }
}; };
base.VariableDeclarator = function (node, st, c) {
c(node.id, st, "Pattern");
if (node.init) c(node.init, st, "Expression");
};
base.Function = function (node, st, c) { base.Function = function (node, st, c) {
if (node.id) c(node.id, st, "Pattern");
for (var i = 0; i < node.params.length; i++) { for (var i = 0; i < node.params.length; i++) {
c(node.params[i], st, "Pattern"); c(node.params[i], st, "Pattern");
}c(node.body, st, "ScopeBody"); }c(node.body, st, node.expression ? "ScopeExpression" : "ScopeBody");
}; };
// FIXME drop these node types in next major version
// (They are awkward, and in ES6 every block can be a scope.)
base.ScopeBody = function (node, st, c) { base.ScopeBody = function (node, st, c) {
return c(node, st, "Statement"); return c(node, st, "Statement");
}; };
base.ScopeExpression = function (node, st, c) {
return c(node, st, "Expression");
};
base.Pattern = function (node, st, c) { base.Pattern = function (node, st, c) {
if (node.type == "Identifier") c(node, st, "VariablePattern");else if (node.type == "MemberExpression") c(node, st, "MemberPattern");else c(node, st); if (node.type == "Identifier") c(node, st, "VariablePattern");else if (node.type == "MemberExpression") c(node, st, "MemberPattern");else c(node, st);
@ -328,12 +337,16 @@ base.MemberExpression = function (node, st, c) {
if (node.computed) c(node.property, st, "Expression"); if (node.computed) c(node.property, st, "Expression");
}; };
base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) { base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) {
if (node.declaration) c(node.declaration, st); if (node.declaration) c(node.declaration, st, node.type == "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression");
if (node.source) c(node.source, st, "Expression");
};
base.ExportAllDeclaration = function (node, st, c) {
c(node.source, st, "Expression");
}; };
base.ImportDeclaration = function (node, st, c) { base.ImportDeclaration = function (node, st, c) {
for (var i = 0; i < node.specifiers.length; i++) { for (var i = 0; i < node.specifiers.length; i++) {
c(node.specifiers[i], st); c(node.specifiers[i], st);
} }c(node.source, st, "Expression");
}; };
base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.Literal = ignore; base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.Literal = ignore;

Wyświetl plik

@ -99,12 +99,15 @@ module.exports = {
assert.equal(parser.parse("if(").toString(), '[If(Var("✖"),Block([]),None())]'); assert.equal(parser.parse("if(").toString(), '[If(Var("✖"),Block([]),None())]');
// todo should this be broken if and a function outside? // todo should this be broken if and a function outside?
assert.equal(parser.parse("if(hello.\nfunction hello() { return 0; }").toString(), '[If(PropAccess(Var("hello"),"✖"),Function("hello",[],[Return(Num("0"))]),None())]'); assert.equal(parser.parse("if(hello.\nfunction hello() { return 0; }").toString(), '[If(PropAccess(Var("hello"),"✖"),Function("hello",[],[Return(Num("0"))]),None())]');
assert.equal(parser.parse("var\nfunction hello() {}").toString(), '[VarDecls([]),Function("hello",[],[])]'); // assert.equal(parser.parse("var\nfunction hello() {}").toString(), '[VarDecls([]),Function("hello",[],[])]');
}, },
"test parse literals": function() { "test parse literals": function() {
assert.equal(parser.parse("true").toString(), '[Var("true")]'); assert.equal(parser.parse("true").toString(), '[Var("true")]');
assert.equal(parser.parse("15").toString(), '[Num("15")]'); assert.equal(parser.parse("15").toString(), '[Num("15")]');
assert.equal(parser.parse("15.5").toString(), '[Num("15.5")]'); assert.equal(parser.parse("15.5").toString(), '[Num("15.5")]');
},
"test es7": function() {
assert.equal(parser.parse("async function a(x) {await y()}").toString(), '[Function("a",[FArg("x")],[Call(Var("y"),[])])]');
} }
}; };

6
node_modules/treehugger/package.json wygenerowano vendored
Wyświetl plik

@ -13,6 +13,10 @@
"url" : "http://github.com/ajaxorg/treehugger.git" "url" : "http://github.com/ajaxorg/treehugger.git"
}, },
"engines" : { "engines" : {
"node" : ">= 0.4.0" "node" : ">= 0.4.0"
},
"scripts": {
"test": "node lib/treehugger/js/parse_test.js",
"acorn": "node ../acorn/bin/build-acorn.js ; mv ../acorn/dist/* lib/acorn/dist"
} }
} }

Wyświetl plik

@ -55,14 +55,14 @@
"c9" "c9"
], ],
"c9plugins": { "c9plugins": {
"c9.ide.language": "#4bdcd49293", "c9.ide.language": "#af265e3604",
"c9.ide.language.css": "#be07d72209", "c9.ide.language.css": "#be07d72209",
"c9.ide.language.generic": "#2b5cc6275e", "c9.ide.language.generic": "#2b5cc6275e",
"c9.ide.language.html": "#9be847c0ce", "c9.ide.language.html": "#9be847c0ce",
"c9.ide.language.html.diff": "#24f3608d26", "c9.ide.language.html.diff": "#24f3608d26",
"c9.ide.language.javascript": "#1a0b1584c2", "c9.ide.language.javascript": "#1a0b1584c2",
"c9.ide.language.javascript.immediate": "#c8b1e5767a", "c9.ide.language.javascript.immediate": "#c8b1e5767a",
"c9.ide.language.javascript.eslint": "#586becb51d", "c9.ide.language.javascript.eslint": "#a234af16c0",
"c9.ide.language.javascript.tern": "#f9ba3813d7", "c9.ide.language.javascript.tern": "#f9ba3813d7",
"c9.ide.language.javascript.infer": "#9cf94f77be", "c9.ide.language.javascript.infer": "#9cf94f77be",
"c9.ide.language.jsonalyzer": "#f0bb823c6f", "c9.ide.language.jsonalyzer": "#f0bb823c6f",