From cc4ffc762ec970376d8fb97afa974324794e1358 Mon Sep 17 00:00:00 2001 From: Jeff Williams Date: Thu, 26 Feb 2015 14:59:05 -0800 Subject: [PATCH] update Espree and LICENSE file --- LICENSE.md | 8 +- lib/jsdoc/src/astbuilder.js | 59 +- node_modules/espree/espree.js | 756 +++++++++++++++----- node_modules/espree/lib/ast-node-factory.js | 36 + node_modules/espree/lib/ast-node-types.js | 4 + node_modules/espree/lib/features.js | 20 +- node_modules/espree/lib/messages.js | 8 + node_modules/espree/lib/string-map.js | 55 ++ node_modules/espree/package.json | 12 +- package.json | 2 +- test/specs/jsdoc/src/astbuilder.js | 2 +- 11 files changed, 731 insertions(+), 231 deletions(-) create mode 100644 node_modules/espree/lib/string-map.js diff --git a/LICENSE.md b/LICENSE.md index ace29362..57b6a91d 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -116,9 +116,9 @@ Copyright (c) Sindre Sorhus . The source code for escape-string-regexp is available at: https://github.com/sindresorhus/escape-string-regexp -## Esprima ## +## Espree ## -Esprima is distributed under the BSD 2-clause license: +Espree is distributed under the BSD 2-clause license: > Redistribution and use in source and binary forms, with or without > modification, are permitted provided that the following conditions are met: @@ -140,10 +140,10 @@ Esprima is distributed under the BSD 2-clause license: > (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF > THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -Copyright (c) 2011-2013 Ariya Hidayat and other Esprima contributors. +Copyright (c) 2011-2015 by the Espree contributors. The source code for Esprima is available at: -https://github.com/ariya/esprima +https://github.com/eslint/espree ## events ## diff --git a/lib/jsdoc/src/astbuilder.js b/lib/jsdoc/src/astbuilder.js index fc65b84c..e8fb9232 100644 --- a/lib/jsdoc/src/astbuilder.js +++ b/lib/jsdoc/src/astbuilder.js @@ -53,6 +53,35 @@ var acceptsLeadingComments = (function() { return accepts; })(); +var espreeOpts = { + comment: true, + loc: true, + range: true, + tokens: true, + ecmaFeatures: { + arrowFunctions: true, + binaryLiterals: true, + blockBindings: true, + defaultParams: true, + destructuring: true, + forOf: true, + generators: true, + globalReturn: true, + jsx: false, + objectLiteralComputedProperties: true, + objectLiteralDuplicateProperties: true, + objectLiteralShorthandMethods: true, + objectLiteralShorthandProperties: true, + octalLiterals: true, + regexUFlag: true, + regexYFlag: true, + restParams: true, + spread: true, + superInFunctions: true, + templateStrings: true, + unicodeCodePointEscapes: true + } +}; // TODO: docs function canAcceptComment(node) { @@ -119,7 +148,7 @@ function scrubComments(comments) { // TODO: docs var AstBuilder = exports.AstBuilder = function() {}; -function parse(source, filename, espreeOpts) { +function parse(source, filename) { var ast; try { @@ -134,33 +163,7 @@ function parse(source, filename, espreeOpts) { // TODO: docs AstBuilder.prototype.build = function(source, filename) { - var ast; - - var espreeOpts = { - comment: true, - loc: true, - range: true, - tokens: true, - ecmaFeatures: { - binaryLiterals: true, - blockBindings: true, - defaultParams: true, - forOf: true, - generators: true, - jsx: false, - objectLiteralComputedProperties: true, - objectLiteralDuplicateProperties: true, - objectLiteralShorthandMethods: true, - objectLiteralShorthandProperties: true, - octalLiterals: true, - regexUFlag: true, - regexYFlag: true, - templateStrings: true, - unicodeCodePointEscapes: true - } - }; - - ast = parse(source, filename, espreeOpts); + var ast = parse(source, filename); if (ast) { this._postProcess(filename, ast); diff --git a/node_modules/espree/espree.js b/node_modules/espree/espree.js index cc2754a5..c5b08649 100644 --- a/node_modules/espree/espree.js +++ b/node_modules/espree/espree.js @@ -41,7 +41,8 @@ var syntax = require("./lib/syntax"), astNodeFactory = require("./lib/ast-node-factory"), defaultFeatures = require("./lib/features"), Messages = require("./lib/messages"), - XHTMLEntities = require("./lib/xhtml-entities"); + XHTMLEntities = require("./lib/xhtml-entities"), + StringMap = require("./lib/string-map"); var Token = tokenInfo.Token, TokenName = tokenInfo.TokenName, @@ -551,8 +552,11 @@ function scanPunctuator() { }; } - // The ... operator only valid in JSX mode for now - if (extra.ecmaFeatures.jsx && state.inJSXSpreadAttribute) { + // The ... operator (spread, restParams, JSX, etc.) + if (extra.ecmaFeatures.spread || + extra.ecmaFeatures.restParams || + (extra.ecmaFeatures.jsx && state.inJSXSpreadAttribute) + ) { if (ch1 === "." && ch2 === "." && ch3 === ".") { index += 3; return { @@ -936,8 +940,10 @@ function scanStringLiteral() { } /** - * Scan a template string and return an ASTNode representation - * @returns {ASTNode} The template string literal + * Scan a template string and return a token. This scans both the first and + * subsequent pieces of a template string and assumes that the first backtick + * or the closing } have already been scanned. + * @returns {Token} The template string token. * @private */ function scanTemplate() { @@ -947,7 +953,8 @@ function scanTemplate() { octal = false, start = index, terminated = false, - tail = false; + tail = false, + head = (source[index] === "`"); ++index; @@ -992,6 +999,7 @@ function scanTemplate() { cooked: cooked, raw: source.slice(start + 1, index - ((tail) ? 1 : 2)) }, + head: head, tail: tail, octal: octal, lineNumber: lineNumber, @@ -1022,6 +1030,10 @@ function scanTemplateElement(options) { template = scanTemplate(); + if (!template.tail) { + extra.curlies.push("template"); + } + peek(); return template; @@ -1368,17 +1380,21 @@ function advance() { return scanJSXIdentifier(); } - // Template strings start with backtick (U+0096). - if (allowTemplateStrings && ch === 96) { - return scanTemplate(); + // Template strings start with backtick (U+0096) or closing curly brace (125) and backtick. + if (allowTemplateStrings) { + + // template strings start with backtick (96) or open curly (125) but only if the open + // curly closes a previously opened curly from a template. + if (ch === 96 || (ch === 125 && extra.curlies[extra.curlies.length - 1] === "template")) { + extra.curlies.pop(); + return scanTemplate(); + } } if (syntax.isIdentifierStart(ch)) { return scanIdentifier(); } - - // Dot (.) U+002E can also start a floating-point number, hence the need // to check the next character. if (ch === 0x2E) { @@ -1457,16 +1473,36 @@ function lex() { lineNumber = token.lineNumber; lineStart = token.lineStart; + if (token.type === Token.Template) { + if (token.tail) { + extra.curlies.pop(); + } else { + extra.curlies.push("template"); + } + } + + if (token.value === "{") { + extra.curlies.push("{"); + } + + if (token.value === "}") { + extra.curlies.pop(); + } + return token; } function peek() { - var pos, line, start; + var pos, + line, + start; pos = index; line = lineNumber; start = lineStart; + lookahead = (typeof extra.tokens !== "undefined") ? collectToken() : advance(); + index = pos; lineNumber = line; lineStart = start; @@ -2305,24 +2341,29 @@ function isLeftHandSide(expr) { function parseArrayInitialiser() { var elements = [], - marker = markerCreate(); + marker = markerCreate(), + tmp; expect("["); while (!match("]")) { if (match(",")) { - lex(); + lex(); // only get here when you have [a,,] or similar elements.push(null); } else { - elements.push(parseAssignmentExpression()); - - if (!match("]")) { - expect(","); + tmp = parseSpreadOrAssignmentExpression(); + elements.push(tmp); + if (tmp && tmp.type === astNodeTypes.SpreadElement) { + if (!match("]")) { + throwError({}, Messages.ElementAfterSpreadElement); + } + } else if (!(match("]"))) { + expect(","); // handles the common case of comma-separated values } } } - lex(); + expect("]"); return markerApply(marker, astNodeFactory.createArrayExpression(elements)); } @@ -2334,8 +2375,7 @@ function parsePropertyFunction(options) { previousYieldAllowed = state.yieldAllowed, params = options.params || [], defaults = options.defaults || [], - body, - marker = markerCreate(); + body; state.yieldAllowed = options.generator; @@ -2352,7 +2392,7 @@ function parsePropertyFunction(options) { strict = previousStrict; state.yieldAllowed = previousYieldAllowed; - return markerApply(marker, astNodeFactory.createFunctionExpression( + return markerApply(options.marker, astNodeFactory.createFunctionExpression( null, params, defaults, @@ -2365,6 +2405,7 @@ function parsePropertyFunction(options) { function parsePropertyMethodFunction(options) { var previousStrict = strict, + marker = markerCreate(), tmp, method; @@ -2380,7 +2421,8 @@ function parsePropertyMethodFunction(options) { params: tmp.params, defaults: tmp.defaults, rest: tmp.rest, - generator: options ? options.generator : false + generator: options ? options.generator : false, + marker: marker }); strict = previousStrict; @@ -2420,11 +2462,12 @@ function parseObjectPropertyKey() { } function parseObjectProperty() { - var token, key, id, param, computed; + var token, key, id, param, computed, methodMarker; var allowComputed = extra.ecmaFeatures.objectLiteralComputedProperties, allowMethod = extra.ecmaFeatures.objectLiteralShorthandMethods, allowShorthand = extra.ecmaFeatures.objectLiteralShorthandProperties, allowGenerators = extra.ecmaFeatures.generators, + allowDestructuring = extra.ecmaFeatures.destructuring, marker = markerCreate(); token = lookahead; @@ -2438,9 +2481,10 @@ function parseObjectProperty() { * Check for getters and setters. Be careful! "get" and "set" are legal * method names. It's only a getter or setter if followed by a space. */ - if (token.value === "get" && !match(":") && !match("(")) { + if (token.value === "get" && !(match(":") || match("("))) { computed = (lookahead.value === "["); key = parseObjectPropertyKey(); + methodMarker = markerCreate(); expect("("); expect(")"); return markerApply( @@ -2448,7 +2492,10 @@ function parseObjectProperty() { astNodeFactory.createProperty( "get", key, - parsePropertyFunction({ generator: false }), + parsePropertyFunction({ + generator: false, + marker: methodMarker + }), false, false, computed @@ -2456,9 +2503,10 @@ function parseObjectProperty() { ); } - if (token.value === "set" && !match(":") && !match("(")) { + if (token.value === "set" && !(match(":") || match("("))) { computed = (lookahead.value === "["); key = parseObjectPropertyKey(); + methodMarker = markerCreate(); expect("("); token = lookahead; param = [ parseVariableIdentifier() ]; @@ -2471,7 +2519,8 @@ function parseObjectProperty() { parsePropertyFunction({ params: param, generator: false, - name: token + name: token, + marker: methodMarker }), false, false, @@ -2515,9 +2564,9 @@ function parseObjectProperty() { * Only other possibility is that this is a shorthand property. Computed * properties cannot use shorthand notation, so that's a syntax error. * If shorthand properties aren't allow, then this is an automatic - * syntax error. + * syntax error. Destructuring is another case with a similar shorthand syntax. */ - if (computed || !allowShorthand) { + if (computed || (!allowShorthand && !allowDestructuring)) { throwUnexpected(lookahead); } @@ -2562,49 +2611,56 @@ function parseObjectProperty() { ) ); - } else { - - /* - * If we've made it here, then that means the property name is represented - * by a string (i.e, { "foo": 2}). The only options here are normal - * property with a colon or a method. - */ - key = parseObjectPropertyKey(); - - // check for property value - if (match(":")) { - lex(); - return markerApply( - marker, - astNodeFactory.createProperty( - "init", - key, - parseAssignmentExpression(), - false, - false, - false - ) - ); - } - - // check for method - if (allowMethod && match("(")) { - return markerApply( - marker, - astNodeFactory.createProperty( - "init", - key, - parsePropertyMethodFunction(), - true, - false, - false - ) - ); - } - - // no other options, this is bad - throwUnexpected(lex()); } + + /* + * If we've made it here, then that means the property name is represented + * by a string (i.e, { "foo": 2}). The only options here are normal + * property with a colon or a method. + */ + key = parseObjectPropertyKey(); + + // check for property value + if (match(":")) { + lex(); + return markerApply( + marker, + astNodeFactory.createProperty( + "init", + key, + parseAssignmentExpression(), + false, + false, + false + ) + ); + } + + // check for method + if (allowMethod && match("(")) { + return markerApply( + marker, + astNodeFactory.createProperty( + "init", + key, + parsePropertyMethodFunction(), + true, + false, + false + ) + ); + } + + // no other options, this is bad + throwUnexpected(lex()); +} + +function getFieldName(key) { + var toString = String; + if (key.type === astNodeTypes.Identifier) { + return key.name; + } + return toString(key.value); } function parseObjectInitialiser() { @@ -2613,39 +2669,30 @@ function parseObjectInitialiser() { properties = [], property, name, - key, + propertyFn, kind, - kindMap = {}, - toString = String; + storedKind, + kindMap = new StringMap(); expect("{"); while (!match("}")) { + property = parseObjectProperty(); if (!property.computed) { - if (property.key.type === astNodeTypes.Identifier) { - name = property.key.name; - } else { - name = toString(property.key.value); - } + name = getFieldName(property.key); + propertyFn = (property.kind === "get") ? PropertyKind.Get : PropertyKind.Set; + kind = (property.kind === "init") ? PropertyKind.Data : propertyFn; - if (property.kind === "init") { - kind = PropertyKind.Data; - } else if (property.kind === "get") { - kind = PropertyKind.Get; - } else { - kind = PropertyKind.Set; - } - - key = "$" + name; - if (Object.prototype.hasOwnProperty.call(kindMap, key)) { - if (kindMap[key] === PropertyKind.Data) { + if (kindMap.has(name)) { + storedKind = kindMap.get(name); + if (storedKind === PropertyKind.Data) { if (kind === PropertyKind.Data && name === "__proto__" && allowDuplicates) { // Duplicate '__proto__' literal properties are forbidden in ES 6 throwErrorTolerant({}, Messages.DuplicatePrototypeProperty); - } else if (kind === PropertyKind.Data && strict && !allowDuplicates) { + } else if (strict && kind === PropertyKind.Data && !allowDuplicates) { // Duplicate literal properties are only forbidden in ES 5 strict mode throwErrorTolerant({}, Messages.StrictDuplicateProperty); } else if (kind !== PropertyKind.Data) { @@ -2654,13 +2701,13 @@ function parseObjectInitialiser() { } else { if (kind === PropertyKind.Data) { throwErrorTolerant({}, Messages.AccessorDataProperty); - } else if (kindMap[key] & kind) { + } else if (storedKind & kind) { throwErrorTolerant({}, Messages.AccessorGetSet); } } - kindMap[key] |= kind; + kindMap.set(name, storedKind | kind); } else { - kindMap[key] = kind; + kindMap.set(name, kind); } } @@ -2721,6 +2768,8 @@ function parseGroupExpression() { expect("("); + ++state.parenthesisCount; + expr = parseExpression(); expect(")"); @@ -2734,7 +2783,8 @@ function parseGroupExpression() { function parsePrimaryExpression() { var type, token, expr, marker, - allowJSX = extra.ecmaFeatures.jsx; + allowJSX = extra.ecmaFeatures.jsx, + allowSuper = extra.ecmaFeatures.superInFunctions; if (match("(")) { return parseGroupExpression(); @@ -2766,6 +2816,13 @@ function parsePrimaryExpression() { if (matchKeyword("function")) { return parseFunctionExpression(); } + + if (allowSuper && matchKeyword("super") && state.inFunctionBody) { + marker = markerCreate(); + lex(); + return markerApply(marker, astNodeFactory.createIdentifier("super")); + } + if (matchKeyword("this")) { lex(); expr = astNodeFactory.createThisExpression(); @@ -2790,7 +2847,7 @@ function parsePrimaryExpression() { } else if (type === Token.Template) { return parseTemplateLiteral(); } else { - throwUnexpected(lex()); + throwUnexpected(lex()); } return markerApply(marker, expr); @@ -2799,16 +2856,21 @@ function parsePrimaryExpression() { // 11.2 Left-Hand-Side Expressions function parseArguments() { - var args = []; + var args = [], arg; expect("("); if (!match(")")) { while (index < length) { - args.push(parseAssignmentExpression()); + arg = parseSpreadOrAssignmentExpression(); + args.push(arg); + if (match(")")) { break; + } else if (arg.type === astNodeTypes.SpreadElement) { + throwError({}, Messages.ElementAfterSpreadElement); } + expect(","); } } @@ -2818,6 +2880,15 @@ function parseArguments() { return args; } +function parseSpreadOrAssignmentExpression() { + if (match("...")) { + var marker = markerCreate(); + lex(); + return markerApply(marker, astNodeFactory.createSpreadElement(parseAssignmentExpression())); + } + return parseAssignmentExpression(); +} + function parseNonComputedProperty() { var token, marker = markerCreate(); @@ -2869,7 +2940,8 @@ function parseLeftHandSideExpressionAllowCall() { expr = matchKeyword("new") ? parseNewExpression() : parsePrimaryExpression(); state.allowIn = previousAllowIn; - while (match(".") || match("[") || match("(") || lookahead.type === Token.Template) { + // only start parsing template literal if the lookahead is a head (beginning with `) + while (match(".") || match("[") || match("(") || (lookahead.type === Token.Template && lookahead.head)) { if (match("(")) { args = parseArguments(); expr = markerApply(marker, astNodeFactory.createCallExpression(expr, args)); @@ -2877,7 +2949,7 @@ function parseLeftHandSideExpressionAllowCall() { expr = markerApply(marker, astNodeFactory.createMemberExpression("[", expr, parseComputedMember())); } else if (match(".")) { expr = markerApply(marker, astNodeFactory.createMemberExpression(".", expr, parseNonComputedMember())); - } else { + } else if (!lookahead.tail) { expr = markerApply(marker, astNodeFactory.createTaggedTemplateExpression(expr, parseTemplateLiteral())); } } @@ -2893,7 +2965,8 @@ function parseLeftHandSideExpression() { expr = matchKeyword("new") ? parseNewExpression() : parsePrimaryExpression(); state.allowIn = previousAllowIn; - while (match(".") || match("[") || lookahead.type === Token.Template) { + // only start parsing template literal if the lookahead is a head (beginning with `) + while (match(".") || match("[") || (lookahead.type === Token.Template && lookahead.head)) { if (match("[")) { expr = markerApply(marker, astNodeFactory.createMemberExpression("[", expr, parseComputedMember())); } else if (match(".")) { @@ -3144,11 +3217,192 @@ function parseConditionalExpression() { return expr; } +// [ES6] 14.2 Arrow Function + +function parseConciseBody() { + if (match("{")) { + return parseFunctionSourceElements(); + } + return parseAssignmentExpression(); +} + +function reinterpretAsCoverFormalsList(expressions) { + var i, len, param, params, defaults, defaultCount, options, rest; + + params = []; + defaults = []; + defaultCount = 0; + rest = null; + options = { + paramSet: new StringMap() + }; + + for (i = 0, len = expressions.length; i < len; i += 1) { + param = expressions[i]; + if (param.type === astNodeTypes.Identifier) { + params.push(param); + defaults.push(null); + validateParam(options, param, param.name); + } else if (param.type === astNodeTypes.ObjectExpression || param.type === astNodeTypes.ArrayExpression) { + reinterpretAsDestructuredParameter(options, param); + params.push(param); + defaults.push(null); + } else if (param.type === astNodeTypes.SpreadElement) { + assert(i === len - 1, "It is guaranteed that SpreadElement is last element by parseExpression"); + if (param.argument.type !== astNodeTypes.Identifier) { + throwError({}, Messages.InvalidLHSInFormalsList); + } + reinterpretAsDestructuredParameter(options, param.argument); + rest = param.argument; + } else if (param.type === astNodeTypes.AssignmentExpression) { + params.push(param.left); + defaults.push(param.right); + ++defaultCount; + validateParam(options, param.left, param.left.name); + } else { + return null; + } + } + + if (options.message === Messages.StrictParamDupe) { + throwError( + strict ? options.stricted : options.firstRestricted, + options.message + ); + } + + // must be here so it's not an array of [null, null] + if (defaultCount === 0) { + defaults = []; + } + + return { + params: params, + defaults: defaults, + rest: rest, + stricted: options.stricted, + firstRestricted: options.firstRestricted, + message: options.message + }; +} + +function parseArrowFunctionExpression(options, marker) { + var previousStrict, body; + + expect("=>"); + previousStrict = strict; + + body = parseConciseBody(); + + if (strict && options.firstRestricted) { + throwError(options.firstRestricted, options.message); + } + if (strict && options.stricted) { + throwErrorTolerant(options.stricted, options.message); + } + + strict = previousStrict; + return markerApply(marker, astNodeFactory.createArrowFunctionExpression( + options.params, + options.defaults, + body, + options.rest, + body.type !== astNodeTypes.BlockStatement + )); +} + // 11.13 Assignment Operators +// 12.14.5 AssignmentPattern + +function reinterpretAsAssignmentBindingPattern(expr) { + var i, len, property, element, + allowDestructuring = extra.ecmaFeatures.destructuring; + + if (!allowDestructuring) { + throwUnexpected(lex()); + } + + if (expr.type === astNodeTypes.ObjectExpression) { + expr.type = astNodeTypes.ObjectPattern; + for (i = 0, len = expr.properties.length; i < len; i += 1) { + property = expr.properties[i]; + if (property.kind !== "init") { + throwErrorTolerant({}, Messages.InvalidLHSInAssignment); + } + reinterpretAsAssignmentBindingPattern(property.value); + } + } else if (expr.type === astNodeTypes.ArrayExpression) { + expr.type = astNodeTypes.ArrayPattern; + for (i = 0, len = expr.elements.length; i < len; i += 1) { + element = expr.elements[i]; + /* istanbul ignore else */ + if (element) { + reinterpretAsAssignmentBindingPattern(element); + } + } + } else if (expr.type === astNodeTypes.Identifier) { + if (syntax.isRestrictedWord(expr.name)) { + throwErrorTolerant({}, Messages.InvalidLHSInAssignment); + } + } else if (expr.type === astNodeTypes.SpreadElement) { + reinterpretAsAssignmentBindingPattern(expr.argument); + if (expr.argument.type === astNodeTypes.ObjectPattern) { + throwErrorTolerant({}, Messages.ObjectPatternAsSpread); + } + } else { + /* istanbul ignore else */ + if (expr.type !== astNodeTypes.MemberExpression && expr.type !== astNodeTypes.CallExpression && expr.type !== astNodeTypes.NewExpression) { + throwErrorTolerant({}, Messages.InvalidLHSInAssignment); + } + } +} + +// 13.2.3 BindingPattern + +function reinterpretAsDestructuredParameter(options, expr) { + var i, len, property, element, + allowDestructuring = extra.ecmaFeatures.destructuring; + + if (!allowDestructuring) { + throwUnexpected(lex()); + } + + if (expr.type === astNodeTypes.ObjectExpression) { + expr.type = astNodeTypes.ObjectPattern; + for (i = 0, len = expr.properties.length; i < len; i += 1) { + property = expr.properties[i]; + if (property.kind !== "init") { + throwErrorTolerant({}, Messages.InvalidLHSInFormalsList); + } + reinterpretAsDestructuredParameter(options, property.value); + } + } else if (expr.type === astNodeTypes.ArrayExpression) { + expr.type = astNodeTypes.ArrayPattern; + for (i = 0, len = expr.elements.length; i < len; i += 1) { + element = expr.elements[i]; + if (element) { + reinterpretAsDestructuredParameter(options, element); + } + } + } else if (expr.type === astNodeTypes.Identifier) { + validateParam(options, expr, expr.name); + } else if (expr.type === astNodeTypes.SpreadElement) { + // BindingRestElement only allows BindingIdentifier + if (expr.argument.type !== astNodeTypes.Identifier) { + throwErrorTolerant({}, Messages.InvalidLHSInFormalsList); + } + validateParam(options, expr.argument, expr.argument.name); + } else { + throwError({}, Messages.InvalidLHSInFormalsList); + } +} + function parseAssignmentExpression() { - var token, left, right, node, + var token, left, right, node, params, marker, + startsWithParen = false, + oldParenthesisCount = state.parenthesisCount, allowGenerators = extra.ecmaFeatures.generators; // Note that 'yield' is treated as a keyword in strict mode, but a @@ -3159,21 +3413,59 @@ function parseAssignmentExpression() { } marker = markerCreate(); - token = lookahead; + if (match("(")) { + token = lookahead2(); + if ((token.value === ")" && token.type === Token.Punctuator) || token.value === "...") { + params = parseParams(); + if (!match("=>")) { + throwUnexpected(lex()); + } + return parseArrowFunctionExpression(params, marker); + } + startsWithParen = true; + } + + // revert to the previous lookahead style object + token = lookahead; node = left = parseConditionalExpression(); - if (matchAssign()) { - // LeftHandSideExpression - if (!isLeftHandSide(left)) { - throwErrorTolerant({}, Messages.InvalidLHSInAssignment); + if (match("=>") && + (state.parenthesisCount === oldParenthesisCount || + state.parenthesisCount === (oldParenthesisCount + 1))) { + + if (node.type === astNodeTypes.Identifier) { + params = reinterpretAsCoverFormalsList([ node ]); + } else if (node.type === astNodeTypes.AssignmentExpression || + node.type === astNodeTypes.ArrayExpression || + node.type === astNodeTypes.ObjectExpression) { + if (!startsWithParen) { + throwUnexpected(lex()); + } + params = reinterpretAsCoverFormalsList([ node ]); + } else if (node.type === astNodeTypes.SequenceExpression) { + params = reinterpretAsCoverFormalsList(node.expressions); } + if (params) { + return parseArrowFunctionExpression(params, marker); + } + } + + if (matchAssign()) { + // 11.13.1 if (strict && left.type === astNodeTypes.Identifier && syntax.isRestrictedWord(left.name)) { throwErrorTolerant(token, Messages.StrictLHSAssignment); } + // ES.next draf 11.13 Runtime Semantics step 1 + if (match("=") && (node.type === astNodeTypes.ObjectExpression || node.type === astNodeTypes.ArrayExpression)) { + reinterpretAsAssignmentBindingPattern(node); + } else if (!isLeftHandSide(node)) { + throwErrorTolerant({}, Messages.InvalidLHSInAssignment); + } + token = lex(); right = parseAssignmentExpression(); node = markerApply(marker, astNodeFactory.createAssignmentExpression(token.value, left, right)); @@ -3185,26 +3477,37 @@ function parseAssignmentExpression() { // 11.14 Comma Operator function parseExpression() { - var expr, - marker = markerCreate(); - - expr = parseAssignmentExpression(); + var marker = markerCreate(), + expr = parseAssignmentExpression(), + expressions = [ expr ], + sequence, spreadFound; if (match(",")) { - expr = astNodeFactory.createSequenceExpression([ expr ]); - while (index < length) { if (!match(",")) { break; } lex(); - expr.expressions.push(parseAssignmentExpression()); + expr = parseSpreadOrAssignmentExpression(); + expressions.push(expr); + + if (expr.type === astNodeTypes.SpreadElement) { + spreadFound = true; + if (!match(")")) { + throwError({}, Messages.ElementAfterSpreadElement); + } + break; + } } - markerApply(marker, expr); + sequence = markerApply(marker, astNodeFactory.createSequenceExpression(expressions)); } - return expr; + if (spreadFound && lookahead2().value !== "=>") { + throwError({}, Messages.IllegalSpread); + } + + return sequence || expr; } // 12.1 Block @@ -3256,18 +3559,29 @@ function parseVariableIdentifier() { } function parseVariableDeclaration(kind) { - var init = null, id, - marker = markerCreate(); - - id = parseVariableIdentifier(); - - // 12.2.1 - if (strict && syntax.isRestrictedWord(id.name)) { - throwErrorTolerant({}, Messages.StrictVarName); + var id, + marker = markerCreate(), + init = null; + if (match("{")) { + id = parseObjectInitialiser(); + reinterpretAsAssignmentBindingPattern(id); + } else if (match("[")) { + id = parseArrayInitialiser(); + reinterpretAsAssignmentBindingPattern(id); + } else { + /* istanbul ignore next */ + id = state.allowKeyword ? parseNonComputedProperty() : parseVariableIdentifier(); + // 12.2.1 + if (strict && syntax.isRestrictedWord(id.name)) { + throwErrorTolerant({}, Messages.StrictVarName); + } } // TODO: Verify against feature flags if (kind === "const") { + if (!match("=")) { + throwError({}, Messages.NoUnintializedConst); + } expect("="); init = parseAssignmentExpression(); } else if (match("=")) { @@ -3522,7 +3836,7 @@ function parseForStatement(opts) { // 12.7 The continue statement function parseContinueStatement() { - var label = null, key; + var label = null; expectKeyword("continue"); @@ -3548,8 +3862,7 @@ function parseContinueStatement() { if (lookahead.type === Token.Identifier) { label = parseVariableIdentifier(); - key = "$" + label.name; - if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) { + if (!state.labelSet.has(label.name)) { throwError({}, Messages.UnknownLabel, label.name); } } @@ -3566,7 +3879,7 @@ function parseContinueStatement() { // 12.8 The break statement function parseBreakStatement() { - var label = null, key; + var label = null; expectKeyword("break"); @@ -3592,8 +3905,7 @@ function parseBreakStatement() { if (lookahead.type === Token.Identifier) { label = parseVariableIdentifier(); - key = "$" + label.name; - if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) { + if (!state.labelSet.has(label.name)) { throwError({}, Messages.UnknownLabel, label.name); } } @@ -3614,7 +3926,7 @@ function parseReturnStatement() { expectKeyword("return"); - if (!state.inFunctionBody) { + if (!state.inFunctionBody && !extra.ecmaFeatures.globalReturn) { throwErrorTolerant({}, Messages.IllegalReturn); } @@ -3685,7 +3997,7 @@ function parseSwitchCase() { if (match("}") || matchKeyword("default") || matchKeyword("case")) { break; } - statement = parseStatement(); + statement = parseSourceElement(); consequent.push(statement); } @@ -3818,7 +4130,6 @@ function parseStatement() { var type = lookahead.type, expr, labeledBody, - key, marker; if (type === Token.EOF) { @@ -3835,6 +4146,8 @@ function parseStatement() { switch (lookahead.value) { case ";": return markerApply(marker, parseEmptyStatement()); + case "{": + return parseBlock(); case "(": return markerApply(marker, parseExpressionStatement()); default: @@ -3886,14 +4199,13 @@ function parseStatement() { if ((expr.type === astNodeTypes.Identifier) && match(":")) { lex(); - key = "$" + expr.name; - if (Object.prototype.hasOwnProperty.call(state.labelSet, key)) { + if (state.labelSet.has(expr.name)) { throwError({}, Messages.Redeclaration, "Label", expr.name); } - state.labelSet[key] = true; + state.labelSet.set(expr.name, true); labeledBody = parseStatement(); - delete state.labelSet[key]; + state.labelSet.delete(expr.name); return markerApply(marker, astNodeFactory.createLabeledStatement(expr, labeledBody)); } @@ -3913,7 +4225,7 @@ function parseStatement() { function parseFunctionSourceElements() { var sourceElement, sourceElements = [], token, directive, firstRestricted, - oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, + oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, oldParenthesisCount, marker = markerCreate(); expect("{"); @@ -3947,8 +4259,9 @@ function parseFunctionSourceElements() { oldInIteration = state.inIteration; oldInSwitch = state.inSwitch; oldInFunctionBody = state.inFunctionBody; + oldParenthesisCount = state.parenthesizedCount; - state.labelSet = {}; + state.labelSet = new StringMap(); state.inIteration = false; state.inSwitch = false; state.inFunctionBody = true; @@ -3974,55 +4287,115 @@ function parseFunctionSourceElements() { state.inIteration = oldInIteration; state.inSwitch = oldInSwitch; state.inFunctionBody = oldInFunctionBody; + state.parenthesizedCount = oldParenthesisCount; return markerApply(marker, astNodeFactory.createBlockStatement(sourceElements)); } -function parseParams(firstRestricted) { - var param, params = [], defaults = [], defaultCount = 0, token, stricted, paramSet, key, message, def, +function validateParam(options, param, name) { + if (strict) { + if (syntax.isRestrictedWord(name)) { + options.stricted = param; + options.message = Messages.StrictParamName; + } + if (options.paramSet.has(name)) { + options.stricted = param; + options.message = Messages.StrictParamDupe; + } + } else if (!options.firstRestricted) { + if (syntax.isRestrictedWord(name)) { + options.firstRestricted = param; + options.message = Messages.StrictParamName; + } else if (syntax.isStrictModeReservedWord(name)) { + options.firstRestricted = param; + options.message = Messages.StrictReservedWord; + } else if (options.paramSet.has(name)) { + options.firstRestricted = param; + options.message = Messages.StrictParamDupe; + } + } + options.paramSet.set(name, true); +} + +function parseParam(options) { + var token, rest, param, def, + allowRestParams = extra.ecmaFeatures.restParams, + allowDestructuring = extra.ecmaFeatures.destructuring, allowDefaultParams = extra.ecmaFeatures.defaultParams; + + token = lookahead; + if (token.value === "...") { + if (!allowRestParams) { + throwUnexpected(lookahead); + } + token = lex(); + rest = true; + } + + if (match("[")) { + if (!allowDestructuring) { + throwUnexpected(lookahead); + } + param = parseArrayInitialiser(); + reinterpretAsDestructuredParameter(options, param); + } else if (match("{")) { + if (rest) { + throwError({}, Messages.ObjectPatternAsRestParameter); + } + if (!allowDestructuring) { + throwUnexpected(lookahead); + } + param = parseObjectInitialiser(); + reinterpretAsDestructuredParameter(options, param); + } else { + param = parseVariableIdentifier(); + validateParam(options, token, token.value); + } + + if (match("=")) { + if (rest) { + throwErrorTolerant(lookahead, Messages.DefaultRestParameter); + } + if (!allowDefaultParams) { + throwUnexpected(lookahead); + } + lex(); + def = parseAssignmentExpression(); + ++options.defaultCount; + } + + if (rest) { + if (!match(")")) { + throwError({}, Messages.ParameterAfterRestParameter); + } + options.rest = param; + return false; + } + + options.params.push(param); + options.defaults.push(def ? def : null); // TODO: determine if null or undefined (see: #55) + + return !match(")"); +} + + +function parseParams(firstRestricted) { + var options, marker = markerCreate(); + + options = { + params: [], + defaultCount: 0, + defaults: [], + rest: null, + firstRestricted: firstRestricted + }; + expect("("); if (!match(")")) { - paramSet = {}; + options.paramSet = new StringMap(); while (index < length) { - def = null; - token = lookahead; - param = parseVariableIdentifier(); - key = "$" + token.value; - if (strict) { - if (syntax.isRestrictedWord(token.value)) { - stricted = token; - message = Messages.StrictParamName; - } - if (Object.prototype.hasOwnProperty.call(paramSet, key)) { - stricted = token; - message = Messages.StrictParamDupe; - } - } else if (!firstRestricted) { - if (syntax.isRestrictedWord(token.value)) { - firstRestricted = token; - message = Messages.StrictParamName; - } else if (syntax.isStrictModeReservedWord(token.value)) { - firstRestricted = token; - message = Messages.StrictReservedWord; - } else if (Object.prototype.hasOwnProperty.call(paramSet, key)) { - firstRestricted = token; - message = Messages.StrictParamDupe; - } - } - if (match("=")) { - if (!allowDefaultParams) { - throwUnexpected(lookahead); - } - lex(); - def = parseAssignmentExpression(); - ++defaultCount; - } - defaults.push(def); - params.push(param); - paramSet[key] = true; - if (match(")")) { + if (!parseParam(options)) { break; } expect(","); @@ -4031,17 +4404,11 @@ function parseParams(firstRestricted) { expect(")"); - if (defaultCount === 0) { - defaults = []; + if (options.defaultCount === 0) { + options.defaults = []; } - return { - params: params, - stricted: stricted, - defaults: defaults, - firstRestricted: firstRestricted, - message: message - }; + return markerApply(marker, options); } function parseFunctionDeclaration() { @@ -4323,6 +4690,7 @@ function tokenize(code, options) { state = { allowIn: true, labelSet: {}, + parenthesisCount: 0, inFunctionBody: false, inIteration: false, inSwitch: false, @@ -4344,10 +4712,14 @@ function tokenize(code, options) { options.tokens = true; extra.tokens = []; extra.tokenize = true; + // The following two fields are necessary to compute the Regex tokens. extra.openParenToken = -1; extra.openCurlyToken = -1; + // Needed when using template string tokenization + extra.curlies = []; + extra.range = (typeof options.range === "boolean") && options.range; extra.loc = (typeof options.loc === "boolean") && options.loc; @@ -4422,7 +4794,8 @@ function parse(code, options) { lookahead = null; state = { allowIn: true, - labelSet: {}, + labelSet: new StringMap(), + parenthesisCount: 0, inFunctionBody: false, inIteration: false, inSwitch: false, @@ -4437,6 +4810,9 @@ function parse(code, options) { ecmaFeatures: defaultFeatures }; + // for template strings + extra.curlies = []; + if (typeof options !== "undefined") { extra.range = (typeof options.range === "boolean") && options.range; extra.loc = (typeof options.loc === "boolean") && options.loc; diff --git a/node_modules/espree/lib/ast-node-factory.js b/node_modules/espree/lib/ast-node-factory.js index c2392653..06b6930a 100644 --- a/node_modules/espree/lib/ast-node-factory.js +++ b/node_modules/espree/lib/ast-node-factory.js @@ -51,6 +51,30 @@ module.exports = { }; }, + /** + * Create an Arrow Function Expression ASTNode + * @param {ASTNode} params The function arguments + * @param {ASTNode} defaults Any default arguments + * @param {ASTNode} body The function body + * @param {ASTNode} rest The rest parameter + * @param {boolean} expression True if the arrow function is created via an expression. + * Always false for declarations, but kept here to be in sync with + * FunctionExpression objects. + * @returns {ASTNode} An ASTNode representing the entire arrow function expression + */ + createArrowFunctionExpression: function (params, defaults, body, rest, expression) { + return { + type: astNodeTypes.ArrowFunctionExpression, + id: null, + params: params, + defaults: defaults, + body: body, + rest: rest, + generator: false, + expression: expression + }; + }, + /** * Create an ASTNode representation of an assignment expression * @param {ASTNode} operator The assignment operator @@ -419,6 +443,18 @@ module.exports = { }; }, + /** + * Create an ASTNode representation of a spread element + * @param {ASTNode} argument The array being spread + * @returns {ASTNode} An ASTNode representing a spread element + */ + createSpreadElement: function (argument) { + return { + type: astNodeTypes.SpreadElement, + argument: argument + }; + }, + /** * Create an ASTNode tagged template expression * @param {ASTNode} tag The tag expression diff --git a/node_modules/espree/lib/ast-node-types.js b/node_modules/espree/lib/ast-node-types.js index 87e1efeb..58fc3452 100644 --- a/node_modules/espree/lib/ast-node-types.js +++ b/node_modules/espree/lib/ast-node-types.js @@ -40,6 +40,8 @@ module.exports = { AssignmentExpression: "AssignmentExpression", ArrayExpression: "ArrayExpression", + ArrayPattern: "ArrayPattern", + ArrowFunctionExpression: "ArrowFunctionExpression", BlockStatement: "BlockStatement", BinaryExpression: "BinaryExpression", BreakStatement: "BreakStatement", @@ -64,10 +66,12 @@ module.exports = { MemberExpression: "MemberExpression", NewExpression: "NewExpression", ObjectExpression: "ObjectExpression", + ObjectPattern: "ObjectPattern", Program: "Program", Property: "Property", ReturnStatement: "ReturnStatement", SequenceExpression: "SequenceExpression", + SpreadElement: "SpreadElement", SwitchCase: "SwitchCase", SwitchStatement: "SwitchStatement", TaggedTemplateExpression: "TaggedTemplateExpression", diff --git a/node_modules/espree/lib/features.js b/node_modules/espree/lib/features.js index c54ba595..3c2b17c3 100644 --- a/node_modules/espree/lib/features.js +++ b/node_modules/espree/lib/features.js @@ -40,9 +40,15 @@ module.exports = { + // enable parsing of arrow functions + arrowFunctions: false, + // enable parsing of let and const blockBindings: true, + // enable parsing of destructured arrays and objects + destructuring: false, + // enable parsing of regex u flag regexUFlag: false, @@ -64,6 +70,9 @@ module.exports = { // enable parsing of default parameters defaultParams: false, + // enable parsing of rest parameters + restParams: false, + // enable parsing of for-of statements forOf: false, @@ -82,6 +91,15 @@ module.exports = { // enable parsing of generators/yield generators: false, + // support the spread operator + spread: false, + + // enable super in functions + superInFunctions: false, + // React JSX parsing - jsx: false + jsx: false, + + // allow return statement in global scope + globalReturn: false }; diff --git a/node_modules/espree/lib/messages.js b/node_modules/espree/lib/messages.js index 4403880e..0d817391 100644 --- a/node_modules/espree/lib/messages.js +++ b/node_modules/espree/lib/messages.js @@ -51,20 +51,28 @@ module.exports = { InvalidRegExpFlag: "Invalid regular expression flag", UnterminatedRegExp: "Invalid regular expression: missing /", InvalidLHSInAssignment: "Invalid left-hand side in assignment", + InvalidLHSInFormalsList: "Invalid left-hand side in formals list", InvalidLHSInForIn: "Invalid left-hand side in for-in", MultipleDefaultsInSwitch: "More than one default clause in switch statement", NoCatchOrFinally: "Missing catch or finally after try", + NoUnintializedConst: "Const must be initialized", UnknownLabel: "Undefined label '%0'", Redeclaration: "%0 '%1' has already been declared", IllegalContinue: "Illegal continue statement", IllegalBreak: "Illegal break statement", IllegalReturn: "Illegal return statement", IllegalYield: "Illegal yield expression", + IllegalSpread: "Illegal spread element", StrictModeWith: "Strict mode code may not include a with statement", StrictCatchVariable: "Catch variable may not be eval or arguments in strict mode", StrictVarName: "Variable name may not be eval or arguments in strict mode", StrictParamName: "Parameter name eval or arguments is not allowed in strict mode", StrictParamDupe: "Strict mode function may not have duplicate parameter names", + ParameterAfterRestParameter: "Rest parameter must be final parameter of an argument list", + DefaultRestParameter: "Rest parameter can not have a default value", + ElementAfterSpreadElement: "Spread must be the final element of an element list", + ObjectPatternAsRestParameter: "Invalid rest parameter", + ObjectPatternAsSpread: "Invalid spread argument", StrictFunctionName: "Function name may not be eval or arguments in strict mode", StrictOctalLiteral: "Octal literals are not allowed in strict mode.", StrictDelete: "Delete of an unqualified identifier in strict mode.", diff --git a/node_modules/espree/lib/string-map.js b/node_modules/espree/lib/string-map.js new file mode 100644 index 00000000..97c87032 --- /dev/null +++ b/node_modules/espree/lib/string-map.js @@ -0,0 +1,55 @@ +/** + * @fileoverview A simple map that helps avoid collisions on the Object prototype. + * @author Jamund Ferguson + * @copyright 2015 Jamund Ferguson. All rights reserved. + * @copyright 2011-2013 Ariya Hidayat + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +"use strict"; + +function StringMap() { + this.$data = {}; +} + +StringMap.prototype.get = function (key) { + key = "$" + key; + return this.$data[key]; +}; + +StringMap.prototype.set = function (key, value) { + key = "$" + key; + this.$data[key] = value; + return this; +}; + +StringMap.prototype.has = function (key) { + key = "$" + key; + return Object.prototype.hasOwnProperty.call(this.$data, key); +}; + +StringMap.prototype.delete = function (key) { + key = "$" + key; + return delete this.$data[key]; +}; + +module.exports = StringMap; diff --git a/node_modules/espree/package.json b/node_modules/espree/package.json index 128ee025..c44ed32b 100644 --- a/node_modules/espree/package.json +++ b/node_modules/espree/package.json @@ -11,7 +11,7 @@ "esparse": "./bin/esparse.js", "esvalidate": "./bin/esvalidate.js" }, - "version": "1.7.1", + "version": "1.9.1", "files": [ "bin", "lib", @@ -83,10 +83,10 @@ "benchmark-quick": "node test/benchmarks.js quick" }, "dependencies": {}, - "readme": "# Espree\n\nEspree is an actively-maintained fork Esprima, a high performance,\nstandard-compliant [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm)\nparser written in ECMAScript (also popularly known as\n[JavaScript](http://en.wikipedia.org/wiki/JavaScript)).\n\n## Features\n\n- Full support for ECMAScript 5.1 ([ECMA-262](http://www.ecma-international.org/publications/standards/Ecma-262.htm))\n- Sensible syntax tree format compatible with Mozilla\n[Parser AST](https://developer.mozilla.org/en/SpiderMonkey/Parser_API)\n- Optional tracking of syntax node location (index-based and line-column)\n- Heavily tested (> 650 unit tests) with full code coverage\n\n## Usage\n\nInstall:\n\n```\nnpm i espree --save\n```\n\nAnd in your Node.js code:\n\n```javascript\nvar espree = require(\"espree\");\n\nvar ast = espree.parse(code);\n```\n\nThere is a second argument to `parse()` that allows you to specify various options:\n\n```javascript\nvar espree = require(\"espree\");\n\nvar ast = espree.parse(code, {\n\n // attach range information to each node\n range: true,\n\n // attach line/column location information to each node\n loc: true,\n\n // create a top-level comments array containing all comments\n comments: true,\n\n // attach comments to the closest relevant node as leadingComments and\n // trailingComments\n attachComment: true,\n\n // create a top-level tokens array containing all tokens\n tokens: true,\n\n // try to continue parsing if an error is encountered, store errors in a\n // top-level errors array\n tolerant: true,\n\n // specify parsing features (default only has blockBindings: true)\n ecmaFeatures: {\n\n // enable parsing of let/const\n blockBindings: true,\n\n // enable parsing of regular expression y flag\n regexYFlag: true,\n\n // enable parsing of regular expression u flag\n regexUFlag: true,\n\n // enable parsing of template strings\n templateStrings: false,\n\n // enable parsing of binary literals\n binaryLiterals: true,\n\n // enable parsing of ES6 octal literals\n octalLiterals: true,\n\n // enable parsing unicode code point escape sequences\n unicodeCodePointEscapes: true,\n\n // enable parsing of default parameters\n defaultParams: false,\n\n // enable parsing of for-of statement\n forOf: true,\n\n // enable parsing computed object literal properties\n objectLiteralComputedProperties: true,\n\n // enable parsing of shorthand object literal methods\n objectLiteralShorthandMethods: true,\n\n // enable parsing of shorthand object literal properties\n objectLiteralShorthandProperties: true,\n\n // Allow duplicate object literal properties (except '__proto__')\n objectLiteralDuplicateProperties: true,\n\n // enable parsing of generators/yield\n generators: true,\n\n // React JSX parsing\n jsx: true\n }\n});\n```\n\n## Plans\n\nEspree starts as a fork of Esprima v1.2.2, the last stable published released of Esprima before work on ECMAScript 6 began. Espree's first version is therefore v1.2.2 and is 100% compatible with Esprima v1.2.2 as a drop-in replacement. The version number will be incremented based on [semantic versioning](http://semver.org/) as features and bug fixes are added.\n\nThe immediate plans are:\n\n1. Move away from giant files and move towards small, modular files that are easier to manage.\n1. Move towards CommonJS for all files and use browserify to create browser bundles.\n1. Support ECMAScript version filtering, allowing users to specify which version the parser should work in (similar to Acorn's `ecmaVersion` property).\n1. Add tests to track comment attachment.\n1. Add well-thought-out features that are useful for tools developers.\n1. Add full support for ECMAScript 6.\n1. Add optional parsing of JSX.\n\n## Esprima Compatibility Going Forward\n\nThe primary goal is to produce the exact same AST structure as Esprima and Acorn, and that takes precedence over anything else. (The AST structure being the SpiderMonkey Parser API with JSX extensions.) Separate from that, Espree may deviate from what Esprima outputs in terms of where and how comments are attached, as well as what additional information is available on AST nodes. That is to say, Espree may add more things to the AST nodes than Esprima does but the overall AST structure produced will be the same.\n\nEspree may also deviate from Esprima in the interface it exposes.\n\n## Frequent and Incremental Releases\n\nEspree will not do giant releases. Releases will happen periodically as changes are made and incremental releases will be made towards larger goals. For instance, we will not have one big release for ECMAScript 6 support. Instead, we will implement ECMAScript 6, piece-by-piece, hiding those pieces behind an `ecmaFeatures` property that allows you to opt-in to use those features.\n\n## Contributing\n\nIssues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing.html), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/espree/issues).\n\nEspree is licensed under a permissive BSD 3-clause license.\n\n## Build Commands\n\n* `npm test` - run all linting and tests\n* `npm run lint` - run all linting\n* `npm run browserify` - creates a version of Espree that is usable in a browser\n\n## Known Incompatibilities\n\nIn an effort to help those wanting to transition from other parsers to Espree, the following is a list of noteworthy incompatibilities with other parsers. These are known differences that we do not intend to change.\n\n### Esprima 1.2.2\n\n* None.\n\n### Esprima/Harmony Branch\n\n* Esprima/Harmony uses a different comment attachment algorithm that results in some comments being added in different places than Espree. The algorithm Espree uses is the same one used in Esprima 1.2.2.\n\n### Esprima-FB\n\n* All Esprima/Harmony incompatibilities.\n* Esprima-FB uses the term \"XJS\" to refer to its JSX support. This is seen primarily in the AST node types, such as `\"XJSElement\"`. Espree uses \"JSX\" to refer to JSX functionality, including AST node types. So, `\"XJSElement\"` in Esprima-FB is `\"JSXElement\"` in Espree (and the same is true for all JSX-related node types).\n\n## Frequently Asked Questions\n\n### Why are you forking Esprima?\n\n[ESLint](http://eslint.org) has been relying on Esprima as its parser from the beginning. While that was fine when the JavaScript language was evolving slowly, the pace of development has increased dramatically and Esprima has fallen behind. ESLint, like many other tools reliant on Esprima, has been stuck in using new JavaScript language features until Esprima updates, and that has caused our users frustration.\n\nWe decided the only way for us to move forward was to create our own parser, bringing us inline with JSHint and JSLint, and allowing us to keep implementing new features as we need them. We chose to fork Esprima instead of starting from scratch in order to move as quickly as possible with a compatible API.\n\n### Have you tried working with Esprima?\n\nYes. Since the start of ESLint, we've regularly filed bugs and feature requests with Esprima. Unfortunately, we've been unable to make much progress towards getting our needs addressed.\n\n### Why don't you just use Facebook's Esprima fork?\n\n`esprima-fb` is Facebook's Esprima fork that features JSX and Flow type annotations. We tried working with `esprima-fb` in our evaluation of how to support ECMAScript 6 and JSX in ESLint. Unfortunately, we were hampered by bugs that were part of Esprima (not necessarily Facebook's code). Since `esprima-fb` tracks the Esprima Harmony branch, that means we still were unable to get fixes or features we needed in a timely manner.\n\n### Why don't you just use Acorn?\n\nAcorn is a great JavaScript parser that produces an AST that is compatible with Esprima. Unfortunately, ESLint relies on more than just the AST to do its job. It relies on Esprima's tokens and comment attachment features to get a complete picture of the source code. We investigated switching to Acorn, but the inconsistencies between Esprima and Acorn created too much work for a project like ESLint.\n\nWe expect there are other tools like ESLint that rely on more than just the AST produced by Esprima, and so a drop-in replacement will help those projects as well as ESLint.\n\n### What ECMAScript 6 features do you support?\n\nPlease see the [tracking issue](https://github.com/eslint/espree/issues/10) for the most up-to-date information.\n\n### Why use Espree instead of Esprima?\n\n* Faster turnaround time on bug fixes\n* More frequent releases\n* Better communication and responsiveness to issues\n* Ongoing development\n\n### Why use Espree instead of Esprima-FB?\n\n* Opt-in to just the ECMAScript 6 features you want\n* JSX support is off by default, so you're not forced to use it to use ECMAScript 6\n* Stricter ECMAScript 6 support\n", + "readme": "# Espree\n\nEspree is an actively-maintained fork Esprima, a high performance,\nstandard-compliant [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm)\nparser written in ECMAScript (also popularly known as\n[JavaScript](http://en.wikipedia.org/wiki/JavaScript)).\n\n## Features\n\n- Full support for ECMAScript 5.1 ([ECMA-262](http://www.ecma-international.org/publications/standards/Ecma-262.htm))\n- Sensible syntax tree format compatible with Mozilla\n[Parser AST](https://developer.mozilla.org/en/SpiderMonkey/Parser_API)\n- Optional tracking of syntax node location (index-based and line-column)\n- Heavily tested (> 650 unit tests) with full code coverage\n\n## Usage\n\nInstall:\n\n```\nnpm i espree --save\n```\n\nAnd in your Node.js code:\n\n```javascript\nvar espree = require(\"espree\");\n\nvar ast = espree.parse(code);\n```\n\nThere is a second argument to `parse()` that allows you to specify various options:\n\n```javascript\nvar espree = require(\"espree\");\n\nvar ast = espree.parse(code, {\n\n // attach range information to each node\n range: true,\n\n // attach line/column location information to each node\n loc: true,\n\n // create a top-level comments array containing all comments\n comments: true,\n\n // attach comments to the closest relevant node as leadingComments and\n // trailingComments\n attachComment: true,\n\n // create a top-level tokens array containing all tokens\n tokens: true,\n\n // try to continue parsing if an error is encountered, store errors in a\n // top-level errors array\n tolerant: true,\n\n // specify parsing features (default only has blockBindings: true)\n ecmaFeatures: {\n\n // enable parsing of arrow functions\n arrowFunctions: true,\n\n // enable parsing of let/const\n blockBindings: true,\n\n // enable parsing of destructured arrays and objects\n destructuring: true,\n\n // enable parsing of regular expression y flag\n regexYFlag: true,\n\n // enable parsing of regular expression u flag\n regexUFlag: true,\n\n // enable parsing of template strings\n templateStrings: false,\n\n // enable parsing of binary literals\n binaryLiterals: true,\n\n // enable parsing of ES6 octal literals\n octalLiterals: true,\n\n // enable parsing unicode code point escape sequences\n unicodeCodePointEscapes: true,\n\n // enable parsing of default parameters\n defaultParams: false,\n\n // enable parsing of rest parameters\n restParams: true,\n\n // enable parsing of for-of statement\n forOf: true,\n\n // enable parsing computed object literal properties\n objectLiteralComputedProperties: true,\n\n // enable parsing of shorthand object literal methods\n objectLiteralShorthandMethods: true,\n\n // enable parsing of shorthand object literal properties\n objectLiteralShorthandProperties: true,\n\n // Allow duplicate object literal properties (except '__proto__')\n objectLiteralDuplicateProperties: true,\n\n // enable parsing of generators/yield\n generators: true,\n\n // support the spread operator\n spread: true,\n\n // enable React JSX parsing\n jsx: true,\n\n // enable return in global scope\n globalReturn: true\n }\n});\n```\n\n## Plans\n\nEspree starts as a fork of Esprima v1.2.2, the last stable published released of Esprima before work on ECMAScript 6 began. Espree's first version is therefore v1.2.2 and is 100% compatible with Esprima v1.2.2 as a drop-in replacement. The version number will be incremented based on [semantic versioning](http://semver.org/) as features and bug fixes are added.\n\nThe immediate plans are:\n\n1. Move away from giant files and move towards small, modular files that are easier to manage.\n1. Move towards CommonJS for all files and use browserify to create browser bundles.\n1. Support ECMAScript version filtering, allowing users to specify which version the parser should work in (similar to Acorn's `ecmaVersion` property).\n1. Add tests to track comment attachment.\n1. Add well-thought-out features that are useful for tools developers.\n1. Add full support for ECMAScript 6.\n1. Add optional parsing of JSX.\n\n## Esprima Compatibility Going Forward\n\nThe primary goal is to produce the exact same AST structure as Esprima and Acorn, and that takes precedence over anything else. (The AST structure being the SpiderMonkey Parser API with JSX extensions.) Separate from that, Espree may deviate from what Esprima outputs in terms of where and how comments are attached, as well as what additional information is available on AST nodes. That is to say, Espree may add more things to the AST nodes than Esprima does but the overall AST structure produced will be the same.\n\nEspree may also deviate from Esprima in the interface it exposes.\n\n## Frequent and Incremental Releases\n\nEspree will not do giant releases. Releases will happen periodically as changes are made and incremental releases will be made towards larger goals. For instance, we will not have one big release for ECMAScript 6 support. Instead, we will implement ECMAScript 6, piece-by-piece, hiding those pieces behind an `ecmaFeatures` property that allows you to opt-in to use those features.\n\n## Contributing\n\nIssues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing.html), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/espree/issues).\n\nEspree is licensed under a permissive BSD 3-clause license.\n\n## Build Commands\n\n* `npm test` - run all linting and tests\n* `npm run lint` - run all linting\n* `npm run browserify` - creates a version of Espree that is usable in a browser\n\n## Known Incompatibilities\n\nIn an effort to help those wanting to transition from other parsers to Espree, the following is a list of noteworthy incompatibilities with other parsers. These are known differences that we do not intend to change.\n\n### Esprima 1.2.2\n\n* None.\n\n### Esprima/Harmony Branch\n\n* Esprima/Harmony uses a different comment attachment algorithm that results in some comments being added in different places than Espree. The algorithm Espree uses is the same one used in Esprima 1.2.2.\n* Template tokens have a `head` property in addition to `tail`. Esprima has only `tail`.\n\n### Esprima-FB\n\n* All Esprima/Harmony incompatibilities.\n* Esprima-FB uses the term \"XJS\" to refer to its JSX support. This is seen primarily in the AST node types, such as `\"XJSElement\"`. Espree uses \"JSX\" to refer to JSX functionality, including AST node types. So, `\"XJSElement\"` in Esprima-FB is `\"JSXElement\"` in Espree (and the same is true for all JSX-related node types).\n\n## Frequently Asked Questions\n\n### Why are you forking Esprima?\n\n[ESLint](http://eslint.org) has been relying on Esprima as its parser from the beginning. While that was fine when the JavaScript language was evolving slowly, the pace of development has increased dramatically and Esprima has fallen behind. ESLint, like many other tools reliant on Esprima, has been stuck in using new JavaScript language features until Esprima updates, and that has caused our users frustration.\n\nWe decided the only way for us to move forward was to create our own parser, bringing us inline with JSHint and JSLint, and allowing us to keep implementing new features as we need them. We chose to fork Esprima instead of starting from scratch in order to move as quickly as possible with a compatible API.\n\n### Have you tried working with Esprima?\n\nYes. Since the start of ESLint, we've regularly filed bugs and feature requests with Esprima. Unfortunately, we've been unable to make much progress towards getting our needs addressed.\n\n### Why don't you just use Facebook's Esprima fork?\n\n`esprima-fb` is Facebook's Esprima fork that features JSX and Flow type annotations. We tried working with `esprima-fb` in our evaluation of how to support ECMAScript 6 and JSX in ESLint. Unfortunately, we were hampered by bugs that were part of Esprima (not necessarily Facebook's code). Since `esprima-fb` tracks the Esprima Harmony branch, that means we still were unable to get fixes or features we needed in a timely manner.\n\n### Why don't you just use Acorn?\n\nAcorn is a great JavaScript parser that produces an AST that is compatible with Esprima. Unfortunately, ESLint relies on more than just the AST to do its job. It relies on Esprima's tokens and comment attachment features to get a complete picture of the source code. We investigated switching to Acorn, but the inconsistencies between Esprima and Acorn created too much work for a project like ESLint.\n\nWe expect there are other tools like ESLint that rely on more than just the AST produced by Esprima, and so a drop-in replacement will help those projects as well as ESLint.\n\n### What ECMAScript 6 features do you support?\n\nPlease see the [tracking issue](https://github.com/eslint/espree/issues/10) for the most up-to-date information.\n\n### Why use Espree instead of Esprima?\n\n* Faster turnaround time on bug fixes\n* More frequent releases\n* Better communication and responsiveness to issues\n* Ongoing development\n\n### Why use Espree instead of Esprima-FB?\n\n* Opt-in to just the ECMAScript 6 features you want\n* JSX support is off by default, so you're not forced to use it to use ECMAScript 6\n* Stricter ECMAScript 6 support\n", "readmeFilename": "README.md", - "_id": "espree@1.7.1", - "_shasum": "894d7649345479db0997bd26bbfd84c67d021677", - "_from": "espree@1.7.1", - "_resolved": "https://registry.npmjs.org/espree/-/espree-1.7.1.tgz" + "_id": "espree@1.9.1", + "_shasum": "f1ac59e5b56c6ac4351f8beb27293c1cee73112f", + "_from": "espree@~1.9.1", + "_resolved": "https://registry.npmjs.org/espree/-/espree-1.9.1.tgz" } diff --git a/package.json b/package.json index feb0ac8d..0ee7fac7 100644 --- a/package.json +++ b/package.json @@ -16,7 +16,7 @@ "async": "~0.9.0", "catharsis": "~0.8.6", "escape-string-regexp": "~1.0.2", - "espree": "1.7.1", + "espree": "~1.9.1", "js2xmlparser": "~0.1.7", "marked": "~0.3.2", "requizzle": "~0.2.0", diff --git a/test/specs/jsdoc/src/astbuilder.js b/test/specs/jsdoc/src/astbuilder.js index 996b3c5a..a368a6b3 100644 --- a/test/specs/jsdoc/src/astbuilder.js +++ b/test/specs/jsdoc/src/astbuilder.js @@ -36,7 +36,7 @@ describe('jsdoc/src/astbuilder', function() { it('should log (not throw) an error when a file cannot be parsed', function() { function parse() { - builder.build('if (true) { return; }', 'bad.js'); + builder.build('qwerty!!!!!', 'bad.js'); } expect(parse).not.toThrow();