(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.babel = 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")) { node.params.push(this.flow_parseTypeAnnotatableIdentifier()); if (!this.isRelational(">")) { this.expect(tt.comma); } } this.expectRelational(">"); return this.finishNode(node, "TypeParameterDeclaration"); }; pp.flow_parseTypeParameterInstantiation = function () { var node = this.startNode(), oldInType = this.inType; node.params = []; this.inType = true; this.expectRelational("<"); while (!this.isRelational(">")) { node.params.push(this.flow_parseType()); if (!this.isRelational(">")) { this.expect(tt.comma); } } this.expectRelational(">"); this.inType = oldInType; return this.finishNode(node, "TypeParameterInstantiation"); }; pp.flow_parseObjectPropertyKey = function () { return this.type === tt.num || this.type === tt.string ? this.parseExprAtom() : this.parseIdent(true); }; pp.flow_parseObjectTypeIndexer = function (node, isStatic) { node["static"] = isStatic; this.expect(tt.bracketL); node.id = this.flow_parseObjectPropertyKey(); this.expect(tt.colon); node.key = this.flow_parseType(); this.expect(tt.bracketR); this.expect(tt.colon); node.value = this.flow_parseType(); this.flow_objectTypeSemicolon(); return this.finishNode(node, "ObjectTypeIndexer"); }; pp.flow_parseObjectTypeMethodish = function (node) { node.params = []; node.rest = null; node.typeParameters = null; if (this.isRelational("<")) { node.typeParameters = this.flow_parseTypeParameterDeclaration(); } this.expect(tt.parenL); while (this.type === tt.name) { node.params.push(this.flow_parseFunctionTypeParam()); if (this.type !== tt.parenR) { this.expect(tt.comma); } } if (this.eat(tt.ellipsis)) { node.rest = this.flow_parseFunctionTypeParam(); } this.expect(tt.parenR); this.expect(tt.colon); node.returnType = this.flow_parseType(); return this.finishNode(node, "FunctionTypeAnnotation"); }; pp.flow_parseObjectTypeMethod = function (start, isStatic, key) { var node = this.startNodeAt(start); node.value = this.flow_parseObjectTypeMethodish(this.startNodeAt(start)); node["static"] = isStatic; node.key = key; node.optional = false; this.flow_objectTypeSemicolon(); return this.finishNode(node, "ObjectTypeProperty"); }; pp.flow_parseObjectTypeCallProperty = function (node, isStatic) { var valueNode = this.startNode(); node["static"] = isStatic; node.value = this.flow_parseObjectTypeMethodish(valueNode); this.flow_objectTypeSemicolon(); return this.finishNode(node, "ObjectTypeCallProperty"); }; pp.flow_parseObjectType = function (allowStatic) { var nodeStart = this.startNode(); var node; var optional = false; var property; var propertyKey; var propertyTypeAnnotation; var token; var isStatic; nodeStart.callProperties = []; nodeStart.properties = []; nodeStart.indexers = []; this.expect(tt.braceL); while (this.type !== tt.braceR) { var start = this.markPosition(); node = this.startNode(); if (allowStatic && this.isContextual("static")) { this.next(); isStatic = true; } if (this.type === tt.bracketL) { nodeStart.indexers.push(this.flow_parseObjectTypeIndexer(node, isStatic)); } else if (this.type === tt.parenL || this.isRelational("<")) { nodeStart.callProperties.push(this.flow_parseObjectTypeCallProperty(node, allowStatic)); } else { if (isStatic && this.type === tt.colon) { propertyKey = this.parseIdent(); } else { propertyKey = this.flow_parseObjectPropertyKey(); } if (this.isRelational("<") || this.type === tt.parenL) { // This is a method property nodeStart.properties.push(this.flow_parseObjectTypeMethod(start, isStatic, propertyKey)); } else { if (this.eat(tt.question)) { optional = true; } this.expect(tt.colon); node.key = propertyKey; node.value = this.flow_parseType(); node.optional = optional; node["static"] = isStatic; this.flow_objectTypeSemicolon(); nodeStart.properties.push(this.finishNode(node, "ObjectTypeProperty")); } } } this.expect(tt.braceR); return this.finishNode(nodeStart, "ObjectTypeAnnotation"); }; pp.flow_objectTypeSemicolon = function () { if (!this.eat(tt.semi) && !this.eat(tt.comma) && this.type !== tt.braceR) { this.unexpected(); } }; pp.flow_parseGenericType = function (start, id) { var node = this.startNodeAt(start); node.typeParameters = null; node.id = id; while (this.eat(tt.dot)) { var node2 = this.startNodeAt(start); node2.qualification = node.id; node2.id = this.parseIdent(); node.id = this.finishNode(node2, "QualifiedTypeIdentifier"); } if (this.isRelational("<")) { node.typeParameters = this.flow_parseTypeParameterInstantiation(); } return this.finishNode(node, "GenericTypeAnnotation"); }; pp.flow_parseVoidType = function () { var node = this.startNode(); this.expect(tt._void); return this.finishNode(node, "VoidTypeAnnotation"); }; pp.flow_parseTypeofType = function () { var node = this.startNode(); this.expect(tt._typeof); node.argument = this.flow_parsePrimaryType(); return this.finishNode(node, "TypeofTypeAnnotation"); }; pp.flow_parseTupleType = function () { var node = this.startNode(); node.types = []; this.expect(tt.bracketL); // We allow trailing commas while (this.pos < this.input.length && this.type !== tt.bracketR) { node.types.push(this.flow_parseType()); if (this.type === tt.bracketR) break; this.expect(tt.comma); } this.expect(tt.bracketR); return this.finishNode(node, "TupleTypeAnnotation"); }; pp.flow_parseFunctionTypeParam = function () { var optional = false; var node = this.startNode(); node.name = this.parseIdent(); if (this.eat(tt.question)) { optional = true; } this.expect(tt.colon); node.optional = optional; node.typeAnnotation = this.flow_parseType(); return this.finishNode(node, "FunctionTypeParam"); }; pp.flow_parseFunctionTypeParams = function () { var ret = { params: [], rest: null }; while (this.type === tt.name) { ret.params.push(this.flow_parseFunctionTypeParam()); if (this.type !== tt.parenR) { this.expect(tt.comma); } } if (this.eat(tt.ellipsis)) { ret.rest = this.flow_parseFunctionTypeParam(); } return ret; }; pp.flow_identToTypeAnnotation = function (start, node, id) { switch (id.name) { case "any": return this.finishNode(node, "AnyTypeAnnotation"); case "bool": case "boolean": return this.finishNode(node, "BooleanTypeAnnotation"); case "number": return this.finishNode(node, "NumberTypeAnnotation"); case "string": return this.finishNode(node, "StringTypeAnnotation"); default: return this.flow_parseGenericType(start, id); } }; // The parsing of types roughly parallels the parsing of expressions, and // primary types are kind of like primary expressions...they're the // primitives with which other types are constructed. pp.flow_parsePrimaryType = function () { var typeIdentifier = null; var params = null; var returnType = null; var start = this.markPosition(); var node = this.startNode(); var rest = null; var tmp; var typeParameters; var token; var type; var isGroupedType = false; switch (this.type) { case tt.name: return this.flow_identToTypeAnnotation(start, node, this.parseIdent()); case tt.braceL: return this.flow_parseObjectType(); case tt.bracketL: return this.flow_parseTupleType(); case tt.relational: if (this.value === "<") { node.typeParameters = this.flow_parseTypeParameterDeclaration(); this.expect(tt.parenL); tmp = this.flow_parseFunctionTypeParams(); node.params = tmp.params; node.rest = tmp.rest; this.expect(tt.parenR); this.expect(tt.arrow); node.returnType = this.flow_parseType(); return this.finishNode(node, "FunctionTypeAnnotation"); } case tt.parenL: this.next(); // Check to see if this is actually a grouped type if (this.type !== tt.parenR && this.type !== tt.ellipsis) { if (this.type === tt.name) { var token = this.lookahead().type; isGroupedType = token !== tt.question && token !== tt.colon; } else { isGroupedType = true; } } if (isGroupedType) { type = this.flow_parseType(); this.expect(tt.parenR); // If we see a => next then someone was probably confused about // function types, so we can provide a better error message if (this.eat(tt.arrow)) { this.raise(node, "Unexpected token =>. It looks like " + "you are trying to write a function type, but you ended up " + "writing a grouped type followed by an =>, which is a syntax " + "error. Remember, function type parameters are named so function " + "types look like (name1: type1, name2: type2) => returnType. You " + "probably wrote (type1) => returnType"); } return type; } tmp = this.flow_parseFunctionTypeParams(); node.params = tmp.params; node.rest = tmp.rest; this.expect(tt.parenR); this.expect(tt.arrow); node.returnType = this.flow_parseType(); node.typeParameters = null; return this.finishNode(node, "FunctionTypeAnnotation"); case tt.string: node.value = this.value; node.raw = this.input.slice(this.start, this.end); this.next(); return this.finishNode(node, "StringLiteralTypeAnnotation"); default: if (this.type.keyword) { switch (this.type.keyword) { case "void": return this.flow_parseVoidType(); case "typeof": return this.flow_parseTypeofType(); } } } this.unexpected(); }; pp.flow_parsePostfixType = function () { var node = this.startNode(); var type = node.elementType = this.flow_parsePrimaryType(); if (this.type === tt.bracketL) { this.expect(tt.bracketL); this.expect(tt.bracketR); return this.finishNode(node, "ArrayTypeAnnotation"); } return type; }; pp.flow_parsePrefixType = function () { var node = this.startNode(); if (this.eat(tt.question)) { node.typeAnnotation = this.flow_parsePrefixType(); return this.finishNode(node, "NullableTypeAnnotation"); } return this.flow_parsePostfixType(); }; pp.flow_parseIntersectionType = function () { var node = this.startNode(); var type = this.flow_parsePrefixType(); node.types = [type]; while (this.eat(tt.bitwiseAND)) { node.types.push(this.flow_parsePrefixType()); } return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation"); }; pp.flow_parseUnionType = function () { var node = this.startNode(); var type = this.flow_parseIntersectionType(); node.types = [type]; while (this.eat(tt.bitwiseOR)) { node.types.push(this.flow_parseIntersectionType()); } return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation"); }; pp.flow_parseType = function () { var oldInType = this.inType; this.inType = true; var type = this.flow_parseUnionType(); this.inType = oldInType; return type; }; pp.flow_parseTypeAnnotation = function () { var node = this.startNode(); var oldInType = this.inType; this.inType = true; this.expect(tt.colon); node.typeAnnotation = this.flow_parseType(); this.inType = oldInType; return this.finishNode(node, "TypeAnnotation"); }; pp.flow_parseTypeAnnotatableIdentifier = function (requireTypeAnnotation, canBeOptionalParam) { var node = this.startNode(); var ident = this.parseIdent(); var isOptionalParam = false; if (canBeOptionalParam && this.eat(tt.question)) { this.expect(tt.question); isOptionalParam = true; } if (requireTypeAnnotation || this.type === tt.colon) { ident.typeAnnotation = this.flow_parseTypeAnnotation(); this.finishNode(ident, ident.type); } if (isOptionalParam) { ident.optional = true; this.finishNode(ident, ident.type); } return ident; }; acorn.plugins.flow = function (instance) { // function name(): string {} instance.extend("parseFunctionBody", function (inner) { return function (node, allowExpression) { if (this.type === tt.colon) { node.returnType = this.flow_parseTypeAnnotation(); } return inner.call(this, node, allowExpression); }; }); instance.extend("parseStatement", function (inner) { return function (declaration, topLevel) { // strict mode handling of `interface` since it's a reserved word if (this.strict && this.type === tt.name && this.value === "interface") { var node = this.startNode(); this.next(); return this.flow_parseInterface(node); } else { return inner.call(this, declaration, topLevel); } }; }); instance.extend("parseExpressionStatement", function (inner) { return function (node, expr) { if (expr.type === "Identifier") { if (expr.name === "declare") { if (this.type === tt._class || this.type === tt.name || this.type === tt._function || this.type === tt._var) { return this.flow_parseDeclare(node); } } else if (this.type === tt.name) { if (expr.name === "interface") { return this.flow_parseInterface(node); } else if (expr.name === "type") { return this.flow_parseTypeAlias(node); } } } return inner.call(this, node, expr); }; }); instance.extend("shouldParseExportDeclaration", function (inner) { return function () { return this.isContextual("type") || inner.call(this); }; }); instance.extend("parseParenItem", function (inner) { return function (node, start) { if (this.type === tt.colon) { var typeCastNode = this.startNodeAt(start); typeCastNode.expression = node; typeCastNode.typeAnnotation = this.flow_parseTypeAnnotation(); return this.finishNode(typeCastNode, "TypeCastExpression"); } else { return node; } }; }); instance.extend("parseClassId", function (inner) { return function (node, isStatement) { inner.call(this, node, isStatement); if (this.isRelational("<")) { node.typeParameters = this.flow_parseTypeParameterDeclaration(); } }; }); instance.extend("readToken", function (inner) { return function (code) { if (this.inType && (code === 62 || code === 60)) { return this.finishOp(tt.relational, 1); } else { return inner.call(this, code); } }; }); instance.extend("jsx_readToken", function (inner) { return function () { if (!this.inType) return inner.call(this); }; }); instance.extend("parseParenArrowList", function (inner) { return function (start, exprList, isAsync) { for (var i = 0; i < exprList.length; i++) { var listItem = exprList[i]; if (listItem.type === "TypeCastExpression") { var expr = listItem.expression; expr.typeAnnotation = listItem.typeAnnotation; exprList[i] = expr; } } return inner.call(this, start, exprList, isAsync); }; }); instance.extend("parseClassProperty", function (inner) { return function (node) { if (this.type === tt.colon) { node.typeAnnotation = this.flow_parseTypeAnnotation(); } return inner.call(this, node); }; }); instance.extend("isClassProperty", function (inner) { return function () { return this.type === tt.colon || inner.call(this); }; }); instance.extend("parseClassMethod", function (inner) { return function (classBody, method, isGenerator, isAsync) { var typeParameters; if (this.isRelational("<")) { typeParameters = this.flow_parseTypeParameterDeclaration(); } method.value = this.parseMethod(isGenerator, isAsync); method.value.typeParameters = typeParameters; classBody.body.push(this.finishNode(method, "MethodDefinition")); }; }); instance.extend("parseClassSuper", function (inner) { return function (node, isStatement) { inner.call(this, node, isStatement); if (node.superClass && this.isRelational("<")) { node.superTypeParameters = this.flow_parseTypeParameterInstantiation(); } if (this.isContextual("implements")) { this.next(); var implemented = node["implements"] = []; do { var node = this.startNode(); node.id = this.parseIdent(); if (this.isRelational("<")) { node.typeParameters = this.flow_parseTypeParameterInstantiation(); } else { node.typeParameters = null; } implemented.push(this.finishNode(node, "ClassImplements")); } while (this.eat(tt.comma)); } }; }); instance.extend("parseObjPropValue", function (inner) { return function (prop) { var typeParameters; if (this.isRelational("<")) { typeParameters = this.flow_parseTypeParameterDeclaration(); if (this.type !== tt.parenL) this.unexpected(); } inner.apply(this, arguments); prop.value.typeParameters = typeParameters; }; }); instance.extend("parseAssignableListItemTypes", function (inner) { return function (param) { if (this.eat(tt.question)) { param.optional = true; } if (this.type === tt.colon) { param.typeAnnotation = this.flow_parseTypeAnnotation(); } this.finishNode(param, param.type); return param; }; }); instance.extend("parseImportSpecifiers", function (inner) { return function (node) { node.isType = false; if (this.isContextual("type")) { var start = this.markPosition(); var typeId = this.parseIdent(); if (this.type === tt.name && this.value !== "from" || this.type === tt.braceL || this.type === tt.star) { node.isType = true; } else { node.specifiers.push(this.parseImportSpecifierDefault(typeId, start)); if (this.isContextual("from")) return; this.eat(tt.comma); } } inner.call(this, node); }; }); // function foo() {} instance.extend("parseFunctionParams", function (inner) { return function (node) { if (this.isRelational("<")) { node.typeParameters = this.flow_parseTypeParameterDeclaration(); } inner.call(this, node); }; }); // var foo: string = bar instance.extend("parseVarHead", function (inner) { return function (decl) { inner.call(this, decl); if (this.type === tt.colon) { decl.id.typeAnnotation = this.flow_parseTypeAnnotation(); this.finishNode(decl.id, decl.id.type); } }; }); }; },{"../src/index":5}],3:[function(require,module,exports){ // A recursive descent parser operates by defining functions for all // syntactic elements, and recursively calling those, each function // advancing the input stream and returning an AST node. Precedence // of constructs (for example, the fact that `!x[1]` means `!(x[1])` // instead of `(!x)[1]` is handled by the fact that the parser // function that parses unary prefix operators is called first, and // in turn calls the function that parses `[]` subscripts — that // way, it'll receive the node for `x[1]` already parsed, and wraps // *that* in the unary operator node. // // Acorn uses an [operator precedence parser][opp] to handle binary // operator precedence, because it is much more compact than using // the technique outlined above, which uses different, nesting // functions to specify precedence, for all of the ten binary // precedence levels that JavaScript defines. // // [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser "use strict"; var _tokentype = require("./tokentype"); var _state = require("./state"); var _identifier = require("./identifier"); var _util = require("./util"); var pp = _state.Parser.prototype; // Check if property name clashes with already added. // Object/class getters and setters are not allowed to clash — // either with each other or with an init property — and in // strict mode, init properties are also not allowed to be repeated. pp.checkPropClash = function (prop, propHash) { if (this.options.ecmaVersion >= 6) return; var key = prop.key, name = undefined; switch (key.type) { case "Identifier": name = key.name;break; case "Literal": name = String(key.value);break; default: return; } var kind = prop.kind || "init", other = undefined; if ((0, _util.has)(propHash, name)) { other = propHash[name]; var isGetSet = kind !== "init"; if ((this.strict || isGetSet) && other[kind] || !(isGetSet ^ other.init)) this.raise(key.start, "Redefinition of property"); } else { other = propHash[name] = { init: false, get: false, set: false }; } other[kind] = true; }; // ### Expression parsing // These nest, from the most general expression type at the top to // 'atomic', nondivisible expression types at the bottom. Most of // the functions will simply let the function(s) below them parse, // and, *if* the syntactic construct they handle is present, wrap // the AST node that the inner parser gave them in another node. // Parse a full expression. The optional arguments are used to // forbid the `in` operator (in for loops initalization expressions) // and provide reference for storing '=' operator inside shorthand // property assignment in contexts where both object expression // and object pattern might appear (so it's possible to raise // delayed syntax error at correct position). pp.parseExpression = function (noIn, refShorthandDefaultPos) { var start = this.markPosition(); var expr = this.parseMaybeAssign(noIn, refShorthandDefaultPos); if (this.type === _tokentype.types.comma) { var node = this.startNodeAt(start); node.expressions = [expr]; while (this.eat(_tokentype.types.comma)) node.expressions.push(this.parseMaybeAssign(noIn, refShorthandDefaultPos)); return this.finishNode(node, "SequenceExpression"); } return expr; }; // Parse an assignment expression. This includes applications of // operators like `+=`. pp.parseMaybeAssign = function (noIn, refShorthandDefaultPos, afterLeftParse) { if (this.type == _tokentype.types._yield && this.inGenerator) return this.parseYield(); var failOnShorthandAssign = undefined; if (!refShorthandDefaultPos) { refShorthandDefaultPos = { start: 0 }; failOnShorthandAssign = true; } else { failOnShorthandAssign = false; } var start = this.markPosition(); if (this.type == _tokentype.types.parenL || this.type == _tokentype.types.name) this.potentialArrowAt = this.start; var left = this.parseMaybeConditional(noIn, refShorthandDefaultPos); if (afterLeftParse) left = afterLeftParse.call(this, left, start); if (this.type.isAssign) { var node = this.startNodeAt(start); node.operator = this.value; node.left = this.type === _tokentype.types.eq ? this.toAssignable(left) : left; refShorthandDefaultPos.start = 0; // reset because shorthand default was used correctly this.checkLVal(left); if (left.parenthesizedExpression) { var errorMsg = undefined; if (left.type === "ObjectPattern") { errorMsg = "`({a}) = 0` use `({a} = 0)`"; } else if (left.type === "ArrayPattern") { errorMsg = "`([a]) = 0` use `([a] = 0)`"; } if (errorMsg) { this.raise(left.start, "You're trying to assign to a parenthesized expression, eg. instead of " + errorMsg); } } this.next(); node.right = this.parseMaybeAssign(noIn); return this.finishNode(node, "AssignmentExpression"); } else if (failOnShorthandAssign && refShorthandDefaultPos.start) { this.unexpected(refShorthandDefaultPos.start); } return left; }; // Parse a ternary conditional (`?:`) operator. pp.parseMaybeConditional = function (noIn, refShorthandDefaultPos) { var start = this.markPosition(); var expr = this.parseExprOps(noIn, refShorthandDefaultPos); if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr; if (this.eat(_tokentype.types.question)) { var node = this.startNodeAt(start); node.test = expr; node.consequent = this.parseMaybeAssign(); this.expect(_tokentype.types.colon); node.alternate = this.parseMaybeAssign(noIn); return this.finishNode(node, "ConditionalExpression"); } return expr; }; // Start the precedence parser. pp.parseExprOps = function (noIn, refShorthandDefaultPos) { var start = this.markPosition(); var expr = this.parseMaybeUnary(refShorthandDefaultPos); if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr; return this.parseExprOp(expr, start, -1, noIn); }; // Parse binary operators with the operator precedence parsing // algorithm. `left` is the left-hand side of the operator. // `minPrec` provides context that allows the function to stop and // defer further parser to one of its callers when it encounters an // operator that has a lower precedence than the set it is parsing. pp.parseExprOp = function (left, leftStart, minPrec, noIn) { var prec = this.type.binop; if (prec != null && (!noIn || this.type !== _tokentype.types._in)) { if (prec > minPrec) { var node = this.startNodeAt(leftStart); node.left = left; node.operator = this.value; var op = this.type; this.next(); var _start = this.markPosition(); node.right = this.parseExprOp(this.parseMaybeUnary(), _start, op.rightAssociative ? prec - 1 : prec, noIn); this.finishNode(node, op === _tokentype.types.logicalOR || op === _tokentype.types.logicalAND ? "LogicalExpression" : "BinaryExpression"); return this.parseExprOp(node, leftStart, minPrec, noIn); } } return left; }; // Parse unary operators, both prefix and postfix. pp.parseMaybeUnary = function (refShorthandDefaultPos) { if (this.type.prefix) { var node = this.startNode(), update = this.type === _tokentype.types.incDec; node.operator = this.value; node.prefix = true; this.next(); node.argument = this.parseMaybeUnary(); if (refShorthandDefaultPos && refShorthandDefaultPos.start) this.unexpected(refShorthandDefaultPos.start); 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"); } var start = this.markPosition(); var expr = this.parseExprSubscripts(refShorthandDefaultPos); if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr; while (this.type.postfix && !this.canInsertSemicolon()) { var node = this.startNodeAt(start); node.operator = this.value; node.prefix = false; node.argument = expr; this.checkLVal(expr); this.next(); expr = this.finishNode(node, "UpdateExpression"); } return expr; }; // Parse call, dot, and `[]`-subscript expressions. pp.parseExprSubscripts = function (refShorthandDefaultPos) { var start = this.markPosition(); var expr = this.parseExprAtom(refShorthandDefaultPos); if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr; return this.parseSubscripts(expr, start); }; pp.parseSubscripts = function (base, start, noCalls) { if (!noCalls && this.eat(_tokentype.types.doubleColon)) { var node = this.startNodeAt(start); node.object = base; node.callee = this.parseNoCallExpr(); return this.parseSubscripts(this.finishNode(node, "BindExpression"), start, noCalls); } else if (this.eat(_tokentype.types.dot)) { var node = this.startNodeAt(start); node.object = base; node.property = this.parseIdent(true); node.computed = false; return this.parseSubscripts(this.finishNode(node, "MemberExpression"), start, noCalls); } else if (this.eat(_tokentype.types.bracketL)) { var node = this.startNodeAt(start); node.object = base; node.property = this.parseExpression(); node.computed = true; this.expect(_tokentype.types.bracketR); return this.parseSubscripts(this.finishNode(node, "MemberExpression"), start, noCalls); } else if (!noCalls && this.eat(_tokentype.types.parenL)) { var node = this.startNodeAt(start); node.callee = base; node.arguments = this.parseExprList(_tokentype.types.parenR, this.options.features["es7.trailingFunctionCommas"]); return this.parseSubscripts(this.finishNode(node, "CallExpression"), start, noCalls); } else if (this.type === _tokentype.types.backQuote) { var node = this.startNodeAt(start); node.tag = base; node.quasi = this.parseTemplate(); return this.parseSubscripts(this.finishNode(node, "TaggedTemplateExpression"), start, noCalls); }return base; }; // Parse a no-call expression (like argument of `new` or `::` operators). pp.parseNoCallExpr = function () { var start = this.markPosition(); return this.parseSubscripts(this.parseExprAtom(), start, true); }; // Parse an atomic expression — either a single token that is an // expression, an expression started by a keyword like `function` or // `new`, or an expression wrapped in punctuation like `()`, `[]`, // or `{}`. pp.parseExprAtom = function (refShorthandDefaultPos) { var node = undefined, canBeArrow = this.potentialArrowAt == this.start; switch (this.type) { case _tokentype.types._this: case _tokentype.types._super: var type = this.type === _tokentype.types._this ? "ThisExpression" : "Super"; node = this.startNode(); this.next(); return this.finishNode(node, type); case _tokentype.types._yield: if (this.inGenerator) this.unexpected(); case _tokentype.types._do: if (this.options.features["es7.doExpressions"]) { var _node = this.startNode(); this.next(); _node.body = this.parseBlock(); return this.finishNode(_node, "DoExpression"); } case _tokentype.types.name: var start = this.markPosition(); node = this.startNode(); var id = this.parseIdent(this.type !== _tokentype.types.name); // if (this.options.features["es7.asyncFunctions"]) { // async functions! if (id.name === "async") { // arrow functions if (this.type === _tokentype.types.parenL) { var expr = this.parseParenAndDistinguishExpression(start, true, true); if (expr && expr.type === "ArrowFunctionExpression") { return expr; } else { node.callee = id; if (!expr) { node.arguments = []; } else if (expr.type === "SequenceExpression") { node.arguments = expr.expressions; } else { node.arguments = [expr]; } return this.parseSubscripts(this.finishNode(node, "CallExpression"), start); } } else if (this.type === _tokentype.types.name) { id = this.parseIdent(); this.expect(_tokentype.types.arrow); return this.parseArrowExpression(node, [id], true); } // normal functions if (this.type === _tokentype.types._function && !this.canInsertSemicolon()) { this.next(); return this.parseFunction(node, false, false, true); } } else if (id.name === "await") { if (this.inAsync) return this.parseAwait(node); } } // if (canBeArrow && !this.canInsertSemicolon() && this.eat(_tokentype.types.arrow)) return this.parseArrowExpression(this.startNodeAt(start), [id]); return id; case _tokentype.types.regexp: var value = this.value; node = this.parseLiteral(value.value); node.regex = { pattern: value.pattern, flags: value.flags }; return node; case _tokentype.types.num:case _tokentype.types.string: return this.parseLiteral(this.value); case _tokentype.types._null:case _tokentype.types._true:case _tokentype.types._false: node = this.startNode(); node.value = this.type === _tokentype.types._null ? null : this.type === _tokentype.types._true; node.raw = this.type.keyword; this.next(); return this.finishNode(node, "Literal"); case _tokentype.types.parenL: return this.parseParenAndDistinguishExpression(null, null, canBeArrow); case _tokentype.types.bracketL: node = this.startNode(); this.next(); // check whether this is array comprehension or regular array if ((this.options.ecmaVersion >= 7 || this.options.features["es7.comprehensions"]) && this.type === _tokentype.types._for) { return this.parseComprehension(node, false); } node.elements = this.parseExprList(_tokentype.types.bracketR, true, true, refShorthandDefaultPos); return this.finishNode(node, "ArrayExpression"); case _tokentype.types.braceL: return this.parseObj(false, refShorthandDefaultPos); case _tokentype.types._function: node = this.startNode(); this.next(); return this.parseFunction(node, false); case _tokentype.types.at: this.parseDecorators(); case _tokentype.types._class: node = this.startNode(); this.takeDecorators(node); return this.parseClass(node, false); case _tokentype.types._new: return this.parseNew(); case _tokentype.types.backQuote: return this.parseTemplate(); case _tokentype.types.doubleColon: node = this.startNode(); this.next(); node.object = null; var callee = node.callee = this.parseNoCallExpr(); if (callee.type !== "MemberExpression") this.raise(callee.start, "Binding should be performed on object property."); return this.finishNode(node, "BindExpression"); default: this.unexpected(); } }; pp.parseLiteral = function (value) { var node = this.startNode(); node.value = value; node.raw = this.input.slice(this.start, this.end); this.next(); return this.finishNode(node, "Literal"); }; pp.parseParenExpression = function () { this.expect(_tokentype.types.parenL); var val = this.parseExpression(); this.expect(_tokentype.types.parenR); return val; }; pp.parseParenAndDistinguishExpression = function (start, isAsync, canBeArrow) { start = start || this.markPosition(); var val = undefined; if (this.options.ecmaVersion >= 6) { this.next(); if ((this.options.features["es7.comprehensions"] || this.options.ecmaVersion >= 7) && this.type === _tokentype.types._for) { return this.parseComprehension(this.startNodeAt(start), true); } var innerStart = this.markPosition(), exprList = [], first = true; var refShorthandDefaultPos = { start: 0 }, spreadStart = undefined, innerParenStart = undefined; while (this.type !== _tokentype.types.parenR) { first ? first = false : this.expect(_tokentype.types.comma); if (this.type === _tokentype.types.ellipsis) { var spreadNodeStart = this.markPosition(); spreadStart = this.start; exprList.push(this.parseParenItem(this.parseRest(), spreadNodeStart)); break; } else { if (this.type === _tokentype.types.parenL && !innerParenStart) { innerParenStart = this.start; } exprList.push(this.parseMaybeAssign(false, refShorthandDefaultPos, this.parseParenItem)); } } var innerEnd = this.markPosition(); this.expect(_tokentype.types.parenR); if (canBeArrow && !this.canInsertSemicolon() && this.eat(_tokentype.types.arrow)) { if (innerParenStart) this.unexpected(innerParenStart); return this.parseParenArrowList(start, exprList, isAsync); } if (!exprList.length) { if (isAsync) { return; } else { this.unexpected(this.lastTokStart); } } if (spreadStart) this.unexpected(spreadStart); if (refShorthandDefaultPos.start) this.unexpected(refShorthandDefaultPos.start); if (exprList.length > 1) { val = this.startNodeAt(innerStart); val.expressions = exprList; this.finishNodeAt(val, "SequenceExpression", innerEnd); } else { val = exprList[0]; } } else { val = this.parseParenExpression(); } if (this.options.preserveParens) { var par = this.startNodeAt(start); par.expression = val; return this.finishNode(par, "ParenthesizedExpression"); } else { val.parenthesizedExpression = true; return val; } }; pp.parseParenArrowList = function (start, exprList, isAsync) { return this.parseArrowExpression(this.startNodeAt(start), exprList, isAsync); }; pp.parseParenItem = function (node, start) { return node; }; // New's precedence is slightly tricky. It must allow its argument // to be a `[]` or dot subscript expression, but not a call — at // least, not without wrapping it in parentheses. Thus, it uses the var empty = []; pp.parseNew = function () { var node = this.startNode(); var meta = this.parseIdent(true); if (this.options.ecmaVersion >= 6 && this.eat(_tokentype.types.dot)) { node.meta = meta; 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"); return this.finishNode(node, "MetaProperty"); } node.callee = this.parseNoCallExpr(); if (this.eat(_tokentype.types.parenL)) node.arguments = this.parseExprList(_tokentype.types.parenR, this.options.features["es7.trailingFunctionCommas"]);else node.arguments = empty; return this.finishNode(node, "NewExpression"); }; // Parse template expression. pp.parseTemplateElement = function () { var elem = this.startNode(); elem.value = { raw: this.input.slice(this.start, this.end), cooked: this.value }; this.next(); elem.tail = this.type === _tokentype.types.backQuote; return this.finishNode(elem, "TemplateElement"); }; pp.parseTemplate = function () { var node = this.startNode(); this.next(); node.expressions = []; var curElt = this.parseTemplateElement(); node.quasis = [curElt]; while (!curElt.tail) { this.expect(_tokentype.types.dollarBraceL); node.expressions.push(this.parseExpression()); this.expect(_tokentype.types.braceR); node.quasis.push(curElt = this.parseTemplateElement()); } this.next(); return this.finishNode(node, "TemplateLiteral"); }; // Parse an object literal or binding pattern. pp.parseObj = function (isPattern, refShorthandDefaultPos) { var node = this.startNode(), first = true, propHash = {}; node.properties = []; var decorators = []; this.next(); while (!this.eat(_tokentype.types.braceR)) { if (!first) { this.expect(_tokentype.types.comma); if (this.afterTrailingComma(_tokentype.types.braceR)) break; } else first = false; while (this.type === _tokentype.types.at) { decorators.push(this.parseDecorator()); } var prop = this.startNode(), isGenerator = false, isAsync = false, _start2 = undefined; if (decorators.length) { prop.decorators = decorators; decorators = []; } if (this.options.features["es7.objectRestSpread"] && this.type === _tokentype.types.ellipsis) { prop = this.parseSpread(); prop.type = "SpreadProperty"; node.properties.push(prop); continue; } if (this.options.ecmaVersion >= 6) { prop.method = false; prop.shorthand = false; if (isPattern || refShorthandDefaultPos) _start2 = this.markPosition(); if (!isPattern) isGenerator = this.eat(_tokentype.types.star); } if (this.options.features["es7.asyncFunctions"] && this.isContextual("async")) { if (isGenerator || isPattern) this.unexpected(); var asyncId = this.parseIdent(); if (this.type === _tokentype.types.colon || this.type === _tokentype.types.parenL) { prop.key = asyncId; } else { isAsync = true; this.parsePropertyName(prop); } } else { this.parsePropertyName(prop); } this.parseObjPropValue(prop, _start2, isGenerator, isAsync, isPattern, refShorthandDefaultPos); this.checkPropClash(prop, propHash); node.properties.push(this.finishNode(prop, "Property")); } if (decorators.length) { this.raise(this.start, "You have trailing decorators with no property"); } return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression"); }; pp.parseObjPropValue = function (prop, start, isGenerator, isAsync, isPattern, refShorthandDefaultPos) { if (this.eat(_tokentype.types.colon)) { prop.value = isPattern ? this.parseMaybeDefault() : this.parseMaybeAssign(false, refShorthandDefaultPos); prop.kind = "init"; } else if (this.options.ecmaVersion >= 6 && this.type === _tokentype.types.parenL) { if (isPattern) this.unexpected(); prop.kind = "init"; prop.method = true; prop.value = this.parseMethod(isGenerator, isAsync); } else if (this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && (this.type != _tokentype.types.comma && this.type != _tokentype.types.braceR)) { if (isGenerator || isAsync || isPattern) this.unexpected(); prop.kind = prop.key.name; this.parsePropertyName(prop); prop.value = this.parseMethod(false); } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { prop.kind = "init"; 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); prop.value = this.parseMaybeDefault(start, prop.key); } else if (this.type === _tokentype.types.eq && refShorthandDefaultPos) { if (!refShorthandDefaultPos.start) refShorthandDefaultPos.start = this.start; prop.value = this.parseMaybeDefault(start, prop.key); } else { prop.value = prop.key; } prop.shorthand = true; } else this.unexpected(); }; pp.parsePropertyName = function (prop) { if (this.options.ecmaVersion >= 6) { if (this.eat(_tokentype.types.bracketL)) { prop.computed = true; prop.key = this.parseMaybeAssign(); this.expect(_tokentype.types.bracketR); return; } else { prop.computed = false; } } prop.key = this.type === _tokentype.types.num || this.type === _tokentype.types.string ? this.parseExprAtom() : this.parseIdent(true); }; // Initialize empty function node. pp.initFunction = function (node, isAsync) { node.id = null; if (this.options.ecmaVersion >= 6) { node.generator = false; node.expression = false; } if (this.options.features["es7.asyncFunctions"]) { node.async = !!isAsync; } }; // Parse object or class method. pp.parseMethod = function (isGenerator, isAsync) { var node = this.startNode(); this.initFunction(node, isAsync); this.expect(_tokentype.types.parenL); node.params = this.parseBindingList(_tokentype.types.parenR, false, this.options.features["es7.trailingFunctionCommas"]); if (this.options.ecmaVersion >= 6) { node.generator = isGenerator; } this.parseFunctionBody(node); return this.finishNode(node, "FunctionExpression"); }; // Parse arrow function expression with given parameters. pp.parseArrowExpression = function (node, params, isAsync) { this.initFunction(node, isAsync); node.params = this.toAssignableList(params, true); this.parseFunctionBody(node, true); return this.finishNode(node, "ArrowFunctionExpression"); }; // Parse function body and check parameters. pp.parseFunctionBody = function (node, allowExpression) { var isExpression = allowExpression && this.type !== _tokentype.types.braceL; var oldInAsync = this.inAsync; this.inAsync = node.async; if (isExpression) { node.body = this.parseMaybeAssign(); node.expression = true; } else { // Start a new scope with regard to labels and the `inFunction` // flag (restore them to their old value afterwards). var oldInFunc = this.inFunction, oldInGen = this.inGenerator, oldLabels = this.labels; this.inFunction = true;this.inGenerator = node.generator;this.labels = []; node.body = this.parseBlock(true); node.expression = false; this.inFunction = oldInFunc;this.inGenerator = oldInGen;this.labels = oldLabels; } this.inAsync = oldInAsync; // If this is a strict mode function, verify that argument names // are not repeated, and it does not try to bind the words `eval` // or `arguments`. if (this.strict || !isExpression && node.body.body.length && this.isUseStrict(node.body.body[0])) { var nameHash = {}, oldStrict = this.strict; this.strict = true; if (node.id) this.checkLVal(node.id, true); for (var i = 0; i < node.params.length; i++) { this.checkLVal(node.params[i], true, nameHash); }this.strict = oldStrict; } }; // Parses a comma-separated list of expressions, and returns them as // an array. `close` is the token type that ends the list, and // `allowEmpty` can be turned on to allow subsequent commas with // nothing in between them to be parsed as `null` (which is needed // for array literals). pp.parseExprList = function (close, allowTrailingComma, allowEmpty, refShorthandDefaultPos) { var elts = [], first = true; while (!this.eat(close)) { if (!first) { this.expect(_tokentype.types.comma); if (allowTrailingComma && this.afterTrailingComma(close)) break; } else first = false; if (allowEmpty && this.type === _tokentype.types.comma) { elts.push(null); } else { if (this.type === _tokentype.types.ellipsis) elts.push(this.parseSpread(refShorthandDefaultPos));else elts.push(this.parseMaybeAssign(false, refShorthandDefaultPos)); } } return elts; }; // Parse the next token as an identifier. If `liberal` is true (used // when parsing properties), it will also convert keywords into // identifiers. pp.parseIdent = function (liberal) { var node = this.startNode(); if (liberal && this.options.allowReserved == "never") liberal = false; 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"); node.name = this.value; } else if (liberal && this.type.keyword) { node.name = this.type.keyword; } else { this.unexpected(); } this.next(); return this.finishNode(node, "Identifier"); }; // Parses await expression inside async function. pp.parseAwait = function (node) { if (this.eat(_tokentype.types.semi) || this.canInsertSemicolon()) { this.unexpected(); } node.all = this.eat(_tokentype.types.star); node.argument = this.parseMaybeUnary(); return this.finishNode(node, "AwaitExpression"); }; // Parses yield expression inside generator. pp.parseYield = function () { var node = this.startNode(); this.next(); if (this.type == _tokentype.types.semi || this.canInsertSemicolon() || this.type != _tokentype.types.star && !this.type.startsExpr) { node.delegate = false; node.argument = null; } else { node.delegate = this.eat(_tokentype.types.star); node.argument = this.parseMaybeAssign(); } return this.finishNode(node, "YieldExpression"); }; // Parses array and generator comprehensions. pp.parseComprehension = function (node, isGenerator) { node.blocks = []; while (this.type === _tokentype.types._for) { var block = this.startNode(); this.next(); this.expect(_tokentype.types.parenL); block.left = this.parseBindingAtom(); this.checkLVal(block.left, true); this.expectContextual("of"); block.right = this.parseExpression(); this.expect(_tokentype.types.parenR); node.blocks.push(this.finishNode(block, "ComprehensionBlock")); } node.filter = this.eat(_tokentype.types._if) ? this.parseParenExpression() : null; node.body = this.parseExpression(); this.expect(isGenerator ? _tokentype.types.parenR : _tokentype.types.bracketR); node.generator = isGenerator; return this.finishNode(node, "ComprehensionExpression"); }; },{"./identifier":4,"./state":12,"./tokentype":16,"./util":17}],4:[function(require,module,exports){ "use strict"; exports.__esModule = true; // Test whether a given character code starts an identifier. exports.isIdentifierStart = isIdentifierStart; // Test whether a given character is part of an identifier. exports.isIdentifierChar = isIdentifierChar; // 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 // predicate containing a big ugly `switch` statement is faster than // a regular expression, and on Chrome the two are about on par. // This function uses `eval` (non-lexical) to produce such a // predicate from a space-separated string of words. // // It starts by sorting the words by length. function makePredicate(words) { words = words.split(" "); return function (str) { return words.indexOf(str) >= 0; }; } // Reserved word lists for various dialects of the language var reservedWords = { 3: makePredicate("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: makePredicate("class enum extends super const export import"), 6: makePredicate("enum await"), strict: makePredicate("implements interface let package private protected public static yield"), strictBind: makePredicate("eval arguments") }; exports.reservedWords = reservedWords; // And the keywords 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 = { 5: makePredicate(ecma5AndLessKeywords), 6: makePredicate(ecma5AndLessKeywords + " let const class extends export import yield super") }; exports.keywords = keywords; // ## Character categories // Big ugly regular expressions that match characters in the // whitespace, identifier, and identifier-start categories. These // are only applied when a character is found to actually have a // code point above 128. // Generated by `tools/generate-identifier-regex.js`. var nonASCIIidentifierStartChars = "ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠ-ࢲऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ"; var nonASCIIidentifierChars = "‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣤ-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఃా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ູົຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏ᦰ-ᧀᧈᧉ᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷼-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-꣄꣐-꣙꣠-꣱꤀-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︭︳︴﹍-﹏0-9_"; var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; // These are a run-length and offset encoded representation of the // >0xffff code points that are a valid part of identifiers. The // offset starts at 0x10000, and each pair of numbers represents an // offset to the next range, and then a size of the range. They were // generated by tools/generate-identifier-regex.js var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 17, 26, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 99, 39, 9, 51, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 98, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 26, 45, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 955, 52, 76, 44, 33, 24, 27, 35, 42, 34, 4, 0, 13, 47, 15, 3, 22, 0, 38, 17, 2, 24, 133, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 32, 4, 287, 47, 21, 1, 2, 0, 185, 46, 82, 47, 21, 0, 60, 42, 502, 63, 32, 0, 449, 56, 1288, 920, 104, 110, 2962, 1070, 13266, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 881, 68, 12, 0, 67, 12, 16481, 1, 3071, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 4149, 196, 1340, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42710, 42, 4148, 12, 221, 16355, 541]; var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 1306, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 52, 0, 13, 2, 49, 13, 16, 9, 83, 11, 168, 11, 6, 9, 8, 2, 57, 0, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 316, 19, 13, 9, 214, 6, 3, 8, 112, 16, 16, 9, 82, 12, 9, 9, 535, 9, 20855, 9, 135, 4, 60, 6, 26, 9, 1016, 45, 17, 3, 19723, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 4305, 6, 792618, 239]; // This has a complexity linear to the value of the code. The // assumption is that looking up astral identifier characters is // rare. function isInAstralSet(code, set) { var pos = 65536; for (var i = 0; i < set.length; i += 2) { pos += set[i]; if (pos > code) return false; pos += set[i + 1]; if (pos >= code) return true; } } function isIdentifierStart(code, astral) { if (code < 65) return code === 36; if (code < 91) return true; if (code < 97) return code === 95; if (code < 123) return true; if (code <= 65535) return code >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code)); if (astral === false) return false; return isInAstralSet(code, astralIdentifierStartCodes); } function isIdentifierChar(code, astral) { if (code < 48) return code === 36; if (code < 58) return true; if (code < 65) return false; if (code < 91) return true; if (code < 97) return code === 95; if (code < 123) return true; if (code <= 65535) return code >= 170 && nonASCIIidentifier.test(String.fromCharCode(code)); if (astral === false) return false; return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); } },{}],5:[function(require,module,exports){ // Acorn is a tiny, fast JavaScript parser written in JavaScript. // // Acorn was written by Marijn Haverbeke, Ingvar Stepanyan, and // various contributors and released under an MIT license. // // Git repositories for Acorn are available at // // http://marijnhaverbeke.nl/git/acorn // https://github.com/marijnh/acorn.git // // Please use the [github bug tracker][ghbt] to report issues. // // [ghbt]: https://github.com/marijnh/acorn/issues // // This file defines the main parser interface. The library also comes // with a [error-tolerant parser][dammit] and an // [abstract syntax tree walker][walk], defined in other files. // // [dammit]: acorn_loose.js // [walk]: util/walk.js "use strict"; exports.__esModule = true; // The main exported interface (under `self.acorn` when in the // browser) is a `parse` function that takes a code string and // returns an abstract syntax tree as specified by [Mozilla parser // API][api]. // // [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API exports.parse = parse; // This function tries to parse a single expression at a given // offset in a string. Useful for parsing mixed-language formats // that embed JavaScript expressions. exports.parseExpressionAt = parseExpressionAt; // Acorn is organized as a tokenizer and a recursive-descent parser. // The `tokenize` export provides an interface to the tokenizer. // Because the tokenizer is optimized for being efficiently used by // the Acorn parser itself, this interface is somewhat crude and not // very modular. exports.tokenizer = tokenizer; var _state = require("./state"); var _options = require("./options"); require("./parseutil"); require("./statement"); require("./lval"); require("./expression"); require("./lookahead"); exports.Parser = _state.Parser; exports.plugins = _state.plugins; exports.defaultOptions = _options.defaultOptions; var _location = require("./location"); exports.SourceLocation = _location.SourceLocation; exports.getLineInfo = _location.getLineInfo; var _node = require("./node"); exports.Node = _node.Node; var _tokentype = require("./tokentype"); exports.TokenType = _tokentype.TokenType; exports.tokTypes = _tokentype.types; var _tokencontext = require("./tokencontext"); exports.TokContext = _tokencontext.TokContext; exports.tokContexts = _tokencontext.types; var _identifier = require("./identifier"); exports.isIdentifierChar = _identifier.isIdentifierChar; exports.isIdentifierStart = _identifier.isIdentifierStart; var _tokenize = require("./tokenize"); exports.Token = _tokenize.Token; var _whitespace = require("./whitespace"); exports.isNewLine = _whitespace.isNewLine; exports.lineBreak = _whitespace.lineBreak; exports.lineBreakG = _whitespace.lineBreakG; var version = "1.0.0";exports.version = version; function parse(input, options) { var p = parser(options, input); var startPos = p.options.locations ? [p.pos, p.curPosition()] : p.pos; p.nextToken(); return p.parseTopLevel(p.options.program || p.startNodeAt(startPos)); } function parseExpressionAt(input, pos, options) { var p = parser(options, input, pos); p.nextToken(); return p.parseExpression(); } function tokenizer(input, options) { return parser(options, input); } function parser(options, input) { return new _state.Parser((0, _options.getOptions)(options), String(input)); } },{"./expression":3,"./identifier":4,"./location":6,"./lookahead":7,"./lval":8,"./node":9,"./options":10,"./parseutil":11,"./state":12,"./statement":13,"./tokencontext":14,"./tokenize":15,"./tokentype":16,"./whitespace":18}],6:[function(require,module,exports){ "use strict"; exports.__esModule = true; // The `getLineInfo` function is mostly useful when the // `locations` option is off (for performance reasons) and you // want to find the line/column position for a given character // offset. `input` should be the code string that the offset refers // into. exports.getLineInfo = getLineInfo; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _state = require("./state"); var _whitespace = require("./whitespace"); // These are used when `options.locations` is on, for the // `startLoc` and `endLoc` properties. var Position = (function () { function Position(line, col) { _classCallCheck(this, Position); this.line = line; this.column = col; } Position.prototype.offset = function offset(n) { return new Position(this.line, this.column + n); }; return Position; })(); exports.Position = Position; var SourceLocation = function SourceLocation(p, start, end) { _classCallCheck(this, SourceLocation); this.start = start; this.end = end; if (p.sourceFile !== null) this.source = p.sourceFile; }; exports.SourceLocation = SourceLocation; function getLineInfo(input, offset) { for (var line = 1, cur = 0;;) { _whitespace.lineBreakG.lastIndex = cur; var match = _whitespace.lineBreakG.exec(input); if (match && match.index < offset) { ++line; cur = match.index + match[0].length; } else { return new Position(line, offset - cur); } } } var pp = _state.Parser.prototype; // This function is used to raise exceptions on parse errors. It // takes an offset integer (into the current `input`) to indicate // the location of the error, attaches the position to the end // of the error message, and then raises a `SyntaxError` with that // message. pp.raise = function (pos, message) { var loc = getLineInfo(this.input, pos); message += " (" + loc.line + ":" + loc.column + ")"; var err = new SyntaxError(message); err.pos = pos;err.loc = loc;err.raisedAt = this.pos; throw err; }; pp.curPosition = function () { return new Position(this.curLine, this.pos - this.lineStart); }; pp.markPosition = function () { return this.options.locations ? [this.start, this.startLoc] : this.start; }; },{"./state":12,"./whitespace":18}],7:[function(require,module,exports){ "use strict"; var _state = require("./state"); var pp = _state.Parser.prototype; var STATE_KEYS = ["lastTokStartLoc", "lastTokEndLoc", "lastTokStart", "lastTokEnd", "lineStart", "startLoc", "endLoc", "start", "pos", "end", "type", "value", "exprAllowed", "potentialArrowAt", "currLine", "input"]; pp.getState = function () { var state = {}; for (var i = 0; i < STATE_KEYS.length; i++) { var key = STATE_KEYS[i]; state[key] = this[key]; } state.context = this.context.slice(); return state; }; pp.lookahead = function () { var old = this.getState(); this.isLookahead = true; this.next(); this.isLookahead = false; var curr = this.getState(); for (var key in old) this[key] = old[key]; return curr; }; },{"./state":12}],8:[function(require,module,exports){ "use strict"; var _tokentype = require("./tokentype"); var _state = require("./state"); var _identifier = require("./identifier"); var _util = require("./util"); var pp = _state.Parser.prototype; // Convert existing expression atom to assignable pattern // if possible. pp.toAssignable = function (node, isBinding) { if (this.options.ecmaVersion >= 6 && node) { switch (node.type) { case "Identifier": case "ObjectPattern": case "ArrayPattern": case "AssignmentPattern": break; case "ObjectExpression": node.type = "ObjectPattern"; for (var i = 0; i < node.properties.length; i++) { var prop = node.properties[i]; if (prop.type === "SpreadProperty") continue; if (prop.kind !== "init") this.raise(prop.key.start, "Object pattern can't contain getter or setter"); this.toAssignable(prop.value, isBinding); } break; case "ArrayExpression": node.type = "ArrayPattern"; this.toAssignableList(node.elements, isBinding); break; case "AssignmentExpression": if (node.operator === "=") { node.type = "AssignmentPattern"; } else { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); } break; case "MemberExpression": if (!isBinding) break; default: this.raise(node.start, "Assigning to rvalue"); } } return node; }; // Convert list of expression atoms to binding list. pp.toAssignableList = function (exprList, isBinding) { var end = exprList.length; if (end) { var last = exprList[end - 1]; if (last && last.type == "RestElement") { --end; } else if (last && last.type == "SpreadElement") { last.type = "RestElement"; var arg = last.argument; this.toAssignable(arg, isBinding); if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern") this.unexpected(arg.start); --end; } } for (var i = 0; i < end; i++) { var elt = exprList[i]; if (elt) this.toAssignable(elt, isBinding); } return exprList; }; // Parses spread element. pp.parseSpread = function (refShorthandDefaultPos) { var node = this.startNode(); this.next(); node.argument = this.parseMaybeAssign(refShorthandDefaultPos); return this.finishNode(node, "SpreadElement"); }; pp.parseRest = function () { var node = this.startNode(); this.next(); node.argument = this.type === _tokentype.types.name || this.type === _tokentype.types.bracketL ? this.parseBindingAtom() : this.unexpected(); return this.finishNode(node, "RestElement"); }; // Parses lvalue (assignable) atom. pp.parseBindingAtom = function () { if (this.options.ecmaVersion < 6) return this.parseIdent(); switch (this.type) { case _tokentype.types.name: return this.parseIdent(); case _tokentype.types.bracketL: var node = this.startNode(); this.next(); node.elements = this.parseBindingList(_tokentype.types.bracketR, true, true); return this.finishNode(node, "ArrayPattern"); case _tokentype.types.braceL: return this.parseObj(true); default: this.unexpected(); } }; pp.parseBindingList = function (close, allowEmpty, allowTrailingComma) { var elts = [], first = true; while (!this.eat(close)) { if (first) first = false;else this.expect(_tokentype.types.comma); if (allowEmpty && this.type === _tokentype.types.comma) { elts.push(null); } else if (allowTrailingComma && this.afterTrailingComma(close)) { break; } else if (this.type === _tokentype.types.ellipsis) { elts.push(this.parseAssignableListItemTypes(this.parseRest())); this.expect(close); break; } else { var left = this.parseMaybeDefault(); this.parseAssignableListItemTypes(left); elts.push(this.parseMaybeDefault(null, left)); } } return elts; }; pp.parseAssignableListItemTypes = function (param) { return param; }; // Parses assignment pattern around given atom if possible. pp.parseMaybeDefault = function (startPos, left) { startPos = startPos || this.markPosition(); left = left || this.parseBindingAtom(); if (!this.eat(_tokentype.types.eq)) return left; var node = this.startNodeAt(startPos); node.operator = "="; node.left = left; node.right = this.parseMaybeAssign(); return this.finishNode(node, "AssignmentPattern"); }; // Verify that a node is an lval — something that can be assigned // to. pp.checkLVal = function (expr, isBinding, checkClashes) { switch (expr.type) { 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 (checkClashes) { if ((0, _util.has)(checkClashes, expr.name)) this.raise(expr.start, "Argument name clash in strict mode"); checkClashes[expr.name] = true; } break; case "MemberExpression": if (isBinding) this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " member expression"); break; case "ObjectPattern": for (var i = 0; i < expr.properties.length; i++) { var prop = expr.properties[i]; if (prop.type === "Property") prop = prop.value; this.checkLVal(prop, isBinding, checkClashes); } break; case "ArrayPattern": for (var i = 0; i < expr.elements.length; i++) { var elem = expr.elements[i]; if (elem) this.checkLVal(elem, isBinding, checkClashes); } break; case "AssignmentPattern": this.checkLVal(expr.left, isBinding, checkClashes); break; case "SpreadProperty": case "RestElement": this.checkLVal(expr.argument, isBinding, checkClashes); break; default: this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " rvalue"); } }; },{"./identifier":4,"./state":12,"./tokentype":16,"./util":17}],9:[function(require,module,exports){ "use strict"; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _state = require("./state"); var _location = require("./location"); // Start an AST node, attaching a start offset. var pp = _state.Parser.prototype; var Node = function Node() { _classCallCheck(this, Node); }; exports.Node = Node; pp.startNode = function () { var node = new Node(); node.start = this.start; if (this.options.locations) node.loc = new _location.SourceLocation(this, this.startLoc); if (this.options.directSourceFile) node.sourceFile = this.options.directSourceFile; if (this.options.ranges) node.range = [this.start, 0]; return node; }; pp.startNodeAt = function (pos) { var node = new Node(), start = pos; if (this.options.locations) { node.loc = new _location.SourceLocation(this, start[1]); start = pos[0]; } node.start = start; if (this.options.directSourceFile) node.sourceFile = this.options.directSourceFile; if (this.options.ranges) node.range = [start, 0]; return node; }; // Finish an AST node, adding `type` and `end` properties. pp.finishNode = function (node, type) { node.type = type; node.end = this.lastTokEnd; if (this.options.locations) node.loc.end = this.lastTokEndLoc; if (this.options.ranges) node.range[1] = this.lastTokEnd; return node; }; // Finish node at given position pp.finishNodeAt = function (node, type, pos) { if (this.options.locations) { node.loc.end = pos[1];pos = pos[0]; } node.type = type; node.end = pos; if (this.options.ranges) node.range[1] = pos; return node; }; },{"./location":6,"./state":12}],10:[function(require,module,exports){ "use strict"; exports.__esModule = true; // Interpret and default an options object exports.getOptions = getOptions; var _util = require("./util"); var _location = require("./location"); // A second optional argument can be given to further configure // the parser process. These options are recognized: var defaultOptions = { // `ecmaVersion` indicates the ECMAScript version to parse. Must // be either 3, or 5, or 6. This influences support for strict // mode, the set of reserved words, support for getters and // setters and other features. ecmaVersion: 5, // Source type ("script" or "module") for different semantics sourceType: "script", // `onInsertedSemicolon` can be a callback that will be called // when a semicolon is automatically inserted. It will be passed // th position of the comma as an offset, and if `locations` is // enabled, it is given the location as a `{line, column}` object // as second argument. onInsertedSemicolon: null, // `onTrailingComma` is similar to `onInsertedSemicolon`, but for // trailing commas. onTrailingComma: null, // By default, reserved words are not enforced. Disable // `allowReserved` to enforce them. When this option has the // value "never", reserved words and keywords can also not be // used as property names. allowReserved: true, // When enabled, a return at the top level is not considered an // error. allowReturnOutsideFunction: false, // When enabled, import/export statements are not constrained to // appearing at the top of the program. allowImportExportEverywhere: false, // When enabled, hashbang directive in the beginning of file // is allowed and treated as a line comment. allowHashBang: false, // When `locations` is on, `loc` properties holding objects with // `start` and `end` properties in `{line, column}` form (with // line being 1-based and column 0-based) will be attached to the // nodes. locations: false, // A function can be passed as `onToken` option, which will // cause Acorn to call that function with object in the same // format as tokenize() returns. Note that you are not // allowed to call the parser from the callback—that will // corrupt its internal state. onToken: null, // A function can be passed as `onComment` option, which will // cause Acorn to call that function with `(block, text, start, // end)` parameters whenever a comment is skipped. `block` is a // boolean indicating whether this is a block (`/* */`) comment, // `text` is the content of the comment, and `start` and `end` are // character offsets that denote the start and end of the comment. // When the `locations` option is on, two more parameters are // passed, the full `{line, column}` locations of the start and // end of the comments. Note that you are not allowed to call the // parser from the callback—that will corrupt its internal state. onComment: null, // Nodes have their start and end characters offsets recorded in // `start` and `end` properties (directly on the node, rather than // the `loc` object, which holds line/column data. To also add a // [semi-standardized][range] `range` property holding a `[start, // end]` array with the same numbers, set the `ranges` option to // `true`. // // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 ranges: false, // It is possible to parse multiple files into a single AST by // passing the tree produced by parsing the first file as // `program` option in subsequent parses. This will add the // toplevel forms of the parsed file to the `Program` (top) node // of an existing parse tree. program: null, // When `locations` is on, you can pass this to record the source // file in every node's `loc` object. sourceFile: null, // This value, if given, is stored in every node, whether // `locations` is on or off. directSourceFile: null, // When enabled, parenthesized expressions are represented by // (non-standard) ParenthesizedExpression nodes preserveParens: false, plugins: {}, // Babel-specific options features: {}, strictMode: null };exports.defaultOptions = defaultOptions; function getOptions(opts) { var options = {}; for (var opt in defaultOptions) { options[opt] = opts && (0, _util.has)(opts, opt) ? opts[opt] : defaultOptions[opt]; }if ((0, _util.isArray)(options.onToken)) { (function () { var tokens = options.onToken; options.onToken = function (token) { return tokens.push(token); }; })(); } if ((0, _util.isArray)(options.onComment)) options.onComment = pushComment(options, options.onComment); return options; } function pushComment(options, array) { return function (block, text, start, end, startLoc, endLoc) { var comment = { type: block ? "Block" : "Line", value: text, start: start, end: end }; if (options.locations) comment.loc = new _location.SourceLocation(this, startLoc, endLoc); if (options.ranges) comment.range = [start, end]; array.push(comment); }; } },{"./location":6,"./util":17}],11:[function(require,module,exports){ "use strict"; var _tokentype = require("./tokentype"); var _state = require("./state"); var _whitespace = require("./whitespace"); var pp = _state.Parser.prototype; // ## Parser utilities // Test whether a statement node is the string literal `"use strict"`. pp.isUseStrict = function (stmt) { return this.options.ecmaVersion >= 5 && stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && stmt.expression.value === "use strict"; }; // Predicate that tests whether the next token is of the given // type, and if yes, consumes it as a side effect. pp.eat = function (type) { if (this.type === type) { this.next(); return true; } else { return false; } }; // Tests whether parsed token is a contextual keyword. pp.isContextual = function (name) { return this.type === _tokentype.types.name && this.value === name; }; // Consumes contextual keyword if possible. pp.eatContextual = function (name) { return this.value === name && this.eat(_tokentype.types.name); }; // Asserts that following token is given contextual keyword. pp.expectContextual = function (name) { if (!this.eatContextual(name)) this.unexpected(); }; // Test whether a semicolon can be inserted at the current position. pp.canInsertSemicolon = function () { return this.type === _tokentype.types.eof || this.type === _tokentype.types.braceR || _whitespace.lineBreak.test(this.input.slice(this.lastTokEnd, this.start)); }; pp.insertSemicolon = function () { if (this.canInsertSemicolon()) { if (this.options.onInsertedSemicolon) this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); return true; } }; // Consume a semicolon, or, failing that, see if we are allowed to // pretend that there is a semicolon at this position. pp.semicolon = function () { if (!this.eat(_tokentype.types.semi) && !this.insertSemicolon()) this.unexpected(); }; pp.afterTrailingComma = function (tokType) { if (this.type == tokType) { if (this.options.onTrailingComma) this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); this.next(); return true; } }; // Expect a token of a given type. If found, consume it, otherwise, // raise an unexpected token error. pp.expect = function (type) { this.eat(type) || this.unexpected(); }; // Raise an unexpected token error. pp.unexpected = function (pos) { this.raise(pos != null ? pos : this.start, "Unexpected token"); }; },{"./state":12,"./tokentype":16,"./whitespace":18}],12:[function(require,module,exports){ "use strict"; exports.__esModule = true; exports.Parser = Parser; var _identifier = require("./identifier"); var _tokentype = require("./tokentype"); function Parser(options, input, startPos) { this.options = options; this.loadPlugins(this.options.plugins); this.sourceFile = this.options.sourceFile || null; this.isKeyword = _identifier.keywords[this.options.ecmaVersion >= 6 ? 6 : 5]; this.isReservedWord = _identifier.reservedWords[this.options.ecmaVersion]; this.input = input; // Set up token state // The current position of the tokenizer in the input. if (startPos) { this.pos = startPos; this.lineStart = Math.max(0, this.input.lastIndexOf("\n", startPos)); this.curLine = this.input.slice(0, this.lineStart).split(_tokentype.lineBreak).length; } else { this.pos = this.lineStart = 0; this.curLine = 1; } // Properties of the current token: // Its type this.type = _tokentype.types.eof; // For tokens that include more information than their type, the value this.value = null; // Its start and end offset this.start = this.end = this.pos; // And, if locations are used, the {line, column} object // corresponding to those offsets this.startLoc = this.endLoc = null; // Position information for the previous token this.lastTokEndLoc = this.lastTokStartLoc = null; this.lastTokStart = this.lastTokEnd = this.pos; // The context stack is used to superficially track syntactic // context to predict whether a regular expression is allowed in a // given position. this.context = this.initialContext(); this.exprAllowed = true; // Figure out if it's a module code. this.inModule = this.options.sourceType === "module"; this.strict = this.options.strictMode === false ? false : this.inModule; // Used to signify the start of a potential arrow function this.potentialArrowAt = -1; // Flags to track whether we are in a function, a generator. this.inFunction = this.inGenerator = false; // Labels in scope. this.labels = []; this.decorators = []; // If enabled, skip leading hashbang line. if (this.pos === 0 && this.options.allowHashBang && this.input.slice(0, 2) === "#!") this.skipLineComment(2); } Parser.prototype.extend = function (name, f) { this[name] = f(this[name]); }; // Registered plugins var plugins = {}; exports.plugins = plugins; Parser.prototype.loadPlugins = function (plugins) { for (var _name in plugins) { var plugin = exports.plugins[_name]; if (!plugin) throw new Error("Plugin '" + _name + "' not found"); plugin(this, plugins[_name]); } }; },{"./identifier":4,"./tokentype":16}],13:[function(require,module,exports){ "use strict"; var _tokentype = require("./tokentype"); var _state = require("./state"); var _whitespace = require("./whitespace"); var pp = _state.Parser.prototype; // ### Statement parsing // Parse a program. Initializes the parser, reads any number of // statements, and wraps them in a Program node. Optionally takes a // `program` argument. If present, the statements will be appended // to its body instead of creating a new node. pp.parseTopLevel = function (node) { var first = true; if (!node.body) node.body = []; while (this.type !== _tokentype.types.eof) { var stmt = this.parseStatement(true, true); node.body.push(stmt); if (first && this.isUseStrict(stmt)) this.setStrict(true); first = false; } this.next(); if (this.options.ecmaVersion >= 6) { node.sourceType = this.options.sourceType; } return this.finishNode(node, "Program"); }; var loopLabel = { kind: "loop" }, switchLabel = { kind: "switch" }; // Parse a single statement. // // If expecting a statement and finding a slash operator, parse a // regular expression literal. This is to handle cases like // `if (foo) /blah/.exec(foo)`, where looking at the previous token // does not help. pp.parseStatement = function (declaration, topLevel) { if (this.type === _tokentype.types.at) { this.parseDecorators(true); } var starttype = this.type, node = this.startNode(); // Most types of statements are recognized by the keyword they // start with. Many are trivial to parse, some require a bit of // complexity. switch (starttype) { case _tokentype.types._break:case _tokentype.types._continue: return this.parseBreakContinueStatement(node, starttype.keyword); case _tokentype.types._debugger: return this.parseDebuggerStatement(node); case _tokentype.types._do: return this.parseDoStatement(node); case _tokentype.types._for: return this.parseForStatement(node); case _tokentype.types._function: if (!declaration && this.options.ecmaVersion >= 6) this.unexpected(); return this.parseFunctionStatement(node); case _tokentype.types._class: if (!declaration) this.unexpected(); this.takeDecorators(node); return this.parseClass(node, true); case _tokentype.types._if: return this.parseIfStatement(node); case _tokentype.types._return: return this.parseReturnStatement(node); case _tokentype.types._switch: return this.parseSwitchStatement(node); case _tokentype.types._throw: return this.parseThrowStatement(node); case _tokentype.types._try: return this.parseTryStatement(node); case _tokentype.types._let:case _tokentype.types._const: if (!declaration) this.unexpected(); // NOTE: falls through to _var case _tokentype.types._var: return this.parseVarStatement(node, starttype); case _tokentype.types._while: return this.parseWhileStatement(node); case _tokentype.types._with: return this.parseWithStatement(node); case _tokentype.types.braceL: return this.parseBlock(); case _tokentype.types.semi: return this.parseEmptyStatement(node); case _tokentype.types._export: case _tokentype.types._import: if (!this.options.allowImportExportEverywhere) { 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'"); } return starttype === _tokentype.types._import ? this.parseImport(node) : this.parseExport(node); case _tokentype.types.name: if (this.options.features["es7.asyncFunctions"] && this.value === "async" && this.lookahead().type === _tokentype.types._function) { this.next(); this.expect(_tokentype.types._function); return this.parseFunction(node, true, false, true); } // If the statement does not start with a statement keyword or a // brace, it's an ExpressionStatement or LabeledStatement. We // simply start parsing an expression, and afterwards, if the // next token is a colon and the expression was a simple // Identifier node, we switch to interpreting it as a label. default: var maybeName = this.value, expr = this.parseExpression(); if (starttype === _tokentype.types.name && expr.type === "Identifier" && this.eat(_tokentype.types.colon)) return this.parseLabeledStatement(node, maybeName, expr);else return this.parseExpressionStatement(node, expr); } }; pp.takeDecorators = function (node) { if (this.decorators.length) { node.decorators = this.decorators; this.decorators = []; } }; pp.parseDecorators = function (allowExport) { while (this.type === _tokentype.types.at) { this.decorators.push(this.parseDecorator()); } if (allowExport && this.type === _tokentype.types._export) { return; } if (this.type !== _tokentype.types._class) { this.raise(this.start, "Leading decorators must be attached to a class declaration"); } }; pp.parseDecorator = function (allowExport) { if (!this.options.features["es7.decorators"]) { this.unexpected(); } var node = this.startNode(); this.next(); node.expression = this.parseMaybeAssign(); return this.finishNode(node, "Decorator"); }; pp.parseBreakContinueStatement = function (node, keyword) { var isBreak = keyword == "break"; this.next(); if (this.eat(_tokentype.types.semi) || this.insertSemicolon()) node.label = null;else if (this.type !== _tokentype.types.name) this.unexpected();else { node.label = this.parseIdent(); this.semicolon(); } // Verify that there is an actual destination to break or // continue to. for (var i = 0; i < this.labels.length; ++i) { var lab = this.labels[i]; if (node.label == null || lab.name === node.label.name) { if (lab.kind != null && (isBreak || lab.kind === "loop")) break; if (node.label && isBreak) break; } } if (i === this.labels.length) this.raise(node.start, "Unsyntactic " + keyword); return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement"); }; pp.parseDebuggerStatement = function (node) { this.next(); this.semicolon(); return this.finishNode(node, "DebuggerStatement"); }; pp.parseDoStatement = function (node) { var start = this.markPosition(); this.next(); this.labels.push(loopLabel); node.body = this.parseStatement(false); this.labels.pop(); if (this.options.features["es7.doExpressions"] && this.type !== _tokentype.types._while) { var container = this.startNodeAt(start); container.expression = this.finishNode(node, "DoExpression"); this.semicolon(); return this.finishNode(container, "ExpressionStatement"); } this.expect(_tokentype.types._while); node.test = this.parseParenExpression(); if (this.options.ecmaVersion >= 6) this.eat(_tokentype.types.semi);else this.semicolon(); return this.finishNode(node, "DoWhileStatement"); }; // Disambiguating between a `for` and a `for`/`in` or `for`/`of` // loop is non-trivial. Basically, we have to parse the init `var` // statement or expression, disallowing the `in` operator (see // the second parameter to `parseExpression`), and then check // whether the next token is `in` or `of`. When there is no init // part (semicolon immediately after the opening parenthesis), it // is a regular `for` loop. pp.parseForStatement = function (node) { this.next(); this.labels.push(loopLabel); this.expect(_tokentype.types.parenL); if (this.type === _tokentype.types.semi) return this.parseFor(node, null); if (this.type === _tokentype.types._var || this.type === _tokentype.types._let || this.type === _tokentype.types._const) { var _init = this.startNode(), varKind = this.type; this.next(); this.parseVar(_init, true, varKind); this.finishNode(_init, "VariableDeclaration"); 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); } var refShorthandDefaultPos = { start: 0 }; var init = this.parseExpression(true, refShorthandDefaultPos); if (this.type === _tokentype.types._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) { this.toAssignable(init); this.checkLVal(init); return this.parseForIn(node, init); } else if (refShorthandDefaultPos.start) { this.unexpected(refShorthandDefaultPos.start); } return this.parseFor(node, init); }; pp.parseFunctionStatement = function (node) { this.next(); return this.parseFunction(node, true); }; pp.parseIfStatement = function (node) { this.next(); node.test = this.parseParenExpression(); node.consequent = this.parseStatement(false); node.alternate = this.eat(_tokentype.types._else) ? this.parseStatement(false) : null; return this.finishNode(node, "IfStatement"); }; pp.parseReturnStatement = function (node) { if (!this.inFunction && !this.options.allowReturnOutsideFunction) this.raise(this.start, "'return' outside of function"); this.next(); // In `return` (and `break`/`continue`), the keywords with // optional arguments, we eagerly look for a semicolon or the // possibility to insert one. if (this.eat(_tokentype.types.semi) || this.insertSemicolon()) node.argument = null;else { node.argument = this.parseExpression();this.semicolon(); } return this.finishNode(node, "ReturnStatement"); }; pp.parseSwitchStatement = function (node) { this.next(); node.discriminant = this.parseParenExpression(); node.cases = []; this.expect(_tokentype.types.braceL); this.labels.push(switchLabel); // Statements under must be grouped (by label) in SwitchCase // nodes. `cur` is used to keep the node that we are currently // adding statements to. for (var cur, sawDefault; this.type != _tokentype.types.braceR;) { if (this.type === _tokentype.types._case || this.type === _tokentype.types._default) { var isCase = this.type === _tokentype.types._case; if (cur) this.finishNode(cur, "SwitchCase"); node.cases.push(cur = this.startNode()); cur.consequent = []; this.next(); if (isCase) { cur.test = this.parseExpression(); } else { if (sawDefault) this.raise(this.lastTokStart, "Multiple default clauses"); sawDefault = true; cur.test = null; } this.expect(_tokentype.types.colon); } else { if (!cur) this.unexpected(); cur.consequent.push(this.parseStatement(true)); } } if (cur) this.finishNode(cur, "SwitchCase"); this.next(); // Closing brace this.labels.pop(); return this.finishNode(node, "SwitchStatement"); }; pp.parseThrowStatement = function (node) { this.next(); if (_whitespace.lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) this.raise(this.lastTokEnd, "Illegal newline after throw"); node.argument = this.parseExpression(); this.semicolon(); return this.finishNode(node, "ThrowStatement"); }; // Reused empty array added for node fields that are always empty. var empty = []; pp.parseTryStatement = function (node) { this.next(); node.block = this.parseBlock(); node.handler = null; if (this.type === _tokentype.types._catch) { var clause = this.startNode(); this.next(); this.expect(_tokentype.types.parenL); clause.param = this.parseBindingAtom(); this.checkLVal(clause.param, true); this.expect(_tokentype.types.parenR); clause.guard = null; clause.body = this.parseBlock(); node.handler = this.finishNode(clause, "CatchClause"); } node.guardedHandlers = empty; node.finalizer = this.eat(_tokentype.types._finally) ? this.parseBlock() : null; if (!node.handler && !node.finalizer) this.raise(node.start, "Missing catch or finally clause"); return this.finishNode(node, "TryStatement"); }; pp.parseVarStatement = function (node, kind) { this.next(); this.parseVar(node, false, kind); this.semicolon(); return this.finishNode(node, "VariableDeclaration"); }; pp.parseWhileStatement = function (node) { this.next(); node.test = this.parseParenExpression(); this.labels.push(loopLabel); node.body = this.parseStatement(false); this.labels.pop(); return this.finishNode(node, "WhileStatement"); }; pp.parseWithStatement = function (node) { if (this.strict) this.raise(this.start, "'with' in strict mode"); this.next(); node.object = this.parseParenExpression(); node.body = this.parseStatement(false); return this.finishNode(node, "WithStatement"); }; pp.parseEmptyStatement = function (node) { this.next(); return this.finishNode(node, "EmptyStatement"); }; pp.parseLabeledStatement = function (node, maybeName, expr) { for (var i = 0; i < this.labels.length; ++i) { if (this.labels[i].name === maybeName) this.raise(expr.start, "Label '" + maybeName + "' is already declared"); }var kind = this.type.isLoop ? "loop" : this.type === _tokentype.types._switch ? "switch" : null; this.labels.push({ name: maybeName, kind: kind }); node.body = this.parseStatement(true); this.labels.pop(); node.label = expr; return this.finishNode(node, "LabeledStatement"); }; pp.parseExpressionStatement = function (node, expr) { node.expression = expr; this.semicolon(); return this.finishNode(node, "ExpressionStatement"); }; // Parse a semicolon-enclosed block of statements, handling `"use // strict"` declarations when `allowStrict` is true (used for // function bodies). pp.parseBlock = function (allowStrict) { var node = this.startNode(), first = true, oldStrict = undefined; node.body = []; this.expect(_tokentype.types.braceL); while (!this.eat(_tokentype.types.braceR)) { var stmt = this.parseStatement(true); node.body.push(stmt); if (first && allowStrict && this.isUseStrict(stmt)) { oldStrict = this.strict; this.setStrict(this.strict = true); } first = false; } if (oldStrict === false) this.setStrict(false); return this.finishNode(node, "BlockStatement"); }; // Parse a regular `for` loop. The disambiguation code in // `parseStatement` will already have parsed the init statement or // expression. pp.parseFor = function (node, init) { node.init = init; this.expect(_tokentype.types.semi); node.test = this.type === _tokentype.types.semi ? null : this.parseExpression(); this.expect(_tokentype.types.semi); node.update = this.type === _tokentype.types.parenR ? null : this.parseExpression(); this.expect(_tokentype.types.parenR); node.body = this.parseStatement(false); this.labels.pop(); return this.finishNode(node, "ForStatement"); }; // Parse a `for`/`in` and `for`/`of` loop, which are almost // same from parser's perspective. pp.parseForIn = function (node, init) { var type = this.type === _tokentype.types._in ? "ForInStatement" : "ForOfStatement"; this.next(); node.left = init; node.right = this.parseExpression(); this.expect(_tokentype.types.parenR); node.body = this.parseStatement(false); this.labels.pop(); return this.finishNode(node, type); }; // Parse a list of variable declarations. pp.parseVar = function (node, isFor, kind) { node.declarations = []; node.kind = kind.keyword; for (;;) { var decl = this.startNode(); this.parseVarHead(decl); if (this.eat(_tokentype.types.eq)) { decl.init = this.parseMaybeAssign(isFor); } else if (kind === _tokentype.types._const && !(this.type === _tokentype.types._in || this.options.ecmaVersion >= 6 && this.isContextual("of"))) { this.unexpected(); } else if (decl.id.type != "Identifier" && !(isFor && (this.type === _tokentype.types._in || this.isContextual("of")))) { this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value"); } else { decl.init = null; } node.declarations.push(this.finishNode(decl, "VariableDeclarator")); if (!this.eat(_tokentype.types.comma)) break; } return node; }; pp.parseVarHead = function (decl) { decl.id = this.parseBindingAtom(); this.checkLVal(decl.id, true); }; // Parse a function declaration or literal (depending on the // `isStatement` parameter). pp.parseFunction = function (node, isStatement, allowExpressionBody, isAsync) { this.initFunction(node, isAsync); if (this.options.ecmaVersion >= 6) node.generator = this.eat(_tokentype.types.star); if (isStatement || this.type === _tokentype.types.name) node.id = this.parseIdent(); this.parseFunctionParams(node); this.parseFunctionBody(node, allowExpressionBody); return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression"); }; pp.parseFunctionParams = function (node) { this.expect(_tokentype.types.parenL); node.params = this.parseBindingList(_tokentype.types.parenR, false, this.options.features["es7.trailingFunctionCommas"]); }; // Parse a class declaration or literal (depending on the // `isStatement` parameter). pp.parseClass = function (node, isStatement) { this.next(); this.parseClassId(node, isStatement); this.parseClassSuper(node); var classBody = this.startNode(); classBody.body = []; this.expect(_tokentype.types.braceL); var decorators = []; while (!this.eat(_tokentype.types.braceR)) { if (this.eat(_tokentype.types.semi)) continue; if (this.type === _tokentype.types.at) { decorators.push(this.parseDecorator()); continue; } var method = this.startNode(); if (decorators.length) { method.decorators = decorators; decorators = []; } var isGenerator = this.eat(_tokentype.types.star), isAsync = false; this.parsePropertyName(method); if (this.type !== _tokentype.types.parenL && !method.computed && method.key.type === "Identifier" && method.key.name === "static") { if (isGenerator) this.unexpected(); method["static"] = true; isGenerator = this.eat(_tokentype.types.star); this.parsePropertyName(method); } else { method["static"] = false; } if (!isGenerator && method.key.type === "Identifier" && !method.computed && this.isClassProperty()) { classBody.body.push(this.parseClassProperty(method)); continue; } if (this.options.features["es7.asyncFunctions"] && this.type !== _tokentype.types.parenL && !method.computed && method.key.type === "Identifier" && method.key.name === "async") { isAsync = true; this.parsePropertyName(method); } method.kind = "method"; if (!method.computed && !isGenerator && !isAsync) { if (method.key.type === "Identifier") { if (this.type !== _tokentype.types.parenL && (method.key.name === "get" || method.key.name === "set")) { method.kind = method.key.name; this.parsePropertyName(method); } else if (!method["static"] && method.key.name === "constructor") { method.kind = "constructor"; } } else if (!method["static"] && method.key.type === "Literal" && method.key.value === "constructor") { method.kind = "constructor"; } } if (method.kind === "constructor" && method.decorators) { this.raise(method.start, "You can't attach decorators to a class constructor"); } this.parseClassMethod(classBody, method, isGenerator, isAsync); } if (decorators.length) { this.raise(this.start, "You have trailing decorators with no method"); } node.body = this.finishNode(classBody, "ClassBody"); return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression"); }; pp.isClassProperty = function () { return this.type === _tokentype.types.eq || (this.type === _tokentype.types.semi || this.canInsertSemicolon()); }; pp.parseClassProperty = function (node) { if (this.type === _tokentype.types.eq) { if (!this.options.features["es7.classProperties"]) this.unexpected(); this.next(); node.value = this.parseMaybeAssign(); } else { node.value = null; } this.semicolon(); return this.finishNode(node, "ClassProperty"); }; pp.parseClassMethod = function (classBody, method, isGenerator, isAsync) { method.value = this.parseMethod(isGenerator, isAsync); classBody.body.push(this.finishNode(method, "MethodDefinition")); }; pp.parseClassId = function (node, isStatement) { node.id = this.type === _tokentype.types.name ? this.parseIdent() : isStatement ? this.unexpected() : null; }; pp.parseClassSuper = function (node) { node.superClass = this.eat(_tokentype.types._extends) ? this.parseExprSubscripts() : null; }; // Parses module export declaration. pp.parseExport = function (node) { this.next(); // export * from '...' if (this.type === _tokentype.types.star) { var specifier = this.startNode(); this.next(); if (this.options.features["es7.exportExtensions"] && this.eatContextual("as")) { specifier.exported = this.parseIdent(); node.specifiers = [this.finishNode(specifier, "ExportNamespaceSpecifier")]; this.parseExportSpecifiersMaybe(node); this.parseExportFrom(node); } else { this.parseExportFrom(node); return this.finishNode(node, "ExportAllDeclaration"); } } else if (this.isExportDefaultSpecifier()) { var specifier = this.startNode(); specifier.exported = this.parseIdent(true); node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")]; if (this.type === _tokentype.types.comma && this.lookahead().type === _tokentype.types.star) { this.expect(_tokentype.types.comma); var _specifier = this.startNode(); this.expect(_tokentype.types.star); this.expectContextual("as"); _specifier.exported = this.parseIdent(); node.specifiers.push(this.finishNode(_specifier, "ExportNamespaceSpecifier")); } else { this.parseExportSpecifiersMaybe(node); } this.parseExportFrom(node); } else if (this.eat(_tokentype.types._default)) { // export default ... var _expr = this.parseMaybeAssign(); var needsSemi = true; if (_expr.type == "FunctionExpression" || _expr.type == "ClassExpression") { needsSemi = false; if (_expr.id) { _expr.type = _expr.type == "FunctionExpression" ? "FunctionDeclaration" : "ClassDeclaration"; } } node.declaration = _expr; if (needsSemi) this.semicolon(); this.checkExport(node); return this.finishNode(node, "ExportDefaultDeclaration"); } else if (this.type.keyword || this.shouldParseExportDeclaration()) { node.declaration = this.parseStatement(true); node.specifiers = []; node.source = null; } else { // export { x, y as z } [from '...'] node.declaration = null; node.specifiers = this.parseExportSpecifiers(); if (this.eatContextual("from")) { node.source = this.type === _tokentype.types.string ? this.parseExprAtom() : this.unexpected(); } else { node.source = null; } this.semicolon(); } this.checkExport(node); return this.finishNode(node, "ExportNamedDeclaration"); }; pp.isExportDefaultSpecifier = function () { if (this.type === _tokentype.types.name) { return this.value !== "type" && this.value !== "async"; } if (this.type !== _tokentype.types._default) { return false; } var lookahead = this.lookahead(); return lookahead.type === _tokentype.types.comma || lookahead.type === _tokentype.types.name && lookahead.value === "from"; }; pp.parseExportSpecifiersMaybe = function (node) { if (this.eat(_tokentype.types.comma)) { node.specifiers = node.specifiers.concat(this.parseExportSpecifiers()); } }; pp.parseExportFrom = function (node) { this.expectContextual("from"); node.source = this.type === _tokentype.types.string ? this.parseExprAtom() : this.unexpected(); this.semicolon(); this.checkExport(node); }; pp.shouldParseExportDeclaration = function () { return this.options.features["es7.asyncFunctions"] && this.isContextual("async"); }; pp.checkExport = function (node) { if (this.decorators.length) { var isClass = node.declaration && (node.declaration.type === "ClassDeclaration" || node.declaration.type === "ClassExpression"); if (!node.declaration || !isClass) { this.raise(node.start, "You can only use decorators on an export when exporting a class"); } this.takeDecorators(node.declaration); } }; // Parses a comma-separated list of module exports. pp.parseExportSpecifiers = function () { var nodes = [], first = true; // export { x, y as z } [from '...'] this.expect(_tokentype.types.braceL); while (!this.eat(_tokentype.types.braceR)) { if (!first) { this.expect(_tokentype.types.comma); if (this.afterTrailingComma(_tokentype.types.braceR)) break; } else first = false; var node = this.startNode(); node.local = this.parseIdent(this.type === _tokentype.types._default); node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local; nodes.push(this.finishNode(node, "ExportSpecifier")); } return nodes; }; // Parses import declaration. pp.parseImport = function (node) { this.next(); // import '...' if (this.type === _tokentype.types.string) { node.specifiers = empty; node.source = this.parseExprAtom(); } else { node.specifiers = []; this.parseImportSpecifiers(node); this.expectContextual("from"); node.source = this.type === _tokentype.types.string ? this.parseExprAtom() : this.unexpected(); } this.semicolon(); return this.finishNode(node, "ImportDeclaration"); }; // Parses a comma-separated list of module imports. pp.parseImportSpecifiers = function (node) { var first = true; if (this.type === _tokentype.types.name) { // import defaultObj, { x, y as z } from '...' var start = this.markPosition(); node.specifiers.push(this.parseImportSpecifierDefault(this.parseIdent(), start)); if (!this.eat(_tokentype.types.comma)) return; } if (this.type === _tokentype.types.star) { var specifier = this.startNode(); this.next(); this.expectContextual("as"); specifier.local = this.parseIdent(); this.checkLVal(specifier.local, true); node.specifiers.push(this.finishNode(specifier, "ImportNamespaceSpecifier")); return; } this.expect(_tokentype.types.braceL); while (!this.eat(_tokentype.types.braceR)) { if (!first) { this.expect(_tokentype.types.comma); if (this.afterTrailingComma(_tokentype.types.braceR)) break; } else first = false; var specifier = this.startNode(); specifier.imported = this.parseIdent(true); specifier.local = this.eatContextual("as") ? this.parseIdent() : specifier.imported; this.checkLVal(specifier.local, true); node.specifiers.push(this.finishNode(specifier, "ImportSpecifier")); } }; pp.parseImportSpecifierDefault = function (id, start) { var node = this.startNodeAt(start); node.local = id; this.checkLVal(node.local, true); return this.finishNode(node, "ImportDefaultSpecifier"); }; },{"./state":12,"./tokentype":16,"./whitespace":18}],14:[function(require,module,exports){ // The algorithm used to determine whether a regexp can appear at a // given point in the program is loosely based on sweet.js' approach. // See https://github.com/mozilla/sweet.js/wiki/design "use strict"; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _state = require("./state"); var _tokentype = require("./tokentype"); var _whitespace = require("./whitespace"); var TokContext = function TokContext(token, isExpr, preserveSpace, override) { _classCallCheck(this, TokContext); this.token = token; this.isExpr = isExpr; this.preserveSpace = preserveSpace; this.override = override; }; exports.TokContext = TokContext; var types = { b_stat: new TokContext("{", false), b_expr: new TokContext("{", true), b_tmpl: new TokContext("${", true), p_stat: new TokContext("(", false), p_expr: new TokContext("(", true), q_tmpl: new TokContext("`", true, true, function (p) { return p.readTmplToken(); }), f_expr: new TokContext("function", true) }; exports.types = types; var pp = _state.Parser.prototype; pp.initialContext = function () { return [types.b_stat]; }; pp.braceIsBlock = function (prevType) { var parent = undefined; if (prevType === _tokentype.types.colon && (parent = this.curContext()).token == "{") return !parent.isExpr; if (prevType === _tokentype.types._return) return _whitespace.lineBreak.test(this.input.slice(this.lastTokEnd, this.start)); if (prevType === _tokentype.types._else || prevType === _tokentype.types.semi || prevType === _tokentype.types.eof) return true; if (prevType == _tokentype.types.braceL) return this.curContext() === types.b_stat; return !this.exprAllowed; }; pp.updateContext = function (prevType) { var update = undefined, type = this.type; if (type.keyword && prevType == _tokentype.types.dot) this.exprAllowed = false;else if (update = type.updateContext) update.call(this, prevType);else this.exprAllowed = type.beforeExpr; }; // Token-specific context update code _tokentype.types.parenR.updateContext = _tokentype.types.braceR.updateContext = function () { if (this.context.length == 1) { this.exprAllowed = true; return; } var out = this.context.pop(); if (out === types.b_stat && this.curContext() === types.f_expr) { this.context.pop(); this.exprAllowed = false; } else if (out === types.b_tmpl) { this.exprAllowed = true; } else { this.exprAllowed = !out.isExpr; } }; _tokentype.types.braceL.updateContext = function (prevType) { this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr); this.exprAllowed = true; }; _tokentype.types.dollarBraceL.updateContext = function () { this.context.push(types.b_tmpl); this.exprAllowed = true; }; _tokentype.types.parenL.updateContext = function (prevType) { var statementParens = prevType === _tokentype.types._if || prevType === _tokentype.types._for || prevType === _tokentype.types._with || prevType === _tokentype.types._while; this.context.push(statementParens ? types.p_stat : types.p_expr); this.exprAllowed = true; }; _tokentype.types.incDec.updateContext = function () {}; _tokentype.types._function.updateContext = function () { if (this.curContext() !== types.b_stat) this.context.push(types.f_expr); this.exprAllowed = false; }; _tokentype.types.backQuote.updateContext = function () { if (this.curContext() === types.q_tmpl) this.context.pop();else this.context.push(types.q_tmpl); this.exprAllowed = false; }; // tokExprAllowed stays unchanged },{"./state":12,"./tokentype":16,"./whitespace":18}],15:[function(require,module,exports){ "use strict"; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _identifier = require("./identifier"); var _tokentype = require("./tokentype"); var _state = require("./state"); var _location = require("./location"); var _whitespace = require("./whitespace"); // Object type used to represent tokens. Note that normally, tokens // simply exist as properties on the parser object. This is only // used for the onToken callback and the external tokenizer. var Token = function Token(p) { _classCallCheck(this, Token); this.type = p.type; this.value = p.value; this.start = p.start; this.end = p.end; if (p.options.locations) this.loc = new _location.SourceLocation(p, p.startLoc, p.endLoc); if (p.options.ranges) this.range = [p.start, p.end]; }; exports.Token = Token; // ## Tokenizer var pp = _state.Parser.prototype; // Move to the next token pp.next = function () { if (this.options.onToken && !this.isLookahead) this.options.onToken(new Token(this)); this.lastTokEnd = this.end; this.lastTokStart = this.start; this.lastTokEndLoc = this.endLoc; this.lastTokStartLoc = this.startLoc; this.nextToken(); }; pp.getToken = function () { this.next(); return new Token(this); }; // If we're in an ES6 environment, make parsers iterable if (typeof Symbol !== "undefined") pp[Symbol.iterator] = function () { var self = this; return { next: function next() { var token = self.getToken(); return { done: token.type === _tokentype.types.eof, value: token }; } }; }; // Toggle strict mode. Re-reads the next number or string to please // pedantic tests (`"use strict"; 010;` should fail). pp.setStrict = function (strict) { this.strict = strict; if (this.type !== _tokentype.types.num && this.type !== _tokentype.types.string) return; this.pos = this.start; if (this.options.locations) { while (this.pos < this.lineStart) { this.lineStart = this.input.lastIndexOf("\n", this.lineStart - 2) + 1; --this.curLine; } } this.nextToken(); }; pp.curContext = function () { return this.context[this.context.length - 1]; }; // Read a single token, updating the parser object's token-related // properties. pp.nextToken = function () { var curContext = this.curContext(); if (!curContext || !curContext.preserveSpace) this.skipSpace(); this.start = this.pos; if (this.options.locations) this.startLoc = this.curPosition(); if (this.pos >= this.input.length) return this.finishToken(_tokentype.types.eof); if (curContext.override) return curContext.override(this);else this.readToken(this.fullCharCodeAtPos()); }; pp.readToken = function (code) { // Identifier or keyword. '\uXXXX' sequences are allowed in // identifiers, so '\' also dispatches to that. if ((0, _identifier.isIdentifierStart)(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) return this.readWord(); return this.getTokenFromCode(code); }; pp.fullCharCodeAtPos = function () { var code = this.input.charCodeAt(this.pos); if (code <= 55295 || code >= 57344) return code; var next = this.input.charCodeAt(this.pos + 1); return (code << 10) + next - 56613888; }; pp.skipBlockComment = function () { var startLoc = this.options.onComment && this.options.locations && this.curPosition(); var start = this.pos, end = this.input.indexOf("*/", this.pos += 2); if (end === -1) this.raise(this.pos - 2, "Unterminated comment"); this.pos = end + 2; if (this.options.locations) { _whitespace.lineBreakG.lastIndex = start; var match = undefined; while ((match = _whitespace.lineBreakG.exec(this.input)) && match.index < this.pos) { ++this.curLine; this.lineStart = match.index + match[0].length; } } if (this.options.onComment) this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, startLoc, this.options.locations && this.curPosition()); }; pp.skipLineComment = function (startSkip) { var start = this.pos; var startLoc = this.options.onComment && this.options.locations && this.curPosition(); var ch = this.input.charCodeAt(this.pos += startSkip); while (this.pos < this.input.length && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) { ++this.pos; ch = this.input.charCodeAt(this.pos); } if (this.options.onComment) this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, startLoc, this.options.locations && this.curPosition()); }; // Called at the start of the parse and after every token. Skips // whitespace and comments, and. pp.skipSpace = function () { while (this.pos < this.input.length) { var ch = this.input.charCodeAt(this.pos); if (ch === 32) { // ' ' ++this.pos; } else if (ch === 13) { ++this.pos; var _next = this.input.charCodeAt(this.pos); if (_next === 10) { ++this.pos; } if (this.options.locations) { ++this.curLine; this.lineStart = this.pos; } } else if (ch === 10 || ch === 8232 || ch === 8233) { ++this.pos; if (this.options.locations) { ++this.curLine; this.lineStart = this.pos; } } else if (ch > 8 && ch < 14) { ++this.pos; } else if (ch === 47) { // '/' var _next2 = this.input.charCodeAt(this.pos + 1); if (_next2 === 42) { // '*' this.skipBlockComment(); } else if (_next2 === 47) { // '/' this.skipLineComment(2); } else break; } else if (ch === 160) { // '\xa0' ++this.pos; } else if (ch >= 5760 && _whitespace.nonASCIIwhitespace.test(String.fromCharCode(ch))) { ++this.pos; } else { break; } } }; // Called at the end of every token. Sets `end`, `val`, and // maintains `context` and `exprAllowed`, and skips the space after // the token, so that the next one's `start` will point at the // right position. pp.finishToken = function (type, val) { this.end = this.pos; if (this.options.locations) this.endLoc = this.curPosition(); var prevType = this.type; this.type = type; this.value = val; this.updateContext(prevType); }; // ### Token reading // This is the function that is called to fetch the next token. It // is somewhat obscure, because it works in character codes rather // than characters, and because operator parsing has been inlined // into it. // // All in the name of speed. // pp.readToken_dot = function () { var next = this.input.charCodeAt(this.pos + 1); if (next >= 48 && next <= 57) return this.readNumber(true); var next2 = this.input.charCodeAt(this.pos + 2); if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.' this.pos += 3; return this.finishToken(_tokentype.types.ellipsis); } else { ++this.pos; return this.finishToken(_tokentype.types.dot); } }; pp.readToken_slash = function () { // '/' var next = this.input.charCodeAt(this.pos + 1); if (this.exprAllowed) { ++this.pos;return this.readRegexp(); } if (next === 61) return this.finishOp(_tokentype.types.assign, 2); return this.finishOp(_tokentype.types.slash, 1); }; pp.readToken_mult_modulo = function (code) { // '%*' var type = code === 42 ? _tokentype.types.star : _tokentype.types.modulo; var width = 1; var next = this.input.charCodeAt(this.pos + 1); if (next === 42) { // '*' width++; next = this.input.charCodeAt(this.pos + 2); type = _tokentype.types.exponent; } if (next === 61) { width++; type = _tokentype.types.assign; } return this.finishOp(type, width); }; pp.readToken_pipe_amp = function (code) { // '|&' var next = this.input.charCodeAt(this.pos + 1); if (next === code) return this.finishOp(code === 124 ? _tokentype.types.logicalOR : _tokentype.types.logicalAND, 2); if (next === 61) return this.finishOp(_tokentype.types.assign, 2); return this.finishOp(code === 124 ? _tokentype.types.bitwiseOR : _tokentype.types.bitwiseAND, 1); }; pp.readToken_caret = function () { // '^' var next = this.input.charCodeAt(this.pos + 1); if (next === 61) return this.finishOp(_tokentype.types.assign, 2); return this.finishOp(_tokentype.types.bitwiseXOR, 1); }; pp.readToken_plus_min = function (code) { // '+-' var next = this.input.charCodeAt(this.pos + 1); if (next === code) { if (next == 45 && this.input.charCodeAt(this.pos + 2) == 62 && _whitespace.lineBreak.test(this.input.slice(this.lastTokEnd, this.pos))) { // A `-->` line comment this.skipLineComment(3); this.skipSpace(); return this.nextToken(); } return this.finishOp(_tokentype.types.incDec, 2); } if (next === 61) return this.finishOp(_tokentype.types.assign, 2); return this.finishOp(_tokentype.types.plusMin, 1); }; pp.readToken_lt_gt = function (code) { // '<>' var next = this.input.charCodeAt(this.pos + 1); var size = 1; if (next === code) { size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; if (this.input.charCodeAt(this.pos + size) === 61) return this.finishOp(_tokentype.types.assign, size + 1); return this.finishOp(_tokentype.types.bitShift, size); } if (next == 33 && code == 60 && this.input.charCodeAt(this.pos + 2) == 45 && this.input.charCodeAt(this.pos + 3) == 45) { if (this.inModule) this.unexpected(); // ` regexps set = set.map(function (s, si, set) { return s.map(this.parse, this) }, this) this.debug(this.pattern, set) // filter out everything that didn't compile properly. set = set.filter(function (s) { return -1 === s.indexOf(false) }) this.debug(this.pattern, set) this.set = set } Minimatch.prototype.parseNegate = parseNegate function parseNegate () { var pattern = this.pattern , negate = false , options = this.options , negateOffset = 0 if (options.nonegate) return for ( var i = 0, l = pattern.length ; i < l && pattern.charAt(i) === "!" ; i ++) { negate = !negate negateOffset ++ } if (negateOffset) this.pattern = pattern.substr(negateOffset) this.negate = negate } // Brace expansion: // a{b,c}d -> abd acd // a{b,}c -> abc ac // a{0..3}d -> a0d a1d a2d a3d // a{b,c{d,e}f}g -> abg acdfg acefg // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg // // Invalid sets are not expanded. // a{2..}b -> a{2..}b // a{b}c -> a{b}c minimatch.braceExpand = function (pattern, options) { return braceExpand(pattern, options) } Minimatch.prototype.braceExpand = braceExpand function braceExpand (pattern, options) { if (!options) { if (this instanceof Minimatch) options = this.options else options = {} } pattern = typeof pattern === "undefined" ? this.pattern : pattern if (typeof pattern === "undefined") { throw new Error("undefined pattern") } if (options.nobrace || !pattern.match(/\{.*\}/)) { // shortcut. no need to expand. return [pattern] } return expand(pattern) } // parse a component of the expanded set. // At this point, no pattern may contain "/" in it // so we're going to return a 2d array, where each entry is the full // pattern, split on '/', and then turned into a regular expression. // A regexp is made at the end which joins each array with an // escaped /, and another full one which joins each regexp with |. // // Following the lead of Bash 4.1, note that "**" only has special meaning // when it is the *only* thing in a path portion. Otherwise, any series // of * is equivalent to a single *. Globstar behavior is enabled by // default, and can be disabled by setting options.noglobstar. Minimatch.prototype.parse = parse var SUBPARSE = {} function parse (pattern, isSub) { var options = this.options // shortcuts if (!options.noglobstar && pattern === "**") return GLOBSTAR if (pattern === "") return "" var re = "" , hasMagic = !!options.nocase , escaping = false // ? => one single character , patternListStack = [] , plType , stateChar , inClass = false , reClassStart = -1 , classStart = -1 // . and .. never match anything that doesn't start with ., // even when options.dot is set. , patternStart = pattern.charAt(0) === "." ? "" // anything // not (start or / followed by . or .. followed by / or end) : options.dot ? "(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))" : "(?!\\.)" , self = this function clearStateChar () { if (stateChar) { // we had some state-tracking character // that wasn't consumed by this pass. switch (stateChar) { case "*": re += star hasMagic = true break case "?": re += qmark hasMagic = true break default: re += "\\"+stateChar break } self.debug('clearStateChar %j %j', stateChar, re) stateChar = false } } for ( var i = 0, len = pattern.length, c ; (i < len) && (c = pattern.charAt(i)) ; i ++ ) { this.debug("%s\t%s %s %j", pattern, i, re, c) // skip over any that are escaped. if (escaping && reSpecials[c]) { re += "\\" + c escaping = false continue } SWITCH: switch (c) { case "/": // completely not allowed, even escaped. // Should already be path-split by now. return false case "\\": clearStateChar() escaping = true continue // the various stateChar values // for the "extglob" stuff. case "?": case "*": case "+": case "@": case "!": this.debug("%s\t%s %s %j <-- stateChar", pattern, i, re, c) // all of those are literals inside a class, except that // the glob [!a] means [^a] in regexp if (inClass) { this.debug(' in class') if (c === "!" && i === classStart + 1) c = "^" re += c continue } // if we already have a stateChar, then it means // that there was something like ** or +? in there. // Handle the stateChar, then proceed with this one. self.debug('call clearStateChar %j', stateChar) clearStateChar() stateChar = c // if extglob is disabled, then +(asdf|foo) isn't a thing. // just clear the statechar *now*, rather than even diving into // the patternList stuff. if (options.noext) clearStateChar() continue case "(": if (inClass) { re += "(" continue } if (!stateChar) { re += "\\(" continue } plType = stateChar patternListStack.push({ type: plType , start: i - 1 , reStart: re.length }) // negation is (?:(?!js)[^/]*) re += stateChar === "!" ? "(?:(?!" : "(?:" this.debug('plType %j %j', stateChar, re) stateChar = false continue case ")": if (inClass || !patternListStack.length) { re += "\\)" continue } clearStateChar() hasMagic = true re += ")" plType = patternListStack.pop().type // negation is (?:(?!js)[^/]*) // The others are (?:) switch (plType) { case "!": re += "[^/]*?)" break case "?": case "+": case "*": re += plType case "@": break // the default anyway } continue case "|": if (inClass || !patternListStack.length || escaping) { re += "\\|" escaping = false continue } clearStateChar() re += "|" continue // these are mostly the same in regexp and glob case "[": // swallow any state-tracking char before the [ clearStateChar() if (inClass) { re += "\\" + c continue } inClass = true classStart = i reClassStart = re.length re += c continue case "]": // a right bracket shall lose its special // meaning and represent itself in // a bracket expression if it occurs // first in the list. -- POSIX.2 2.8.3.2 if (i === classStart + 1 || !inClass) { re += "\\" + c escaping = false continue } // handle the case where we left a class open. // "[z-a]" is valid, equivalent to "\[z-a\]" if (inClass) { // split where the last [ was, make sure we don't have // an invalid re. if so, re-walk the contents of the // would-be class to re-translate any characters that // were passed through as-is // TODO: It would probably be faster to determine this // without a try/catch and a new RegExp, but it's tricky // to do safely. For now, this is safe and works. var cs = pattern.substring(classStart + 1, i) try { new RegExp('[' + cs + ']') } catch (er) { // not a valid class! var sp = this.parse(cs, SUBPARSE) re = re.substr(0, reClassStart) + "\\[" + sp[0] + '\\]' hasMagic = hasMagic || sp[1] inClass = false continue } } // finish up the class. hasMagic = true inClass = false re += c continue default: // swallow any state char that wasn't consumed clearStateChar() if (escaping) { // no need escaping = false } else if (reSpecials[c] && !(c === "^" && inClass)) { re += "\\" } re += c } // switch } // for // handle the case where we left a class open. // "[abc" is valid, equivalent to "\[abc" if (inClass) { // split where the last [ was, and escape it // this is a huge pita. We now have to re-walk // the contents of the would-be class to re-translate // any characters that were passed through as-is var cs = pattern.substr(classStart + 1) , sp = this.parse(cs, SUBPARSE) re = re.substr(0, reClassStart) + "\\[" + sp[0] hasMagic = hasMagic || sp[1] } // handle the case where we had a +( thing at the *end* // of the pattern. // each pattern list stack adds 3 chars, and we need to go through // and escape any | chars that were passed through as-is for the regexp. // Go through and escape them, taking care not to double-escape any // | chars that were already escaped. var pl while (pl = patternListStack.pop()) { var tail = re.slice(pl.reStart + 3) // maybe some even number of \, then maybe 1 \, followed by a | tail = tail.replace(/((?:\\{2})*)(\\?)\|/g, function (_, $1, $2) { if (!$2) { // the | isn't already escaped, so escape it. $2 = "\\" } // need to escape all those slashes *again*, without escaping the // one that we need for escaping the | character. As it works out, // escaping an even number of slashes can be done by simply repeating // it exactly after itself. That's why this trick works. // // I am sorry that you have to see this. return $1 + $1 + $2 + "|" }) this.debug("tail=%j\n %s", tail, tail) var t = pl.type === "*" ? star : pl.type === "?" ? qmark : "\\" + pl.type hasMagic = true re = re.slice(0, pl.reStart) + t + "\\(" + tail } // handle trailing things that only matter at the very end. clearStateChar() if (escaping) { // trailing \\ re += "\\\\" } // only need to apply the nodot start if the re starts with // something that could conceivably capture a dot var addPatternStart = false switch (re.charAt(0)) { case ".": case "[": case "(": addPatternStart = true } // if the re is not "" at this point, then we need to make sure // it doesn't match against an empty path part. // Otherwise a/* will match a/, which it should not. if (re !== "" && hasMagic) re = "(?=.)" + re if (addPatternStart) re = patternStart + re // parsing just a piece of a larger pattern. if (isSub === SUBPARSE) { return [ re, hasMagic ] } // skip the regexp for non-magical patterns // unescape anything in it, though, so that it'll be // an exact match against a file etc. if (!hasMagic) { return globUnescape(pattern) } var flags = options.nocase ? "i" : "" , regExp = new RegExp("^" + re + "$", flags) regExp._glob = pattern regExp._src = re return regExp } minimatch.makeRe = function (pattern, options) { return new Minimatch(pattern, options || {}).makeRe() } Minimatch.prototype.makeRe = makeRe function makeRe () { if (this.regexp || this.regexp === false) return this.regexp // at this point, this.set is a 2d array of partial // pattern strings, or "**". // // It's better to use .match(). This function shouldn't // be used, really, but it's pretty convenient sometimes, // when you just want to work with a regex. var set = this.set if (!set.length) return this.regexp = false var options = this.options var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot , flags = options.nocase ? "i" : "" var re = set.map(function (pattern) { return pattern.map(function (p) { return (p === GLOBSTAR) ? twoStar : (typeof p === "string") ? regExpEscape(p) : p._src }).join("\\\/") }).join("|") // must match entire pattern // ending in a * or ** will make it less strict. re = "^(?:" + re + ")$" // can match anything, as long as it's not this. if (this.negate) re = "^(?!" + re + ").*$" try { return this.regexp = new RegExp(re, flags) } catch (ex) { return this.regexp = false } } minimatch.match = function (list, pattern, options) { options = options || {} var mm = new Minimatch(pattern, options) list = list.filter(function (f) { return mm.match(f) }) if (mm.options.nonull && !list.length) { list.push(pattern) } return list } Minimatch.prototype.match = match function match (f, partial) { this.debug("match", f, this.pattern) // short-circuit in the case of busted things. // comments, etc. if (this.comment) return false if (this.empty) return f === "" if (f === "/" && partial) return true var options = this.options // windows: need to use /, not \ if (isWindows) f = f.split("\\").join("/") // treat the test path as a set of pathparts. f = f.split(slashSplit) this.debug(this.pattern, "split", f) // just ONE of the pattern sets in this.set needs to match // in order for it to be valid. If negating, then just one // match means that we have failed. // Either way, return on the first hit. var set = this.set this.debug(this.pattern, "set", set) // Find the basename of the path by looking for the last non-empty segment var filename; for (var i = f.length - 1; i >= 0; i--) { filename = f[i] if (filename) break } for (var i = 0, l = set.length; i < l; i ++) { var pattern = set[i], file = f if (options.matchBase && pattern.length === 1) { file = [filename] } var hit = this.matchOne(file, pattern, partial) if (hit) { if (options.flipNegate) return true return !this.negate } } // didn't get any hits. this is success if it's a negative // pattern, failure otherwise. if (options.flipNegate) return false return this.negate } // set partial to true to test if, for example, // "/a/b" matches the start of "/*/b/*/d" // Partial means, if you run out of file before you run // out of pattern, then that's fine, as long as all // the parts match. Minimatch.prototype.matchOne = function (file, pattern, partial) { var options = this.options this.debug("matchOne", { "this": this , file: file , pattern: pattern }) this.debug("matchOne", file.length, pattern.length) for ( var fi = 0 , pi = 0 , fl = file.length , pl = pattern.length ; (fi < fl) && (pi < pl) ; fi ++, pi ++ ) { this.debug("matchOne loop") var p = pattern[pi] , f = file[fi] this.debug(pattern, p, f) // should be impossible. // some invalid regexp stuff in the set. if (p === false) return false if (p === GLOBSTAR) { this.debug('GLOBSTAR', [pattern, p, f]) // "**" // a/**/b/**/c would match the following: // a/b/x/y/z/c // a/x/y/z/b/c // a/b/x/b/x/c // a/b/c // To do this, take the rest of the pattern after // the **, and see if it would match the file remainder. // If so, return success. // If not, the ** "swallows" a segment, and try again. // This is recursively awful. // // a/**/b/**/c matching a/b/x/y/z/c // - a matches a // - doublestar // - matchOne(b/x/y/z/c, b/**/c) // - b matches b // - doublestar // - matchOne(x/y/z/c, c) -> no // - matchOne(y/z/c, c) -> no // - matchOne(z/c, c) -> no // - matchOne(c, c) yes, hit var fr = fi , pr = pi + 1 if (pr === pl) { this.debug('** at the end') // a ** at the end will just swallow the rest. // We have found a match. // however, it will not swallow /.x, unless // options.dot is set. // . and .. are *never* matched by **, for explosively // exponential reasons. for ( ; fi < fl; fi ++) { if (file[fi] === "." || file[fi] === ".." || (!options.dot && file[fi].charAt(0) === ".")) return false } return true } // ok, let's see if we can swallow whatever we can. WHILE: while (fr < fl) { var swallowee = file[fr] this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) // XXX remove this slice. Just pass the start index. if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { this.debug('globstar found match!', fr, fl, swallowee) // found a match. return true } else { // can't swallow "." or ".." ever. // can only swallow ".foo" when explicitly asked. if (swallowee === "." || swallowee === ".." || (!options.dot && swallowee.charAt(0) === ".")) { this.debug("dot detected!", file, fr, pattern, pr) break WHILE } // ** swallows a segment, and continue. this.debug('globstar swallow a segment, and continue') fr ++ } } // no match was found. // However, in partial mode, we can't say this is necessarily over. // If there's more *pattern* left, then if (partial) { // ran out of file this.debug("\n>>> no match, partial?", file, fr, pattern, pr) if (fr === fl) return true } return false } // something other than ** // non-magic patterns just have to match exactly // patterns with magic have been turned into regexps. var hit if (typeof p === "string") { if (options.nocase) { hit = f.toLowerCase() === p.toLowerCase() } else { hit = f === p } this.debug("string match", p, f, hit) } else { hit = f.match(p) this.debug("pattern match", p, f, hit) } if (!hit) return false } // Note: ending in / means that we'll get a final "" // at the end of the pattern. This can only match a // corresponding "" at the end of the file. // If the file ends in /, then it can only match a // a pattern that ends in /, unless the pattern just // doesn't have any more for it. But, a/b/ should *not* // match "a/b/*", even though "" matches against the // [^/]*? pattern, except in partial mode, where it might // simply not be reached yet. // However, a/b/ should still satisfy a/* // now either we fell off the end of the pattern, or we're done. if (fi === fl && pi === pl) { // ran out of pattern and filename at the same time. // an exact hit! return true } else if (fi === fl) { // ran out of file, but still had pattern left. // this is ok if we're doing the match as part of // a glob fs traversal. return partial } else if (pi === pl) { // ran out of pattern, still have file left. // this is only acceptable if we're on the very last // empty segment of a file with a trailing slash. // a/* should match a/b/ var emptyFileEnd = (fi === fl - 1) && (file[fi] === "") return emptyFileEnd } // should be unreachable. throw new Error("wtf?") } // replace stuff like \* with * function globUnescape (s) { return s.replace(/\\(.)/g, "$1") } function regExpEscape (s) { return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&") } }).call(this,require('_process')) },{"_process":200,"brace-expansion":431}],431:[function(require,module,exports){ var concatMap = require('concat-map'); var balanced = require('balanced-match'); module.exports = expandTop; var escSlash = '\0SLASH'+Math.random()+'\0'; var escOpen = '\0OPEN'+Math.random()+'\0'; var escClose = '\0CLOSE'+Math.random()+'\0'; var escComma = '\0COMMA'+Math.random()+'\0'; var escPeriod = '\0PERIOD'+Math.random()+'\0'; function numeric(str) { return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0); } function escapeBraces(str) { return str.split('\\\\').join(escSlash) .split('\\{').join(escOpen) .split('\\}').join(escClose) .split('\\,').join(escComma) .split('\\.').join(escPeriod); } function unescapeBraces(str) { return str.split(escSlash).join('\\') .split(escOpen).join('{') .split(escClose).join('}') .split(escComma).join(',') .split(escPeriod).join('.'); } // Basically just str.split(","), but handling cases // where we have nested braced sections, which should be // treated as individual members, like {a,{b,c},d} function parseCommaParts(str) { if (!str) return ['']; var parts = []; var m = balanced('{', '}', str); if (!m) return str.split(','); var pre = m.pre; var body = m.body; var post = m.post; var p = pre.split(','); p[p.length-1] += '{' + body + '}'; var postParts = parseCommaParts(post); if (post.length) { p[p.length-1] += postParts.shift(); p.push.apply(p, postParts); } parts.push.apply(parts, p); return parts; } function expandTop(str) { if (!str) return []; return expand(escapeBraces(str), true).map(unescapeBraces); } function identity(e) { return e; } function embrace(str) { return '{' + str + '}'; } function isPadded(el) { return /^-?0\d/.test(el); } function lte(i, y) { return i <= y; } function gte(i, y) { return i >= y; } function expand(str, isTop) { var expansions = []; var m = balanced('{', '}', str); if (!m || /\$$/.test(m.pre)) return [str]; var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); var isSequence = isNumericSequence || isAlphaSequence; var isOptions = /^(.*,)+(.+)?$/.test(m.body); if (!isSequence && !isOptions) { // {a},b} if (m.post.match(/,.*}/)) { str = m.pre + '{' + m.body + escClose + m.post; return expand(str); } return [str]; } var n; if (isSequence) { n = m.body.split(/\.\./); } else { n = parseCommaParts(m.body); if (n.length === 1) { // x{{a,b}}y ==> x{a}y x{b}y n = expand(n[0], false).map(embrace); if (n.length === 1) { var post = m.post.length ? expand(m.post, false) : ['']; return post.map(function(p) { return m.pre + n[0] + p; }); } } } // at this point, n is the parts, and we know it's not a comma set // with a single entry. // no need to expand pre, since it is guaranteed to be free of brace-sets var pre = m.pre; var post = m.post.length ? expand(m.post, false) : ['']; var N; if (isSequence) { var x = numeric(n[0]); var y = numeric(n[1]); var width = Math.max(n[0].length, n[1].length) var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1; var test = lte; var reverse = y < x; if (reverse) { incr *= -1; test = gte; } var pad = n.some(isPadded); N = []; for (var i = x; test(i, y); i += incr) { var c; if (isAlphaSequence) { c = String.fromCharCode(i); if (c === '\\') c = ''; } else { c = String(i); if (pad) { var need = width - c.length; if (need > 0) { var z = new Array(need + 1).join('0'); if (i < 0) c = '-' + z + c.slice(1); else c = z + c; } } } N.push(c); } } else { N = concatMap(n, function(el) { return expand(el, false) }); } for (var j = 0; j < N.length; j++) { for (var k = 0; k < post.length; k++) { var expansion = pre + N[j] + post[k]; if (!isTop || isSequence || expansion) expansions.push(expansion); } } return expansions; } },{"balanced-match":432,"concat-map":433}],432:[function(require,module,exports){ module.exports = balanced; function balanced(a, b, str) { var bal = 0; var m = {}; var ended = false; for (var i = 0; i < str.length; i++) { if (a == str.substr(i, a.length)) { if (!('start' in m)) m.start = i; bal++; } else if (b == str.substr(i, b.length) && 'start' in m) { ended = true; bal--; if (!bal) { m.end = i; m.pre = str.substr(0, m.start); m.body = (m.end - m.start > 1) ? str.substring(m.start + a.length, m.end) : ''; m.post = str.slice(m.end + b.length); return m; } } } // if we opened more than we closed, find the one we closed if (bal && ended) { var start = m.start + a.length; m = balanced(a, b, str.substr(start)); if (m) { m.start += start; m.end += start; m.pre = str.slice(0, start) + m.pre; } return m; } } },{}],433:[function(require,module,exports){ module.exports = function (xs, fn) { var res = []; for (var i = 0; i < xs.length; i++) { var x = fn(xs[i], i); if (isArray(x)) res.push.apply(res, x); else res.push(x); } return res; }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; },{}],434:[function(require,module,exports){ (function (process){ 'use strict'; function posix(path) { return path.charAt(0) === '/'; }; function win32(path) { // https://github.com/joyent/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; var result = splitDeviceRe.exec(path); var device = result[1] || ''; var isUnc = !!device && device.charAt(1) !== ':'; // UNC paths are always absolute return !!result[2] || isUnc; }; module.exports = process.platform === 'win32' ? win32 : posix; module.exports.posix = posix; module.exports.win32 = win32; }).call(this,require('_process')) },{"_process":200}],435:[function(require,module,exports){ "use strict"; var originalObject = Object; var originalDefProp = Object.defineProperty; var originalCreate = Object.create; function defProp(obj, name, value) { if (originalDefProp) try { originalDefProp.call(originalObject, obj, name, { value: value }); } catch (definePropertyIsBrokenInIE8) { obj[name] = value; } else { obj[name] = value; } } // For functions that will be invoked using .call or .apply, we need to // define those methods on the function objects themselves, rather than // inheriting them from Function.prototype, so that a malicious or clumsy // third party cannot interfere with the functionality of this module by // redefining Function.prototype.call or .apply. function makeSafeToCall(fun) { if (fun) { defProp(fun, "call", fun.call); defProp(fun, "apply", fun.apply); } return fun; } makeSafeToCall(originalDefProp); makeSafeToCall(originalCreate); var hasOwn = makeSafeToCall(Object.prototype.hasOwnProperty); var numToStr = makeSafeToCall(Number.prototype.toString); var strSlice = makeSafeToCall(String.prototype.slice); var cloner = function(){}; function create(prototype) { if (originalCreate) { return originalCreate.call(originalObject, prototype); } cloner.prototype = prototype || null; return new cloner; } var rand = Math.random; var uniqueKeys = create(null); function makeUniqueKey() { // Collisions are highly unlikely, but this module is in the business of // making guarantees rather than safe bets. do var uniqueKey = internString(strSlice.call(numToStr.call(rand(), 36), 2)); while (hasOwn.call(uniqueKeys, uniqueKey)); return uniqueKeys[uniqueKey] = uniqueKey; } function internString(str) { var obj = {}; obj[str] = true; return Object.keys(obj)[0]; } // External users might find this function useful, but it is not necessary // for the typical use of this module. defProp(exports, "makeUniqueKey", makeUniqueKey); // Object.getOwnPropertyNames is the only way to enumerate non-enumerable // properties, so if we wrap it to ignore our secret keys, there should be // no way (except guessing) to access those properties. var originalGetOPNs = Object.getOwnPropertyNames; Object.getOwnPropertyNames = function getOwnPropertyNames(object) { for (var names = originalGetOPNs(object), src = 0, dst = 0, len = names.length; src < len; ++src) { if (!hasOwn.call(uniqueKeys, names[src])) { if (src > dst) { names[dst] = names[src]; } ++dst; } } names.length = dst; return names; }; function defaultCreatorFn(object) { return create(null); } function makeAccessor(secretCreatorFn) { var brand = makeUniqueKey(); var passkey = create(null); secretCreatorFn = secretCreatorFn || defaultCreatorFn; function register(object) { var secret; // Created lazily. function vault(key, forget) { // Only code that has access to the passkey can retrieve (or forget) // the secret object. if (key === passkey) { return forget ? secret = null : secret || (secret = secretCreatorFn(object)); } } defProp(object, brand, vault); } function accessor(object) { if (!hasOwn.call(object, brand)) register(object); return object[brand](passkey); } accessor.forget = function(object) { if (hasOwn.call(object, brand)) object[brand](passkey, true); }; return accessor; } defProp(exports, "makeAccessor", makeAccessor); },{}],436:[function(require,module,exports){ /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * https://raw.github.com/facebook/regenerator/master/LICENSE file. An * additional grant of patent rights can be found in the PATENTS file in * the same directory. */ var assert = require("assert"); var types = require("recast").types; var isArray = types.builtInTypes.array; var b = types.builders; var n = types.namedTypes; var leap = require("./leap"); var meta = require("./meta"); var util = require("./util"); var runtimeProperty = util.runtimeProperty; var hasOwn = Object.prototype.hasOwnProperty; function Emitter(contextId) { assert.ok(this instanceof Emitter); n.Identifier.assert(contextId); Object.defineProperties(this, { // In order to make sure the context object does not collide with // anything in the local scope, we might have to rename it, so we // refer to it symbolically instead of just assuming that it will be // called "context". contextId: { value: contextId }, // An append-only list of Statements that grows each time this.emit is // called. listing: { value: [] }, // A sparse array whose keys correspond to locations in this.listing // that have been marked as branch/jump targets. marked: { value: [true] }, // The last location will be marked when this.getDispatchLoop is // called. finalLoc: { value: loc() }, // A list of all leap.TryEntry statements emitted. tryEntries: { value: [] } }); // The .leapManager property needs to be defined by a separate // defineProperties call so that .finalLoc will be visible to the // leap.LeapManager constructor. Object.defineProperties(this, { // Each time we evaluate the body of a loop, we tell this.leapManager // to enter a nested loop context that determines the meaning of break // and continue statements therein. leapManager: { value: new leap.LeapManager(this) } }); } var Ep = Emitter.prototype; exports.Emitter = Emitter; // Offsets into this.listing that could be used as targets for branches or // jumps are represented as numeric Literal nodes. This representation has // the amazingly convenient benefit of allowing the exact value of the // location to be determined at any time, even after generating code that // refers to the location. function loc() { return b.literal(-1); } // Sets the exact value of the given location to the offset of the next // Statement emitted. Ep.mark = function(loc) { n.Literal.assert(loc); var index = this.listing.length; if (loc.value === -1) { loc.value = index; } else { // Locations can be marked redundantly, but their values cannot change // once set the first time. assert.strictEqual(loc.value, index); } this.marked[index] = true; return loc; }; Ep.emit = function(node) { if (n.Expression.check(node)) node = b.expressionStatement(node); n.Statement.assert(node); this.listing.push(node); }; // Shorthand for emitting assignment statements. This will come in handy // for assignments to temporary variables. Ep.emitAssign = function(lhs, rhs) { this.emit(this.assign(lhs, rhs)); return lhs; }; // Shorthand for an assignment statement. Ep.assign = function(lhs, rhs) { return b.expressionStatement( b.assignmentExpression("=", lhs, rhs)); }; // Convenience function for generating expressions like context.next, // context.sent, and context.rval. Ep.contextProperty = function(name, computed) { return b.memberExpression( this.contextId, computed ? b.literal(name) : b.identifier(name), !!computed ); }; var volatileContextPropertyNames = { prev: true, next: true, sent: true, rval: true }; // A "volatile" context property is a MemberExpression like context.sent // that should probably be stored in a temporary variable when there's a // possibility the property will get overwritten. Ep.isVolatileContextProperty = function(expr) { if (n.MemberExpression.check(expr)) { if (expr.computed) { // If it's a computed property such as context[couldBeAnything], // assume the worst in terms of volatility. return true; } if (n.Identifier.check(expr.object) && n.Identifier.check(expr.property) && expr.object.name === this.contextId.name && hasOwn.call(volatileContextPropertyNames, expr.property.name)) { return true; } } return false; }; // Shorthand for setting context.rval and jumping to `context.stop()`. Ep.stop = function(rval) { if (rval) { this.setReturnValue(rval); } this.jump(this.finalLoc); }; Ep.setReturnValue = function(valuePath) { n.Expression.assert(valuePath.value); this.emitAssign( this.contextProperty("rval"), this.explodeExpression(valuePath) ); }; Ep.clearPendingException = function(tryLoc, assignee) { n.Literal.assert(tryLoc); var catchCall = b.callExpression( this.contextProperty("catch", true), [tryLoc] ); if (assignee) { this.emitAssign(assignee, catchCall); } else { this.emit(catchCall); } }; // Emits code for an unconditional jump to the given location, even if the // exact value of the location is not yet known. Ep.jump = function(toLoc) { this.emitAssign(this.contextProperty("next"), toLoc); this.emit(b.breakStatement()); }; // Conditional jump. Ep.jumpIf = function(test, toLoc) { n.Expression.assert(test); n.Literal.assert(toLoc); this.emit(b.ifStatement( test, b.blockStatement([ this.assign(this.contextProperty("next"), toLoc), b.breakStatement() ]) )); }; // Conditional jump, with the condition negated. Ep.jumpIfNot = function(test, toLoc) { n.Expression.assert(test); n.Literal.assert(toLoc); var negatedTest; if (n.UnaryExpression.check(test) && test.operator === "!") { // Avoid double negation. negatedTest = test.argument; } else { negatedTest = b.unaryExpression("!", test); } this.emit(b.ifStatement( negatedTest, b.blockStatement([ this.assign(this.contextProperty("next"), toLoc), b.breakStatement() ]) )); }; // Returns a unique MemberExpression that can be used to store and // retrieve temporary values. Since the object of the member expression is // the context object, which is presumed to coexist peacefully with all // other local variables, and since we just increment `nextTempId` // monotonically, uniqueness is assured. var nextTempId = 0; Ep.makeTempVar = function() { return this.contextProperty("t" + nextTempId++); }; Ep.getContextFunction = function(id) { return b.functionExpression( id || null/*Anonymous*/, [this.contextId], b.blockStatement([this.getDispatchLoop()]), false, // Not a generator anymore! false // Nor an expression. ); }; // Turns this.listing into a loop of the form // // while (1) switch (context.next) { // case 0: // ... // case n: // return context.stop(); // } // // Each marked location in this.listing will correspond to one generated // case statement. Ep.getDispatchLoop = function() { var self = this; var cases = []; var current; // If we encounter a break, continue, or return statement in a switch // case, we can skip the rest of the statements until the next case. var alreadyEnded = false; self.listing.forEach(function(stmt, i) { if (self.marked.hasOwnProperty(i)) { cases.push(b.switchCase( b.literal(i), current = [])); alreadyEnded = false; } if (!alreadyEnded) { current.push(stmt); if (isSwitchCaseEnder(stmt)) alreadyEnded = true; } }); // Now that we know how many statements there will be in this.listing, // we can finally resolve this.finalLoc.value. this.finalLoc.value = this.listing.length; cases.push( b.switchCase(this.finalLoc, [ // Intentionally fall through to the "end" case... ]), // So that the runtime can jump to the final location without having // to know its offset, we provide the "end" case as a synonym. b.switchCase(b.literal("end"), [ // This will check/clear both context.thrown and context.rval. b.returnStatement( b.callExpression(this.contextProperty("stop"), []) ) ]) ); return b.whileStatement( b.literal(1), b.switchStatement( b.assignmentExpression( "=", this.contextProperty("prev"), this.contextProperty("next") ), cases ) ); }; // See comment above re: alreadyEnded. function isSwitchCaseEnder(stmt) { return n.BreakStatement.check(stmt) || n.ContinueStatement.check(stmt) || n.ReturnStatement.check(stmt) || n.ThrowStatement.check(stmt); } Ep.getTryLocsList = function() { if (this.tryEntries.length === 0) { // To avoid adding a needless [] to the majority of runtime.wrap // argument lists, force the caller to handle this case specially. return null; } var lastLocValue = 0; return b.arrayExpression( this.tryEntries.map(function(tryEntry) { var thisLocValue = tryEntry.firstLoc.value; assert.ok(thisLocValue >= lastLocValue, "try entries out of order"); lastLocValue = thisLocValue; var ce = tryEntry.catchEntry; var fe = tryEntry.finallyEntry; var locs = [ tryEntry.firstLoc, // The null here makes a hole in the array. ce ? ce.firstLoc : null ]; if (fe) { locs[2] = fe.firstLoc; locs[3] = fe.afterLoc; } return b.arrayExpression(locs); }) ); }; // All side effects must be realized in order. // If any subexpression harbors a leap, all subexpressions must be // neutered of side effects. // No destructive modification of AST nodes. Ep.explode = function(path, ignoreResult) { assert.ok(path instanceof types.NodePath); var node = path.value; var self = this; n.Node.assert(node); if (n.Statement.check(node)) return self.explodeStatement(path); if (n.Expression.check(node)) return self.explodeExpression(path, ignoreResult); if (n.Declaration.check(node)) throw getDeclError(node); switch (node.type) { case "Program": return path.get("body").map( self.explodeStatement, self ); case "VariableDeclarator": throw getDeclError(node); // These node types should be handled by their parent nodes // (ObjectExpression, SwitchStatement, and TryStatement, respectively). case "Property": case "SwitchCase": case "CatchClause": throw new Error( node.type + " nodes should be handled by their parents"); default: throw new Error( "unknown Node of type " + JSON.stringify(node.type)); } }; function getDeclError(node) { return new Error( "all declarations should have been transformed into " + "assignments before the Exploder began its work: " + JSON.stringify(node)); } Ep.explodeStatement = function(path, labelId) { assert.ok(path instanceof types.NodePath); var stmt = path.value; var self = this; n.Statement.assert(stmt); if (labelId) { n.Identifier.assert(labelId); } else { labelId = null; } // Explode BlockStatement nodes even if they do not contain a yield, // because we don't want or need the curly braces. if (n.BlockStatement.check(stmt)) { return path.get("body").each( self.explodeStatement, self ); } if (!meta.containsLeap(stmt)) { // Technically we should be able to avoid emitting the statement // altogether if !meta.hasSideEffects(stmt), but that leads to // confusing generated code (for instance, `while (true) {}` just // disappears) and is probably a more appropriate job for a dedicated // dead code elimination pass. self.emit(stmt); return; } switch (stmt.type) { case "ExpressionStatement": self.explodeExpression(path.get("expression"), true); break; case "LabeledStatement": var after = loc(); // Did you know you can break from any labeled block statement or // control structure? Well, you can! Note: when a labeled loop is // encountered, the leap.LabeledEntry created here will immediately // enclose a leap.LoopEntry on the leap manager's stack, and both // entries will have the same label. Though this works just fine, it // may seem a bit redundant. In theory, we could check here to // determine if stmt knows how to handle its own label; for example, // stmt happens to be a WhileStatement and so we know it's going to // establish its own LoopEntry when we explode it (below). Then this // LabeledEntry would be unnecessary. Alternatively, we might be // tempted not to pass stmt.label down into self.explodeStatement, // because we've handled the label here, but that's a mistake because // labeled loops may contain labeled continue statements, which is not // something we can handle in this generic case. All in all, I think a // little redundancy greatly simplifies the logic of this case, since // it's clear that we handle all possible LabeledStatements correctly // here, regardless of whether they interact with the leap manager // themselves. Also remember that labels and break/continue-to-label // statements are rare, and all of this logic happens at transform // time, so it has no additional runtime cost. self.leapManager.withEntry( new leap.LabeledEntry(after, stmt.label), function() { self.explodeStatement(path.get("body"), stmt.label); } ); self.mark(after); break; case "WhileStatement": var before = loc(); var after = loc(); self.mark(before); self.jumpIfNot(self.explodeExpression(path.get("test")), after); self.leapManager.withEntry( new leap.LoopEntry(after, before, labelId), function() { self.explodeStatement(path.get("body")); } ); self.jump(before); self.mark(after); break; case "DoWhileStatement": var first = loc(); var test = loc(); var after = loc(); self.mark(first); self.leapManager.withEntry( new leap.LoopEntry(after, test, labelId), function() { self.explode(path.get("body")); } ); self.mark(test); self.jumpIf(self.explodeExpression(path.get("test")), first); self.mark(after); break; case "ForStatement": var head = loc(); var update = loc(); var after = loc(); if (stmt.init) { // We pass true here to indicate that if stmt.init is an expression // then we do not care about its result. self.explode(path.get("init"), true); } self.mark(head); if (stmt.test) { self.jumpIfNot(self.explodeExpression(path.get("test")), after); } else { // No test means continue unconditionally. } self.leapManager.withEntry( new leap.LoopEntry(after, update, labelId), function() { self.explodeStatement(path.get("body")); } ); self.mark(update); if (stmt.update) { // We pass true here to indicate that if stmt.update is an // expression then we do not care about its result. self.explode(path.get("update"), true); } self.jump(head); self.mark(after); break; case "ForInStatement": n.Identifier.assert(stmt.left); var head = loc(); var after = loc(); var keyIterNextFn = self.makeTempVar(); self.emitAssign( keyIterNextFn, b.callExpression( runtimeProperty("keys"), [self.explodeExpression(path.get("right"))] ) ); self.mark(head); var keyInfoTmpVar = self.makeTempVar(); self.jumpIf( b.memberExpression( b.assignmentExpression( "=", keyInfoTmpVar, b.callExpression(keyIterNextFn, []) ), b.identifier("done"), false ), after ); self.emitAssign( stmt.left, b.memberExpression( keyInfoTmpVar, b.identifier("value"), false ) ); self.leapManager.withEntry( new leap.LoopEntry(after, head, labelId), function() { self.explodeStatement(path.get("body")); } ); self.jump(head); self.mark(after); break; case "BreakStatement": self.emitAbruptCompletion({ type: "break", target: self.leapManager.getBreakLoc(stmt.label) }); break; case "ContinueStatement": self.emitAbruptCompletion({ type: "continue", target: self.leapManager.getContinueLoc(stmt.label) }); break; case "SwitchStatement": // Always save the discriminant into a temporary variable in case the // test expressions overwrite values like context.sent. var disc = self.emitAssign( self.makeTempVar(), self.explodeExpression(path.get("discriminant")) ); var after = loc(); var defaultLoc = loc(); var condition = defaultLoc; var caseLocs = []; // If there are no cases, .cases might be undefined. var cases = stmt.cases || []; for (var i = cases.length - 1; i >= 0; --i) { var c = cases[i]; n.SwitchCase.assert(c); if (c.test) { condition = b.conditionalExpression( b.binaryExpression("===", disc, c.test), caseLocs[i] = loc(), condition ); } else { caseLocs[i] = defaultLoc; } } self.jump(self.explodeExpression( new types.NodePath(condition, path, "discriminant") )); self.leapManager.withEntry( new leap.SwitchEntry(after), function() { path.get("cases").each(function(casePath) { var c = casePath.value; var i = casePath.name; self.mark(caseLocs[i]); casePath.get("consequent").each( self.explodeStatement, self ); }); } ); self.mark(after); if (defaultLoc.value === -1) { self.mark(defaultLoc); assert.strictEqual(after.value, defaultLoc.value); } break; case "IfStatement": var elseLoc = stmt.alternate && loc(); var after = loc(); self.jumpIfNot( self.explodeExpression(path.get("test")), elseLoc || after ); self.explodeStatement(path.get("consequent")); if (elseLoc) { self.jump(after); self.mark(elseLoc); self.explodeStatement(path.get("alternate")); } self.mark(after); break; case "ReturnStatement": self.emitAbruptCompletion({ type: "return", value: self.explodeExpression(path.get("argument")) }); break; case "WithStatement": throw new Error( node.type + " not supported in generator functions."); case "TryStatement": var after = loc(); var handler = stmt.handler; if (!handler && stmt.handlers) { handler = stmt.handlers[0] || null; } var catchLoc = handler && loc(); var catchEntry = catchLoc && new leap.CatchEntry( catchLoc, handler.param ); var finallyLoc = stmt.finalizer && loc(); var finallyEntry = finallyLoc && new leap.FinallyEntry(finallyLoc, after); var tryEntry = new leap.TryEntry( self.getUnmarkedCurrentLoc(), catchEntry, finallyEntry ); self.tryEntries.push(tryEntry); self.updateContextPrevLoc(tryEntry.firstLoc); self.leapManager.withEntry(tryEntry, function() { self.explodeStatement(path.get("block")); if (catchLoc) { if (finallyLoc) { // If we have both a catch block and a finally block, then // because we emit the catch block first, we need to jump over // it to the finally block. self.jump(finallyLoc); } else { // If there is no finally block, then we need to jump over the // catch block to the fall-through location. self.jump(after); } self.updateContextPrevLoc(self.mark(catchLoc)); var bodyPath = path.get("handler", "body"); var safeParam = self.makeTempVar(); self.clearPendingException(tryEntry.firstLoc, safeParam); var catchScope = bodyPath.scope; var catchParamName = handler.param.name; n.CatchClause.assert(catchScope.node); assert.strictEqual(catchScope.lookup(catchParamName), catchScope); types.visit(bodyPath, { visitIdentifier: function(path) { if (util.isReference(path, catchParamName) && path.scope.lookup(catchParamName) === catchScope) { return safeParam; } this.traverse(path); }, visitFunction: function(path) { if (path.scope.declares(catchParamName)) { // Don't descend into nested scopes that shadow the catch // parameter with their own declarations. This isn't // logically necessary because of the path.scope.lookup we // do in visitIdentifier, but it saves time. return false; } this.traverse(path); } }); self.leapManager.withEntry(catchEntry, function() { self.explodeStatement(bodyPath); }); } if (finallyLoc) { self.updateContextPrevLoc(self.mark(finallyLoc)); self.leapManager.withEntry(finallyEntry, function() { self.explodeStatement(path.get("finalizer")); }); self.emit(b.returnStatement(b.callExpression( self.contextProperty("finish"), [finallyEntry.firstLoc] ))); } }); self.mark(after); break; case "ThrowStatement": self.emit(b.throwStatement( self.explodeExpression(path.get("argument")) )); break; default: throw new Error( "unknown Statement of type " + JSON.stringify(stmt.type)); } }; Ep.emitAbruptCompletion = function(record) { if (!isValidCompletion(record)) { assert.ok( false, "invalid completion record: " + JSON.stringify(record) ); } assert.notStrictEqual( record.type, "normal", "normal completions are not abrupt" ); var abruptArgs = [b.literal(record.type)]; if (record.type === "break" || record.type === "continue") { n.Literal.assert(record.target); abruptArgs[1] = record.target; } else if (record.type === "return" || record.type === "throw") { if (record.value) { n.Expression.assert(record.value); abruptArgs[1] = record.value; } } this.emit( b.returnStatement( b.callExpression( this.contextProperty("abrupt"), abruptArgs ) ) ); }; function isValidCompletion(record) { var type = record.type; if (type === "normal") { return !hasOwn.call(record, "target"); } if (type === "break" || type === "continue") { return !hasOwn.call(record, "value") && n.Literal.check(record.target); } if (type === "return" || type === "throw") { return hasOwn.call(record, "value") && !hasOwn.call(record, "target"); } return false; } // Not all offsets into emitter.listing are potential jump targets. For // example, execution typically falls into the beginning of a try block // without jumping directly there. This method returns the current offset // without marking it, so that a switch case will not necessarily be // generated for this offset (I say "not necessarily" because the same // location might end up being marked in the process of emitting other // statements). There's no logical harm in marking such locations as jump // targets, but minimizing the number of switch cases keeps the generated // code shorter. Ep.getUnmarkedCurrentLoc = function() { return b.literal(this.listing.length); }; // The context.prev property takes the value of context.next whenever we // evaluate the switch statement discriminant, which is generally good // enough for tracking the last location we jumped to, but sometimes // context.prev needs to be more precise, such as when we fall // successfully out of a try block and into a finally block without // jumping. This method exists to update context.prev to the freshest // available location. If we were implementing a full interpreter, we // would know the location of the current instruction with complete // precision at all times, but we don't have that luxury here, as it would // be costly and verbose to set context.prev before every statement. Ep.updateContextPrevLoc = function(loc) { if (loc) { n.Literal.assert(loc); if (loc.value === -1) { // If an uninitialized location literal was passed in, set its value // to the current this.listing.length. loc.value = this.listing.length; } else { // Otherwise assert that the location matches the current offset. assert.strictEqual(loc.value, this.listing.length); } } else { loc = this.getUnmarkedCurrentLoc(); } // Make sure context.prev is up to date in case we fell into this try // statement without jumping to it. TODO Consider avoiding this // assignment when we know control must have jumped here. this.emitAssign(this.contextProperty("prev"), loc); }; Ep.explodeExpression = function(path, ignoreResult) { assert.ok(path instanceof types.NodePath); var expr = path.value; if (expr) { n.Expression.assert(expr); } else { return expr; } var self = this; var result; // Used optionally by several cases below. function finish(expr) { n.Expression.assert(expr); if (ignoreResult) { self.emit(expr); } else { return expr; } } // If the expression does not contain a leap, then we either emit the // expression as a standalone statement or return it whole. if (!meta.containsLeap(expr)) { return finish(expr); } // If any child contains a leap (such as a yield or labeled continue or // break statement), then any sibling subexpressions will almost // certainly have to be exploded in order to maintain the order of their // side effects relative to the leaping child(ren). var hasLeapingChildren = meta.containsLeap.onlyChildren(expr); // In order to save the rest of explodeExpression from a combinatorial // trainwreck of special cases, explodeViaTempVar is responsible for // deciding when a subexpression needs to be "exploded," which is my // very technical term for emitting the subexpression as an assignment // to a temporary variable and the substituting the temporary variable // for the original subexpression. Think of exploded view diagrams, not // Michael Bay movies. The point of exploding subexpressions is to // control the precise order in which the generated code realizes the // side effects of those subexpressions. function explodeViaTempVar(tempVar, childPath, ignoreChildResult) { assert.ok(childPath instanceof types.NodePath); assert.ok( !ignoreChildResult || !tempVar, "Ignoring the result of a child expression but forcing it to " + "be assigned to a temporary variable?" ); var result = self.explodeExpression(childPath, ignoreChildResult); if (ignoreChildResult) { // Side effects already emitted above. } else if (tempVar || (hasLeapingChildren && (self.isVolatileContextProperty(result) || meta.hasSideEffects(result)))) { // If tempVar was provided, then the result will always be assigned // to it, even if the result does not otherwise need to be assigned // to a temporary variable. When no tempVar is provided, we have // the flexibility to decide whether a temporary variable is really // necessary. In general, temporary assignment is required only // when some other child contains a leap and the child in question // is a context property like $ctx.sent that might get overwritten // or an expression with side effects that need to occur in proper // sequence relative to the leap. result = self.emitAssign( tempVar || self.makeTempVar(), result ); } return result; } // If ignoreResult is true, then we must take full responsibility for // emitting the expression with all its side effects, and we should not // return a result. switch (expr.type) { case "MemberExpression": return finish(b.memberExpression( self.explodeExpression(path.get("object")), expr.computed ? explodeViaTempVar(null, path.get("property")) : expr.property, expr.computed )); case "CallExpression": var oldCalleePath = path.get("callee"); var newCallee = self.explodeExpression(oldCalleePath); // If the callee was not previously a MemberExpression, then the // CallExpression was "unqualified," meaning its `this` object should // be the global object. If the exploded expression has become a // MemberExpression, then we need to force it to be unqualified by // using the (0, object.property)(...) trick; otherwise, it will // receive the object of the MemberExpression as its `this` object. if (!n.MemberExpression.check(oldCalleePath.node) && n.MemberExpression.check(newCallee)) { newCallee = b.sequenceExpression([ b.literal(0), newCallee ]); } return finish(b.callExpression( newCallee, path.get("arguments").map(function(argPath) { return explodeViaTempVar(null, argPath); }) )); case "NewExpression": return finish(b.newExpression( explodeViaTempVar(null, path.get("callee")), path.get("arguments").map(function(argPath) { return explodeViaTempVar(null, argPath); }) )); case "ObjectExpression": return finish(b.objectExpression( path.get("properties").map(function(propPath) { return b.property( propPath.value.kind, propPath.value.key, explodeViaTempVar(null, propPath.get("value")) ); }) )); case "ArrayExpression": return finish(b.arrayExpression( path.get("elements").map(function(elemPath) { return explodeViaTempVar(null, elemPath); }) )); case "SequenceExpression": var lastIndex = expr.expressions.length - 1; path.get("expressions").each(function(exprPath) { if (exprPath.name === lastIndex) { result = self.explodeExpression(exprPath, ignoreResult); } else { self.explodeExpression(exprPath, true); } }); return result; case "LogicalExpression": var after = loc(); if (!ignoreResult) { result = self.makeTempVar(); } var left = explodeViaTempVar(result, path.get("left")); if (expr.operator === "&&") { self.jumpIfNot(left, after); } else { assert.strictEqual(expr.operator, "||"); self.jumpIf(left, after); } explodeViaTempVar(result, path.get("right"), ignoreResult); self.mark(after); return result; case "ConditionalExpression": var elseLoc = loc(); var after = loc(); var test = self.explodeExpression(path.get("test")); self.jumpIfNot(test, elseLoc); if (!ignoreResult) { result = self.makeTempVar(); } explodeViaTempVar(result, path.get("consequent"), ignoreResult); self.jump(after); self.mark(elseLoc); explodeViaTempVar(result, path.get("alternate"), ignoreResult); self.mark(after); return result; case "UnaryExpression": return finish(b.unaryExpression( expr.operator, // Can't (and don't need to) break up the syntax of the argument. // Think about delete a[b]. self.explodeExpression(path.get("argument")), !!expr.prefix )); case "BinaryExpression": return finish(b.binaryExpression( expr.operator, explodeViaTempVar(null, path.get("left")), explodeViaTempVar(null, path.get("right")) )); case "AssignmentExpression": return finish(b.assignmentExpression( expr.operator, self.explodeExpression(path.get("left")), self.explodeExpression(path.get("right")) )); case "UpdateExpression": return finish(b.updateExpression( expr.operator, self.explodeExpression(path.get("argument")), expr.prefix )); case "YieldExpression": var after = loc(); var arg = expr.argument && self.explodeExpression(path.get("argument")); if (arg && expr.delegate) { var result = self.makeTempVar(); self.emit(b.returnStatement(b.callExpression( self.contextProperty("delegateYield"), [ arg, b.literal(result.property.name), after ] ))); self.mark(after); return result; } self.emitAssign(self.contextProperty("next"), after); self.emit(b.returnStatement(arg || null)); self.mark(after); return self.contextProperty("sent"); default: throw new Error( "unknown Expression of type " + JSON.stringify(expr.type)); } }; },{"./leap":438,"./meta":439,"./util":440,"assert":190,"recast":469}],437:[function(require,module,exports){ /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * https://raw.github.com/facebook/regenerator/master/LICENSE file. An * additional grant of patent rights can be found in the PATENTS file in * the same directory. */ var assert = require("assert"); var types = require("recast").types; var n = types.namedTypes; var b = types.builders; var hasOwn = Object.prototype.hasOwnProperty; // The hoist function takes a FunctionExpression or FunctionDeclaration // and replaces any Declaration nodes in its body with assignments, then // returns a VariableDeclaration containing just the names of the removed // declarations. exports.hoist = function(funPath) { assert.ok(funPath instanceof types.NodePath); n.Function.assert(funPath.value); var vars = {}; function varDeclToExpr(vdec, includeIdentifiers) { n.VariableDeclaration.assert(vdec); var exprs = []; vdec.declarations.forEach(function(dec) { vars[dec.id.name] = dec.id; if (dec.init) { exprs.push(b.assignmentExpression( "=", dec.id, dec.init )); } else if (includeIdentifiers) { exprs.push(dec.id); } }); if (exprs.length === 0) return null; if (exprs.length === 1) return exprs[0]; return b.sequenceExpression(exprs); } types.visit(funPath.get("body"), { visitVariableDeclaration: function(path) { var expr = varDeclToExpr(path.value, false); if (expr === null) { path.replace(); } else { // We don't need to traverse this expression any further because // there can't be any new declarations inside an expression. return b.expressionStatement(expr); } // Since the original node has been either removed or replaced, // avoid traversing it any further. return false; }, visitForStatement: function(path) { var init = path.value.init; if (n.VariableDeclaration.check(init)) { path.get("init").replace(varDeclToExpr(init, false)); } this.traverse(path); }, visitForInStatement: function(path) { var left = path.value.left; if (n.VariableDeclaration.check(left)) { path.get("left").replace(varDeclToExpr(left, true)); } this.traverse(path); }, visitFunctionDeclaration: function(path) { var node = path.value; vars[node.id.name] = node.id; var parentNode = path.parent.node; var assignment = b.expressionStatement( b.assignmentExpression( "=", node.id, b.functionExpression( node.id, node.params, node.body, node.generator, node.expression ) ) ); if (n.BlockStatement.check(path.parent.node)) { // Insert the assignment form before the first statement in the // enclosing block. path.parent.get("body").unshift(assignment); // Remove the function declaration now that we've inserted the // equivalent assignment form at the beginning of the block. path.replace(); } else { // If the parent node is not a block statement, then we can just // replace the declaration with the equivalent assignment form // without worrying about hoisting it. path.replace(assignment); } // Don't hoist variables out of inner functions. return false; }, visitFunctionExpression: function(path) { // Don't descend into nested function expressions. return false; } }); var paramNames = {}; funPath.get("params").each(function(paramPath) { var param = paramPath.value; if (n.Identifier.check(param)) { paramNames[param.name] = param; } else { // Variables declared by destructuring parameter patterns will be // harmlessly re-declared. } }); var declarations = []; Object.keys(vars).forEach(function(name) { if (!hasOwn.call(paramNames, name)) { declarations.push(b.variableDeclarator(vars[name], null)); } }); if (declarations.length === 0) { return null; // Be sure to handle this case! } return b.variableDeclaration("var", declarations); }; },{"assert":190,"recast":469}],438:[function(require,module,exports){ /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * https://raw.github.com/facebook/regenerator/master/LICENSE file. An * additional grant of patent rights can be found in the PATENTS file in * the same directory. */ var assert = require("assert"); var types = require("recast").types; var n = types.namedTypes; var b = types.builders; var inherits = require("util").inherits; var hasOwn = Object.prototype.hasOwnProperty; function Entry() { assert.ok(this instanceof Entry); } function FunctionEntry(returnLoc) { Entry.call(this); n.Literal.assert(returnLoc); this.returnLoc = returnLoc; } inherits(FunctionEntry, Entry); exports.FunctionEntry = FunctionEntry; function LoopEntry(breakLoc, continueLoc, label) { Entry.call(this); n.Literal.assert(breakLoc); n.Literal.assert(continueLoc); if (label) { n.Identifier.assert(label); } else { label = null; } this.breakLoc = breakLoc; this.continueLoc = continueLoc; this.label = label; } inherits(LoopEntry, Entry); exports.LoopEntry = LoopEntry; function SwitchEntry(breakLoc) { Entry.call(this); n.Literal.assert(breakLoc); this.breakLoc = breakLoc; } inherits(SwitchEntry, Entry); exports.SwitchEntry = SwitchEntry; function TryEntry(firstLoc, catchEntry, finallyEntry) { Entry.call(this); n.Literal.assert(firstLoc); if (catchEntry) { assert.ok(catchEntry instanceof CatchEntry); } else { catchEntry = null; } if (finallyEntry) { assert.ok(finallyEntry instanceof FinallyEntry); } else { finallyEntry = null; } // Have to have one or the other (or both). assert.ok(catchEntry || finallyEntry); this.firstLoc = firstLoc; this.catchEntry = catchEntry; this.finallyEntry = finallyEntry; } inherits(TryEntry, Entry); exports.TryEntry = TryEntry; function CatchEntry(firstLoc, paramId) { Entry.call(this); n.Literal.assert(firstLoc); n.Identifier.assert(paramId); this.firstLoc = firstLoc; this.paramId = paramId; } inherits(CatchEntry, Entry); exports.CatchEntry = CatchEntry; function FinallyEntry(firstLoc, afterLoc) { Entry.call(this); n.Literal.assert(firstLoc); n.Literal.assert(afterLoc); this.firstLoc = firstLoc; this.afterLoc = afterLoc; } inherits(FinallyEntry, Entry); exports.FinallyEntry = FinallyEntry; function LabeledEntry(breakLoc, label) { Entry.call(this); n.Literal.assert(breakLoc); n.Identifier.assert(label); this.breakLoc = breakLoc; this.label = label; } inherits(LabeledEntry, Entry); exports.LabeledEntry = LabeledEntry; function LeapManager(emitter) { assert.ok(this instanceof LeapManager); var Emitter = require("./emit").Emitter; assert.ok(emitter instanceof Emitter); this.emitter = emitter; this.entryStack = [new FunctionEntry(emitter.finalLoc)]; } var LMp = LeapManager.prototype; exports.LeapManager = LeapManager; LMp.withEntry = function(entry, callback) { assert.ok(entry instanceof Entry); this.entryStack.push(entry); try { callback.call(this.emitter); } finally { var popped = this.entryStack.pop(); assert.strictEqual(popped, entry); } }; LMp._findLeapLocation = function(property, label) { for (var i = this.entryStack.length - 1; i >= 0; --i) { var entry = this.entryStack[i]; var loc = entry[property]; if (loc) { if (label) { if (entry.label && entry.label.name === label.name) { return loc; } } else if (entry instanceof LabeledEntry) { // Ignore LabeledEntry entries unless we are actually breaking to // a label. } else { return loc; } } } return null; }; LMp.getBreakLoc = function(label) { return this._findLeapLocation("breakLoc", label); }; LMp.getContinueLoc = function(label) { return this._findLeapLocation("continueLoc", label); }; },{"./emit":436,"assert":190,"recast":469,"util":216}],439:[function(require,module,exports){ /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * https://raw.github.com/facebook/regenerator/master/LICENSE file. An * additional grant of patent rights can be found in the PATENTS file in * the same directory. */ var assert = require("assert"); var m = require("private").makeAccessor(); var types = require("recast").types; var isArray = types.builtInTypes.array; var n = types.namedTypes; var hasOwn = Object.prototype.hasOwnProperty; function makePredicate(propertyName, knownTypes) { function onlyChildren(node) { n.Node.assert(node); // Assume no side effects until we find out otherwise. var result = false; function check(child) { if (result) { // Do nothing. } else if (isArray.check(child)) { child.some(check); } else if (n.Node.check(child)) { assert.strictEqual(result, false); result = predicate(child); } return result; } types.eachField(node, function(name, child) { check(child); }); return result; } function predicate(node) { n.Node.assert(node); var meta = m(node); if (hasOwn.call(meta, propertyName)) return meta[propertyName]; // Certain types are "opaque," which means they have no side // effects or leaps and we don't care about their subexpressions. if (hasOwn.call(opaqueTypes, node.type)) return meta[propertyName] = false; if (hasOwn.call(knownTypes, node.type)) return meta[propertyName] = true; return meta[propertyName] = onlyChildren(node); } predicate.onlyChildren = onlyChildren; return predicate; } var opaqueTypes = { FunctionExpression: true }; // These types potentially have side effects regardless of what side // effects their subexpressions have. var sideEffectTypes = { CallExpression: true, // Anything could happen! ForInStatement: true, // Modifies the key variable. UnaryExpression: true, // Think delete. BinaryExpression: true, // Might invoke .toString() or .valueOf(). AssignmentExpression: true, // Side-effecting by definition. UpdateExpression: true, // Updates are essentially assignments. NewExpression: true // Similar to CallExpression. }; // These types are the direct cause of all leaps in control flow. var leapTypes = { YieldExpression: true, BreakStatement: true, ContinueStatement: true, ReturnStatement: true, ThrowStatement: true }; // All leap types are also side effect types. for (var type in leapTypes) { if (hasOwn.call(leapTypes, type)) { sideEffectTypes[type] = leapTypes[type]; } } exports.hasSideEffects = makePredicate("hasSideEffects", sideEffectTypes); exports.containsLeap = makePredicate("containsLeap", leapTypes); },{"assert":190,"private":435,"recast":469}],440:[function(require,module,exports){ /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * https://raw.github.com/facebook/regenerator/master/LICENSE file. An * additional grant of patent rights can be found in the PATENTS file in * the same directory. */ var assert = require("assert"); var types = require("recast").types; var n = types.namedTypes; var b = types.builders; var hasOwn = Object.prototype.hasOwnProperty; exports.defaults = function(obj) { var len = arguments.length; var extension; for (var i = 1; i < len; ++i) { if ((extension = arguments[i])) { for (var key in extension) { if (hasOwn.call(extension, key) && !hasOwn.call(obj, key)) { obj[key] = extension[key]; } } } } return obj; }; exports.runtimeProperty = function(name) { return b.memberExpression( b.identifier("regeneratorRuntime"), b.identifier(name), false ); }; // Inspired by the isReference function from ast-util: // https://github.com/eventualbuddha/ast-util/blob/9bf91c5ce8/lib/index.js#L466-L506 exports.isReference = function(path, name) { var node = path.value; if (!n.Identifier.check(node)) { return false; } if (name && node.name !== name) { return false; } var parent = path.parent.value; switch (parent.type) { case "VariableDeclarator": return path.name === "init"; case "MemberExpression": return path.name === "object" || ( parent.computed && path.name === "property" ); case "FunctionExpression": case "FunctionDeclaration": case "ArrowFunctionExpression": if (path.name === "id") { return false; } if (parent.params === path.parentPath && parent.params[path.name] === node) { return false; } return true; case "ClassDeclaration": case "ClassExpression": return path.name !== "id"; case "CatchClause": return path.name !== "param"; case "Property": case "MethodDefinition": return path.name !== "key"; case "ImportSpecifier": case "ImportDefaultSpecifier": case "ImportNamespaceSpecifier": case "LabeledStatement": return false; default: return true; } }; },{"assert":190,"recast":469}],441:[function(require,module,exports){ /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * https://raw.github.com/facebook/regenerator/master/LICENSE file. An * additional grant of patent rights can be found in the PATENTS file in * the same directory. */ var assert = require("assert"); var fs = require("fs"); var recast = require("recast"); var types = recast.types; var n = types.namedTypes; var b = types.builders; var isArray = types.builtInTypes.array; var isObject = types.builtInTypes.object; var NodePath = types.NodePath; var hoist = require("./hoist").hoist; var Emitter = require("./emit").Emitter; var runtimeProperty = require("./util").runtimeProperty; var getMarkInfo = require("private").makeAccessor(); exports.transform = function transform(node, options) { options = options || {}; var path = node instanceof NodePath ? node : new NodePath(node); visitor.visit(path, options); node = path.value; if (options.includeRuntime === true || (options.includeRuntime === 'if used' && visitor.wasChangeReported())) { injectRuntime(n.File.check(node) ? node.program : node); } options.madeChanges = visitor.wasChangeReported(); return node; }; function injectRuntime(program) { n.Program.assert(program); // Include the runtime by modifying the AST rather than by concatenating // strings. This technique will allow for more accurate source mapping. var runtimePath = require("..").runtime.path; var runtime = fs.readFileSync(runtimePath, "utf8"); var runtimeBody = recast.parse(runtime, { sourceFileName: runtimePath }).program.body; var body = program.body; body.unshift.apply(body, runtimeBody); } var visitor = types.PathVisitor.fromMethodsObject({ reset: function(node, options) { this.options = options; }, visitFunction: function(path) { // Calling this.traverse(path) first makes for a post-order traversal. this.traverse(path); var node = path.value; var shouldTransformAsync = node.async && !this.options.disableAsync; if (!node.generator && !shouldTransformAsync) { return; } this.reportChanged(); node.generator = false; if (node.expression) { // Transform expression lambdas into normal functions. node.expression = false; node.body = b.blockStatement([ b.returnStatement(node.body) ]); } if (shouldTransformAsync) { awaitVisitor.visit(path.get("body")); } var outerBody = []; var innerBody = []; var bodyPath = path.get("body", "body"); bodyPath.each(function(childPath) { var node = childPath.value; if (node && node._blockHoist != null) { outerBody.push(node); } else { innerBody.push(node); } }); if (outerBody.length > 0) { // Only replace the inner body if we actually hoisted any statements // to the outer body. bodyPath.replace(innerBody); } var outerFnExpr = getOuterFnExpr(path); // Note that getOuterFnExpr has the side-effect of ensuring that the // function has a name (so node.id will always be an Identifier), even // if a temporary name has to be synthesized. n.Identifier.assert(node.id); var innerFnId = b.identifier(node.id.name + "$"); var contextId = path.scope.declareTemporary("context$"); var argsId = path.scope.declareTemporary("args$"); var shouldAliasArguments = renameArguments(path, argsId); var vars = hoist(path); if (shouldAliasArguments) { vars = vars || b.variableDeclaration("var", []); vars.declarations.push(b.variableDeclarator( argsId, b.identifier("arguments") )); } var emitter = new Emitter(contextId); emitter.explode(path.get("body")); if (vars && vars.declarations.length > 0) { outerBody.push(vars); } var wrapArgs = [ emitter.getContextFunction(innerFnId), // Async functions don't care about the outer function because they // don't need it to be marked and don't inherit from its .prototype. shouldTransformAsync ? b.literal(null) : outerFnExpr, b.thisExpression() ]; var tryLocsList = emitter.getTryLocsList(); if (tryLocsList) { wrapArgs.push(tryLocsList); } var wrapCall = b.callExpression( runtimeProperty(shouldTransformAsync ? "async" : "wrap"), wrapArgs ); outerBody.push(b.returnStatement(wrapCall)); node.body = b.blockStatement(outerBody); if (shouldTransformAsync) { node.async = false; return; } if (n.Expression.check(node)) { return b.callExpression(runtimeProperty("mark"), [node]); } }, visitForOfStatement: function(path) { this.traverse(path); var node = path.value; var tempIterId = path.scope.declareTemporary("t$"); var tempIterDecl = b.variableDeclarator( tempIterId, b.callExpression( runtimeProperty("values"), [node.right] ) ); var tempInfoId = path.scope.declareTemporary("t$"); var tempInfoDecl = b.variableDeclarator(tempInfoId, null); var init = node.left; var loopId; if (n.VariableDeclaration.check(init)) { loopId = init.declarations[0].id; init.declarations.push(tempIterDecl, tempInfoDecl); } else { loopId = init; init = b.variableDeclaration("var", [ tempIterDecl, tempInfoDecl ]); } n.Identifier.assert(loopId); var loopIdAssignExprStmt = b.expressionStatement( b.assignmentExpression( "=", loopId, b.memberExpression( tempInfoId, b.identifier("value"), false ) ) ); if (n.BlockStatement.check(node.body)) { node.body.body.unshift(loopIdAssignExprStmt); } else { node.body = b.blockStatement([ loopIdAssignExprStmt, node.body ]); } return b.forStatement( init, b.unaryExpression( "!", b.memberExpression( b.assignmentExpression( "=", tempInfoId, b.callExpression( b.memberExpression( tempIterId, b.identifier("next"), false ), [] ) ), b.identifier("done"), false ) ), null, node.body ); } }); // Given a NodePath for a Function, return an Expression node that can be // used to refer reliably to the function object from inside the function. // This expression is essentially a replacement for arguments.callee, with // the key advantage that it works in strict mode. function getOuterFnExpr(funPath) { var node = funPath.value; n.Function.assert(node); if (!node.async && // Async functions don't need to be marked. n.FunctionDeclaration.check(node)) { var pp = funPath.parent; while (pp && !(n.BlockStatement.check(pp.value) || n.Program.check(pp.value))) { pp = pp.parent; } if (!pp) { return node.id; } var markDecl = getRuntimeMarkDecl(pp); var markedArray = markDecl.declarations[0].id; var funDeclIdArray = markDecl.declarations[0].init.callee.object; n.ArrayExpression.assert(funDeclIdArray); var index = funDeclIdArray.elements.length; funDeclIdArray.elements.push(node.id); return b.memberExpression( markedArray, b.literal(index), true ); } return node.id || ( node.id = funPath.scope.parent.declareTemporary("callee$") ); } function getRuntimeMarkDecl(blockPath) { assert.ok(blockPath instanceof NodePath); var block = blockPath.node; isArray.assert(block.body); var info = getMarkInfo(block); if (info.decl) { return info.decl; } info.decl = b.variableDeclaration("var", [ b.variableDeclarator( blockPath.scope.declareTemporary("marked"), b.callExpression( b.memberExpression( b.arrayExpression([]), b.identifier("map"), false ), [runtimeProperty("mark")] ) ) ]); for (var i = 0; i < block.body.length; ++i) { if (!shouldNotHoistAbove(blockPath.get("body", i))) { break; } } blockPath.get("body").insertAt(i, info.decl); return info.decl; } function shouldNotHoistAbove(stmtPath) { var value = stmtPath.value; n.Statement.assert(value); // If the first statement is a "use strict" declaration, make sure to // insert hoisted declarations afterwards. return n.ExpressionStatement.check(value) && n.Literal.check(value.expression) && value.expression.value === "use strict"; } function renameArguments(funcPath, argsId) { assert.ok(funcPath instanceof types.NodePath); var func = funcPath.value; var didReplaceArguments = false; var hasImplicitArguments = false; recast.visit(funcPath, { visitFunction: function(path) { if (path.value === func) { hasImplicitArguments = !path.scope.lookup("arguments"); this.traverse(path); } else { return false; } }, visitIdentifier: function(path) { if (path.value.name === "arguments") { var isMemberProperty = n.MemberExpression.check(path.parent.node) && path.name === "property" && !path.parent.node.computed; if (!isMemberProperty) { path.replace(argsId); didReplaceArguments = true; return false; } } this.traverse(path); } }); // If the traversal replaced any arguments identifiers, and those // identifiers were free variables, then we need to alias the outer // function's arguments object to the variable named by argsId. return didReplaceArguments && hasImplicitArguments; } var awaitVisitor = types.PathVisitor.fromMethodsObject({ visitFunction: function(path) { return false; // Don't descend into nested function scopes. }, visitAwaitExpression: function(path) { // Convert await and await* expressions to yield expressions. var argument = path.value.argument; // If the parser supports await* syntax using a boolean .all property // (#171), desugar that syntax to yield Promise.all(argument). if (path.value.all) { argument = b.callExpression( b.memberExpression( b.identifier("Promise"), b.identifier("all"), false ), [argument] ); } return b.yieldExpression(argument, false); } }); },{"..":442,"./emit":436,"./hoist":437,"./util":440,"assert":190,"fs":189,"private":435,"recast":469}],442:[function(require,module,exports){ (function (__dirname){ /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * https://raw.github.com/facebook/regenerator/master/LICENSE file. An * additional grant of patent rights can be found in the PATENTS file in * the same directory. */ var assert = require("assert"); var path = require("path"); var fs = require("fs"); var through = require("through"); var transform = require("./lib/visit").transform; var utils = require("./lib/util"); var recast = require("recast"); var types = recast.types; var genOrAsyncFunExp = /\bfunction\s*\*|\basync\b/; var blockBindingExp = /\b(let|const)\s+/; function exports(file, options) { var data = []; return through(write, end); function write(buf) { data.push(buf); } function end() { this.queue(compile(data.join(""), options).code); this.queue(null); } } // To get a writable stream for use as a browserify transform, call // require("regenerator")(). module.exports = exports; // To include the runtime globally in the current node process, call // require("regenerator").runtime(). function runtime() { require("./runtime"); } exports.runtime = runtime; runtime.path = path.join(__dirname, "runtime.js"); function compile(source, options) { options = normalizeOptions(options); if (!genOrAsyncFunExp.test(source)) { return { // Shortcut: no generators or async functions to transform. code: (options.includeRuntime === true ? fs.readFileSync( path.join(__dirname, "runtime.js"), "utf-8" ) + "\n" : "") + source }; } var recastOptions = getRecastOptions(options); var ast = recast.parse(source, recastOptions); var nodePath = new types.NodePath(ast); var programPath = nodePath.get("program"); if (shouldVarify(source, options)) { // Transpile let/const into var declarations. varifyAst(programPath.node); } transform(programPath, options); return recast.print(nodePath, recastOptions); } function normalizeOptions(options) { options = utils.defaults(options || {}, { includeRuntime: false, supportBlockBinding: true }); if (!options.esprima) { options.esprima = require("esprima-fb"); } assert.ok( /harmony/.test(options.esprima.version), "Bad esprima version: " + options.esprima.version ); return options; } function getRecastOptions(options) { var recastOptions = { range: true }; function copy(name) { if (name in options) { recastOptions[name] = options[name]; } } copy("esprima"); copy("sourceFileName"); copy("sourceMapName"); copy("inputSourceMap"); copy("sourceRoot"); return recastOptions; } function shouldVarify(source, options) { var supportBlockBinding = !!options.supportBlockBinding; if (supportBlockBinding) { if (!blockBindingExp.test(source)) { supportBlockBinding = false; } } return supportBlockBinding; } function varify(source, options) { var recastOptions = getRecastOptions(normalizeOptions(options)); var ast = recast.parse(source, recastOptions); varifyAst(ast.program); return recast.print(ast, recastOptions).code; } function varifyAst(ast) { types.namedTypes.Program.assert(ast); var defsResult = require("defs")(ast, { ast: true, disallowUnknownReferences: false, disallowDuplicated: false, disallowVars: false, loopClosures: "iife" }); if (defsResult.errors) { throw new Error(defsResult.errors.join("\n")) } return ast; } // Convenience for just translating let/const to var declarations. exports.varify = varify; // Transforms a string of source code, returning the { code, map? } result // from recast.print. exports.compile = compile; // To modify an AST directly, call require("regenerator").transform(ast). exports.transform = transform; }).call(this,"/node_modules/regenerator") },{"./lib/util":440,"./lib/visit":441,"./runtime":472,"assert":190,"defs":443,"esprima-fb":458,"fs":189,"path":199,"recast":469,"through":471}],443:[function(require,module,exports){ "use strict"; var assert = require("assert"); var is = require("simple-is"); var fmt = require("simple-fmt"); var stringmap = require("stringmap"); var stringset = require("stringset"); var alter = require("alter"); var traverse = require("ast-traverse"); var breakable = require("breakable"); var Scope = require("./scope"); var error = require("./error"); var getline = error.getline; var options = require("./options"); var Stats = require("./stats"); var jshint_vars = require("./jshint_globals/vars.js"); function isConstLet(kind) { return is.someof(kind, ["const", "let"]); } function isVarConstLet(kind) { return is.someof(kind, ["var", "const", "let"]); } function isNonFunctionBlock(node) { return node.type === "BlockStatement" && is.noneof(node.$parent.type, ["FunctionDeclaration", "FunctionExpression"]); } function isForWithConstLet(node) { return node.type === "ForStatement" && node.init && node.init.type === "VariableDeclaration" && isConstLet(node.init.kind); } function isForInOfWithConstLet(node) { return isForInOf(node) && node.left.type === "VariableDeclaration" && isConstLet(node.left.kind); } function isForInOf(node) { return is.someof(node.type, ["ForInStatement", "ForOfStatement"]); } function isFunction(node) { return is.someof(node.type, ["FunctionDeclaration", "FunctionExpression"]); } function isLoop(node) { return is.someof(node.type, ["ForStatement", "ForInStatement", "ForOfStatement", "WhileStatement", "DoWhileStatement"]); } function isReference(node) { var parent = node.$parent; return node.$refToScope || node.type === "Identifier" && !(parent.type === "VariableDeclarator" && parent.id === node) && // var|let|const $ !(parent.type === "MemberExpression" && parent.computed === false && parent.property === node) && // obj.$ !(parent.type === "Property" && parent.key === node) && // {$: ...} !(parent.type === "LabeledStatement" && parent.label === node) && // $: ... !(parent.type === "CatchClause" && parent.param === node) && // catch($) !(isFunction(parent) && parent.id === node) && // function $(.. !(isFunction(parent) && is.someof(node, parent.params)) && // function f($).. true; } function isLvalue(node) { return isReference(node) && ((node.$parent.type === "AssignmentExpression" && node.$parent.left === node) || (node.$parent.type === "UpdateExpression" && node.$parent.argument === node)); } function createScopes(node, parent) { assert(!node.$scope); node.$parent = parent; node.$scope = node.$parent ? node.$parent.$scope : null; // may be overridden if (node.type === "Program") { // Top-level program is a scope // There's no block-scope under it node.$scope = new Scope({ kind: "hoist", node: node, parent: null, }); } else if (isFunction(node)) { // Function is a scope, with params in it // There's no block-scope under it node.$scope = new Scope({ kind: "hoist", node: node, parent: node.$parent.$scope, }); // function has a name if (node.id) { assert(node.id.type === "Identifier"); if (node.type === "FunctionDeclaration") { // Function name goes in parent scope for declared functions node.$parent.$scope.add(node.id.name, "fun", node.id, null); } else if (node.type === "FunctionExpression") { // Function name goes in function's scope for named function expressions node.$scope.add(node.id.name, "fun", node.id, null); } else { assert(false); } } node.params.forEach(function(param) { node.$scope.add(param.name, "param", param, null); }); } else if (node.type === "VariableDeclaration") { // Variable declarations names goes in current scope assert(isVarConstLet(node.kind)); node.declarations.forEach(function(declarator) { assert(declarator.type === "VariableDeclarator"); var name = declarator.id.name; if (options.disallowVars && node.kind === "var") { error(getline(declarator), "var {0} is not allowed (use let or const)", name); } node.$scope.add(name, node.kind, declarator.id, declarator.range[1]); }); } else if (isForWithConstLet(node) || isForInOfWithConstLet(node)) { // For(In/Of) loop with const|let declaration is a scope, with declaration in it // There may be a block-scope under it node.$scope = new Scope({ kind: "block", node: node, parent: node.$parent.$scope, }); } else if (isNonFunctionBlock(node)) { // A block node is a scope unless parent is a function node.$scope = new Scope({ kind: "block", node: node, parent: node.$parent.$scope, }); } else if (node.type === "CatchClause") { var identifier = node.param; node.$scope = new Scope({ kind: "catch-block", node: node, parent: node.$parent.$scope, }); node.$scope.add(identifier.name, "caught", identifier, null); // All hoist-scope keeps track of which variables that are propagated through, // i.e. an reference inside the scope points to a declaration outside the scope. // This is used to mark "taint" the name since adding a new variable in the scope, // with a propagated name, would change the meaning of the existing references. // // catch(e) is special because even though e is a variable in its own scope, // we want to make sure that catch(e){let e} is never transformed to // catch(e){var e} (but rather var e$0). For that reason we taint the use of e // in the closest hoist-scope, i.e. where var e$0 belongs. node.$scope.closestHoistScope().markPropagates(identifier.name); } } function createTopScope(programScope, environments, globals) { function inject(obj) { for (var name in obj) { var writeable = obj[name]; var kind = (writeable ? "var" : "const"); if (topScope.hasOwn(name)) { topScope.remove(name); } topScope.add(name, kind, {loc: {start: {line: -1}}}, -1); } } var topScope = new Scope({ kind: "hoist", node: {}, parent: null, }); var complementary = { undefined: false, Infinity: false, console: false, }; inject(complementary); inject(jshint_vars.reservedVars); inject(jshint_vars.ecmaIdentifiers); if (environments) { environments.forEach(function(env) { if (!jshint_vars[env]) { error(-1, 'environment "{0}" not found', env); } else { inject(jshint_vars[env]); } }); } if (globals) { inject(globals); } // link it in programScope.parent = topScope; topScope.children.push(programScope); return topScope; } function setupReferences(ast, allIdentifiers, opts) { var analyze = (is.own(opts, "analyze") ? opts.analyze : true); function visit(node) { if (!isReference(node)) { return; } allIdentifiers.add(node.name); var scope = node.$scope.lookup(node.name); if (analyze && !scope && options.disallowUnknownReferences) { error(getline(node), "reference to unknown global variable {0}", node.name); } // check const and let for referenced-before-declaration if (analyze && scope && is.someof(scope.getKind(node.name), ["const", "let"])) { var allowedFromPos = scope.getFromPos(node.name); var referencedAtPos = node.range[0]; assert(is.finitenumber(allowedFromPos)); assert(is.finitenumber(referencedAtPos)); if (referencedAtPos < allowedFromPos) { if (!node.$scope.hasFunctionScopeBetween(scope)) { error(getline(node), "{0} is referenced before its declaration", node.name); } } } node.$refToScope = scope; } traverse(ast, {pre: visit}); } // TODO for loops init and body props are parallel to each other but init scope is outer that of body // TODO is this a problem? function varify(ast, stats, allIdentifiers, changes) { function unique(name) { assert(allIdentifiers.has(name)); for (var cnt = 0; ; cnt++) { var genName = name + "$" + String(cnt); if (!allIdentifiers.has(genName)) { return genName; } } } function renameDeclarations(node) { if (node.type === "VariableDeclaration" && isConstLet(node.kind)) { var hoistScope = node.$scope.closestHoistScope(); var origScope = node.$scope; // text change const|let => var changes.push({ start: node.range[0], end: node.range[0] + node.kind.length, str: "var", }); node.declarations.forEach(function(declarator) { assert(declarator.type === "VariableDeclarator"); var name = declarator.id.name; stats.declarator(node.kind); // rename if // 1) name already exists in hoistScope, or // 2) name is already propagated (passed) through hoistScope or manually tainted var rename = (origScope !== hoistScope && (hoistScope.hasOwn(name) || hoistScope.doesPropagate(name))); var newName = (rename ? unique(name) : name); origScope.remove(name); hoistScope.add(newName, "var", declarator.id, declarator.range[1]); origScope.moves = origScope.moves || stringmap(); origScope.moves.set(name, { name: newName, scope: hoistScope, }); allIdentifiers.add(newName); if (newName !== name) { stats.rename(name, newName, getline(declarator)); declarator.id.originalName = name; declarator.id.name = newName; // textchange var x => var x$1 changes.push({ start: declarator.id.range[0], end: declarator.id.range[1], str: newName, }); } }); // ast change const|let => var node.kind = "var"; } } function renameReferences(node) { if (!node.$refToScope) { return; } var move = node.$refToScope.moves && node.$refToScope.moves.get(node.name); if (!move) { return; } node.$refToScope = move.scope; if (node.name !== move.name) { node.originalName = node.name; node.name = move.name; if (node.alterop) { // node has no range because it is the result of another alter operation var existingOp = null; for (var i = 0; i < changes.length; i++) { var op = changes[i]; if (op.node === node) { existingOp = op; break; } } assert(existingOp); // modify op existingOp.str = move.name; } else { changes.push({ start: node.range[0], end: node.range[1], str: move.name, }); } } } traverse(ast, {pre: renameDeclarations}); traverse(ast, {pre: renameReferences}); ast.$scope.traverse({pre: function(scope) { delete scope.moves; }}); } function detectLoopClosures(ast) { traverse(ast, {pre: visit}); function detectIifyBodyBlockers(body, node) { return breakable(function(brk) { traverse(body, {pre: function(n) { // if we hit an inner function of the loop body, don't traverse further if (isFunction(n)) { return false; } var err = true; // reset to false in else-statement below var msg = "loop-variable {0} is captured by a loop-closure that can't be transformed due to use of {1} at line {2}"; if (n.type === "BreakStatement") { error(getline(node), msg, node.name, "break", getline(n)); } else if (n.type === "ContinueStatement") { error(getline(node), msg, node.name, "continue", getline(n)); } else if (n.type === "ReturnStatement") { error(getline(node), msg, node.name, "return", getline(n)); } else if (n.type === "YieldExpression") { error(getline(node), msg, node.name, "yield", getline(n)); } else if (n.type === "Identifier" && n.name === "arguments") { error(getline(node), msg, node.name, "arguments", getline(n)); } else if (n.type === "VariableDeclaration" && n.kind === "var") { error(getline(node), msg, node.name, "var", getline(n)); } else { err = false; } if (err) { brk(true); // break traversal } }}); return false; }); } function visit(node) { // forbidden pattern: // * * * * var loopNode = null; if (isReference(node) && node.$refToScope && isConstLet(node.$refToScope.getKind(node.name))) { // traverse nodes up towards root from constlet-def // if we hit a function (before a loop) - ok! // if we hit a loop - maybe-ouch // if we reach root - ok! for (var n = node.$refToScope.node; ; ) { if (isFunction(n)) { // we're ok (function-local) return; } else if (isLoop(n)) { loopNode = n; // maybe not ok (between loop and function) break; } n = n.$parent; if (!n) { // ok (reached root) return; } } assert(isLoop(loopNode)); // traverse scopes from reference-scope up towards definition-scope // if we hit a function, ouch! var defScope = node.$refToScope; var generateIIFE = (options.loopClosures === "iife"); for (var s = node.$scope; s; s = s.parent) { if (s === defScope) { // we're ok return; } else if (isFunction(s.node)) { // not ok (there's a function between the reference and definition) // may be transformable via IIFE if (!generateIIFE) { var msg = "loop-variable {0} is captured by a loop-closure. Tried \"loopClosures\": \"iife\" in defs-config.json?"; return error(getline(node), msg, node.name); } // here be dragons // for (let x = ..; .. ; ..) { (function(){x})() } is forbidden because of current // spec and VM status if (loopNode.type === "ForStatement" && defScope.node === loopNode) { var declarationNode = defScope.getNode(node.name); return error(getline(declarationNode), "Not yet specced ES6 feature. {0} is declared in for-loop header and then captured in loop closure", declarationNode.name); } // speak now or forever hold your peace if (detectIifyBodyBlockers(loopNode.body, node)) { // error already generated return; } // mark loop for IIFE-insertion loopNode.$iify = true; } } } } } function transformLoopClosures(root, ops, options) { function insertOp(pos, str, node) { var op = { start: pos, end: pos, str: str, } if (node) { op.node = node; } ops.push(op); } traverse(root, {pre: function(node) { if (!node.$iify) { return; } var hasBlock = (node.body.type === "BlockStatement"); var insertHead = (hasBlock ? node.body.range[0] + 1 : // just after body { node.body.range[0]); // just before existing expression var insertFoot = (hasBlock ? node.body.range[1] - 1 : // just before body } node.body.range[1]); // just after existing expression var forInName = (isForInOf(node) && node.left.declarations[0].id.name);; var iifeHead = fmt("(function({0}){", forInName ? forInName : ""); var iifeTail = fmt("}).call(this{0});", forInName ? ", " + forInName : ""); // modify AST var iifeFragment = options.parse(iifeHead + iifeTail); var iifeExpressionStatement = iifeFragment.body[0]; var iifeBlockStatement = iifeExpressionStatement.expression.callee.object.body; if (hasBlock) { var forBlockStatement = node.body; var tmp = forBlockStatement.body; forBlockStatement.body = [iifeExpressionStatement]; iifeBlockStatement.body = tmp; } else { var tmp$0 = node.body; node.body = iifeExpressionStatement; iifeBlockStatement.body[0] = tmp$0; } // create ops insertOp(insertHead, iifeHead); if (forInName) { insertOp(insertFoot, "}).call(this, "); var args = iifeExpressionStatement.expression.arguments; var iifeArgumentIdentifier = args[1]; iifeArgumentIdentifier.alterop = true; insertOp(insertFoot, forInName, iifeArgumentIdentifier); insertOp(insertFoot, ");"); } else { insertOp(insertFoot, iifeTail); } }}); } function detectConstAssignment(ast) { traverse(ast, {pre: function(node) { if (isLvalue(node)) { var scope = node.$scope.lookup(node.name); if (scope && scope.getKind(node.name) === "const") { error(getline(node), "can't assign to const variable {0}", node.name); } } }}); } function detectConstantLets(ast) { traverse(ast, {pre: function(node) { if (isLvalue(node)) { var scope = node.$scope.lookup(node.name); if (scope) { scope.markWrite(node.name); } } }}); ast.$scope.detectUnmodifiedLets(); } function setupScopeAndReferences(root, opts) { // setup scopes traverse(root, {pre: createScopes}); var topScope = createTopScope(root.$scope, options.environments, options.globals); // allIdentifiers contains all declared and referenced vars // collect all declaration names (including those in topScope) var allIdentifiers = stringset(); topScope.traverse({pre: function(scope) { allIdentifiers.addMany(scope.decls.keys()); }}); // setup node.$refToScope, check for errors. // also collects all referenced names to allIdentifiers setupReferences(root, allIdentifiers, opts); return allIdentifiers; } function cleanupTree(root) { traverse(root, {pre: function(node) { for (var prop in node) { if (prop[0] === "$") { delete node[prop]; } } }}); } function run(src, config) { // alter the options singleton with user configuration for (var key in config) { options[key] = config[key]; } var parsed; if (is.object(src)) { if (!options.ast) { return { errors: [ "Can't produce string output when input is an AST. " + "Did you forget to set options.ast = true?" ], }; } // Received an AST object as src, so no need to parse it. parsed = src; } else if (is.string(src)) { try { parsed = options.parse(src, { loc: true, range: true, }); } catch (e) { return { errors: [ fmt("line {0} column {1}: Error during input file parsing\n{2}\n{3}", e.lineNumber, e.column, src.split("\n")[e.lineNumber - 1], fmt.repeat(" ", e.column - 1) + "^") ], }; } } else { return { errors: ["Input was neither an AST object nor a string."], }; } var ast = parsed; // TODO detect unused variables (never read) error.reset(); var allIdentifiers = setupScopeAndReferences(ast, {}); // static analysis passes detectLoopClosures(ast); detectConstAssignment(ast); //detectConstantLets(ast); var changes = []; transformLoopClosures(ast, changes, options); //ast.$scope.print(); process.exit(-1); if (error.errors.length >= 1) { return { errors: error.errors, }; } if (changes.length > 0) { cleanupTree(ast); allIdentifiers = setupScopeAndReferences(ast, {analyze: false}); } assert(error.errors.length === 0); // change constlet declarations to var, renamed if needed // varify modifies the scopes and AST accordingly and // returns a list of change fragments (to use with alter) var stats = new Stats(); varify(ast, stats, allIdentifiers, changes); if (options.ast) { // return the modified AST instead of src code // get rid of all added $ properties first, such as $parent and $scope cleanupTree(ast); return { stats: stats, ast: ast, }; } else { // apply changes produced by varify and return the transformed src var transformedSrc = alter(src, changes); return { stats: stats, src: transformedSrc, }; } } module.exports = run; },{"./error":444,"./jshint_globals/vars.js":445,"./options":446,"./scope":447,"./stats":448,"alter":449,"assert":190,"ast-traverse":451,"breakable":452,"simple-fmt":454,"simple-is":455,"stringmap":456,"stringset":457}],444:[function(require,module,exports){ "use strict"; var fmt = require("simple-fmt"); var assert = require("assert"); function error(line, var_args) { assert(arguments.length >= 2); var msg = (arguments.length === 2 ? String(var_args) : fmt.apply(fmt, Array.prototype.slice.call(arguments, 1))); error.errors.push(line === -1 ? msg : fmt("line {0}: {1}", line, msg)); } error.reset = function() { error.errors = []; }; error.getline = function(node) { if (node && node.loc && node.loc.start) { return node.loc.start.line; } return -1; }; error.reset(); module.exports = error; },{"assert":190,"simple-fmt":454}],445:[function(require,module,exports){ // jshint -W001 "use strict"; // Identifiers provided by the ECMAScript standard. exports.reservedVars = { arguments : false, NaN : false }; exports.ecmaIdentifiers = { Array : false, Boolean : false, Date : false, decodeURI : false, decodeURIComponent : false, encodeURI : false, encodeURIComponent : false, Error : false, "eval" : false, EvalError : false, Function : false, hasOwnProperty : false, isFinite : false, isNaN : false, JSON : false, Math : false, Map : false, Number : false, Object : false, parseInt : false, parseFloat : false, RangeError : false, ReferenceError : false, RegExp : false, Set : false, String : false, SyntaxError : false, TypeError : false, URIError : false, WeakMap : false }; // Global variables commonly provided by a web browser environment. exports.browser = { ArrayBuffer : false, ArrayBufferView : false, Audio : false, Blob : false, addEventListener : false, applicationCache : false, atob : false, blur : false, btoa : false, clearInterval : false, clearTimeout : false, close : false, closed : false, DataView : false, DOMParser : false, defaultStatus : false, document : false, Element : false, event : false, FileReader : false, Float32Array : false, Float64Array : false, FormData : false, focus : false, frames : false, getComputedStyle : false, HTMLElement : false, HTMLAnchorElement : false, HTMLBaseElement : false, HTMLBlockquoteElement: false, HTMLBodyElement : false, HTMLBRElement : false, HTMLButtonElement : false, HTMLCanvasElement : false, HTMLDirectoryElement : false, HTMLDivElement : false, HTMLDListElement : false, HTMLFieldSetElement : false, HTMLFontElement : false, HTMLFormElement : false, HTMLFrameElement : false, HTMLFrameSetElement : false, HTMLHeadElement : false, HTMLHeadingElement : false, HTMLHRElement : false, HTMLHtmlElement : false, HTMLIFrameElement : false, HTMLImageElement : false, HTMLInputElement : false, HTMLIsIndexElement : false, HTMLLabelElement : false, HTMLLayerElement : false, HTMLLegendElement : false, HTMLLIElement : false, HTMLLinkElement : false, HTMLMapElement : false, HTMLMenuElement : false, HTMLMetaElement : false, HTMLModElement : false, HTMLObjectElement : false, HTMLOListElement : false, HTMLOptGroupElement : false, HTMLOptionElement : false, HTMLParagraphElement : false, HTMLParamElement : false, HTMLPreElement : false, HTMLQuoteElement : false, HTMLScriptElement : false, HTMLSelectElement : false, HTMLStyleElement : false, HTMLTableCaptionElement: false, HTMLTableCellElement : false, HTMLTableColElement : false, HTMLTableElement : false, HTMLTableRowElement : false, HTMLTableSectionElement: false, HTMLTextAreaElement : false, HTMLTitleElement : false, HTMLUListElement : false, HTMLVideoElement : false, history : false, Int16Array : false, Int32Array : false, Int8Array : false, Image : false, length : false, localStorage : false, location : false, MessageChannel : false, MessageEvent : false, MessagePort : false, moveBy : false, moveTo : false, MutationObserver : false, name : false, Node : false, NodeFilter : false, navigator : false, onbeforeunload : true, onblur : true, onerror : true, onfocus : true, onload : true, onresize : true, onunload : true, open : false, openDatabase : false, opener : false, Option : false, parent : false, print : false, removeEventListener : false, resizeBy : false, resizeTo : false, screen : false, scroll : false, scrollBy : false, scrollTo : false, sessionStorage : false, setInterval : false, setTimeout : false, SharedWorker : false, status : false, top : false, Uint16Array : false, Uint32Array : false, Uint8Array : false, Uint8ClampedArray : false, WebSocket : false, window : false, Worker : false, XMLHttpRequest : false, XMLSerializer : false, XPathEvaluator : false, XPathException : false, XPathExpression : false, XPathNamespace : false, XPathNSResolver : false, XPathResult : false }; exports.devel = { alert : false, confirm: false, console: false, Debug : false, opera : false, prompt : false }; exports.worker = { importScripts: true, postMessage : true, self : true }; // Widely adopted global names that are not part of ECMAScript standard exports.nonstandard = { escape : false, unescape: false }; // Globals provided by popular JavaScript environments. exports.couch = { "require" : false, respond : false, getRow : false, emit : false, send : false, start : false, sum : false, log : false, exports : false, module : false, provides : false }; exports.node = { __filename : false, __dirname : false, Buffer : false, DataView : false, console : false, exports : true, // In Node it is ok to exports = module.exports = foo(); GLOBAL : false, global : false, module : false, process : false, require : false, setTimeout : false, clearTimeout : false, setInterval : false, clearInterval: false }; exports.phantom = { phantom : true, require : true, WebPage : true }; exports.rhino = { defineClass : false, deserialize : false, gc : false, help : false, importPackage: false, "java" : false, load : false, loadClass : false, print : false, quit : false, readFile : false, readUrl : false, runCommand : false, seal : false, serialize : false, spawn : false, sync : false, toint32 : false, version : false }; exports.wsh = { ActiveXObject : true, Enumerator : true, GetObject : true, ScriptEngine : true, ScriptEngineBuildVersion : true, ScriptEngineMajorVersion : true, ScriptEngineMinorVersion : true, VBArray : true, WSH : true, WScript : true, XDomainRequest : true }; // Globals provided by popular JavaScript libraries. exports.dojo = { dojo : false, dijit : false, dojox : false, define : false, "require": false }; exports.jquery = { "$" : false, jQuery : false }; exports.mootools = { "$" : false, "$$" : false, Asset : false, Browser : false, Chain : false, Class : false, Color : false, Cookie : false, Core : false, Document : false, DomReady : false, DOMEvent : false, DOMReady : false, Drag : false, Element : false, Elements : false, Event : false, Events : false, Fx : false, Group : false, Hash : false, HtmlTable : false, Iframe : false, IframeShim : false, InputValidator: false, instanceOf : false, Keyboard : false, Locale : false, Mask : false, MooTools : false, Native : false, Options : false, OverText : false, Request : false, Scroller : false, Slick : false, Slider : false, Sortables : false, Spinner : false, Swiff : false, Tips : false, Type : false, typeOf : false, URI : false, Window : false }; exports.prototypejs = { "$" : false, "$$" : false, "$A" : false, "$F" : false, "$H" : false, "$R" : false, "$break" : false, "$continue" : false, "$w" : false, Abstract : false, Ajax : false, Class : false, Enumerable : false, Element : false, Event : false, Field : false, Form : false, Hash : false, Insertion : false, ObjectRange : false, PeriodicalExecuter: false, Position : false, Prototype : false, Selector : false, Template : false, Toggle : false, Try : false, Autocompleter : false, Builder : false, Control : false, Draggable : false, Draggables : false, Droppables : false, Effect : false, Sortable : false, SortableObserver : false, Sound : false, Scriptaculous : false }; exports.yui = { YUI : false, Y : false, YUI_config: false }; },{}],446:[function(require,module,exports){ // default configuration module.exports = { disallowVars: false, disallowDuplicated: true, disallowUnknownReferences: true, parse: require("esprima-fb").parse, }; },{"esprima-fb":453}],447:[function(require,module,exports){ "use strict"; var assert = require("assert"); var stringmap = require("stringmap"); var stringset = require("stringset"); var is = require("simple-is"); var fmt = require("simple-fmt"); var error = require("./error"); var getline = error.getline; var options = require("./options"); function Scope(args) { assert(is.someof(args.kind, ["hoist", "block", "catch-block"])); assert(is.object(args.node)); assert(args.parent === null || is.object(args.parent)); // kind === "hoist": function scopes, program scope, injected globals // kind === "block": ES6 block scopes // kind === "catch-block": catch block scopes this.kind = args.kind; // the AST node the block corresponds to this.node = args.node; // parent scope this.parent = args.parent; // children scopes for easier traversal (populated internally) this.children = []; // scope declarations. decls[variable_name] = { // kind: "fun" for functions, // "param" for function parameters, // "caught" for catch parameter // "var", // "const", // "let" // node: the AST node the declaration corresponds to // from: source code index from which it is visible at earliest // (only stored for "const", "let" [and "var"] nodes) // } this.decls = stringmap(); // names of all declarations within this scope that was ever written // TODO move to decls.w? // TODO create corresponding read? this.written = stringset(); // names of all variables declared outside this hoist scope but // referenced in this scope (immediately or in child). // only stored on hoist scopes for efficiency // (because we currently generate lots of empty block scopes) this.propagates = (this.kind === "hoist" ? stringset() : null); // scopes register themselves with their parents for easier traversal if (this.parent) { this.parent.children.push(this); } } Scope.prototype.print = function(indent) { indent = indent || 0; var scope = this; var names = this.decls.keys().map(function(name) { return fmt("{0} [{1}]", name, scope.decls.get(name).kind); }).join(", "); var propagates = this.propagates ? this.propagates.items().join(", ") : ""; console.log(fmt("{0}{1}: {2}. propagates: {3}", fmt.repeat(" ", indent), this.node.type, names, propagates)); this.children.forEach(function(c) { c.print(indent + 2); }); }; Scope.prototype.add = function(name, kind, node, referableFromPos) { assert(is.someof(kind, ["fun", "param", "var", "caught", "const", "let"])); function isConstLet(kind) { return is.someof(kind, ["const", "let"]); } var scope = this; // search nearest hoist-scope for fun, param and var's // const, let and caught variables go directly in the scope (which may be hoist, block or catch-block) if (is.someof(kind, ["fun", "param", "var"])) { while (scope.kind !== "hoist") { if (scope.decls.has(name) && isConstLet(scope.decls.get(name).kind)) { // could be caught return error(getline(node), "{0} is already declared", name); } scope = scope.parent; } } // name exists in scope and either new or existing kind is const|let => error if (scope.decls.has(name) && (options.disallowDuplicated || isConstLet(scope.decls.get(name).kind) || isConstLet(kind))) { return error(getline(node), "{0} is already declared", name); } var declaration = { kind: kind, node: node, }; if (referableFromPos) { assert(is.someof(kind, ["var", "const", "let"])); declaration.from = referableFromPos; } scope.decls.set(name, declaration); }; Scope.prototype.getKind = function(name) { assert(is.string(name)); var decl = this.decls.get(name); return decl ? decl.kind : null; }; Scope.prototype.getNode = function(name) { assert(is.string(name)); var decl = this.decls.get(name); return decl ? decl.node : null; }; Scope.prototype.getFromPos = function(name) { assert(is.string(name)); var decl = this.decls.get(name); return decl ? decl.from : null; }; Scope.prototype.hasOwn = function(name) { return this.decls.has(name); }; Scope.prototype.remove = function(name) { return this.decls.remove(name); }; Scope.prototype.doesPropagate = function(name) { return this.propagates.has(name); }; Scope.prototype.markPropagates = function(name) { this.propagates.add(name); }; Scope.prototype.closestHoistScope = function() { var scope = this; while (scope.kind !== "hoist") { scope = scope.parent; } return scope; }; Scope.prototype.hasFunctionScopeBetween = function(outer) { function isFunction(node) { return is.someof(node.type, ["FunctionDeclaration", "FunctionExpression"]); } for (var scope = this; scope; scope = scope.parent) { if (scope === outer) { return false; } if (isFunction(scope.node)) { return true; } } throw new Error("wasn't inner scope of outer"); }; Scope.prototype.lookup = function(name) { for (var scope = this; scope; scope = scope.parent) { if (scope.decls.has(name)) { return scope; } else if (scope.kind === "hoist") { scope.propagates.add(name); } } return null; }; Scope.prototype.markWrite = function(name) { assert(is.string(name)); this.written.add(name); }; // detects let variables that are never modified (ignores top-level) Scope.prototype.detectUnmodifiedLets = function() { var outmost = this; function detect(scope) { if (scope !== outmost) { scope.decls.keys().forEach(function(name) { if (scope.getKind(name) === "let" && !scope.written.has(name)) { return error(getline(scope.getNode(name)), "{0} is declared as let but never modified so could be const", name); } }); } scope.children.forEach(function(childScope) { detect(childScope); }); } detect(this); }; Scope.prototype.traverse = function(options) { options = options || {}; var pre = options.pre; var post = options.post; function visit(scope) { if (pre) { pre(scope); } scope.children.forEach(function(childScope) { visit(childScope); }); if (post) { post(scope); } } visit(this); }; module.exports = Scope; },{"./error":444,"./options":446,"assert":190,"simple-fmt":454,"simple-is":455,"stringmap":456,"stringset":457}],448:[function(require,module,exports){ var fmt = require("simple-fmt"); var is = require("simple-is"); var assert = require("assert"); function Stats() { this.lets = 0; this.consts = 0; this.renames = []; } Stats.prototype.declarator = function(kind) { assert(is.someof(kind, ["const", "let"])); if (kind === "const") { this.consts++; } else { this.lets++; } }; Stats.prototype.rename = function(oldName, newName, line) { this.renames.push({ oldName: oldName, newName: newName, line: line, }); }; Stats.prototype.toString = function() { // console.log("defs.js stats for file {0}:", filename) var renames = this.renames.map(function(r) { return r; }).sort(function(a, b) { return a.line - b.line; }); // sort a copy of renames var renameStr = renames.map(function(rename) { return fmt("\nline {0}: {1} => {2}", rename.line, rename.oldName, rename.newName); }).join(""); var sum = this.consts + this.lets; var constlets = (sum === 0 ? "can't calculate const coverage (0 consts, 0 lets)" : fmt("{0}% const coverage ({1} consts, {2} lets)", Math.floor(100 * this.consts / sum), this.consts, this.lets)); return constlets + renameStr + "\n"; }; module.exports = Stats; },{"assert":190,"simple-fmt":454,"simple-is":455}],449:[function(require,module,exports){ // alter.js // MIT licensed, see LICENSE file // Copyright (c) 2013 Olov Lassus var assert = require("assert"); var stableSort = require("stable"); // fragments is a list of {start: index, end: index, str: string to replace with} function alter(str, fragments) { "use strict"; var isArray = Array.isArray || function(v) { return Object.prototype.toString.call(v) === "[object Array]"; };; assert(typeof str === "string"); assert(isArray(fragments)); // stableSort isn't in-place so no need to copy array first var sortedFragments = stableSort(fragments, function(a, b) { return a.start - b.start; }); var outs = []; var pos = 0; for (var i = 0; i < sortedFragments.length; i++) { var frag = sortedFragments[i]; assert(pos <= frag.start); assert(frag.start <= frag.end); outs.push(str.slice(pos, frag.start)); outs.push(frag.str); pos = frag.end; } if (pos < str.length) { outs.push(str.slice(pos)); } return outs.join(""); } if (typeof module !== "undefined" && typeof module.exports !== "undefined") { module.exports = alter; } },{"assert":190,"stable":450}],450:[function(require,module,exports){ //! stable.js 0.1.5, https://github.com/Two-Screen/stable //! © 2014 Angry Bytes and contributors. MIT licensed. (function() { // A stable array sort, because `Array#sort()` is not guaranteed stable. // This is an implementation of merge sort, without recursion. var stable = function(arr, comp) { return exec(arr.slice(), comp); }; stable.inplace = function(arr, comp) { var result = exec(arr, comp); // This simply copies back if the result isn't in the original array, // which happens on an odd number of passes. if (result !== arr) { pass(result, null, arr.length, arr); } return arr; }; // Execute the sort using the input array and a second buffer as work space. // Returns one of those two, containing the final result. function exec(arr, comp) { if (typeof(comp) !== 'function') { comp = function(a, b) { return String(a).localeCompare(b); }; } // Short-circuit when there's nothing to sort. var len = arr.length; if (len <= 1) { return arr; } // Rather than dividing input, simply iterate chunks of 1, 2, 4, 8, etc. // Chunks are the size of the left or right hand in merge sort. // Stop when the left-hand covers all of the array. var buffer = new Array(len); for (var chk = 1; chk < len; chk *= 2) { pass(arr, comp, chk, buffer); var tmp = arr; arr = buffer; buffer = tmp; } return arr; } // Run a single pass with the given chunk size. var pass = function(arr, comp, chk, result) { var len = arr.length; var i = 0; // Step size / double chunk size. var dbl = chk * 2; // Bounds of the left and right chunks. var l, r, e; // Iterators over the left and right chunk. var li, ri; // Iterate over pairs of chunks. for (l = 0; l < len; l += dbl) { r = l + chk; e = r + chk; if (r > len) r = len; if (e > len) e = len; // Iterate both chunks in parallel. li = l; ri = r; while (true) { // Compare the chunks. if (li < r && ri < e) { // This works for a regular `sort()` compatible comparator, // but also for a simple comparator like: `a > b` if (comp(arr[li], arr[ri]) <= 0) { result[i++] = arr[li++]; } else { result[i++] = arr[ri++]; } } // Nothing to compare, just flush what's left. else if (li < r) { result[i++] = arr[li++]; } else if (ri < e) { result[i++] = arr[ri++]; } // Both iterators are at the chunk ends. else { break; } } } }; // Export using CommonJS or to the window. if (typeof(module) !== 'undefined') { module.exports = stable; } else { window.stable = stable; } })(); },{}],451:[function(require,module,exports){ function traverse(root, options) { "use strict"; options = options || {}; var pre = options.pre; var post = options.post; var skipProperty = options.skipProperty; function visit(node, parent, prop, idx) { if (!node || typeof node.type !== "string") { return; } var res = undefined; if (pre) { res = pre(node, parent, prop, idx); } if (res !== false) { for (var prop in node) { if (skipProperty ? skipProperty(prop, node) : prop[0] === "$") { continue; } var child = node[prop]; if (Array.isArray(child)) { for (var i = 0; i < child.length; i++) { visit(child[i], node, prop, i); } } else { visit(child, node, prop); } } } if (post) { post(node, parent, prop, idx); } } visit(root, null); }; if (typeof module !== "undefined" && typeof module.exports !== "undefined") { module.exports = traverse; } },{}],452:[function(require,module,exports){ // breakable.js // MIT licensed, see LICENSE file // Copyright (c) 2013-2014 Olov Lassus var breakable = (function() { "use strict"; function Val(val, brk) { this.val = val; this.brk = brk; } function make_brk() { return function brk(val) { throw new Val(val, brk); }; } function breakable(fn) { var brk = make_brk(); try { return fn(brk); } catch (e) { if (e instanceof Val && e.brk === brk) { return e.val; } throw e; } } return breakable; })(); if (typeof module !== "undefined" && typeof module.exports !== "undefined") { module.exports = breakable; } },{}],453:[function(require,module,exports){ /* Copyright (C) 2013 Ariya Hidayat Copyright (C) 2013 Thaddee Tyl Copyright (C) 2012 Ariya Hidayat Copyright (C) 2012 Mathias Bynens Copyright (C) 2012 Joost-Wim Boekesteijn Copyright (C) 2012 Kris Kowal Copyright (C) 2012 Yusuke Suzuki Copyright (C) 2012 Arpad Borsos Copyright (C) 2011 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. */ /*jslint bitwise:true plusplus:true */ /*global esprima:true, define:true, exports:true, window: true, throwError: true, generateStatement: true, peek: true, parseAssignmentExpression: true, parseBlock: true, parseClassExpression: true, parseClassDeclaration: true, parseExpression: true, parseDeclareClass: true, parseDeclareFunction: true, parseDeclareModule: true, parseDeclareVariable: true, parseForStatement: true, parseFunctionDeclaration: true, parseFunctionExpression: true, parseFunctionSourceElements: true, parseVariableIdentifier: true, parseImportSpecifier: true, parseInterface: true, parseLeftHandSideExpression: true, parseParams: true, validateParam: true, parseSpreadOrAssignmentExpression: true, parseStatement: true, parseSourceElement: true, parseConciseBody: true, advanceXJSChild: true, isXJSIdentifierStart: true, isXJSIdentifierPart: true, scanXJSStringLiteral: true, scanXJSIdentifier: true, parseXJSAttributeValue: true, parseXJSChild: true, parseXJSElement: true, parseXJSExpressionContainer: true, parseXJSEmptyExpression: true, parseFunctionTypeParam: true, parsePrimaryType: true, parseTypeAlias: true, parseType: true, parseTypeAnnotatableIdentifier: true, parseTypeAnnotation: true, parseYieldExpression: true, parseAwaitExpression: true */ (function (root, factory) { 'use strict'; // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, // Rhino, and plain browser loading. if (typeof define === 'function' && define.amd) { define(['exports'], factory); } else if (typeof exports !== 'undefined') { factory(exports); } else { factory((root.esprima = {})); } }(this, function (exports) { 'use strict'; var Token, TokenName, FnExprTokens, Syntax, PropertyKind, Messages, Regex, SyntaxTreeDelegate, XHTMLEntities, ClassPropertyType, source, strict, index, lineNumber, lineStart, length, delegate, lookahead, state, extra; Token = { BooleanLiteral: 1, EOF: 2, Identifier: 3, Keyword: 4, NullLiteral: 5, NumericLiteral: 6, Punctuator: 7, StringLiteral: 8, RegularExpression: 9, Template: 10, XJSIdentifier: 11, XJSText: 12 }; TokenName = {}; TokenName[Token.BooleanLiteral] = 'Boolean'; TokenName[Token.EOF] = ''; TokenName[Token.Identifier] = 'Identifier'; TokenName[Token.Keyword] = 'Keyword'; TokenName[Token.NullLiteral] = 'Null'; TokenName[Token.NumericLiteral] = 'Numeric'; TokenName[Token.Punctuator] = 'Punctuator'; TokenName[Token.StringLiteral] = 'String'; TokenName[Token.XJSIdentifier] = 'XJSIdentifier'; TokenName[Token.XJSText] = 'XJSText'; TokenName[Token.RegularExpression] = 'RegularExpression'; // A function following one of those tokens is an expression. FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new', 'return', 'case', 'delete', 'throw', 'void', // assignment operators '=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=', '&=', '|=', '^=', ',', // binary/unary operators '+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&', '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=', '<=', '<', '>', '!=', '!==']; Syntax = { AnyTypeAnnotation: 'AnyTypeAnnotation', ArrayExpression: 'ArrayExpression', ArrayPattern: 'ArrayPattern', ArrayTypeAnnotation: 'ArrayTypeAnnotation', ArrowFunctionExpression: 'ArrowFunctionExpression', AssignmentExpression: 'AssignmentExpression', BinaryExpression: 'BinaryExpression', BlockStatement: 'BlockStatement', BooleanTypeAnnotation: 'BooleanTypeAnnotation', BreakStatement: 'BreakStatement', CallExpression: 'CallExpression', CatchClause: 'CatchClause', ClassBody: 'ClassBody', ClassDeclaration: 'ClassDeclaration', ClassExpression: 'ClassExpression', ClassImplements: 'ClassImplements', ClassProperty: 'ClassProperty', ComprehensionBlock: 'ComprehensionBlock', ComprehensionExpression: 'ComprehensionExpression', ConditionalExpression: 'ConditionalExpression', ContinueStatement: 'ContinueStatement', DebuggerStatement: 'DebuggerStatement', DeclareClass: 'DeclareClass', DeclareFunction: 'DeclareFunction', DeclareModule: 'DeclareModule', DeclareVariable: 'DeclareVariable', DoWhileStatement: 'DoWhileStatement', EmptyStatement: 'EmptyStatement', ExportDeclaration: 'ExportDeclaration', ExportBatchSpecifier: 'ExportBatchSpecifier', ExportSpecifier: 'ExportSpecifier', ExpressionStatement: 'ExpressionStatement', ForInStatement: 'ForInStatement', ForOfStatement: 'ForOfStatement', ForStatement: 'ForStatement', FunctionDeclaration: 'FunctionDeclaration', FunctionExpression: 'FunctionExpression', FunctionTypeAnnotation: 'FunctionTypeAnnotation', FunctionTypeParam: 'FunctionTypeParam', GenericTypeAnnotation: 'GenericTypeAnnotation', Identifier: 'Identifier', IfStatement: 'IfStatement', ImportDeclaration: 'ImportDeclaration', ImportDefaultSpecifier: 'ImportDefaultSpecifier', ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', ImportSpecifier: 'ImportSpecifier', InterfaceDeclaration: 'InterfaceDeclaration', InterfaceExtends: 'InterfaceExtends', IntersectionTypeAnnotation: 'IntersectionTypeAnnotation', LabeledStatement: 'LabeledStatement', Literal: 'Literal', LogicalExpression: 'LogicalExpression', MemberExpression: 'MemberExpression', MethodDefinition: 'MethodDefinition', ModuleSpecifier: 'ModuleSpecifier', NewExpression: 'NewExpression', NullableTypeAnnotation: 'NullableTypeAnnotation', NumberTypeAnnotation: 'NumberTypeAnnotation', ObjectExpression: 'ObjectExpression', ObjectPattern: 'ObjectPattern', ObjectTypeAnnotation: 'ObjectTypeAnnotation', ObjectTypeCallProperty: 'ObjectTypeCallProperty', ObjectTypeIndexer: 'ObjectTypeIndexer', ObjectTypeProperty: 'ObjectTypeProperty', Program: 'Program', Property: 'Property', QualifiedTypeIdentifier: 'QualifiedTypeIdentifier', ReturnStatement: 'ReturnStatement', SequenceExpression: 'SequenceExpression', SpreadElement: 'SpreadElement', SpreadProperty: 'SpreadProperty', StringLiteralTypeAnnotation: 'StringLiteralTypeAnnotation', StringTypeAnnotation: 'StringTypeAnnotation', SwitchCase: 'SwitchCase', SwitchStatement: 'SwitchStatement', TaggedTemplateExpression: 'TaggedTemplateExpression', TemplateElement: 'TemplateElement', TemplateLiteral: 'TemplateLiteral', ThisExpression: 'ThisExpression', ThrowStatement: 'ThrowStatement', TupleTypeAnnotation: 'TupleTypeAnnotation', TryStatement: 'TryStatement', TypeAlias: 'TypeAlias', TypeAnnotation: 'TypeAnnotation', TypeofTypeAnnotation: 'TypeofTypeAnnotation', TypeParameterDeclaration: 'TypeParameterDeclaration', TypeParameterInstantiation: 'TypeParameterInstantiation', UnaryExpression: 'UnaryExpression', UnionTypeAnnotation: 'UnionTypeAnnotation', UpdateExpression: 'UpdateExpression', VariableDeclaration: 'VariableDeclaration', VariableDeclarator: 'VariableDeclarator', VoidTypeAnnotation: 'VoidTypeAnnotation', WhileStatement: 'WhileStatement', WithStatement: 'WithStatement', XJSIdentifier: 'XJSIdentifier', XJSNamespacedName: 'XJSNamespacedName', XJSMemberExpression: 'XJSMemberExpression', XJSEmptyExpression: 'XJSEmptyExpression', XJSExpressionContainer: 'XJSExpressionContainer', XJSElement: 'XJSElement', XJSClosingElement: 'XJSClosingElement', XJSOpeningElement: 'XJSOpeningElement', XJSAttribute: 'XJSAttribute', XJSSpreadAttribute: 'XJSSpreadAttribute', XJSText: 'XJSText', YieldExpression: 'YieldExpression', AwaitExpression: 'AwaitExpression' }; PropertyKind = { Data: 1, Get: 2, Set: 4 }; ClassPropertyType = { 'static': 'static', prototype: 'prototype' }; // Error messages should be identical to V8. Messages = { UnexpectedToken: 'Unexpected token %0', UnexpectedNumber: 'Unexpected number', UnexpectedString: 'Unexpected string', UnexpectedIdentifier: 'Unexpected identifier', UnexpectedReserved: 'Unexpected reserved word', UnexpectedTemplate: 'Unexpected quasi %0', UnexpectedEOS: 'Unexpected end of input', NewlineAfterThrow: 'Illegal newline after throw', InvalidRegExp: 'Invalid regular expression', 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', UnknownLabel: 'Undefined label \'%0\'', Redeclaration: '%0 \'%1\' has already been declared', IllegalContinue: 'Illegal continue statement', IllegalBreak: 'Illegal break statement', IllegalDuplicateClassProperty: 'Illegal duplicate property in class definition', IllegalReturn: 'Illegal return statement', 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', PropertyAfterSpreadProperty: 'A rest property must be the final property of an object literal', 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.', StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode', AccessorDataProperty: 'Object literal may not have data and accessor property with the same name', AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name', StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode', StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode', StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode', StrictReservedWord: 'Use of future reserved word in strict mode', MissingFromClause: 'Missing from clause', NoAsAfterImportNamespace: 'Missing as after import *', InvalidModuleSpecifier: 'Invalid module specifier', NoUnintializedConst: 'Const must be initialized', ComprehensionRequiresBlock: 'Comprehension must have at least one block', ComprehensionError: 'Comprehension Error', EachNotAllowed: 'Each is not supported', InvalidXJSAttributeValue: 'XJS value should be either an expression or a quoted XJS text', ExpectedXJSClosingTag: 'Expected corresponding XJS closing tag for %0', AdjacentXJSElements: 'Adjacent XJS elements must be wrapped in an enclosing tag', ConfusedAboutFunctionType: 'Unexpected token =>. It looks like ' + 'you are trying to write a function type, but you ended up ' + 'writing a grouped type followed by an =>, which is a syntax ' + 'error. Remember, function type parameters are named so function ' + 'types look like (name1: type1, name2: type2) => returnType. You ' + 'probably wrote (type1) => returnType' }; // See also tools/generate-unicode-regex.py. Regex = { NonAsciiIdentifierStart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'), NonAsciiIdentifierPart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'), LeadingZeros: new RegExp('^0+(?!$)') }; // Ensure the condition is true, otherwise throw an error. // This is only to have a better contract semantic, i.e. another safety net // to catch a logic error. The condition shall be fulfilled in normal case. // Do NOT use this to enforce a certain condition on any user input. function assert(condition, message) { if (!condition) { throw new Error('ASSERT: ' + message); } } function isDecimalDigit(ch) { return (ch >= 48 && ch <= 57); // 0..9 } function isHexDigit(ch) { return '0123456789abcdefABCDEF'.indexOf(ch) >= 0; } function isOctalDigit(ch) { return '01234567'.indexOf(ch) >= 0; } // 7.2 White Space function isWhiteSpace(ch) { return (ch === 32) || // space (ch === 9) || // tab (ch === 0xB) || (ch === 0xC) || (ch === 0xA0) || (ch >= 0x1680 && '\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\uFEFF'.indexOf(String.fromCharCode(ch)) > 0); } // 7.3 Line Terminators function isLineTerminator(ch) { return (ch === 10) || (ch === 13) || (ch === 0x2028) || (ch === 0x2029); } // 7.6 Identifier Names and Identifiers function isIdentifierStart(ch) { return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore) (ch >= 65 && ch <= 90) || // A..Z (ch >= 97 && ch <= 122) || // a..z (ch === 92) || // \ (backslash) ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch))); } function isIdentifierPart(ch) { return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore) (ch >= 65 && ch <= 90) || // A..Z (ch >= 97 && ch <= 122) || // a..z (ch >= 48 && ch <= 57) || // 0..9 (ch === 92) || // \ (backslash) ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch))); } // 7.6.1.2 Future Reserved Words function isFutureReservedWord(id) { switch (id) { case 'class': case 'enum': case 'export': case 'extends': case 'import': case 'super': return true; default: return false; } } function isStrictModeReservedWord(id) { switch (id) { case 'implements': case 'interface': case 'package': case 'private': case 'protected': case 'public': case 'static': case 'yield': case 'let': return true; default: return false; } } function isRestrictedWord(id) { return id === 'eval' || id === 'arguments'; } // 7.6.1.1 Keywords function isKeyword(id) { if (strict && isStrictModeReservedWord(id)) { return true; } // 'const' is specialized as Keyword in V8. // 'yield' is only treated as a keyword in strict mode. // 'let' is for compatiblity with SpiderMonkey and ES.next. // Some others are from future reserved words. switch (id.length) { case 2: return (id === 'if') || (id === 'in') || (id === 'do'); case 3: return (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try') || (id === 'let'); case 4: return (id === 'this') || (id === 'else') || (id === 'case') || (id === 'void') || (id === 'with') || (id === 'enum'); case 5: return (id === 'while') || (id === 'break') || (id === 'catch') || (id === 'throw') || (id === 'const') || (id === 'class') || (id === 'super'); case 6: return (id === 'return') || (id === 'typeof') || (id === 'delete') || (id === 'switch') || (id === 'export') || (id === 'import'); case 7: return (id === 'default') || (id === 'finally') || (id === 'extends'); case 8: return (id === 'function') || (id === 'continue') || (id === 'debugger'); case 10: return (id === 'instanceof'); default: return false; } } // 7.4 Comments function skipComment() { var ch, blockComment, lineComment; blockComment = false; lineComment = false; while (index < length) { ch = source.charCodeAt(index); if (lineComment) { ++index; if (isLineTerminator(ch)) { lineComment = false; if (ch === 13 && source.charCodeAt(index) === 10) { ++index; } ++lineNumber; lineStart = index; } } else if (blockComment) { if (isLineTerminator(ch)) { if (ch === 13) { ++index; } if (ch !== 13 || source.charCodeAt(index) === 10) { ++lineNumber; ++index; lineStart = index; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } } else { ch = source.charCodeAt(index++); if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } // Block comment ends with '*/' (char #42, char #47). if (ch === 42) { ch = source.charCodeAt(index); if (ch === 47) { ++index; blockComment = false; } } } } else if (ch === 47) { ch = source.charCodeAt(index + 1); // Line comment starts with '//' (char #47, char #47). if (ch === 47) { index += 2; lineComment = true; } else if (ch === 42) { // Block comment starts with '/*' (char #47, char #42). index += 2; blockComment = true; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } else { break; } } else if (isWhiteSpace(ch)) { ++index; } else if (isLineTerminator(ch)) { ++index; if (ch === 13 && source.charCodeAt(index) === 10) { ++index; } ++lineNumber; lineStart = index; } else { break; } } } function scanHexEscape(prefix) { var i, len, ch, code = 0; len = (prefix === 'u') ? 4 : 2; for (i = 0; i < len; ++i) { if (index < length && isHexDigit(source[index])) { ch = source[index++]; code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); } else { return ''; } } return String.fromCharCode(code); } function scanUnicodeCodePointEscape() { var ch, code, cu1, cu2; ch = source[index]; code = 0; // At least, one hex digit is required. if (ch === '}') { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } while (index < length) { ch = source[index++]; if (!isHexDigit(ch)) { break; } code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); } if (code > 0x10FFFF || ch !== '}') { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } // UTF-16 Encoding if (code <= 0xFFFF) { return String.fromCharCode(code); } cu1 = ((code - 0x10000) >> 10) + 0xD800; cu2 = ((code - 0x10000) & 1023) + 0xDC00; return String.fromCharCode(cu1, cu2); } function getEscapedIdentifier() { var ch, id; ch = source.charCodeAt(index++); id = String.fromCharCode(ch); // '\u' (char #92, char #117) denotes an escaped character. if (ch === 92) { if (source.charCodeAt(index) !== 117) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } ++index; ch = scanHexEscape('u'); if (!ch || ch === '\\' || !isIdentifierStart(ch.charCodeAt(0))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } id = ch; } while (index < length) { ch = source.charCodeAt(index); if (!isIdentifierPart(ch)) { break; } ++index; id += String.fromCharCode(ch); // '\u' (char #92, char #117) denotes an escaped character. if (ch === 92) { id = id.substr(0, id.length - 1); if (source.charCodeAt(index) !== 117) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } ++index; ch = scanHexEscape('u'); if (!ch || ch === '\\' || !isIdentifierPart(ch.charCodeAt(0))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } id += ch; } } return id; } function getIdentifier() { var start, ch; start = index++; while (index < length) { ch = source.charCodeAt(index); if (ch === 92) { // Blackslash (char #92) marks Unicode escape sequence. index = start; return getEscapedIdentifier(); } if (isIdentifierPart(ch)) { ++index; } else { break; } } return source.slice(start, index); } function scanIdentifier() { var start, id, type; start = index; // Backslash (char #92) starts an escaped character. id = (source.charCodeAt(index) === 92) ? getEscapedIdentifier() : getIdentifier(); // There is no keyword or literal with only one character. // Thus, it must be an identifier. if (id.length === 1) { type = Token.Identifier; } else if (isKeyword(id)) { type = Token.Keyword; } else if (id === 'null') { type = Token.NullLiteral; } else if (id === 'true' || id === 'false') { type = Token.BooleanLiteral; } else { type = Token.Identifier; } return { type: type, value: id, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // 7.7 Punctuators function scanPunctuator() { var start = index, code = source.charCodeAt(index), code2, ch1 = source[index], ch2, ch3, ch4; switch (code) { // Check for most common single-character punctuators. case 40: // ( open bracket case 41: // ) close bracket case 59: // ; semicolon case 44: // , comma case 123: // { open curly brace case 125: // } close curly brace case 91: // [ case 93: // ] case 58: // : case 63: // ? case 126: // ~ ++index; if (extra.tokenize) { if (code === 40) { extra.openParenToken = extra.tokens.length; } else if (code === 123) { extra.openCurlyToken = extra.tokens.length; } } return { type: Token.Punctuator, value: String.fromCharCode(code), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; default: code2 = source.charCodeAt(index + 1); // '=' (char #61) marks an assignment or comparison operator. if (code2 === 61) { switch (code) { case 37: // % case 38: // & case 42: // *: case 43: // + case 45: // - case 47: // / case 60: // < case 62: // > case 94: // ^ case 124: // | index += 2; return { type: Token.Punctuator, value: String.fromCharCode(code) + String.fromCharCode(code2), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; case 33: // ! case 61: // = index += 2; // !== and === if (source.charCodeAt(index) === 61) { ++index; } return { type: Token.Punctuator, value: source.slice(start, index), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; default: break; } } break; } // Peek more characters. ch2 = source[index + 1]; ch3 = source[index + 2]; ch4 = source[index + 3]; // 4-character punctuator: >>>= if (ch1 === '>' && ch2 === '>' && ch3 === '>') { if (ch4 === '=') { index += 4; return { type: Token.Punctuator, value: '>>>=', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } } // 3-character punctuators: === !== >>> <<= >>= if (ch1 === '>' && ch2 === '>' && ch3 === '>') { index += 3; return { type: Token.Punctuator, value: '>>>', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '<' && ch2 === '<' && ch3 === '=') { index += 3; return { type: Token.Punctuator, value: '<<=', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '>' && ch2 === '>' && ch3 === '=') { index += 3; return { type: Token.Punctuator, value: '>>=', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '.' && ch2 === '.' && ch3 === '.') { index += 3; return { type: Token.Punctuator, value: '...', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // Other 2-character punctuators: ++ -- << >> && || // Don't match these tokens if we're in a type, since they never can // occur and can mess up types like Map> if (ch1 === ch2 && ('+-<>&|'.indexOf(ch1) >= 0) && !state.inType) { index += 2; return { type: Token.Punctuator, value: ch1 + ch2, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '=' && ch2 === '>') { index += 2; return { type: Token.Punctuator, value: '=>', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) { ++index; return { type: Token.Punctuator, value: ch1, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '.') { ++index; return { type: Token.Punctuator, value: ch1, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } // 7.8.3 Numeric Literals function scanHexLiteral(start) { var number = ''; while (index < length) { if (!isHexDigit(source[index])) { break; } number += source[index++]; } if (number.length === 0) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } if (isIdentifierStart(source.charCodeAt(index))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.NumericLiteral, value: parseInt('0x' + number, 16), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanOctalLiteral(prefix, start) { var number, octal; if (isOctalDigit(prefix)) { octal = true; number = '0' + source[index++]; } else { octal = false; ++index; number = ''; } while (index < length) { if (!isOctalDigit(source[index])) { break; } number += source[index++]; } if (!octal && number.length === 0) { // only 0o or 0O throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.NumericLiteral, value: parseInt(number, 8), octal: octal, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanNumericLiteral() { var number, start, ch, octal; ch = source[index]; assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'), 'Numeric literal must start with a decimal digit or a decimal point'); start = index; number = ''; if (ch !== '.') { number = source[index++]; ch = source[index]; // Hex number starts with '0x'. // Octal number starts with '0'. // Octal number in ES6 starts with '0o'. // Binary number in ES6 starts with '0b'. if (number === '0') { if (ch === 'x' || ch === 'X') { ++index; return scanHexLiteral(start); } if (ch === 'b' || ch === 'B') { ++index; number = ''; while (index < length) { ch = source[index]; if (ch !== '0' && ch !== '1') { break; } number += source[index++]; } if (number.length === 0) { // only 0b or 0B throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } if (index < length) { ch = source.charCodeAt(index); if (isIdentifierStart(ch) || isDecimalDigit(ch)) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } return { type: Token.NumericLiteral, value: parseInt(number, 2), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch === 'o' || ch === 'O' || isOctalDigit(ch)) { return scanOctalLiteral(ch, start); } // decimal number starts with '0' such as '09' is illegal. if (ch && isDecimalDigit(ch.charCodeAt(0))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } ch = source[index]; } if (ch === '.') { number += source[index++]; while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } ch = source[index]; } if (ch === 'e' || ch === 'E') { number += source[index++]; ch = source[index]; if (ch === '+' || ch === '-') { number += source[index++]; } if (isDecimalDigit(source.charCodeAt(index))) { while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } } else { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } if (isIdentifierStart(source.charCodeAt(index))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.NumericLiteral, value: parseFloat(number), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // 7.8.4 String Literals function scanStringLiteral() { var str = '', quote, start, ch, code, unescaped, restore, octal = false; quote = source[index]; assert((quote === '\'' || quote === '"'), 'String literal must starts with a quote'); start = index; ++index; while (index < length) { ch = source[index++]; if (ch === quote) { quote = ''; break; } else if (ch === '\\') { ch = source[index++]; if (!ch || !isLineTerminator(ch.charCodeAt(0))) { switch (ch) { case 'n': str += '\n'; break; case 'r': str += '\r'; break; case 't': str += '\t'; break; case 'u': case 'x': if (source[index] === '{') { ++index; str += scanUnicodeCodePointEscape(); } else { restore = index; unescaped = scanHexEscape(ch); if (unescaped) { str += unescaped; } else { index = restore; str += ch; } } break; case 'b': str += '\b'; break; case 'f': str += '\f'; break; case 'v': str += '\x0B'; break; default: if (isOctalDigit(ch)) { code = '01234567'.indexOf(ch); // \0 is not octal escape sequence if (code !== 0) { octal = true; } if (index < length && isOctalDigit(source[index])) { octal = true; code = code * 8 + '01234567'.indexOf(source[index++]); // 3 digits are only allowed when string starts // with 0, 1, 2, 3 if ('0123'.indexOf(ch) >= 0 && index < length && isOctalDigit(source[index])) { code = code * 8 + '01234567'.indexOf(source[index++]); } } str += String.fromCharCode(code); } else { str += ch; } break; } } else { ++lineNumber; if (ch === '\r' && source[index] === '\n') { ++index; } lineStart = index; } } else if (isLineTerminator(ch.charCodeAt(0))) { break; } else { str += ch; } } if (quote !== '') { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.StringLiteral, value: str, octal: octal, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanTemplate() { var cooked = '', ch, start, terminated, tail, restore, unescaped, code, octal; terminated = false; tail = false; start = index; ++index; while (index < length) { ch = source[index++]; if (ch === '`') { tail = true; terminated = true; break; } else if (ch === '$') { if (source[index] === '{') { ++index; terminated = true; break; } cooked += ch; } else if (ch === '\\') { ch = source[index++]; if (!isLineTerminator(ch.charCodeAt(0))) { switch (ch) { case 'n': cooked += '\n'; break; case 'r': cooked += '\r'; break; case 't': cooked += '\t'; break; case 'u': case 'x': if (source[index] === '{') { ++index; cooked += scanUnicodeCodePointEscape(); } else { restore = index; unescaped = scanHexEscape(ch); if (unescaped) { cooked += unescaped; } else { index = restore; cooked += ch; } } break; case 'b': cooked += '\b'; break; case 'f': cooked += '\f'; break; case 'v': cooked += '\v'; break; default: if (isOctalDigit(ch)) { code = '01234567'.indexOf(ch); // \0 is not octal escape sequence if (code !== 0) { octal = true; } if (index < length && isOctalDigit(source[index])) { octal = true; code = code * 8 + '01234567'.indexOf(source[index++]); // 3 digits are only allowed when string starts // with 0, 1, 2, 3 if ('0123'.indexOf(ch) >= 0 && index < length && isOctalDigit(source[index])) { code = code * 8 + '01234567'.indexOf(source[index++]); } } cooked += String.fromCharCode(code); } else { cooked += ch; } break; } } else { ++lineNumber; if (ch === '\r' && source[index] === '\n') { ++index; } lineStart = index; } } else if (isLineTerminator(ch.charCodeAt(0))) { ++lineNumber; if (ch === '\r' && source[index] === '\n') { ++index; } lineStart = index; cooked += '\n'; } else { cooked += ch; } } if (!terminated) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.Template, value: { cooked: cooked, raw: source.slice(start + 1, index - ((tail) ? 1 : 2)) }, tail: tail, octal: octal, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanTemplateElement(option) { var startsWith, template; lookahead = null; skipComment(); startsWith = (option.head) ? '`' : '}'; if (source[index] !== startsWith) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } template = scanTemplate(); peek(); return template; } function scanRegExp() { var str, ch, start, pattern, flags, value, classMarker = false, restore, terminated = false, tmp; lookahead = null; skipComment(); start = index; ch = source[index]; assert(ch === '/', 'Regular expression literal must start with a slash'); str = source[index++]; while (index < length) { ch = source[index++]; str += ch; if (classMarker) { if (ch === ']') { classMarker = false; } } else { if (ch === '\\') { ch = source[index++]; // ECMA-262 7.8.5 if (isLineTerminator(ch.charCodeAt(0))) { throwError({}, Messages.UnterminatedRegExp); } str += ch; } else if (ch === '/') { terminated = true; break; } else if (ch === '[') { classMarker = true; } else if (isLineTerminator(ch.charCodeAt(0))) { throwError({}, Messages.UnterminatedRegExp); } } } if (!terminated) { throwError({}, Messages.UnterminatedRegExp); } // Exclude leading and trailing slash. pattern = str.substr(1, str.length - 2); flags = ''; while (index < length) { ch = source[index]; if (!isIdentifierPart(ch.charCodeAt(0))) { break; } ++index; if (ch === '\\' && index < length) { ch = source[index]; if (ch === 'u') { ++index; restore = index; ch = scanHexEscape('u'); if (ch) { flags += ch; for (str += '\\u'; restore < index; ++restore) { str += source[restore]; } } else { index = restore; flags += 'u'; str += '\\u'; } } else { str += '\\'; } } else { flags += ch; str += ch; } } tmp = pattern; if (flags.indexOf('u') >= 0) { // Replace each astral symbol and every Unicode code point // escape sequence that represents such a symbol with a single // ASCII symbol to avoid throwing on regular expressions that // are only valid in combination with the `/u` flag. tmp = tmp .replace(/\\u\{([0-9a-fA-F]{5,6})\}/g, 'x') .replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, 'x'); } // First, detect invalid regular expressions. try { value = new RegExp(tmp); } catch (e) { throwError({}, Messages.InvalidRegExp); } // Return a regular expression object for this pattern-flag pair, or // `null` in case the current environment doesn't support the flags it // uses. try { value = new RegExp(pattern, flags); } catch (exception) { value = null; } peek(); if (extra.tokenize) { return { type: Token.RegularExpression, value: value, regex: { pattern: pattern, flags: flags }, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } return { literal: str, value: value, regex: { pattern: pattern, flags: flags }, range: [start, index] }; } function isIdentifierName(token) { return token.type === Token.Identifier || token.type === Token.Keyword || token.type === Token.BooleanLiteral || token.type === Token.NullLiteral; } function advanceSlash() { var prevToken, checkToken; // Using the following algorithm: // https://github.com/mozilla/sweet.js/wiki/design prevToken = extra.tokens[extra.tokens.length - 1]; if (!prevToken) { // Nothing before that: it cannot be a division. return scanRegExp(); } if (prevToken.type === 'Punctuator') { if (prevToken.value === ')') { checkToken = extra.tokens[extra.openParenToken - 1]; if (checkToken && checkToken.type === 'Keyword' && (checkToken.value === 'if' || checkToken.value === 'while' || checkToken.value === 'for' || checkToken.value === 'with')) { return scanRegExp(); } return scanPunctuator(); } if (prevToken.value === '}') { // Dividing a function by anything makes little sense, // but we have to check for that. if (extra.tokens[extra.openCurlyToken - 3] && extra.tokens[extra.openCurlyToken - 3].type === 'Keyword') { // Anonymous function. checkToken = extra.tokens[extra.openCurlyToken - 4]; if (!checkToken) { return scanPunctuator(); } } else if (extra.tokens[extra.openCurlyToken - 4] && extra.tokens[extra.openCurlyToken - 4].type === 'Keyword') { // Named function. checkToken = extra.tokens[extra.openCurlyToken - 5]; if (!checkToken) { return scanRegExp(); } } else { return scanPunctuator(); } // checkToken determines whether the function is // a declaration or an expression. if (FnExprTokens.indexOf(checkToken.value) >= 0) { // It is an expression. return scanPunctuator(); } // It is a declaration. return scanRegExp(); } return scanRegExp(); } if (prevToken.type === 'Keyword') { return scanRegExp(); } return scanPunctuator(); } function advance() { var ch; if (!state.inXJSChild) { skipComment(); } if (index >= length) { return { type: Token.EOF, lineNumber: lineNumber, lineStart: lineStart, range: [index, index] }; } if (state.inXJSChild) { return advanceXJSChild(); } ch = source.charCodeAt(index); // Very common: ( and ) and ; if (ch === 40 || ch === 41 || ch === 58) { return scanPunctuator(); } // String literal starts with single quote (#39) or double quote (#34). if (ch === 39 || ch === 34) { if (state.inXJSTag) { return scanXJSStringLiteral(); } return scanStringLiteral(); } if (state.inXJSTag && isXJSIdentifierStart(ch)) { return scanXJSIdentifier(); } if (ch === 96) { return scanTemplate(); } if (isIdentifierStart(ch)) { return scanIdentifier(); } // Dot (.) char #46 can also start a floating-point number, hence the need // to check the next character. if (ch === 46) { if (isDecimalDigit(source.charCodeAt(index + 1))) { return scanNumericLiteral(); } return scanPunctuator(); } if (isDecimalDigit(ch)) { return scanNumericLiteral(); } // Slash (/) char #47 can also start a regex. if (extra.tokenize && ch === 47) { return advanceSlash(); } return scanPunctuator(); } function lex() { var token; token = lookahead; index = token.range[1]; lineNumber = token.lineNumber; lineStart = token.lineStart; lookahead = advance(); index = token.range[1]; lineNumber = token.lineNumber; lineStart = token.lineStart; return token; } function peek() { var pos, line, start; pos = index; line = lineNumber; start = lineStart; lookahead = advance(); index = pos; lineNumber = line; lineStart = start; } function lookahead2() { var adv, pos, line, start, result; // If we are collecting the tokens, don't grab the next one yet. adv = (typeof extra.advance === 'function') ? extra.advance : advance; pos = index; line = lineNumber; start = lineStart; // Scan for the next immediate token. if (lookahead === null) { lookahead = adv(); } index = lookahead.range[1]; lineNumber = lookahead.lineNumber; lineStart = lookahead.lineStart; // Grab the token right after. result = adv(); index = pos; lineNumber = line; lineStart = start; return result; } function rewind(token) { index = token.range[0]; lineNumber = token.lineNumber; lineStart = token.lineStart; lookahead = token; } function markerCreate() { if (!extra.loc && !extra.range) { return undefined; } skipComment(); return {offset: index, line: lineNumber, col: index - lineStart}; } function markerCreatePreserveWhitespace() { if (!extra.loc && !extra.range) { return undefined; } return {offset: index, line: lineNumber, col: index - lineStart}; } function processComment(node) { var lastChild, trailingComments, bottomRight = extra.bottomRightStack, last = bottomRight[bottomRight.length - 1]; if (node.type === Syntax.Program) { if (node.body.length > 0) { return; } } if (extra.trailingComments.length > 0) { if (extra.trailingComments[0].range[0] >= node.range[1]) { trailingComments = extra.trailingComments; extra.trailingComments = []; } else { extra.trailingComments.length = 0; } } else { if (last && last.trailingComments && last.trailingComments[0].range[0] >= node.range[1]) { trailingComments = last.trailingComments; delete last.trailingComments; } } // Eating the stack. if (last) { while (last && last.range[0] >= node.range[0]) { lastChild = last; last = bottomRight.pop(); } } if (lastChild) { if (lastChild.leadingComments && lastChild.leadingComments[lastChild.leadingComments.length - 1].range[1] <= node.range[0]) { node.leadingComments = lastChild.leadingComments; delete lastChild.leadingComments; } } else if (extra.leadingComments.length > 0 && extra.leadingComments[extra.leadingComments.length - 1].range[1] <= node.range[0]) { node.leadingComments = extra.leadingComments; extra.leadingComments = []; } if (trailingComments) { node.trailingComments = trailingComments; } bottomRight.push(node); } function markerApply(marker, node) { if (extra.range) { node.range = [marker.offset, index]; } if (extra.loc) { node.loc = { start: { line: marker.line, column: marker.col }, end: { line: lineNumber, column: index - lineStart } }; node = delegate.postProcess(node); } if (extra.attachComment) { processComment(node); } return node; } SyntaxTreeDelegate = { name: 'SyntaxTree', postProcess: function (node) { return node; }, createArrayExpression: function (elements) { return { type: Syntax.ArrayExpression, elements: elements }; }, createAssignmentExpression: function (operator, left, right) { return { type: Syntax.AssignmentExpression, operator: operator, left: left, right: right }; }, createBinaryExpression: function (operator, left, right) { var type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression : Syntax.BinaryExpression; return { type: type, operator: operator, left: left, right: right }; }, createBlockStatement: function (body) { return { type: Syntax.BlockStatement, body: body }; }, createBreakStatement: function (label) { return { type: Syntax.BreakStatement, label: label }; }, createCallExpression: function (callee, args) { return { type: Syntax.CallExpression, callee: callee, 'arguments': args }; }, createCatchClause: function (param, body) { return { type: Syntax.CatchClause, param: param, body: body }; }, createConditionalExpression: function (test, consequent, alternate) { return { type: Syntax.ConditionalExpression, test: test, consequent: consequent, alternate: alternate }; }, createContinueStatement: function (label) { return { type: Syntax.ContinueStatement, label: label }; }, createDebuggerStatement: function () { return { type: Syntax.DebuggerStatement }; }, createDoWhileStatement: function (body, test) { return { type: Syntax.DoWhileStatement, body: body, test: test }; }, createEmptyStatement: function () { return { type: Syntax.EmptyStatement }; }, createExpressionStatement: function (expression) { return { type: Syntax.ExpressionStatement, expression: expression }; }, createForStatement: function (init, test, update, body) { return { type: Syntax.ForStatement, init: init, test: test, update: update, body: body }; }, createForInStatement: function (left, right, body) { return { type: Syntax.ForInStatement, left: left, right: right, body: body, each: false }; }, createForOfStatement: function (left, right, body) { return { type: Syntax.ForOfStatement, left: left, right: right, body: body }; }, createFunctionDeclaration: function (id, params, defaults, body, rest, generator, expression, isAsync, returnType, typeParameters) { var funDecl = { type: Syntax.FunctionDeclaration, id: id, params: params, defaults: defaults, body: body, rest: rest, generator: generator, expression: expression, returnType: returnType, typeParameters: typeParameters }; if (isAsync) { funDecl.async = true; } return funDecl; }, createFunctionExpression: function (id, params, defaults, body, rest, generator, expression, isAsync, returnType, typeParameters) { var funExpr = { type: Syntax.FunctionExpression, id: id, params: params, defaults: defaults, body: body, rest: rest, generator: generator, expression: expression, returnType: returnType, typeParameters: typeParameters }; if (isAsync) { funExpr.async = true; } return funExpr; }, createIdentifier: function (name) { return { type: Syntax.Identifier, name: name, // Only here to initialize the shape of the object to ensure // that the 'typeAnnotation' key is ordered before others that // are added later (like 'loc' and 'range'). This just helps // keep the shape of Identifier nodes consistent with everything // else. typeAnnotation: undefined, optional: undefined }; }, createTypeAnnotation: function (typeAnnotation) { return { type: Syntax.TypeAnnotation, typeAnnotation: typeAnnotation }; }, createFunctionTypeAnnotation: function (params, returnType, rest, typeParameters) { return { type: Syntax.FunctionTypeAnnotation, params: params, returnType: returnType, rest: rest, typeParameters: typeParameters }; }, createFunctionTypeParam: function (name, typeAnnotation, optional) { return { type: Syntax.FunctionTypeParam, name: name, typeAnnotation: typeAnnotation, optional: optional }; }, createNullableTypeAnnotation: function (typeAnnotation) { return { type: Syntax.NullableTypeAnnotation, typeAnnotation: typeAnnotation }; }, createArrayTypeAnnotation: function (elementType) { return { type: Syntax.ArrayTypeAnnotation, elementType: elementType }; }, createGenericTypeAnnotation: function (id, typeParameters) { return { type: Syntax.GenericTypeAnnotation, id: id, typeParameters: typeParameters }; }, createQualifiedTypeIdentifier: function (qualification, id) { return { type: Syntax.QualifiedTypeIdentifier, qualification: qualification, id: id }; }, createTypeParameterDeclaration: function (params) { return { type: Syntax.TypeParameterDeclaration, params: params }; }, createTypeParameterInstantiation: function (params) { return { type: Syntax.TypeParameterInstantiation, params: params }; }, createAnyTypeAnnotation: function () { return { type: Syntax.AnyTypeAnnotation }; }, createBooleanTypeAnnotation: function () { return { type: Syntax.BooleanTypeAnnotation }; }, createNumberTypeAnnotation: function () { return { type: Syntax.NumberTypeAnnotation }; }, createStringTypeAnnotation: function () { return { type: Syntax.StringTypeAnnotation }; }, createStringLiteralTypeAnnotation: function (token) { return { type: Syntax.StringLiteralTypeAnnotation, value: token.value, raw: source.slice(token.range[0], token.range[1]) }; }, createVoidTypeAnnotation: function () { return { type: Syntax.VoidTypeAnnotation }; }, createTypeofTypeAnnotation: function (argument) { return { type: Syntax.TypeofTypeAnnotation, argument: argument }; }, createTupleTypeAnnotation: function (types) { return { type: Syntax.TupleTypeAnnotation, types: types }; }, createObjectTypeAnnotation: function (properties, indexers, callProperties) { return { type: Syntax.ObjectTypeAnnotation, properties: properties, indexers: indexers, callProperties: callProperties }; }, createObjectTypeIndexer: function (id, key, value, isStatic) { return { type: Syntax.ObjectTypeIndexer, id: id, key: key, value: value, static: isStatic }; }, createObjectTypeCallProperty: function (value, isStatic) { return { type: Syntax.ObjectTypeCallProperty, value: value, static: isStatic }; }, createObjectTypeProperty: function (key, value, optional, isStatic) { return { type: Syntax.ObjectTypeProperty, key: key, value: value, optional: optional, static: isStatic }; }, createUnionTypeAnnotation: function (types) { return { type: Syntax.UnionTypeAnnotation, types: types }; }, createIntersectionTypeAnnotation: function (types) { return { type: Syntax.IntersectionTypeAnnotation, types: types }; }, createTypeAlias: function (id, typeParameters, right) { return { type: Syntax.TypeAlias, id: id, typeParameters: typeParameters, right: right }; }, createInterface: function (id, typeParameters, body, extended) { return { type: Syntax.InterfaceDeclaration, id: id, typeParameters: typeParameters, body: body, extends: extended }; }, createInterfaceExtends: function (id, typeParameters) { return { type: Syntax.InterfaceExtends, id: id, typeParameters: typeParameters }; }, createDeclareFunction: function (id) { return { type: Syntax.DeclareFunction, id: id }; }, createDeclareVariable: function (id) { return { type: Syntax.DeclareVariable, id: id }; }, createDeclareModule: function (id, body) { return { type: Syntax.DeclareModule, id: id, body: body }; }, createXJSAttribute: function (name, value) { return { type: Syntax.XJSAttribute, name: name, value: value || null }; }, createXJSSpreadAttribute: function (argument) { return { type: Syntax.XJSSpreadAttribute, argument: argument }; }, createXJSIdentifier: function (name) { return { type: Syntax.XJSIdentifier, name: name }; }, createXJSNamespacedName: function (namespace, name) { return { type: Syntax.XJSNamespacedName, namespace: namespace, name: name }; }, createXJSMemberExpression: function (object, property) { return { type: Syntax.XJSMemberExpression, object: object, property: property }; }, createXJSElement: function (openingElement, closingElement, children) { return { type: Syntax.XJSElement, openingElement: openingElement, closingElement: closingElement, children: children }; }, createXJSEmptyExpression: function () { return { type: Syntax.XJSEmptyExpression }; }, createXJSExpressionContainer: function (expression) { return { type: Syntax.XJSExpressionContainer, expression: expression }; }, createXJSOpeningElement: function (name, attributes, selfClosing) { return { type: Syntax.XJSOpeningElement, name: name, selfClosing: selfClosing, attributes: attributes }; }, createXJSClosingElement: function (name) { return { type: Syntax.XJSClosingElement, name: name }; }, createIfStatement: function (test, consequent, alternate) { return { type: Syntax.IfStatement, test: test, consequent: consequent, alternate: alternate }; }, createLabeledStatement: function (label, body) { return { type: Syntax.LabeledStatement, label: label, body: body }; }, createLiteral: function (token) { var object = { type: Syntax.Literal, value: token.value, raw: source.slice(token.range[0], token.range[1]) }; if (token.regex) { object.regex = token.regex; } return object; }, createMemberExpression: function (accessor, object, property) { return { type: Syntax.MemberExpression, computed: accessor === '[', object: object, property: property }; }, createNewExpression: function (callee, args) { return { type: Syntax.NewExpression, callee: callee, 'arguments': args }; }, createObjectExpression: function (properties) { return { type: Syntax.ObjectExpression, properties: properties }; }, createPostfixExpression: function (operator, argument) { return { type: Syntax.UpdateExpression, operator: operator, argument: argument, prefix: false }; }, createProgram: function (body) { return { type: Syntax.Program, body: body }; }, createProperty: function (kind, key, value, method, shorthand, computed) { return { type: Syntax.Property, key: key, value: value, kind: kind, method: method, shorthand: shorthand, computed: computed }; }, createReturnStatement: function (argument) { return { type: Syntax.ReturnStatement, argument: argument }; }, createSequenceExpression: function (expressions) { return { type: Syntax.SequenceExpression, expressions: expressions }; }, createSwitchCase: function (test, consequent) { return { type: Syntax.SwitchCase, test: test, consequent: consequent }; }, createSwitchStatement: function (discriminant, cases) { return { type: Syntax.SwitchStatement, discriminant: discriminant, cases: cases }; }, createThisExpression: function () { return { type: Syntax.ThisExpression }; }, createThrowStatement: function (argument) { return { type: Syntax.ThrowStatement, argument: argument }; }, createTryStatement: function (block, guardedHandlers, handlers, finalizer) { return { type: Syntax.TryStatement, block: block, guardedHandlers: guardedHandlers, handlers: handlers, finalizer: finalizer }; }, createUnaryExpression: function (operator, argument) { if (operator === '++' || operator === '--') { return { type: Syntax.UpdateExpression, operator: operator, argument: argument, prefix: true }; } return { type: Syntax.UnaryExpression, operator: operator, argument: argument, prefix: true }; }, createVariableDeclaration: function (declarations, kind) { return { type: Syntax.VariableDeclaration, declarations: declarations, kind: kind }; }, createVariableDeclarator: function (id, init) { return { type: Syntax.VariableDeclarator, id: id, init: init }; }, createWhileStatement: function (test, body) { return { type: Syntax.WhileStatement, test: test, body: body }; }, createWithStatement: function (object, body) { return { type: Syntax.WithStatement, object: object, body: body }; }, createTemplateElement: function (value, tail) { return { type: Syntax.TemplateElement, value: value, tail: tail }; }, createTemplateLiteral: function (quasis, expressions) { return { type: Syntax.TemplateLiteral, quasis: quasis, expressions: expressions }; }, createSpreadElement: function (argument) { return { type: Syntax.SpreadElement, argument: argument }; }, createSpreadProperty: function (argument) { return { type: Syntax.SpreadProperty, argument: argument }; }, createTaggedTemplateExpression: function (tag, quasi) { return { type: Syntax.TaggedTemplateExpression, tag: tag, quasi: quasi }; }, createArrowFunctionExpression: function (params, defaults, body, rest, expression, isAsync) { var arrowExpr = { type: Syntax.ArrowFunctionExpression, id: null, params: params, defaults: defaults, body: body, rest: rest, generator: false, expression: expression }; if (isAsync) { arrowExpr.async = true; } return arrowExpr; }, createMethodDefinition: function (propertyType, kind, key, value) { return { type: Syntax.MethodDefinition, key: key, value: value, kind: kind, 'static': propertyType === ClassPropertyType.static }; }, createClassProperty: function (key, typeAnnotation, computed, isStatic) { return { type: Syntax.ClassProperty, key: key, typeAnnotation: typeAnnotation, computed: computed, static: isStatic }; }, createClassBody: function (body) { return { type: Syntax.ClassBody, body: body }; }, createClassImplements: function (id, typeParameters) { return { type: Syntax.ClassImplements, id: id, typeParameters: typeParameters }; }, createClassExpression: function (id, superClass, body, typeParameters, superTypeParameters, implemented) { return { type: Syntax.ClassExpression, id: id, superClass: superClass, body: body, typeParameters: typeParameters, superTypeParameters: superTypeParameters, implements: implemented }; }, createClassDeclaration: function (id, superClass, body, typeParameters, superTypeParameters, implemented) { return { type: Syntax.ClassDeclaration, id: id, superClass: superClass, body: body, typeParameters: typeParameters, superTypeParameters: superTypeParameters, implements: implemented }; }, createModuleSpecifier: function (token) { return { type: Syntax.ModuleSpecifier, value: token.value, raw: source.slice(token.range[0], token.range[1]) }; }, createExportSpecifier: function (id, name) { return { type: Syntax.ExportSpecifier, id: id, name: name }; }, createExportBatchSpecifier: function () { return { type: Syntax.ExportBatchSpecifier }; }, createImportDefaultSpecifier: function (id) { return { type: Syntax.ImportDefaultSpecifier, id: id }; }, createImportNamespaceSpecifier: function (id) { return { type: Syntax.ImportNamespaceSpecifier, id: id }; }, createExportDeclaration: function (isDefault, declaration, specifiers, source) { return { type: Syntax.ExportDeclaration, 'default': !!isDefault, declaration: declaration, specifiers: specifiers, source: source }; }, createImportSpecifier: function (id, name) { return { type: Syntax.ImportSpecifier, id: id, name: name }; }, createImportDeclaration: function (specifiers, source) { return { type: Syntax.ImportDeclaration, specifiers: specifiers, source: source }; }, createYieldExpression: function (argument, delegate) { return { type: Syntax.YieldExpression, argument: argument, delegate: delegate }; }, createAwaitExpression: function (argument) { return { type: Syntax.AwaitExpression, argument: argument }; }, createComprehensionExpression: function (filter, blocks, body) { return { type: Syntax.ComprehensionExpression, filter: filter, blocks: blocks, body: body }; } }; // Return true if there is a line terminator before the next token. function peekLineTerminator() { var pos, line, start, found; pos = index; line = lineNumber; start = lineStart; skipComment(); found = lineNumber !== line; index = pos; lineNumber = line; lineStart = start; return found; } // Throw an exception function throwError(token, messageFormat) { var error, args = Array.prototype.slice.call(arguments, 2), msg = messageFormat.replace( /%(\d)/g, function (whole, index) { assert(index < args.length, 'Message reference must be in range'); return args[index]; } ); if (typeof token.lineNumber === 'number') { error = new Error('Line ' + token.lineNumber + ': ' + msg); error.index = token.range[0]; error.lineNumber = token.lineNumber; error.column = token.range[0] - lineStart + 1; } else { error = new Error('Line ' + lineNumber + ': ' + msg); error.index = index; error.lineNumber = lineNumber; error.column = index - lineStart + 1; } error.description = msg; throw error; } function throwErrorTolerant() { try { throwError.apply(null, arguments); } catch (e) { if (extra.errors) { extra.errors.push(e); } else { throw e; } } } // Throw an exception because of the token. function throwUnexpected(token) { if (token.type === Token.EOF) { throwError(token, Messages.UnexpectedEOS); } if (token.type === Token.NumericLiteral) { throwError(token, Messages.UnexpectedNumber); } if (token.type === Token.StringLiteral || token.type === Token.XJSText) { throwError(token, Messages.UnexpectedString); } if (token.type === Token.Identifier) { throwError(token, Messages.UnexpectedIdentifier); } if (token.type === Token.Keyword) { if (isFutureReservedWord(token.value)) { throwError(token, Messages.UnexpectedReserved); } else if (strict && isStrictModeReservedWord(token.value)) { throwErrorTolerant(token, Messages.StrictReservedWord); return; } throwError(token, Messages.UnexpectedToken, token.value); } if (token.type === Token.Template) { throwError(token, Messages.UnexpectedTemplate, token.value.raw); } // BooleanLiteral, NullLiteral, or Punctuator. throwError(token, Messages.UnexpectedToken, token.value); } // Expect the next token to match the specified punctuator. // If not, an exception will be thrown. function expect(value) { var token = lex(); if (token.type !== Token.Punctuator || token.value !== value) { throwUnexpected(token); } } // Expect the next token to match the specified keyword. // If not, an exception will be thrown. function expectKeyword(keyword, contextual) { var token = lex(); if (token.type !== (contextual ? Token.Identifier : Token.Keyword) || token.value !== keyword) { throwUnexpected(token); } } // Expect the next token to match the specified contextual keyword. // If not, an exception will be thrown. function expectContextualKeyword(keyword) { return expectKeyword(keyword, true); } // Return true if the next token matches the specified punctuator. function match(value) { return lookahead.type === Token.Punctuator && lookahead.value === value; } // Return true if the next token matches the specified keyword function matchKeyword(keyword, contextual) { var expectedType = contextual ? Token.Identifier : Token.Keyword; return lookahead.type === expectedType && lookahead.value === keyword; } // Return true if the next token matches the specified contextual keyword function matchContextualKeyword(keyword) { return matchKeyword(keyword, true); } // Return true if the next token is an assignment operator function matchAssign() { var op; if (lookahead.type !== Token.Punctuator) { return false; } op = lookahead.value; return op === '=' || op === '*=' || op === '/=' || op === '%=' || op === '+=' || op === '-=' || op === '<<=' || op === '>>=' || op === '>>>=' || op === '&=' || op === '^=' || op === '|='; } // Note that 'yield' is treated as a keyword in strict mode, but a // contextual keyword (identifier) in non-strict mode, so we need to // use matchKeyword('yield', false) and matchKeyword('yield', true) // (i.e. matchContextualKeyword) appropriately. function matchYield() { return state.yieldAllowed && matchKeyword('yield', !strict); } function matchAsync() { var backtrackToken = lookahead, matches = false; if (matchContextualKeyword('async')) { lex(); // Make sure peekLineTerminator() starts after 'async'. matches = !peekLineTerminator(); rewind(backtrackToken); // Revert the lex(). } return matches; } function matchAwait() { return state.awaitAllowed && matchContextualKeyword('await'); } function consumeSemicolon() { var line, oldIndex = index, oldLineNumber = lineNumber, oldLineStart = lineStart, oldLookahead = lookahead; // Catch the very common case first: immediately a semicolon (char #59). if (source.charCodeAt(index) === 59) { lex(); return; } line = lineNumber; skipComment(); if (lineNumber !== line) { index = oldIndex; lineNumber = oldLineNumber; lineStart = oldLineStart; lookahead = oldLookahead; return; } if (match(';')) { lex(); return; } if (lookahead.type !== Token.EOF && !match('}')) { throwUnexpected(lookahead); } } // Return true if provided expression is LeftHandSideExpression function isLeftHandSide(expr) { return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression; } function isAssignableLeftHandSide(expr) { return isLeftHandSide(expr) || expr.type === Syntax.ObjectPattern || expr.type === Syntax.ArrayPattern; } // 11.1.4 Array Initialiser function parseArrayInitialiser() { var elements = [], blocks = [], filter = null, tmp, possiblecomprehension = true, body, marker = markerCreate(); expect('['); while (!match(']')) { if (lookahead.value === 'for' && lookahead.type === Token.Keyword) { if (!possiblecomprehension) { throwError({}, Messages.ComprehensionError); } matchKeyword('for'); tmp = parseForStatement({ignoreBody: true}); tmp.of = tmp.type === Syntax.ForOfStatement; tmp.type = Syntax.ComprehensionBlock; if (tmp.left.kind) { // can't be let or const throwError({}, Messages.ComprehensionError); } blocks.push(tmp); } else if (lookahead.value === 'if' && lookahead.type === Token.Keyword) { if (!possiblecomprehension) { throwError({}, Messages.ComprehensionError); } expectKeyword('if'); expect('('); filter = parseExpression(); expect(')'); } else if (lookahead.value === ',' && lookahead.type === Token.Punctuator) { possiblecomprehension = false; // no longer allowed. lex(); elements.push(null); } else { tmp = parseSpreadOrAssignmentExpression(); elements.push(tmp); if (tmp && tmp.type === Syntax.SpreadElement) { if (!match(']')) { throwError({}, Messages.ElementAfterSpreadElement); } } else if (!(match(']') || matchKeyword('for') || matchKeyword('if'))) { expect(','); // this lexes. possiblecomprehension = false; } } } expect(']'); if (filter && !blocks.length) { throwError({}, Messages.ComprehensionRequiresBlock); } if (blocks.length) { if (elements.length !== 1) { throwError({}, Messages.ComprehensionError); } return markerApply(marker, delegate.createComprehensionExpression(filter, blocks, elements[0])); } return markerApply(marker, delegate.createArrayExpression(elements)); } // 11.1.5 Object Initialiser function parsePropertyFunction(options) { var previousStrict, previousYieldAllowed, previousAwaitAllowed, params, defaults, body, marker = markerCreate(); previousStrict = strict; previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = options.generator; previousAwaitAllowed = state.awaitAllowed; state.awaitAllowed = options.async; params = options.params || []; defaults = options.defaults || []; body = parseConciseBody(); if (options.name && strict && isRestrictedWord(params[0].name)) { throwErrorTolerant(options.name, Messages.StrictParamName); } strict = previousStrict; state.yieldAllowed = previousYieldAllowed; state.awaitAllowed = previousAwaitAllowed; return markerApply(marker, delegate.createFunctionExpression( null, params, defaults, body, options.rest || null, options.generator, body.type !== Syntax.BlockStatement, options.async, options.returnType, options.typeParameters )); } function parsePropertyMethodFunction(options) { var previousStrict, tmp, method; previousStrict = strict; strict = true; tmp = parseParams(); if (tmp.stricted) { throwErrorTolerant(tmp.stricted, tmp.message); } method = parsePropertyFunction({ params: tmp.params, defaults: tmp.defaults, rest: tmp.rest, generator: options.generator, async: options.async, returnType: tmp.returnType, typeParameters: options.typeParameters }); strict = previousStrict; return method; } function parseObjectPropertyKey() { var marker = markerCreate(), token = lex(), propertyKey, result; // Note: This function is called only from parseObjectProperty(), where // EOF and Punctuator tokens are already filtered out. if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) { if (strict && token.octal) { throwErrorTolerant(token, Messages.StrictOctalLiteral); } return markerApply(marker, delegate.createLiteral(token)); } if (token.type === Token.Punctuator && token.value === '[') { // For computed properties we should skip the [ and ], and // capture in marker only the assignment expression itself. marker = markerCreate(); propertyKey = parseAssignmentExpression(); result = markerApply(marker, propertyKey); expect(']'); return result; } return markerApply(marker, delegate.createIdentifier(token.value)); } function parseObjectProperty() { var token, key, id, value, param, expr, computed, marker = markerCreate(), returnType; token = lookahead; computed = (token.value === '['); if (token.type === Token.Identifier || computed || matchAsync()) { id = parseObjectPropertyKey(); if (match(':')) { lex(); return markerApply( marker, delegate.createProperty( 'init', id, parseAssignmentExpression(), false, false, computed ) ); } if (match('(')) { return markerApply( marker, delegate.createProperty( 'init', id, parsePropertyMethodFunction({ generator: false, async: false }), true, false, computed ) ); } // Property Assignment: Getter and Setter. if (token.value === 'get') { computed = (lookahead.value === '['); key = parseObjectPropertyKey(); expect('('); expect(')'); if (match(':')) { returnType = parseTypeAnnotation(); } return markerApply( marker, delegate.createProperty( 'get', key, parsePropertyFunction({ generator: false, async: false, returnType: returnType }), false, false, computed ) ); } if (token.value === 'set') { computed = (lookahead.value === '['); key = parseObjectPropertyKey(); expect('('); token = lookahead; param = [ parseTypeAnnotatableIdentifier() ]; expect(')'); if (match(':')) { returnType = parseTypeAnnotation(); } return markerApply( marker, delegate.createProperty( 'set', key, parsePropertyFunction({ params: param, generator: false, async: false, name: token, returnType: returnType }), false, false, computed ) ); } if (token.value === 'async') { computed = (lookahead.value === '['); key = parseObjectPropertyKey(); return markerApply( marker, delegate.createProperty( 'init', key, parsePropertyMethodFunction({ generator: false, async: true }), true, false, computed ) ); } if (computed) { // Computed properties can only be used with full notation. throwUnexpected(lookahead); } return markerApply( marker, delegate.createProperty('init', id, id, false, true, false) ); } if (token.type === Token.EOF || token.type === Token.Punctuator) { if (!match('*')) { throwUnexpected(token); } lex(); computed = (lookahead.type === Token.Punctuator && lookahead.value === '['); id = parseObjectPropertyKey(); if (!match('(')) { throwUnexpected(lex()); } return markerApply(marker, delegate.createProperty('init', id, parsePropertyMethodFunction({ generator: true }), true, false, computed)); } key = parseObjectPropertyKey(); if (match(':')) { lex(); return markerApply(marker, delegate.createProperty('init', key, parseAssignmentExpression(), false, false, false)); } if (match('(')) { return markerApply(marker, delegate.createProperty('init', key, parsePropertyMethodFunction({ generator: false }), true, false, false)); } throwUnexpected(lex()); } function parseObjectSpreadProperty() { var marker = markerCreate(); expect('...'); return markerApply(marker, delegate.createSpreadProperty(parseAssignmentExpression())); } function parseObjectInitialiser() { var properties = [], property, name, key, kind, map = {}, toString = String, marker = markerCreate(); expect('{'); while (!match('}')) { if (match('...')) { property = parseObjectSpreadProperty(); } else { property = parseObjectProperty(); if (property.key.type === Syntax.Identifier) { name = property.key.name; } else { name = toString(property.key.value); } kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set; key = '$' + name; if (Object.prototype.hasOwnProperty.call(map, key)) { if (map[key] === PropertyKind.Data) { if (strict && kind === PropertyKind.Data) { throwErrorTolerant({}, Messages.StrictDuplicateProperty); } else if (kind !== PropertyKind.Data) { throwErrorTolerant({}, Messages.AccessorDataProperty); } } else { if (kind === PropertyKind.Data) { throwErrorTolerant({}, Messages.AccessorDataProperty); } else if (map[key] & kind) { throwErrorTolerant({}, Messages.AccessorGetSet); } } map[key] |= kind; } else { map[key] = kind; } } properties.push(property); if (!match('}')) { expect(','); } } expect('}'); return markerApply(marker, delegate.createObjectExpression(properties)); } function parseTemplateElement(option) { var marker = markerCreate(), token = scanTemplateElement(option); if (strict && token.octal) { throwError(token, Messages.StrictOctalLiteral); } return markerApply(marker, delegate.createTemplateElement({ raw: token.value.raw, cooked: token.value.cooked }, token.tail)); } function parseTemplateLiteral() { var quasi, quasis, expressions, marker = markerCreate(); quasi = parseTemplateElement({ head: true }); quasis = [ quasi ]; expressions = []; while (!quasi.tail) { expressions.push(parseExpression()); quasi = parseTemplateElement({ head: false }); quasis.push(quasi); } return markerApply(marker, delegate.createTemplateLiteral(quasis, expressions)); } // 11.1.6 The Grouping Operator function parseGroupExpression() { var expr; expect('('); ++state.parenthesizedCount; expr = parseExpression(); expect(')'); return expr; } function matchAsyncFuncExprOrDecl() { var token; if (matchAsync()) { token = lookahead2(); if (token.type === Token.Keyword && token.value === 'function') { return true; } } return false; } // 11.1 Primary Expressions function parsePrimaryExpression() { var marker, type, token, expr; type = lookahead.type; if (type === Token.Identifier) { marker = markerCreate(); return markerApply(marker, delegate.createIdentifier(lex().value)); } if (type === Token.StringLiteral || type === Token.NumericLiteral) { if (strict && lookahead.octal) { throwErrorTolerant(lookahead, Messages.StrictOctalLiteral); } marker = markerCreate(); return markerApply(marker, delegate.createLiteral(lex())); } if (type === Token.Keyword) { if (matchKeyword('this')) { marker = markerCreate(); lex(); return markerApply(marker, delegate.createThisExpression()); } if (matchKeyword('function')) { return parseFunctionExpression(); } if (matchKeyword('class')) { return parseClassExpression(); } if (matchKeyword('super')) { marker = markerCreate(); lex(); return markerApply(marker, delegate.createIdentifier('super')); } } if (type === Token.BooleanLiteral) { marker = markerCreate(); token = lex(); token.value = (token.value === 'true'); return markerApply(marker, delegate.createLiteral(token)); } if (type === Token.NullLiteral) { marker = markerCreate(); token = lex(); token.value = null; return markerApply(marker, delegate.createLiteral(token)); } if (match('[')) { return parseArrayInitialiser(); } if (match('{')) { return parseObjectInitialiser(); } if (match('(')) { return parseGroupExpression(); } if (match('/') || match('/=')) { marker = markerCreate(); return markerApply(marker, delegate.createLiteral(scanRegExp())); } if (type === Token.Template) { return parseTemplateLiteral(); } if (match('<')) { return parseXJSElement(); } throwUnexpected(lex()); } // 11.2 Left-Hand-Side Expressions function parseArguments() { var args = [], arg; expect('('); if (!match(')')) { while (index < length) { arg = parseSpreadOrAssignmentExpression(); args.push(arg); if (match(')')) { break; } else if (arg.type === Syntax.SpreadElement) { throwError({}, Messages.ElementAfterSpreadElement); } expect(','); } } expect(')'); return args; } function parseSpreadOrAssignmentExpression() { if (match('...')) { var marker = markerCreate(); lex(); return markerApply(marker, delegate.createSpreadElement(parseAssignmentExpression())); } return parseAssignmentExpression(); } function parseNonComputedProperty() { var marker = markerCreate(), token = lex(); if (!isIdentifierName(token)) { throwUnexpected(token); } return markerApply(marker, delegate.createIdentifier(token.value)); } function parseNonComputedMember() { expect('.'); return parseNonComputedProperty(); } function parseComputedMember() { var expr; expect('['); expr = parseExpression(); expect(']'); return expr; } function parseNewExpression() { var callee, args, marker = markerCreate(); expectKeyword('new'); callee = parseLeftHandSideExpression(); args = match('(') ? parseArguments() : []; return markerApply(marker, delegate.createNewExpression(callee, args)); } function parseLeftHandSideExpressionAllowCall() { var expr, args, marker = markerCreate(); expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); while (match('.') || match('[') || match('(') || lookahead.type === Token.Template) { if (match('(')) { args = parseArguments(); expr = markerApply(marker, delegate.createCallExpression(expr, args)); } else if (match('[')) { expr = markerApply(marker, delegate.createMemberExpression('[', expr, parseComputedMember())); } else if (match('.')) { expr = markerApply(marker, delegate.createMemberExpression('.', expr, parseNonComputedMember())); } else { expr = markerApply(marker, delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral())); } } return expr; } function parseLeftHandSideExpression() { var expr, marker = markerCreate(); expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); while (match('.') || match('[') || lookahead.type === Token.Template) { if (match('[')) { expr = markerApply(marker, delegate.createMemberExpression('[', expr, parseComputedMember())); } else if (match('.')) { expr = markerApply(marker, delegate.createMemberExpression('.', expr, parseNonComputedMember())); } else { expr = markerApply(marker, delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral())); } } return expr; } // 11.3 Postfix Expressions function parsePostfixExpression() { var marker = markerCreate(), expr = parseLeftHandSideExpressionAllowCall(), token; if (lookahead.type !== Token.Punctuator) { return expr; } if ((match('++') || match('--')) && !peekLineTerminator()) { // 11.3.1, 11.3.2 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { throwErrorTolerant({}, Messages.StrictLHSPostfix); } if (!isLeftHandSide(expr)) { throwError({}, Messages.InvalidLHSInAssignment); } token = lex(); expr = markerApply(marker, delegate.createPostfixExpression(token.value, expr)); } return expr; } // 11.4 Unary Operators function parseUnaryExpression() { var marker, token, expr; if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) { return parsePostfixExpression(); } if (match('++') || match('--')) { marker = markerCreate(); token = lex(); expr = parseUnaryExpression(); // 11.4.4, 11.4.5 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { throwErrorTolerant({}, Messages.StrictLHSPrefix); } if (!isLeftHandSide(expr)) { throwError({}, Messages.InvalidLHSInAssignment); } return markerApply(marker, delegate.createUnaryExpression(token.value, expr)); } if (match('+') || match('-') || match('~') || match('!')) { marker = markerCreate(); token = lex(); expr = parseUnaryExpression(); return markerApply(marker, delegate.createUnaryExpression(token.value, expr)); } if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) { marker = markerCreate(); token = lex(); expr = parseUnaryExpression(); expr = markerApply(marker, delegate.createUnaryExpression(token.value, expr)); if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) { throwErrorTolerant({}, Messages.StrictDelete); } return expr; } return parsePostfixExpression(); } function binaryPrecedence(token, allowIn) { var prec = 0; if (token.type !== Token.Punctuator && token.type !== Token.Keyword) { return 0; } switch (token.value) { case '||': prec = 1; break; case '&&': prec = 2; break; case '|': prec = 3; break; case '^': prec = 4; break; case '&': prec = 5; break; case '==': case '!=': case '===': case '!==': prec = 6; break; case '<': case '>': case '<=': case '>=': case 'instanceof': prec = 7; break; case 'in': prec = allowIn ? 7 : 0; break; case '<<': case '>>': case '>>>': prec = 8; break; case '+': case '-': prec = 9; break; case '*': case '/': case '%': prec = 11; break; default: break; } return prec; } // 11.5 Multiplicative Operators // 11.6 Additive Operators // 11.7 Bitwise Shift Operators // 11.8 Relational Operators // 11.9 Equality Operators // 11.10 Binary Bitwise Operators // 11.11 Binary Logical Operators function parseBinaryExpression() { var expr, token, prec, previousAllowIn, stack, right, operator, left, i, marker, markers; previousAllowIn = state.allowIn; state.allowIn = true; marker = markerCreate(); left = parseUnaryExpression(); token = lookahead; prec = binaryPrecedence(token, previousAllowIn); if (prec === 0) { return left; } token.prec = prec; lex(); markers = [marker, markerCreate()]; right = parseUnaryExpression(); stack = [left, token, right]; while ((prec = binaryPrecedence(lookahead, previousAllowIn)) > 0) { // Reduce: make a binary expression from the three topmost entries. while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) { right = stack.pop(); operator = stack.pop().value; left = stack.pop(); expr = delegate.createBinaryExpression(operator, left, right); markers.pop(); marker = markers.pop(); markerApply(marker, expr); stack.push(expr); markers.push(marker); } // Shift. token = lex(); token.prec = prec; stack.push(token); markers.push(markerCreate()); expr = parseUnaryExpression(); stack.push(expr); } state.allowIn = previousAllowIn; // Final reduce to clean-up the stack. i = stack.length - 1; expr = stack[i]; markers.pop(); while (i > 1) { expr = delegate.createBinaryExpression(stack[i - 1].value, stack[i - 2], expr); i -= 2; marker = markers.pop(); markerApply(marker, expr); } return expr; } // 11.12 Conditional Operator function parseConditionalExpression() { var expr, previousAllowIn, consequent, alternate, marker = markerCreate(); expr = parseBinaryExpression(); if (match('?')) { lex(); previousAllowIn = state.allowIn; state.allowIn = true; consequent = parseAssignmentExpression(); state.allowIn = previousAllowIn; expect(':'); alternate = parseAssignmentExpression(); expr = markerApply(marker, delegate.createConditionalExpression(expr, consequent, alternate)); } return expr; } // 11.13 Assignment Operators function reinterpretAsAssignmentBindingPattern(expr) { var i, len, property, element; if (expr.type === Syntax.ObjectExpression) { expr.type = Syntax.ObjectPattern; for (i = 0, len = expr.properties.length; i < len; i += 1) { property = expr.properties[i]; if (property.type === Syntax.SpreadProperty) { if (i < len - 1) { throwError({}, Messages.PropertyAfterSpreadProperty); } reinterpretAsAssignmentBindingPattern(property.argument); } else { if (property.kind !== 'init') { throwError({}, Messages.InvalidLHSInAssignment); } reinterpretAsAssignmentBindingPattern(property.value); } } } else if (expr.type === Syntax.ArrayExpression) { expr.type = Syntax.ArrayPattern; for (i = 0, len = expr.elements.length; i < len; i += 1) { element = expr.elements[i]; if (element) { reinterpretAsAssignmentBindingPattern(element); } } } else if (expr.type === Syntax.Identifier) { if (isRestrictedWord(expr.name)) { throwError({}, Messages.InvalidLHSInAssignment); } } else if (expr.type === Syntax.SpreadElement) { reinterpretAsAssignmentBindingPattern(expr.argument); if (expr.argument.type === Syntax.ObjectPattern) { throwError({}, Messages.ObjectPatternAsSpread); } } else { if (expr.type !== Syntax.MemberExpression && expr.type !== Syntax.CallExpression && expr.type !== Syntax.NewExpression) { throwError({}, Messages.InvalidLHSInAssignment); } } } function reinterpretAsDestructuredParameter(options, expr) { var i, len, property, element; if (expr.type === Syntax.ObjectExpression) { expr.type = Syntax.ObjectPattern; for (i = 0, len = expr.properties.length; i < len; i += 1) { property = expr.properties[i]; if (property.type === Syntax.SpreadProperty) { if (i < len - 1) { throwError({}, Messages.PropertyAfterSpreadProperty); } reinterpretAsDestructuredParameter(options, property.argument); } else { if (property.kind !== 'init') { throwError({}, Messages.InvalidLHSInFormalsList); } reinterpretAsDestructuredParameter(options, property.value); } } } else if (expr.type === Syntax.ArrayExpression) { expr.type = Syntax.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 === Syntax.Identifier) { validateParam(options, expr, expr.name); } else { if (expr.type !== Syntax.MemberExpression) { throwError({}, Messages.InvalidLHSInFormalsList); } } } function reinterpretAsCoverFormalsList(expressions) { var i, len, param, params, defaults, defaultCount, options, rest; params = []; defaults = []; defaultCount = 0; rest = null; options = { paramSet: {} }; for (i = 0, len = expressions.length; i < len; i += 1) { param = expressions[i]; if (param.type === Syntax.Identifier) { params.push(param); defaults.push(null); validateParam(options, param, param.name); } else if (param.type === Syntax.ObjectExpression || param.type === Syntax.ArrayExpression) { reinterpretAsDestructuredParameter(options, param); params.push(param); defaults.push(null); } else if (param.type === Syntax.SpreadElement) { assert(i === len - 1, 'It is guaranteed that SpreadElement is last element by parseExpression'); reinterpretAsDestructuredParameter(options, param.argument); rest = param.argument; } else if (param.type === Syntax.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 ); } 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, previousYieldAllowed, previousAwaitAllowed, body; expect('=>'); previousStrict = strict; previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = false; previousAwaitAllowed = state.awaitAllowed; state.awaitAllowed = !!options.async; body = parseConciseBody(); if (strict && options.firstRestricted) { throwError(options.firstRestricted, options.message); } if (strict && options.stricted) { throwErrorTolerant(options.stricted, options.message); } strict = previousStrict; state.yieldAllowed = previousYieldAllowed; state.awaitAllowed = previousAwaitAllowed; return markerApply(marker, delegate.createArrowFunctionExpression( options.params, options.defaults, body, options.rest, body.type !== Syntax.BlockStatement, !!options.async )); } function parseAssignmentExpression() { var marker, expr, token, params, oldParenthesizedCount, backtrackToken = lookahead, possiblyAsync = false; if (matchYield()) { return parseYieldExpression(); } if (matchAwait()) { return parseAwaitExpression(); } oldParenthesizedCount = state.parenthesizedCount; marker = markerCreate(); if (matchAsyncFuncExprOrDecl()) { return parseFunctionExpression(); } if (matchAsync()) { // We can't be completely sure that this 'async' token is // actually a contextual keyword modifying a function // expression, so we might have to un-lex() it later by // calling rewind(backtrackToken). possiblyAsync = true; lex(); } if (match('(')) { token = lookahead2(); if ((token.type === Token.Punctuator && token.value === ')') || token.value === '...') { params = parseParams(); if (!match('=>')) { throwUnexpected(lex()); } params.async = possiblyAsync; return parseArrowFunctionExpression(params, marker); } } token = lookahead; // If the 'async' keyword is not followed by a '(' character or an // identifier, then it can't be an arrow function modifier, and we // should interpret it as a normal identifer. if (possiblyAsync && !match('(') && token.type !== Token.Identifier) { possiblyAsync = false; rewind(backtrackToken); } expr = parseConditionalExpression(); if (match('=>') && (state.parenthesizedCount === oldParenthesizedCount || state.parenthesizedCount === (oldParenthesizedCount + 1))) { if (expr.type === Syntax.Identifier) { params = reinterpretAsCoverFormalsList([ expr ]); } else if (expr.type === Syntax.SequenceExpression) { params = reinterpretAsCoverFormalsList(expr.expressions); } if (params) { params.async = possiblyAsync; return parseArrowFunctionExpression(params, marker); } } // If we haven't returned by now, then the 'async' keyword was not // a function modifier, and we should rewind and interpret it as a // normal identifier. if (possiblyAsync) { possiblyAsync = false; rewind(backtrackToken); expr = parseConditionalExpression(); } if (matchAssign()) { // 11.13.1 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { throwErrorTolerant(token, Messages.StrictLHSAssignment); } // ES.next draf 11.13 Runtime Semantics step 1 if (match('=') && (expr.type === Syntax.ObjectExpression || expr.type === Syntax.ArrayExpression)) { reinterpretAsAssignmentBindingPattern(expr); } else if (!isLeftHandSide(expr)) { throwError({}, Messages.InvalidLHSInAssignment); } expr = markerApply(marker, delegate.createAssignmentExpression(lex().value, expr, parseAssignmentExpression())); } return expr; } // 11.14 Comma Operator function parseExpression() { var marker, expr, expressions, sequence, coverFormalsList, spreadFound, oldParenthesizedCount; oldParenthesizedCount = state.parenthesizedCount; marker = markerCreate(); expr = parseAssignmentExpression(); expressions = [ expr ]; if (match(',')) { while (index < length) { if (!match(',')) { break; } lex(); expr = parseSpreadOrAssignmentExpression(); expressions.push(expr); if (expr.type === Syntax.SpreadElement) { spreadFound = true; if (!match(')')) { throwError({}, Messages.ElementAfterSpreadElement); } break; } } sequence = markerApply(marker, delegate.createSequenceExpression(expressions)); } if (match('=>')) { // Do not allow nested parentheses on the LHS of the =>. if (state.parenthesizedCount === oldParenthesizedCount || state.parenthesizedCount === (oldParenthesizedCount + 1)) { expr = expr.type === Syntax.SequenceExpression ? expr.expressions : expressions; coverFormalsList = reinterpretAsCoverFormalsList(expr); if (coverFormalsList) { return parseArrowFunctionExpression(coverFormalsList, marker); } } throwUnexpected(lex()); } if (spreadFound && lookahead2().value !== '=>') { throwError({}, Messages.IllegalSpread); } return sequence || expr; } // 12.1 Block function parseStatementList() { var list = [], statement; while (index < length) { if (match('}')) { break; } statement = parseSourceElement(); if (typeof statement === 'undefined') { break; } list.push(statement); } return list; } function parseBlock() { var block, marker = markerCreate(); expect('{'); block = parseStatementList(); expect('}'); return markerApply(marker, delegate.createBlockStatement(block)); } // 12.2 Variable Statement function parseTypeParameterDeclaration() { var marker = markerCreate(), paramTypes = []; expect('<'); while (!match('>')) { paramTypes.push(parseVariableIdentifier()); if (!match('>')) { expect(','); } } expect('>'); return markerApply(marker, delegate.createTypeParameterDeclaration( paramTypes )); } function parseTypeParameterInstantiation() { var marker = markerCreate(), oldInType = state.inType, paramTypes = []; state.inType = true; expect('<'); while (!match('>')) { paramTypes.push(parseType()); if (!match('>')) { expect(','); } } expect('>'); state.inType = oldInType; return markerApply(marker, delegate.createTypeParameterInstantiation( paramTypes )); } function parseObjectTypeIndexer(marker, isStatic) { var id, key, value; expect('['); id = parseObjectPropertyKey(); expect(':'); key = parseType(); expect(']'); expect(':'); value = parseType(); return markerApply(marker, delegate.createObjectTypeIndexer( id, key, value, isStatic )); } function parseObjectTypeMethodish(marker) { var params = [], rest = null, returnType, typeParameters = null; if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } expect('('); while (lookahead.type === Token.Identifier) { params.push(parseFunctionTypeParam()); if (!match(')')) { expect(','); } } if (match('...')) { lex(); rest = parseFunctionTypeParam(); } expect(')'); expect(':'); returnType = parseType(); return markerApply(marker, delegate.createFunctionTypeAnnotation( params, returnType, rest, typeParameters )); } function parseObjectTypeMethod(marker, isStatic, key) { var optional = false, value; value = parseObjectTypeMethodish(marker); return markerApply(marker, delegate.createObjectTypeProperty( key, value, optional, isStatic )); } function parseObjectTypeCallProperty(marker, isStatic) { var valueMarker = markerCreate(); return markerApply(marker, delegate.createObjectTypeCallProperty( parseObjectTypeMethodish(valueMarker), isStatic )); } function parseObjectType(allowStatic) { var callProperties = [], indexers = [], marker, optional = false, properties = [], property, propertyKey, propertyTypeAnnotation, token, isStatic; expect('{'); while (!match('}')) { marker = markerCreate(); if (allowStatic && matchContextualKeyword('static')) { token = lex(); isStatic = true; } if (match('[')) { indexers.push(parseObjectTypeIndexer(marker, isStatic)); } else if (match('(') || match('<')) { callProperties.push(parseObjectTypeCallProperty(marker, allowStatic)); } else { if (isStatic && match(':')) { propertyKey = markerApply(marker, delegate.createIdentifier(token)); throwErrorTolerant(token, Messages.StrictReservedWord); } else { propertyKey = parseObjectPropertyKey(); } if (match('<') || match('(')) { // This is a method property properties.push(parseObjectTypeMethod(marker, isStatic, propertyKey)); } else { if (match('?')) { lex(); optional = true; } expect(':'); propertyTypeAnnotation = parseType(); properties.push(markerApply(marker, delegate.createObjectTypeProperty( propertyKey, propertyTypeAnnotation, optional, isStatic ))); } } if (match(';')) { lex(); } else if (!match('}')) { throwUnexpected(lookahead); } } expect('}'); return delegate.createObjectTypeAnnotation( properties, indexers, callProperties ); } function parseGenericType() { var marker = markerCreate(), returnType = null, typeParameters = null, typeIdentifier, typeIdentifierMarker = markerCreate; typeIdentifier = parseVariableIdentifier(); while (match('.')) { expect('.'); typeIdentifier = markerApply(marker, delegate.createQualifiedTypeIdentifier( typeIdentifier, parseVariableIdentifier() )); } if (match('<')) { typeParameters = parseTypeParameterInstantiation(); } return markerApply(marker, delegate.createGenericTypeAnnotation( typeIdentifier, typeParameters )); } function parseVoidType() { var marker = markerCreate(); expectKeyword('void'); return markerApply(marker, delegate.createVoidTypeAnnotation()); } function parseTypeofType() { var argument, marker = markerCreate(); expectKeyword('typeof'); argument = parsePrimaryType(); return markerApply(marker, delegate.createTypeofTypeAnnotation( argument )); } function parseTupleType() { var marker = markerCreate(), types = []; expect('['); // We allow trailing commas while (index < length && !match(']')) { types.push(parseType()); if (match(']')) { break; } expect(','); } expect(']'); return markerApply(marker, delegate.createTupleTypeAnnotation( types )); } function parseFunctionTypeParam() { var marker = markerCreate(), name, optional = false, typeAnnotation; name = parseVariableIdentifier(); if (match('?')) { lex(); optional = true; } expect(':'); typeAnnotation = parseType(); return markerApply(marker, delegate.createFunctionTypeParam( name, typeAnnotation, optional )); } function parseFunctionTypeParams() { var ret = { params: [], rest: null }; while (lookahead.type === Token.Identifier) { ret.params.push(parseFunctionTypeParam()); if (!match(')')) { expect(','); } } if (match('...')) { lex(); ret.rest = parseFunctionTypeParam(); } return ret; } // The parsing of types roughly parallels the parsing of expressions, and // primary types are kind of like primary expressions...they're the // primitives with which other types are constructed. function parsePrimaryType() { var typeIdentifier = null, params = null, returnType = null, marker = markerCreate(), rest = null, tmp, typeParameters, token, type, isGroupedType = false; switch (lookahead.type) { case Token.Identifier: switch (lookahead.value) { case 'any': lex(); return markerApply(marker, delegate.createAnyTypeAnnotation()); case 'bool': // fallthrough case 'boolean': lex(); return markerApply(marker, delegate.createBooleanTypeAnnotation()); case 'number': lex(); return markerApply(marker, delegate.createNumberTypeAnnotation()); case 'string': lex(); return markerApply(marker, delegate.createStringTypeAnnotation()); } return markerApply(marker, parseGenericType()); case Token.Punctuator: switch (lookahead.value) { case '{': return markerApply(marker, parseObjectType()); case '[': return parseTupleType(); case '<': typeParameters = parseTypeParameterDeclaration(); expect('('); tmp = parseFunctionTypeParams(); params = tmp.params; rest = tmp.rest; expect(')'); expect('=>'); returnType = parseType(); return markerApply(marker, delegate.createFunctionTypeAnnotation( params, returnType, rest, typeParameters )); case '(': lex(); // Check to see if this is actually a grouped type if (!match(')') && !match('...')) { if (lookahead.type === Token.Identifier) { token = lookahead2(); isGroupedType = token.value !== '?' && token.value !== ':'; } else { isGroupedType = true; } } if (isGroupedType) { type = parseType(); expect(')'); // If we see a => next then someone was probably confused about // function types, so we can provide a better error message if (match('=>')) { throwError({}, Messages.ConfusedAboutFunctionType); } return type; } tmp = parseFunctionTypeParams(); params = tmp.params; rest = tmp.rest; expect(')'); expect('=>'); returnType = parseType(); return markerApply(marker, delegate.createFunctionTypeAnnotation( params, returnType, rest, null /* typeParameters */ )); } break; case Token.Keyword: switch (lookahead.value) { case 'void': return markerApply(marker, parseVoidType()); case 'typeof': return markerApply(marker, parseTypeofType()); } break; case Token.StringLiteral: token = lex(); if (token.octal) { throwError(token, Messages.StrictOctalLiteral); } return markerApply(marker, delegate.createStringLiteralTypeAnnotation( token )); } throwUnexpected(lookahead); } function parsePostfixType() { var marker = markerCreate(), t = parsePrimaryType(); if (match('[')) { expect('['); expect(']'); return markerApply(marker, delegate.createArrayTypeAnnotation(t)); } return t; } function parsePrefixType() { var marker = markerCreate(); if (match('?')) { lex(); return markerApply(marker, delegate.createNullableTypeAnnotation( parsePrefixType() )); } return parsePostfixType(); } function parseIntersectionType() { var marker = markerCreate(), type, types; type = parsePrefixType(); types = [type]; while (match('&')) { lex(); types.push(parsePrefixType()); } return types.length === 1 ? type : markerApply(marker, delegate.createIntersectionTypeAnnotation( types )); } function parseUnionType() { var marker = markerCreate(), type, types; type = parseIntersectionType(); types = [type]; while (match('|')) { lex(); types.push(parseIntersectionType()); } return types.length === 1 ? type : markerApply(marker, delegate.createUnionTypeAnnotation( types )); } function parseType() { var oldInType = state.inType, type; state.inType = true; type = parseUnionType(); state.inType = oldInType; return type; } function parseTypeAnnotation() { var marker = markerCreate(), type; expect(':'); type = parseType(); return markerApply(marker, delegate.createTypeAnnotation(type)); } function parseVariableIdentifier() { var marker = markerCreate(), token = lex(); if (token.type !== Token.Identifier) { throwUnexpected(token); } return markerApply(marker, delegate.createIdentifier(token.value)); } function parseTypeAnnotatableIdentifier(requireTypeAnnotation, canBeOptionalParam) { var marker = markerCreate(), ident = parseVariableIdentifier(), isOptionalParam = false; if (canBeOptionalParam && match('?')) { expect('?'); isOptionalParam = true; } if (requireTypeAnnotation || match(':')) { ident.typeAnnotation = parseTypeAnnotation(); ident = markerApply(marker, ident); } if (isOptionalParam) { ident.optional = true; ident = markerApply(marker, ident); } return ident; } function parseVariableDeclaration(kind) { var id, marker = markerCreate(), init = null, typeAnnotationMarker = markerCreate(); if (match('{')) { id = parseObjectInitialiser(); reinterpretAsAssignmentBindingPattern(id); if (match(':')) { id.typeAnnotation = parseTypeAnnotation(); markerApply(typeAnnotationMarker, id); } } else if (match('[')) { id = parseArrayInitialiser(); reinterpretAsAssignmentBindingPattern(id); if (match(':')) { id.typeAnnotation = parseTypeAnnotation(); markerApply(typeAnnotationMarker, id); } } else { id = state.allowKeyword ? parseNonComputedProperty() : parseTypeAnnotatableIdentifier(); // 12.2.1 if (strict && isRestrictedWord(id.name)) { throwErrorTolerant({}, Messages.StrictVarName); } } if (kind === 'const') { if (!match('=')) { throwError({}, Messages.NoUnintializedConst); } expect('='); init = parseAssignmentExpression(); } else if (match('=')) { lex(); init = parseAssignmentExpression(); } return markerApply(marker, delegate.createVariableDeclarator(id, init)); } function parseVariableDeclarationList(kind) { var list = []; do { list.push(parseVariableDeclaration(kind)); if (!match(',')) { break; } lex(); } while (index < length); return list; } function parseVariableStatement() { var declarations, marker = markerCreate(); expectKeyword('var'); declarations = parseVariableDeclarationList(); consumeSemicolon(); return markerApply(marker, delegate.createVariableDeclaration(declarations, 'var')); } // kind may be `const` or `let` // Both are experimental and not in the specification yet. // see http://wiki.ecmascript.org/doku.php?id=harmony:const // and http://wiki.ecmascript.org/doku.php?id=harmony:let function parseConstLetDeclaration(kind) { var declarations, marker = markerCreate(); expectKeyword(kind); declarations = parseVariableDeclarationList(kind); consumeSemicolon(); return markerApply(marker, delegate.createVariableDeclaration(declarations, kind)); } // people.mozilla.org/~jorendorff/es6-draft.html function parseModuleSpecifier() { var marker = markerCreate(), specifier; if (lookahead.type !== Token.StringLiteral) { throwError({}, Messages.InvalidModuleSpecifier); } specifier = delegate.createModuleSpecifier(lookahead); lex(); return markerApply(marker, specifier); } function parseExportBatchSpecifier() { var marker = markerCreate(); expect('*'); return markerApply(marker, delegate.createExportBatchSpecifier()); } function parseExportSpecifier() { var id, name = null, marker = markerCreate(), from; if (matchKeyword('default')) { lex(); id = markerApply(marker, delegate.createIdentifier('default')); // export {default} from "something"; } else { id = parseVariableIdentifier(); } if (matchContextualKeyword('as')) { lex(); name = parseNonComputedProperty(); } return markerApply(marker, delegate.createExportSpecifier(id, name)); } function parseExportDeclaration() { var backtrackToken, id, previousAllowKeyword, declaration = null, isExportFromIdentifier, src = null, specifiers = [], marker = markerCreate(); expectKeyword('export'); if (matchKeyword('default')) { // covers: // export default ... lex(); if (matchKeyword('function') || matchKeyword('class')) { backtrackToken = lookahead; lex(); if (isIdentifierName(lookahead)) { // covers: // export default function foo () {} // export default class foo {} id = parseNonComputedProperty(); rewind(backtrackToken); return markerApply(marker, delegate.createExportDeclaration(true, parseSourceElement(), [id], null)); } // covers: // export default function () {} // export default class {} rewind(backtrackToken); switch (lookahead.value) { case 'class': return markerApply(marker, delegate.createExportDeclaration(true, parseClassExpression(), [], null)); case 'function': return markerApply(marker, delegate.createExportDeclaration(true, parseFunctionExpression(), [], null)); } } if (matchContextualKeyword('from')) { throwError({}, Messages.UnexpectedToken, lookahead.value); } // covers: // export default {}; // export default []; if (match('{')) { declaration = parseObjectInitialiser(); } else if (match('[')) { declaration = parseArrayInitialiser(); } else { declaration = parseAssignmentExpression(); } consumeSemicolon(); return markerApply(marker, delegate.createExportDeclaration(true, declaration, [], null)); } // non-default export if (lookahead.type === Token.Keyword) { // covers: // export var f = 1; switch (lookahead.value) { case 'let': case 'const': case 'var': case 'class': case 'function': return markerApply(marker, delegate.createExportDeclaration(false, parseSourceElement(), specifiers, null)); } } if (match('*')) { // covers: // export * from "foo"; specifiers.push(parseExportBatchSpecifier()); if (!matchContextualKeyword('from')) { throwError({}, lookahead.value ? Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value); } lex(); src = parseModuleSpecifier(); consumeSemicolon(); return markerApply(marker, delegate.createExportDeclaration(false, null, specifiers, src)); } expect('{'); do { isExportFromIdentifier = isExportFromIdentifier || matchKeyword('default'); specifiers.push(parseExportSpecifier()); } while (match(',') && lex()); expect('}'); if (matchContextualKeyword('from')) { // covering: // export {default} from "foo"; // export {foo} from "foo"; lex(); src = parseModuleSpecifier(); consumeSemicolon(); } else if (isExportFromIdentifier) { // covering: // export {default}; // missing fromClause throwError({}, lookahead.value ? Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value); } else { // cover // export {foo}; consumeSemicolon(); } return markerApply(marker, delegate.createExportDeclaration(false, declaration, specifiers, src)); } function parseImportSpecifier() { // import {} ...; var id, name = null, marker = markerCreate(); id = parseNonComputedProperty(); if (matchContextualKeyword('as')) { lex(); name = parseVariableIdentifier(); } return markerApply(marker, delegate.createImportSpecifier(id, name)); } function parseNamedImports() { var specifiers = []; // {foo, bar as bas} expect('{'); do { specifiers.push(parseImportSpecifier()); } while (match(',') && lex()); expect('}'); return specifiers; } function parseImportDefaultSpecifier() { // import ...; var id, marker = markerCreate(); id = parseNonComputedProperty(); return markerApply(marker, delegate.createImportDefaultSpecifier(id)); } function parseImportNamespaceSpecifier() { // import <* as foo> ...; var id, marker = markerCreate(); expect('*'); if (!matchContextualKeyword('as')) { throwError({}, Messages.NoAsAfterImportNamespace); } lex(); id = parseNonComputedProperty(); return markerApply(marker, delegate.createImportNamespaceSpecifier(id)); } function parseImportDeclaration() { var specifiers, src, marker = markerCreate(); expectKeyword('import'); specifiers = []; if (lookahead.type === Token.StringLiteral) { // covers: // import "foo"; src = parseModuleSpecifier(); consumeSemicolon(); return markerApply(marker, delegate.createImportDeclaration(specifiers, src)); } if (!matchKeyword('default') && isIdentifierName(lookahead)) { // covers: // import foo // import foo, ... specifiers.push(parseImportDefaultSpecifier()); if (match(',')) { lex(); } } if (match('*')) { // covers: // import foo, * as foo // import * as foo specifiers.push(parseImportNamespaceSpecifier()); } else if (match('{')) { // covers: // import foo, {bar} // import {bar} specifiers = specifiers.concat(parseNamedImports()); } if (!matchContextualKeyword('from')) { throwError({}, lookahead.value ? Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value); } lex(); src = parseModuleSpecifier(); consumeSemicolon(); return markerApply(marker, delegate.createImportDeclaration(specifiers, src)); } // 12.3 Empty Statement function parseEmptyStatement() { var marker = markerCreate(); expect(';'); return markerApply(marker, delegate.createEmptyStatement()); } // 12.4 Expression Statement function parseExpressionStatement() { var marker = markerCreate(), expr = parseExpression(); consumeSemicolon(); return markerApply(marker, delegate.createExpressionStatement(expr)); } // 12.5 If statement function parseIfStatement() { var test, consequent, alternate, marker = markerCreate(); expectKeyword('if'); expect('('); test = parseExpression(); expect(')'); consequent = parseStatement(); if (matchKeyword('else')) { lex(); alternate = parseStatement(); } else { alternate = null; } return markerApply(marker, delegate.createIfStatement(test, consequent, alternate)); } // 12.6 Iteration Statements function parseDoWhileStatement() { var body, test, oldInIteration, marker = markerCreate(); expectKeyword('do'); oldInIteration = state.inIteration; state.inIteration = true; body = parseStatement(); state.inIteration = oldInIteration; expectKeyword('while'); expect('('); test = parseExpression(); expect(')'); if (match(';')) { lex(); } return markerApply(marker, delegate.createDoWhileStatement(body, test)); } function parseWhileStatement() { var test, body, oldInIteration, marker = markerCreate(); expectKeyword('while'); expect('('); test = parseExpression(); expect(')'); oldInIteration = state.inIteration; state.inIteration = true; body = parseStatement(); state.inIteration = oldInIteration; return markerApply(marker, delegate.createWhileStatement(test, body)); } function parseForVariableDeclaration() { var marker = markerCreate(), token = lex(), declarations = parseVariableDeclarationList(); return markerApply(marker, delegate.createVariableDeclaration(declarations, token.value)); } function parseForStatement(opts) { var init, test, update, left, right, body, operator, oldInIteration, marker = markerCreate(); init = test = update = null; expectKeyword('for'); // http://wiki.ecmascript.org/doku.php?id=proposals:iterators_and_generators&s=each if (matchContextualKeyword('each')) { throwError({}, Messages.EachNotAllowed); } expect('('); if (match(';')) { lex(); } else { if (matchKeyword('var') || matchKeyword('let') || matchKeyword('const')) { state.allowIn = false; init = parseForVariableDeclaration(); state.allowIn = true; if (init.declarations.length === 1) { if (matchKeyword('in') || matchContextualKeyword('of')) { operator = lookahead; if (!((operator.value === 'in' || init.kind !== 'var') && init.declarations[0].init)) { lex(); left = init; right = parseExpression(); init = null; } } } } else { state.allowIn = false; init = parseExpression(); state.allowIn = true; if (matchContextualKeyword('of')) { operator = lex(); left = init; right = parseExpression(); init = null; } else if (matchKeyword('in')) { // LeftHandSideExpression if (!isAssignableLeftHandSide(init)) { throwError({}, Messages.InvalidLHSInForIn); } operator = lex(); left = init; right = parseExpression(); init = null; } } if (typeof left === 'undefined') { expect(';'); } } if (typeof left === 'undefined') { if (!match(';')) { test = parseExpression(); } expect(';'); if (!match(')')) { update = parseExpression(); } } expect(')'); oldInIteration = state.inIteration; state.inIteration = true; if (!(opts !== undefined && opts.ignoreBody)) { body = parseStatement(); } state.inIteration = oldInIteration; if (typeof left === 'undefined') { return markerApply(marker, delegate.createForStatement(init, test, update, body)); } if (operator.value === 'in') { return markerApply(marker, delegate.createForInStatement(left, right, body)); } return markerApply(marker, delegate.createForOfStatement(left, right, body)); } // 12.7 The continue statement function parseContinueStatement() { var label = null, key, marker = markerCreate(); expectKeyword('continue'); // Optimize the most common form: 'continue;'. if (source.charCodeAt(index) === 59) { lex(); if (!state.inIteration) { throwError({}, Messages.IllegalContinue); } return markerApply(marker, delegate.createContinueStatement(null)); } if (peekLineTerminator()) { if (!state.inIteration) { throwError({}, Messages.IllegalContinue); } return markerApply(marker, delegate.createContinueStatement(null)); } if (lookahead.type === Token.Identifier) { label = parseVariableIdentifier(); key = '$' + label.name; if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) { throwError({}, Messages.UnknownLabel, label.name); } } consumeSemicolon(); if (label === null && !state.inIteration) { throwError({}, Messages.IllegalContinue); } return markerApply(marker, delegate.createContinueStatement(label)); } // 12.8 The break statement function parseBreakStatement() { var label = null, key, marker = markerCreate(); expectKeyword('break'); // Catch the very common case first: immediately a semicolon (char #59). if (source.charCodeAt(index) === 59) { lex(); if (!(state.inIteration || state.inSwitch)) { throwError({}, Messages.IllegalBreak); } return markerApply(marker, delegate.createBreakStatement(null)); } if (peekLineTerminator()) { if (!(state.inIteration || state.inSwitch)) { throwError({}, Messages.IllegalBreak); } return markerApply(marker, delegate.createBreakStatement(null)); } if (lookahead.type === Token.Identifier) { label = parseVariableIdentifier(); key = '$' + label.name; if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) { throwError({}, Messages.UnknownLabel, label.name); } } consumeSemicolon(); if (label === null && !(state.inIteration || state.inSwitch)) { throwError({}, Messages.IllegalBreak); } return markerApply(marker, delegate.createBreakStatement(label)); } // 12.9 The return statement function parseReturnStatement() { var argument = null, marker = markerCreate(); expectKeyword('return'); if (!state.inFunctionBody) { throwErrorTolerant({}, Messages.IllegalReturn); } // 'return' followed by a space and an identifier is very common. if (source.charCodeAt(index) === 32) { if (isIdentifierStart(source.charCodeAt(index + 1))) { argument = parseExpression(); consumeSemicolon(); return markerApply(marker, delegate.createReturnStatement(argument)); } } if (peekLineTerminator()) { return markerApply(marker, delegate.createReturnStatement(null)); } if (!match(';')) { if (!match('}') && lookahead.type !== Token.EOF) { argument = parseExpression(); } } consumeSemicolon(); return markerApply(marker, delegate.createReturnStatement(argument)); } // 12.10 The with statement function parseWithStatement() { var object, body, marker = markerCreate(); if (strict) { throwErrorTolerant({}, Messages.StrictModeWith); } expectKeyword('with'); expect('('); object = parseExpression(); expect(')'); body = parseStatement(); return markerApply(marker, delegate.createWithStatement(object, body)); } // 12.10 The swith statement function parseSwitchCase() { var test, consequent = [], sourceElement, marker = markerCreate(); if (matchKeyword('default')) { lex(); test = null; } else { expectKeyword('case'); test = parseExpression(); } expect(':'); while (index < length) { if (match('}') || matchKeyword('default') || matchKeyword('case')) { break; } sourceElement = parseSourceElement(); if (typeof sourceElement === 'undefined') { break; } consequent.push(sourceElement); } return markerApply(marker, delegate.createSwitchCase(test, consequent)); } function parseSwitchStatement() { var discriminant, cases, clause, oldInSwitch, defaultFound, marker = markerCreate(); expectKeyword('switch'); expect('('); discriminant = parseExpression(); expect(')'); expect('{'); cases = []; if (match('}')) { lex(); return markerApply(marker, delegate.createSwitchStatement(discriminant, cases)); } oldInSwitch = state.inSwitch; state.inSwitch = true; defaultFound = false; while (index < length) { if (match('}')) { break; } clause = parseSwitchCase(); if (clause.test === null) { if (defaultFound) { throwError({}, Messages.MultipleDefaultsInSwitch); } defaultFound = true; } cases.push(clause); } state.inSwitch = oldInSwitch; expect('}'); return markerApply(marker, delegate.createSwitchStatement(discriminant, cases)); } // 12.13 The throw statement function parseThrowStatement() { var argument, marker = markerCreate(); expectKeyword('throw'); if (peekLineTerminator()) { throwError({}, Messages.NewlineAfterThrow); } argument = parseExpression(); consumeSemicolon(); return markerApply(marker, delegate.createThrowStatement(argument)); } // 12.14 The try statement function parseCatchClause() { var param, body, marker = markerCreate(); expectKeyword('catch'); expect('('); if (match(')')) { throwUnexpected(lookahead); } param = parseExpression(); // 12.14.1 if (strict && param.type === Syntax.Identifier && isRestrictedWord(param.name)) { throwErrorTolerant({}, Messages.StrictCatchVariable); } expect(')'); body = parseBlock(); return markerApply(marker, delegate.createCatchClause(param, body)); } function parseTryStatement() { var block, handlers = [], finalizer = null, marker = markerCreate(); expectKeyword('try'); block = parseBlock(); if (matchKeyword('catch')) { handlers.push(parseCatchClause()); } if (matchKeyword('finally')) { lex(); finalizer = parseBlock(); } if (handlers.length === 0 && !finalizer) { throwError({}, Messages.NoCatchOrFinally); } return markerApply(marker, delegate.createTryStatement(block, [], handlers, finalizer)); } // 12.15 The debugger statement function parseDebuggerStatement() { var marker = markerCreate(); expectKeyword('debugger'); consumeSemicolon(); return markerApply(marker, delegate.createDebuggerStatement()); } // 12 Statements function parseStatement() { var type = lookahead.type, marker, expr, labeledBody, key; if (type === Token.EOF) { throwUnexpected(lookahead); } if (type === Token.Punctuator) { switch (lookahead.value) { case ';': return parseEmptyStatement(); case '{': return parseBlock(); case '(': return parseExpressionStatement(); default: break; } } if (type === Token.Keyword) { switch (lookahead.value) { case 'break': return parseBreakStatement(); case 'continue': return parseContinueStatement(); case 'debugger': return parseDebuggerStatement(); case 'do': return parseDoWhileStatement(); case 'for': return parseForStatement(); case 'function': return parseFunctionDeclaration(); case 'class': return parseClassDeclaration(); case 'if': return parseIfStatement(); case 'return': return parseReturnStatement(); case 'switch': return parseSwitchStatement(); case 'throw': return parseThrowStatement(); case 'try': return parseTryStatement(); case 'var': return parseVariableStatement(); case 'while': return parseWhileStatement(); case 'with': return parseWithStatement(); default: break; } } if (matchAsyncFuncExprOrDecl()) { return parseFunctionDeclaration(); } marker = markerCreate(); expr = parseExpression(); // 12.12 Labelled Statements if ((expr.type === Syntax.Identifier) && match(':')) { lex(); key = '$' + expr.name; if (Object.prototype.hasOwnProperty.call(state.labelSet, key)) { throwError({}, Messages.Redeclaration, 'Label', expr.name); } state.labelSet[key] = true; labeledBody = parseStatement(); delete state.labelSet[key]; return markerApply(marker, delegate.createLabeledStatement(expr, labeledBody)); } consumeSemicolon(); return markerApply(marker, delegate.createExpressionStatement(expr)); } // 13 Function Definition function parseConciseBody() { if (match('{')) { return parseFunctionSourceElements(); } return parseAssignmentExpression(); } function parseFunctionSourceElements() { var sourceElement, sourceElements = [], token, directive, firstRestricted, oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, oldParenthesizedCount, marker = markerCreate(); expect('{'); while (index < length) { if (lookahead.type !== Token.StringLiteral) { break; } token = lookahead; sourceElement = parseSourceElement(); sourceElements.push(sourceElement); if (sourceElement.expression.type !== Syntax.Literal) { // this is not directive break; } directive = source.slice(token.range[0] + 1, token.range[1] - 1); if (directive === 'use strict') { strict = true; if (firstRestricted) { throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral); } } else { if (!firstRestricted && token.octal) { firstRestricted = token; } } } oldLabelSet = state.labelSet; oldInIteration = state.inIteration; oldInSwitch = state.inSwitch; oldInFunctionBody = state.inFunctionBody; oldParenthesizedCount = state.parenthesizedCount; state.labelSet = {}; state.inIteration = false; state.inSwitch = false; state.inFunctionBody = true; state.parenthesizedCount = 0; while (index < length) { if (match('}')) { break; } sourceElement = parseSourceElement(); if (typeof sourceElement === 'undefined') { break; } sourceElements.push(sourceElement); } expect('}'); state.labelSet = oldLabelSet; state.inIteration = oldInIteration; state.inSwitch = oldInSwitch; state.inFunctionBody = oldInFunctionBody; state.parenthesizedCount = oldParenthesizedCount; return markerApply(marker, delegate.createBlockStatement(sourceElements)); } function validateParam(options, param, name) { var key = '$' + name; if (strict) { if (isRestrictedWord(name)) { options.stricted = param; options.message = Messages.StrictParamName; } if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { options.stricted = param; options.message = Messages.StrictParamDupe; } } else if (!options.firstRestricted) { if (isRestrictedWord(name)) { options.firstRestricted = param; options.message = Messages.StrictParamName; } else if (isStrictModeReservedWord(name)) { options.firstRestricted = param; options.message = Messages.StrictReservedWord; } else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { options.firstRestricted = param; options.message = Messages.StrictParamDupe; } } options.paramSet[key] = true; } function parseParam(options) { var marker, token, rest, param, def; token = lookahead; if (token.value === '...') { token = lex(); rest = true; } if (match('[')) { marker = markerCreate(); param = parseArrayInitialiser(); reinterpretAsDestructuredParameter(options, param); if (match(':')) { param.typeAnnotation = parseTypeAnnotation(); markerApply(marker, param); } } else if (match('{')) { marker = markerCreate(); if (rest) { throwError({}, Messages.ObjectPatternAsRestParameter); } param = parseObjectInitialiser(); reinterpretAsDestructuredParameter(options, param); if (match(':')) { param.typeAnnotation = parseTypeAnnotation(); markerApply(marker, param); } } else { param = rest ? parseTypeAnnotatableIdentifier( false, /* requireTypeAnnotation */ false /* canBeOptionalParam */ ) : parseTypeAnnotatableIdentifier( false, /* requireTypeAnnotation */ true /* canBeOptionalParam */ ); validateParam(options, token, token.value); } if (match('=')) { if (rest) { throwErrorTolerant(lookahead, Messages.DefaultRestParameter); } 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); return !match(')'); } function parseParams(firstRestricted) { var options, marker = markerCreate(); options = { params: [], defaultCount: 0, defaults: [], rest: null, firstRestricted: firstRestricted }; expect('('); if (!match(')')) { options.paramSet = {}; while (index < length) { if (!parseParam(options)) { break; } expect(','); } } expect(')'); if (options.defaultCount === 0) { options.defaults = []; } if (match(':')) { options.returnType = parseTypeAnnotation(); } return markerApply(marker, options); } function parseFunctionDeclaration() { var id, body, token, tmp, firstRestricted, message, generator, isAsync, previousStrict, previousYieldAllowed, previousAwaitAllowed, marker = markerCreate(), typeParameters; isAsync = false; if (matchAsync()) { lex(); isAsync = true; } expectKeyword('function'); generator = false; if (match('*')) { lex(); generator = true; } token = lookahead; id = parseVariableIdentifier(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } if (strict) { if (isRestrictedWord(token.value)) { throwErrorTolerant(token, Messages.StrictFunctionName); } } else { if (isRestrictedWord(token.value)) { firstRestricted = token; message = Messages.StrictFunctionName; } else if (isStrictModeReservedWord(token.value)) { firstRestricted = token; message = Messages.StrictReservedWord; } } tmp = parseParams(firstRestricted); firstRestricted = tmp.firstRestricted; if (tmp.message) { message = tmp.message; } previousStrict = strict; previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = generator; previousAwaitAllowed = state.awaitAllowed; state.awaitAllowed = isAsync; body = parseFunctionSourceElements(); if (strict && firstRestricted) { throwError(firstRestricted, message); } if (strict && tmp.stricted) { throwErrorTolerant(tmp.stricted, message); } strict = previousStrict; state.yieldAllowed = previousYieldAllowed; state.awaitAllowed = previousAwaitAllowed; return markerApply( marker, delegate.createFunctionDeclaration( id, tmp.params, tmp.defaults, body, tmp.rest, generator, false, isAsync, tmp.returnType, typeParameters ) ); } function parseFunctionExpression() { var token, id = null, firstRestricted, message, tmp, body, generator, isAsync, previousStrict, previousYieldAllowed, previousAwaitAllowed, marker = markerCreate(), typeParameters; isAsync = false; if (matchAsync()) { lex(); isAsync = true; } expectKeyword('function'); generator = false; if (match('*')) { lex(); generator = true; } if (!match('(')) { if (!match('<')) { token = lookahead; id = parseVariableIdentifier(); if (strict) { if (isRestrictedWord(token.value)) { throwErrorTolerant(token, Messages.StrictFunctionName); } } else { if (isRestrictedWord(token.value)) { firstRestricted = token; message = Messages.StrictFunctionName; } else if (isStrictModeReservedWord(token.value)) { firstRestricted = token; message = Messages.StrictReservedWord; } } } if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } } tmp = parseParams(firstRestricted); firstRestricted = tmp.firstRestricted; if (tmp.message) { message = tmp.message; } previousStrict = strict; previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = generator; previousAwaitAllowed = state.awaitAllowed; state.awaitAllowed = isAsync; body = parseFunctionSourceElements(); if (strict && firstRestricted) { throwError(firstRestricted, message); } if (strict && tmp.stricted) { throwErrorTolerant(tmp.stricted, message); } strict = previousStrict; state.yieldAllowed = previousYieldAllowed; state.awaitAllowed = previousAwaitAllowed; return markerApply( marker, delegate.createFunctionExpression( id, tmp.params, tmp.defaults, body, tmp.rest, generator, false, isAsync, tmp.returnType, typeParameters ) ); } function parseYieldExpression() { var delegateFlag, expr, marker = markerCreate(); expectKeyword('yield', !strict); delegateFlag = false; if (match('*')) { lex(); delegateFlag = true; } expr = parseAssignmentExpression(); return markerApply(marker, delegate.createYieldExpression(expr, delegateFlag)); } function parseAwaitExpression() { var expr, marker = markerCreate(); expectContextualKeyword('await'); expr = parseAssignmentExpression(); return markerApply(marker, delegate.createAwaitExpression(expr)); } // 14 Classes function parseMethodDefinition(existingPropNames, key, isStatic, generator, computed) { var token, param, propType, isValidDuplicateProp = false, isAsync, typeParameters, tokenValue, returnType, annotationMarker; propType = isStatic ? ClassPropertyType.static : ClassPropertyType.prototype; if (generator) { return delegate.createMethodDefinition( propType, '', key, parsePropertyMethodFunction({ generator: true }) ); } tokenValue = key.type === 'Identifier' && key.name; if (tokenValue === 'get' && !match('(')) { key = parseObjectPropertyKey(); // It is a syntax error if any other properties have a name // duplicating this one unless they are a setter if (existingPropNames[propType].hasOwnProperty(key.name)) { isValidDuplicateProp = // There isn't already a getter for this prop existingPropNames[propType][key.name].get === undefined // There isn't already a data prop by this name && existingPropNames[propType][key.name].data === undefined // The only existing prop by this name is a setter && existingPropNames[propType][key.name].set !== undefined; if (!isValidDuplicateProp) { throwError(key, Messages.IllegalDuplicateClassProperty); } } else { existingPropNames[propType][key.name] = {}; } existingPropNames[propType][key.name].get = true; expect('('); expect(')'); if (match(':')) { returnType = parseTypeAnnotation(); } return delegate.createMethodDefinition( propType, 'get', key, parsePropertyFunction({ generator: false, returnType: returnType }) ); } if (tokenValue === 'set' && !match('(')) { key = parseObjectPropertyKey(); // It is a syntax error if any other properties have a name // duplicating this one unless they are a getter if (existingPropNames[propType].hasOwnProperty(key.name)) { isValidDuplicateProp = // There isn't already a setter for this prop existingPropNames[propType][key.name].set === undefined // There isn't already a data prop by this name && existingPropNames[propType][key.name].data === undefined // The only existing prop by this name is a getter && existingPropNames[propType][key.name].get !== undefined; if (!isValidDuplicateProp) { throwError(key, Messages.IllegalDuplicateClassProperty); } } else { existingPropNames[propType][key.name] = {}; } existingPropNames[propType][key.name].set = true; expect('('); token = lookahead; param = [ parseTypeAnnotatableIdentifier() ]; expect(')'); if (match(':')) { returnType = parseTypeAnnotation(); } return delegate.createMethodDefinition( propType, 'set', key, parsePropertyFunction({ params: param, generator: false, name: token, returnType: returnType }) ); } if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } isAsync = tokenValue === 'async' && !match('('); if (isAsync) { key = parseObjectPropertyKey(); } // It is a syntax error if any other properties have the same name as a // non-getter, non-setter method if (existingPropNames[propType].hasOwnProperty(key.name)) { throwError(key, Messages.IllegalDuplicateClassProperty); } else { existingPropNames[propType][key.name] = {}; } existingPropNames[propType][key.name].data = true; return delegate.createMethodDefinition( propType, '', key, parsePropertyMethodFunction({ generator: false, async: isAsync, typeParameters: typeParameters }) ); } function parseClassProperty(existingPropNames, key, computed, isStatic) { var typeAnnotation; typeAnnotation = parseTypeAnnotation(); expect(';'); return delegate.createClassProperty( key, typeAnnotation, computed, isStatic ); } function parseClassElement(existingProps) { var computed, generator = false, key, marker = markerCreate(), isStatic = false; if (match(';')) { lex(); return; } if (lookahead.value === 'static') { lex(); isStatic = true; } if (match('*')) { lex(); generator = true; } computed = (lookahead.value === '['); key = parseObjectPropertyKey(); if (!generator && lookahead.value === ':') { return markerApply(marker, parseClassProperty(existingProps, key, computed, isStatic)); } return markerApply(marker, parseMethodDefinition( existingProps, key, isStatic, generator, computed )); } function parseClassBody() { var classElement, classElements = [], existingProps = {}, marker = markerCreate(); existingProps[ClassPropertyType.static] = {}; existingProps[ClassPropertyType.prototype] = {}; expect('{'); while (index < length) { if (match('}')) { break; } classElement = parseClassElement(existingProps); if (typeof classElement !== 'undefined') { classElements.push(classElement); } } expect('}'); return markerApply(marker, delegate.createClassBody(classElements)); } function parseClassImplements() { var id, implemented = [], marker, typeParameters; expectContextualKeyword('implements'); while (index < length) { marker = markerCreate(); id = parseVariableIdentifier(); if (match('<')) { typeParameters = parseTypeParameterInstantiation(); } else { typeParameters = null; } implemented.push(markerApply(marker, delegate.createClassImplements( id, typeParameters ))); if (!match(',')) { break; } expect(','); } return implemented; } function parseClassExpression() { var id, implemented, previousYieldAllowed, superClass = null, superTypeParameters, marker = markerCreate(), typeParameters; expectKeyword('class'); if (!matchKeyword('extends') && !matchContextualKeyword('implements') && !match('{')) { id = parseVariableIdentifier(); } if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } if (matchKeyword('extends')) { expectKeyword('extends'); previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = false; superClass = parseLeftHandSideExpressionAllowCall(); if (match('<')) { superTypeParameters = parseTypeParameterInstantiation(); } state.yieldAllowed = previousYieldAllowed; } if (matchContextualKeyword('implements')) { implemented = parseClassImplements(); } return markerApply(marker, delegate.createClassExpression( id, superClass, parseClassBody(), typeParameters, superTypeParameters, implemented )); } function parseClassDeclaration() { var id, implemented, previousYieldAllowed, superClass = null, superTypeParameters, marker = markerCreate(), typeParameters; expectKeyword('class'); id = parseVariableIdentifier(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } if (matchKeyword('extends')) { expectKeyword('extends'); previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = false; superClass = parseLeftHandSideExpressionAllowCall(); if (match('<')) { superTypeParameters = parseTypeParameterInstantiation(); } state.yieldAllowed = previousYieldAllowed; } if (matchContextualKeyword('implements')) { implemented = parseClassImplements(); } return markerApply(marker, delegate.createClassDeclaration( id, superClass, parseClassBody(), typeParameters, superTypeParameters, implemented )); } // 15 Program function parseSourceElement() { var token; if (lookahead.type === Token.Keyword) { switch (lookahead.value) { case 'const': case 'let': return parseConstLetDeclaration(lookahead.value); case 'function': return parseFunctionDeclaration(); default: return parseStatement(); } } if (matchContextualKeyword('type') && lookahead2().type === Token.Identifier) { return parseTypeAlias(); } if (matchContextualKeyword('interface') && lookahead2().type === Token.Identifier) { return parseInterface(); } if (matchContextualKeyword('declare')) { token = lookahead2(); if (token.type === Token.Keyword) { switch (token.value) { case 'class': return parseDeclareClass(); case 'function': return parseDeclareFunction(); case 'var': return parseDeclareVariable(); } } else if (token.type === Token.Identifier && token.value === 'module') { return parseDeclareModule(); } } if (lookahead.type !== Token.EOF) { return parseStatement(); } } function parseProgramElement() { if (lookahead.type === Token.Keyword) { switch (lookahead.value) { case 'export': return parseExportDeclaration(); case 'import': return parseImportDeclaration(); } } return parseSourceElement(); } function parseProgramElements() { var sourceElement, sourceElements = [], token, directive, firstRestricted; while (index < length) { token = lookahead; if (token.type !== Token.StringLiteral) { break; } sourceElement = parseProgramElement(); sourceElements.push(sourceElement); if (sourceElement.expression.type !== Syntax.Literal) { // this is not directive break; } directive = source.slice(token.range[0] + 1, token.range[1] - 1); if (directive === 'use strict') { strict = true; if (firstRestricted) { throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral); } } else { if (!firstRestricted && token.octal) { firstRestricted = token; } } } while (index < length) { sourceElement = parseProgramElement(); if (typeof sourceElement === 'undefined') { break; } sourceElements.push(sourceElement); } return sourceElements; } function parseProgram() { var body, marker = markerCreate(); strict = false; peek(); body = parseProgramElements(); return markerApply(marker, delegate.createProgram(body)); } // The following functions are needed only when the option to preserve // the comments is active. function addComment(type, value, start, end, loc) { var comment; assert(typeof start === 'number', 'Comment must have valid position'); // Because the way the actual token is scanned, often the comments // (if any) are skipped twice during the lexical analysis. // Thus, we need to skip adding a comment if the comment array already // handled it. if (state.lastCommentStart >= start) { return; } state.lastCommentStart = start; comment = { type: type, value: value }; if (extra.range) { comment.range = [start, end]; } if (extra.loc) { comment.loc = loc; } extra.comments.push(comment); if (extra.attachComment) { extra.leadingComments.push(comment); extra.trailingComments.push(comment); } } function scanComment() { var comment, ch, loc, start, blockComment, lineComment; comment = ''; blockComment = false; lineComment = false; while (index < length) { ch = source[index]; if (lineComment) { ch = source[index++]; if (isLineTerminator(ch.charCodeAt(0))) { loc.end = { line: lineNumber, column: index - lineStart - 1 }; lineComment = false; addComment('Line', comment, start, index - 1, loc); if (ch === '\r' && source[index] === '\n') { ++index; } ++lineNumber; lineStart = index; comment = ''; } else if (index >= length) { lineComment = false; comment += ch; loc.end = { line: lineNumber, column: length - lineStart }; addComment('Line', comment, start, length, loc); } else { comment += ch; } } else if (blockComment) { if (isLineTerminator(ch.charCodeAt(0))) { if (ch === '\r') { ++index; comment += '\r'; } if (ch !== '\r' || source[index] === '\n') { comment += source[index]; ++lineNumber; ++index; lineStart = index; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } } else { ch = source[index++]; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } comment += ch; if (ch === '*') { ch = source[index]; if (ch === '/') { comment = comment.substr(0, comment.length - 1); blockComment = false; ++index; loc.end = { line: lineNumber, column: index - lineStart }; addComment('Block', comment, start, index, loc); comment = ''; } } } } else if (ch === '/') { ch = source[index + 1]; if (ch === '/') { loc = { start: { line: lineNumber, column: index - lineStart } }; start = index; index += 2; lineComment = true; if (index >= length) { loc.end = { line: lineNumber, column: index - lineStart }; lineComment = false; addComment('Line', comment, start, index, loc); } } else if (ch === '*') { start = index; index += 2; blockComment = true; loc = { start: { line: lineNumber, column: index - lineStart - 2 } }; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } else { break; } } else if (isWhiteSpace(ch.charCodeAt(0))) { ++index; } else if (isLineTerminator(ch.charCodeAt(0))) { ++index; if (ch === '\r' && source[index] === '\n') { ++index; } ++lineNumber; lineStart = index; } else { break; } } } // 16 XJS XHTMLEntities = { quot: '\u0022', amp: '&', apos: '\u0027', lt: '<', gt: '>', nbsp: '\u00A0', iexcl: '\u00A1', cent: '\u00A2', pound: '\u00A3', curren: '\u00A4', yen: '\u00A5', brvbar: '\u00A6', sect: '\u00A7', uml: '\u00A8', copy: '\u00A9', ordf: '\u00AA', laquo: '\u00AB', not: '\u00AC', shy: '\u00AD', reg: '\u00AE', macr: '\u00AF', deg: '\u00B0', plusmn: '\u00B1', sup2: '\u00B2', sup3: '\u00B3', acute: '\u00B4', micro: '\u00B5', para: '\u00B6', middot: '\u00B7', cedil: '\u00B8', sup1: '\u00B9', ordm: '\u00BA', raquo: '\u00BB', frac14: '\u00BC', frac12: '\u00BD', frac34: '\u00BE', iquest: '\u00BF', Agrave: '\u00C0', Aacute: '\u00C1', Acirc: '\u00C2', Atilde: '\u00C3', Auml: '\u00C4', Aring: '\u00C5', AElig: '\u00C6', Ccedil: '\u00C7', Egrave: '\u00C8', Eacute: '\u00C9', Ecirc: '\u00CA', Euml: '\u00CB', Igrave: '\u00CC', Iacute: '\u00CD', Icirc: '\u00CE', Iuml: '\u00CF', ETH: '\u00D0', Ntilde: '\u00D1', Ograve: '\u00D2', Oacute: '\u00D3', Ocirc: '\u00D4', Otilde: '\u00D5', Ouml: '\u00D6', times: '\u00D7', Oslash: '\u00D8', Ugrave: '\u00D9', Uacute: '\u00DA', Ucirc: '\u00DB', Uuml: '\u00DC', Yacute: '\u00DD', THORN: '\u00DE', szlig: '\u00DF', agrave: '\u00E0', aacute: '\u00E1', acirc: '\u00E2', atilde: '\u00E3', auml: '\u00E4', aring: '\u00E5', aelig: '\u00E6', ccedil: '\u00E7', egrave: '\u00E8', eacute: '\u00E9', ecirc: '\u00EA', euml: '\u00EB', igrave: '\u00EC', iacute: '\u00ED', icirc: '\u00EE', iuml: '\u00EF', eth: '\u00F0', ntilde: '\u00F1', ograve: '\u00F2', oacute: '\u00F3', ocirc: '\u00F4', otilde: '\u00F5', ouml: '\u00F6', divide: '\u00F7', oslash: '\u00F8', ugrave: '\u00F9', uacute: '\u00FA', ucirc: '\u00FB', uuml: '\u00FC', yacute: '\u00FD', thorn: '\u00FE', yuml: '\u00FF', OElig: '\u0152', oelig: '\u0153', Scaron: '\u0160', scaron: '\u0161', Yuml: '\u0178', fnof: '\u0192', circ: '\u02C6', tilde: '\u02DC', Alpha: '\u0391', Beta: '\u0392', Gamma: '\u0393', Delta: '\u0394', Epsilon: '\u0395', Zeta: '\u0396', Eta: '\u0397', Theta: '\u0398', Iota: '\u0399', Kappa: '\u039A', Lambda: '\u039B', Mu: '\u039C', Nu: '\u039D', Xi: '\u039E', Omicron: '\u039F', Pi: '\u03A0', Rho: '\u03A1', Sigma: '\u03A3', Tau: '\u03A4', Upsilon: '\u03A5', Phi: '\u03A6', Chi: '\u03A7', Psi: '\u03A8', Omega: '\u03A9', alpha: '\u03B1', beta: '\u03B2', gamma: '\u03B3', delta: '\u03B4', epsilon: '\u03B5', zeta: '\u03B6', eta: '\u03B7', theta: '\u03B8', iota: '\u03B9', kappa: '\u03BA', lambda: '\u03BB', mu: '\u03BC', nu: '\u03BD', xi: '\u03BE', omicron: '\u03BF', pi: '\u03C0', rho: '\u03C1', sigmaf: '\u03C2', sigma: '\u03C3', tau: '\u03C4', upsilon: '\u03C5', phi: '\u03C6', chi: '\u03C7', psi: '\u03C8', omega: '\u03C9', thetasym: '\u03D1', upsih: '\u03D2', piv: '\u03D6', ensp: '\u2002', emsp: '\u2003', thinsp: '\u2009', zwnj: '\u200C', zwj: '\u200D', lrm: '\u200E', rlm: '\u200F', ndash: '\u2013', mdash: '\u2014', lsquo: '\u2018', rsquo: '\u2019', sbquo: '\u201A', ldquo: '\u201C', rdquo: '\u201D', bdquo: '\u201E', dagger: '\u2020', Dagger: '\u2021', bull: '\u2022', hellip: '\u2026', permil: '\u2030', prime: '\u2032', Prime: '\u2033', lsaquo: '\u2039', rsaquo: '\u203A', oline: '\u203E', frasl: '\u2044', euro: '\u20AC', image: '\u2111', weierp: '\u2118', real: '\u211C', trade: '\u2122', alefsym: '\u2135', larr: '\u2190', uarr: '\u2191', rarr: '\u2192', darr: '\u2193', harr: '\u2194', crarr: '\u21B5', lArr: '\u21D0', uArr: '\u21D1', rArr: '\u21D2', dArr: '\u21D3', hArr: '\u21D4', forall: '\u2200', part: '\u2202', exist: '\u2203', empty: '\u2205', nabla: '\u2207', isin: '\u2208', notin: '\u2209', ni: '\u220B', prod: '\u220F', sum: '\u2211', minus: '\u2212', lowast: '\u2217', radic: '\u221A', prop: '\u221D', infin: '\u221E', ang: '\u2220', and: '\u2227', or: '\u2228', cap: '\u2229', cup: '\u222A', 'int': '\u222B', there4: '\u2234', sim: '\u223C', cong: '\u2245', asymp: '\u2248', ne: '\u2260', equiv: '\u2261', le: '\u2264', ge: '\u2265', sub: '\u2282', sup: '\u2283', nsub: '\u2284', sube: '\u2286', supe: '\u2287', oplus: '\u2295', otimes: '\u2297', perp: '\u22A5', sdot: '\u22C5', lceil: '\u2308', rceil: '\u2309', lfloor: '\u230A', rfloor: '\u230B', lang: '\u2329', rang: '\u232A', loz: '\u25CA', spades: '\u2660', clubs: '\u2663', hearts: '\u2665', diams: '\u2666' }; function getQualifiedXJSName(object) { if (object.type === Syntax.XJSIdentifier) { return object.name; } if (object.type === Syntax.XJSNamespacedName) { return object.namespace.name + ':' + object.name.name; } if (object.type === Syntax.XJSMemberExpression) { return ( getQualifiedXJSName(object.object) + '.' + getQualifiedXJSName(object.property) ); } } function isXJSIdentifierStart(ch) { // exclude backslash (\) return (ch !== 92) && isIdentifierStart(ch); } function isXJSIdentifierPart(ch) { // exclude backslash (\) and add hyphen (-) return (ch !== 92) && (ch === 45 || isIdentifierPart(ch)); } function scanXJSIdentifier() { var ch, start, value = ''; start = index; while (index < length) { ch = source.charCodeAt(index); if (!isXJSIdentifierPart(ch)) { break; } value += source[index++]; } return { type: Token.XJSIdentifier, value: value, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanXJSEntity() { var ch, str = '', start = index, count = 0, code; ch = source[index]; assert(ch === '&', 'Entity must start with an ampersand'); index++; while (index < length && count++ < 10) { ch = source[index++]; if (ch === ';') { break; } str += ch; } // Well-formed entity (ending was found). if (ch === ';') { // Numeric entity. if (str[0] === '#') { if (str[1] === 'x') { code = +('0' + str.substr(1)); } else { // Removing leading zeros in order to avoid treating as octal in old browsers. code = +str.substr(1).replace(Regex.LeadingZeros, ''); } if (!isNaN(code)) { return String.fromCharCode(code); } } else if (XHTMLEntities[str]) { return XHTMLEntities[str]; } } // Treat non-entity sequences as regular text. index = start + 1; return '&'; } function scanXJSText(stopChars) { var ch, str = '', start; start = index; while (index < length) { ch = source[index]; if (stopChars.indexOf(ch) !== -1) { break; } if (ch === '&') { str += scanXJSEntity(); } else { index++; if (ch === '\r' && source[index] === '\n') { str += ch; ch = source[index]; index++; } if (isLineTerminator(ch.charCodeAt(0))) { ++lineNumber; lineStart = index; } str += ch; } } return { type: Token.XJSText, value: str, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanXJSStringLiteral() { var innerToken, quote, start; quote = source[index]; assert((quote === '\'' || quote === '"'), 'String literal must starts with a quote'); start = index; ++index; innerToken = scanXJSText([quote]); if (quote !== source[index]) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } ++index; innerToken.range = [start, index]; return innerToken; } /** * Between XJS opening and closing tags (e.g. HERE), anything that * is not another XJS tag and is not an expression wrapped by {} is text. */ function advanceXJSChild() { var ch = source.charCodeAt(index); // { (123) and < (60) if (ch !== 123 && ch !== 60) { return scanXJSText(['<', '{']); } return scanPunctuator(); } function parseXJSIdentifier() { var token, marker = markerCreate(); if (lookahead.type !== Token.XJSIdentifier) { throwUnexpected(lookahead); } token = lex(); return markerApply(marker, delegate.createXJSIdentifier(token.value)); } function parseXJSNamespacedName() { var namespace, name, marker = markerCreate(); namespace = parseXJSIdentifier(); expect(':'); name = parseXJSIdentifier(); return markerApply(marker, delegate.createXJSNamespacedName(namespace, name)); } function parseXJSMemberExpression() { var marker = markerCreate(), expr = parseXJSIdentifier(); while (match('.')) { lex(); expr = markerApply(marker, delegate.createXJSMemberExpression(expr, parseXJSIdentifier())); } return expr; } function parseXJSElementName() { if (lookahead2().value === ':') { return parseXJSNamespacedName(); } if (lookahead2().value === '.') { return parseXJSMemberExpression(); } return parseXJSIdentifier(); } function parseXJSAttributeName() { if (lookahead2().value === ':') { return parseXJSNamespacedName(); } return parseXJSIdentifier(); } function parseXJSAttributeValue() { var value, marker; if (match('{')) { value = parseXJSExpressionContainer(); if (value.expression.type === Syntax.XJSEmptyExpression) { throwError( value, 'XJS attributes must only be assigned a non-empty ' + 'expression' ); } } else if (match('<')) { value = parseXJSElement(); } else if (lookahead.type === Token.XJSText) { marker = markerCreate(); value = markerApply(marker, delegate.createLiteral(lex())); } else { throwError({}, Messages.InvalidXJSAttributeValue); } return value; } function parseXJSEmptyExpression() { var marker = markerCreatePreserveWhitespace(); while (source.charAt(index) !== '}') { index++; } return markerApply(marker, delegate.createXJSEmptyExpression()); } function parseXJSExpressionContainer() { var expression, origInXJSChild, origInXJSTag, marker = markerCreate(); origInXJSChild = state.inXJSChild; origInXJSTag = state.inXJSTag; state.inXJSChild = false; state.inXJSTag = false; expect('{'); if (match('}')) { expression = parseXJSEmptyExpression(); } else { expression = parseExpression(); } state.inXJSChild = origInXJSChild; state.inXJSTag = origInXJSTag; expect('}'); return markerApply(marker, delegate.createXJSExpressionContainer(expression)); } function parseXJSSpreadAttribute() { var expression, origInXJSChild, origInXJSTag, marker = markerCreate(); origInXJSChild = state.inXJSChild; origInXJSTag = state.inXJSTag; state.inXJSChild = false; state.inXJSTag = false; expect('{'); expect('...'); expression = parseAssignmentExpression(); state.inXJSChild = origInXJSChild; state.inXJSTag = origInXJSTag; expect('}'); return markerApply(marker, delegate.createXJSSpreadAttribute(expression)); } function parseXJSAttribute() { var name, marker; if (match('{')) { return parseXJSSpreadAttribute(); } marker = markerCreate(); name = parseXJSAttributeName(); // HTML empty attribute if (match('=')) { lex(); return markerApply(marker, delegate.createXJSAttribute(name, parseXJSAttributeValue())); } return markerApply(marker, delegate.createXJSAttribute(name)); } function parseXJSChild() { var token, marker; if (match('{')) { token = parseXJSExpressionContainer(); } else if (lookahead.type === Token.XJSText) { marker = markerCreatePreserveWhitespace(); token = markerApply(marker, delegate.createLiteral(lex())); } else { token = parseXJSElement(); } return token; } function parseXJSClosingElement() { var name, origInXJSChild, origInXJSTag, marker = markerCreate(); origInXJSChild = state.inXJSChild; origInXJSTag = state.inXJSTag; state.inXJSChild = false; state.inXJSTag = true; expect('<'); expect('/'); name = parseXJSElementName(); // Because advance() (called by lex() called by expect()) expects there // to be a valid token after >, it needs to know whether to look for a // standard JS token or an XJS text node state.inXJSChild = origInXJSChild; state.inXJSTag = origInXJSTag; expect('>'); return markerApply(marker, delegate.createXJSClosingElement(name)); } function parseXJSOpeningElement() { var name, attribute, attributes = [], selfClosing = false, origInXJSChild, origInXJSTag, marker = markerCreate(); origInXJSChild = state.inXJSChild; origInXJSTag = state.inXJSTag; state.inXJSChild = false; state.inXJSTag = true; expect('<'); name = parseXJSElementName(); while (index < length && lookahead.value !== '/' && lookahead.value !== '>') { attributes.push(parseXJSAttribute()); } state.inXJSTag = origInXJSTag; if (lookahead.value === '/') { expect('/'); // Because advance() (called by lex() called by expect()) expects // there to be a valid token after >, it needs to know whether to // look for a standard JS token or an XJS text node state.inXJSChild = origInXJSChild; expect('>'); selfClosing = true; } else { state.inXJSChild = true; expect('>'); } return markerApply(marker, delegate.createXJSOpeningElement(name, attributes, selfClosing)); } function parseXJSElement() { var openingElement, closingElement = null, children = [], origInXJSChild, origInXJSTag, marker = markerCreate(); origInXJSChild = state.inXJSChild; origInXJSTag = state.inXJSTag; openingElement = parseXJSOpeningElement(); if (!openingElement.selfClosing) { while (index < length) { state.inXJSChild = false; // Call lookahead2() with inXJSChild = false because one
two
; // // the default error message is a bit incomprehensible. Since it's // rarely (never?) useful to write a less-than sign after an XJS // element, we disallow it here in the parser in order to provide a // better error message. (In the rare case that the less-than operator // was intended, the left tag can be wrapped in parentheses.) if (!origInXJSChild && match('<')) { throwError(lookahead, Messages.AdjacentXJSElements); } return markerApply(marker, delegate.createXJSElement(openingElement, closingElement, children)); } function parseTypeAlias() { var id, marker = markerCreate(), typeParameters = null, right; expectContextualKeyword('type'); id = parseVariableIdentifier(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } expect('='); right = parseType(); consumeSemicolon(); return markerApply(marker, delegate.createTypeAlias(id, typeParameters, right)); } function parseInterfaceExtends() { var marker = markerCreate(), id, typeParameters = null; id = parseVariableIdentifier(); if (match('<')) { typeParameters = parseTypeParameterInstantiation(); } return markerApply(marker, delegate.createInterfaceExtends( id, typeParameters )); } function parseInterfaceish(marker, allowStatic) { var body, bodyMarker, extended = [], id, typeParameters = null; id = parseVariableIdentifier(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } if (matchKeyword('extends')) { expectKeyword('extends'); while (index < length) { extended.push(parseInterfaceExtends()); if (!match(',')) { break; } expect(','); } } bodyMarker = markerCreate(); body = markerApply(bodyMarker, parseObjectType(allowStatic)); return markerApply(marker, delegate.createInterface( id, typeParameters, body, extended )); } function parseInterface() { var body, bodyMarker, extended = [], id, marker = markerCreate(), typeParameters = null; expectContextualKeyword('interface'); return parseInterfaceish(marker, /* allowStatic */false); } function parseDeclareClass() { var marker = markerCreate(), ret; expectContextualKeyword('declare'); expectKeyword('class'); ret = parseInterfaceish(marker, /* allowStatic */true); ret.type = Syntax.DeclareClass; return ret; } function parseDeclareFunction() { var id, idMarker, marker = markerCreate(), params, returnType, rest, tmp, typeParameters = null, value, valueMarker; expectContextualKeyword('declare'); expectKeyword('function'); idMarker = markerCreate(); id = parseVariableIdentifier(); valueMarker = markerCreate(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } expect('('); tmp = parseFunctionTypeParams(); params = tmp.params; rest = tmp.rest; expect(')'); expect(':'); returnType = parseType(); value = markerApply(valueMarker, delegate.createFunctionTypeAnnotation( params, returnType, rest, typeParameters )); id.typeAnnotation = markerApply(valueMarker, delegate.createTypeAnnotation( value )); markerApply(idMarker, id); consumeSemicolon(); return markerApply(marker, delegate.createDeclareFunction( id )); } function parseDeclareVariable() { var id, marker = markerCreate(); expectContextualKeyword('declare'); expectKeyword('var'); id = parseTypeAnnotatableIdentifier(); consumeSemicolon(); return markerApply(marker, delegate.createDeclareVariable( id )); } function parseDeclareModule() { var body = [], bodyMarker, id, idMarker, marker = markerCreate(), token; expectContextualKeyword('declare'); expectContextualKeyword('module'); if (lookahead.type === Token.StringLiteral) { if (strict && lookahead.octal) { throwErrorTolerant(lookahead, Messages.StrictOctalLiteral); } idMarker = markerCreate(); id = markerApply(idMarker, delegate.createLiteral(lex())); } else { id = parseVariableIdentifier(); } bodyMarker = markerCreate(); expect('{'); while (index < length && !match('}')) { token = lookahead2(); switch (token.value) { case 'class': body.push(parseDeclareClass()); break; case 'function': body.push(parseDeclareFunction()); break; case 'var': body.push(parseDeclareVariable()); break; default: throwUnexpected(lookahead); } } expect('}'); return markerApply(marker, delegate.createDeclareModule( id, markerApply(bodyMarker, delegate.createBlockStatement(body)) )); } function collectToken() { var start, loc, token, range, value, entry; if (!state.inXJSChild) { skipComment(); } start = index; loc = { start: { line: lineNumber, column: index - lineStart } }; token = extra.advance(); loc.end = { line: lineNumber, column: index - lineStart }; if (token.type !== Token.EOF) { range = [token.range[0], token.range[1]]; value = source.slice(token.range[0], token.range[1]); entry = { type: TokenName[token.type], value: value, range: range, loc: loc }; if (token.regex) { entry.regex = { pattern: token.regex.pattern, flags: token.regex.flags }; } extra.tokens.push(entry); } return token; } function collectRegex() { var pos, loc, regex, token; skipComment(); pos = index; loc = { start: { line: lineNumber, column: index - lineStart } }; regex = extra.scanRegExp(); loc.end = { line: lineNumber, column: index - lineStart }; if (!extra.tokenize) { // Pop the previous token, which is likely '/' or '/=' if (extra.tokens.length > 0) { token = extra.tokens[extra.tokens.length - 1]; if (token.range[0] === pos && token.type === 'Punctuator') { if (token.value === '/' || token.value === '/=') { extra.tokens.pop(); } } } extra.tokens.push({ type: 'RegularExpression', value: regex.literal, regex: regex.regex, range: [pos, index], loc: loc }); } return regex; } function filterTokenLocation() { var i, entry, token, tokens = []; for (i = 0; i < extra.tokens.length; ++i) { entry = extra.tokens[i]; token = { type: entry.type, value: entry.value }; if (entry.regex) { token.regex = { pattern: entry.regex.pattern, flags: entry.regex.flags }; } if (extra.range) { token.range = entry.range; } if (extra.loc) { token.loc = entry.loc; } tokens.push(token); } extra.tokens = tokens; } function patch() { if (extra.comments) { extra.skipComment = skipComment; skipComment = scanComment; } if (typeof extra.tokens !== 'undefined') { extra.advance = advance; extra.scanRegExp = scanRegExp; advance = collectToken; scanRegExp = collectRegex; } } function unpatch() { if (typeof extra.skipComment === 'function') { skipComment = extra.skipComment; } if (typeof extra.scanRegExp === 'function') { advance = extra.advance; scanRegExp = extra.scanRegExp; } } // This is used to modify the delegate. function extend(object, properties) { var entry, result = {}; for (entry in object) { if (object.hasOwnProperty(entry)) { result[entry] = object[entry]; } } for (entry in properties) { if (properties.hasOwnProperty(entry)) { result[entry] = properties[entry]; } } return result; } function tokenize(code, options) { var toString, token, tokens; toString = String; if (typeof code !== 'string' && !(code instanceof String)) { code = toString(code); } delegate = SyntaxTreeDelegate; source = code; index = 0; lineNumber = (source.length > 0) ? 1 : 0; lineStart = 0; length = source.length; lookahead = null; state = { allowKeyword: true, allowIn: true, labelSet: {}, inFunctionBody: false, inIteration: false, inSwitch: false, lastCommentStart: -1 }; extra = {}; // Options matching. options = options || {}; // Of course we collect tokens here. 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; extra.range = (typeof options.range === 'boolean') && options.range; extra.loc = (typeof options.loc === 'boolean') && options.loc; if (typeof options.comment === 'boolean' && options.comment) { extra.comments = []; } if (typeof options.tolerant === 'boolean' && options.tolerant) { extra.errors = []; } if (length > 0) { if (typeof source[0] === 'undefined') { // Try first to convert to a string. This is good as fast path // for old IE which understands string indexing for string // literals only and not for string object. if (code instanceof String) { source = code.valueOf(); } } } patch(); try { peek(); if (lookahead.type === Token.EOF) { return extra.tokens; } token = lex(); while (lookahead.type !== Token.EOF) { try { token = lex(); } catch (lexError) { token = lookahead; if (extra.errors) { extra.errors.push(lexError); // We have to break on the first error // to avoid infinite loops. break; } else { throw lexError; } } } filterTokenLocation(); tokens = extra.tokens; if (typeof extra.comments !== 'undefined') { tokens.comments = extra.comments; } if (typeof extra.errors !== 'undefined') { tokens.errors = extra.errors; } } catch (e) { throw e; } finally { unpatch(); extra = {}; } return tokens; } function parse(code, options) { var program, toString; toString = String; if (typeof code !== 'string' && !(code instanceof String)) { code = toString(code); } delegate = SyntaxTreeDelegate; source = code; index = 0; lineNumber = (source.length > 0) ? 1 : 0; lineStart = 0; length = source.length; lookahead = null; state = { allowKeyword: false, allowIn: true, labelSet: {}, parenthesizedCount: 0, inFunctionBody: false, inIteration: false, inSwitch: false, inXJSChild: false, inXJSTag: false, inType: false, lastCommentStart: -1, yieldAllowed: false, awaitAllowed: false }; extra = {}; if (typeof options !== 'undefined') { extra.range = (typeof options.range === 'boolean') && options.range; extra.loc = (typeof options.loc === 'boolean') && options.loc; extra.attachComment = (typeof options.attachComment === 'boolean') && options.attachComment; if (extra.loc && options.source !== null && options.source !== undefined) { delegate = extend(delegate, { 'postProcess': function (node) { node.loc.source = toString(options.source); return node; } }); } if (typeof options.tokens === 'boolean' && options.tokens) { extra.tokens = []; } if (typeof options.comment === 'boolean' && options.comment) { extra.comments = []; } if (typeof options.tolerant === 'boolean' && options.tolerant) { extra.errors = []; } if (extra.attachComment) { extra.range = true; extra.comments = []; extra.bottomRightStack = []; extra.trailingComments = []; extra.leadingComments = []; } } if (length > 0) { if (typeof source[0] === 'undefined') { // Try first to convert to a string. This is good as fast path // for old IE which understands string indexing for string // literals only and not for string object. if (code instanceof String) { source = code.valueOf(); } } } patch(); try { program = parseProgram(); if (typeof extra.comments !== 'undefined') { program.comments = extra.comments; } if (typeof extra.tokens !== 'undefined') { filterTokenLocation(); program.tokens = extra.tokens; } if (typeof extra.errors !== 'undefined') { program.errors = extra.errors; } } catch (e) { throw e; } finally { unpatch(); extra = {}; } return program; } // Sync with *.json manifests. exports.version = '8001.1001.0-dev-harmony-fb'; exports.tokenize = tokenize; exports.parse = parse; // Deep copy. exports.Syntax = (function () { var name, types = {}; if (typeof Object.create === 'function') { types = Object.create(null); } for (name in Syntax) { if (Syntax.hasOwnProperty(name)) { types[name] = Syntax[name]; } } if (typeof Object.freeze === 'function') { Object.freeze(types); } return types; }()); })); /* vim: set sw=4 ts=4 et tw=80 : */ },{}],454:[function(require,module,exports){ // simple-fmt.js // MIT licensed, see LICENSE file // Copyright (c) 2013 Olov Lassus var fmt = (function() { "use strict"; function fmt(str, var_args) { var args = Array.prototype.slice.call(arguments, 1); return str.replace(/\{(\d+)\}/g, function(s, match) { return (match in args ? args[match] : s); }); } function obj(str, obj) { return str.replace(/\{([_$a-zA-Z0-9][_$a-zA-Z0-9]*)\}/g, function(s, match) { return (match in obj ? obj[match] : s); }); } function repeat(str, n) { return (new Array(n + 1)).join(str); } fmt.fmt = fmt; fmt.obj = obj; fmt.repeat = repeat; return fmt; })(); if (typeof module !== "undefined" && typeof module.exports !== "undefined") { module.exports = fmt; } },{}],455:[function(require,module,exports){ // simple-is.js // MIT licensed, see LICENSE file // Copyright (c) 2013 Olov Lassus var is = (function() { "use strict"; var hasOwnProperty = Object.prototype.hasOwnProperty; var toString = Object.prototype.toString; var _undefined = void 0; return { nan: function(v) { return v !== v; }, boolean: function(v) { return typeof v === "boolean"; }, number: function(v) { return typeof v === "number"; }, string: function(v) { return typeof v === "string"; }, fn: function(v) { return typeof v === "function"; }, object: function(v) { return v !== null && typeof v === "object"; }, primitive: function(v) { var t = typeof v; return v === null || v === _undefined || t === "boolean" || t === "number" || t === "string"; }, array: Array.isArray || function(v) { return toString.call(v) === "[object Array]"; }, finitenumber: function(v) { return typeof v === "number" && isFinite(v); }, someof: function(v, values) { return values.indexOf(v) >= 0; }, noneof: function(v, values) { return values.indexOf(v) === -1; }, own: function(obj, prop) { return hasOwnProperty.call(obj, prop); }, }; })(); if (typeof module !== "undefined" && typeof module.exports !== "undefined") { module.exports = is; } },{}],456:[function(require,module,exports){ // stringmap.js // MIT licensed, see LICENSE file // Copyright (c) 2013 Olov Lassus var StringMap = (function() { "use strict"; // to save us a few characters var hasOwnProperty = Object.prototype.hasOwnProperty; var create = (function() { function hasOwnEnumerableProps(obj) { for (var prop in obj) { if (hasOwnProperty.call(obj, prop)) { return true; } } return false; } // FF <= 3.6: // o = {}; o.hasOwnProperty("__proto__" or "__count__" or "__parent__") => true // o = {"__proto__": null}; Object.prototype.hasOwnProperty.call(o, "__proto__" or "__count__" or "__parent__") => false function hasOwnPollutedProps(obj) { return hasOwnProperty.call(obj, "__count__") || hasOwnProperty.call(obj, "__parent__"); } var useObjectCreate = false; if (typeof Object.create === "function") { if (!hasOwnEnumerableProps(Object.create(null))) { useObjectCreate = true; } } if (useObjectCreate === false) { if (hasOwnEnumerableProps({})) { throw new Error("StringMap environment error 0, please file a bug at https://github.com/olov/stringmap/issues"); } } // no throw yet means we can create objects without own enumerable props (safe-guard against VMs and shims) var o = (useObjectCreate ? Object.create(null) : {}); var useProtoClear = false; if (hasOwnPollutedProps(o)) { o.__proto__ = null; if (hasOwnEnumerableProps(o) || hasOwnPollutedProps(o)) { throw new Error("StringMap environment error 1, please file a bug at https://github.com/olov/stringmap/issues"); } useProtoClear = true; } // no throw yet means we can create objects without own polluted props (safe-guard against VMs and shims) return function() { var o = (useObjectCreate ? Object.create(null) : {}); if (useProtoClear) { o.__proto__ = null; } return o; }; })(); // stringmap ctor function stringmap(optional_object) { // use with or without new if (!(this instanceof stringmap)) { return new stringmap(optional_object); } this.obj = create(); this.hasProto = false; // false (no __proto__ key) or true (has __proto__ key) this.proto = undefined; // value for __proto__ key when hasProto is true, undefined otherwise if (optional_object) { this.setMany(optional_object); } }; // primitive methods that deals with data representation stringmap.prototype.has = function(key) { // The type-check of key in has, get, set and delete is important because otherwise an object // {toString: function() { return "__proto__"; }} can avoid the key === "__proto__" test. // The alternative to type-checking would be to force string conversion, i.e. key = String(key); if (typeof key !== "string") { throw new Error("StringMap expected string key"); } return (key === "__proto__" ? this.hasProto : hasOwnProperty.call(this.obj, key)); }; stringmap.prototype.get = function(key) { if (typeof key !== "string") { throw new Error("StringMap expected string key"); } return (key === "__proto__" ? this.proto : (hasOwnProperty.call(this.obj, key) ? this.obj[key] : undefined)); }; stringmap.prototype.set = function(key, value) { if (typeof key !== "string") { throw new Error("StringMap expected string key"); } if (key === "__proto__") { this.hasProto = true; this.proto = value; } else { this.obj[key] = value; } }; stringmap.prototype.remove = function(key) { if (typeof key !== "string") { throw new Error("StringMap expected string key"); } var didExist = this.has(key); if (key === "__proto__") { this.hasProto = false; this.proto = undefined; } else { delete this.obj[key]; } return didExist; }; // alias remove to delete but beware: // sm.delete("key"); // OK in ES5 and later // sm['delete']("key"); // OK in all ES versions // sm.remove("key"); // OK in all ES versions stringmap.prototype['delete'] = stringmap.prototype.remove; stringmap.prototype.isEmpty = function() { for (var key in this.obj) { if (hasOwnProperty.call(this.obj, key)) { return false; } } return !this.hasProto; }; stringmap.prototype.size = function() { var len = 0; for (var key in this.obj) { if (hasOwnProperty.call(this.obj, key)) { ++len; } } return (this.hasProto ? len + 1 : len); }; stringmap.prototype.keys = function() { var keys = []; for (var key in this.obj) { if (hasOwnProperty.call(this.obj, key)) { keys.push(key); } } if (this.hasProto) { keys.push("__proto__"); } return keys; }; stringmap.prototype.values = function() { var values = []; for (var key in this.obj) { if (hasOwnProperty.call(this.obj, key)) { values.push(this.obj[key]); } } if (this.hasProto) { values.push(this.proto); } return values; }; stringmap.prototype.items = function() { var items = []; for (var key in this.obj) { if (hasOwnProperty.call(this.obj, key)) { items.push([key, this.obj[key]]); } } if (this.hasProto) { items.push(["__proto__", this.proto]); } return items; }; // methods that rely on the above primitives stringmap.prototype.setMany = function(object) { if (object === null || (typeof object !== "object" && typeof object !== "function")) { throw new Error("StringMap expected Object"); } for (var key in object) { if (hasOwnProperty.call(object, key)) { this.set(key, object[key]); } } return this; }; stringmap.prototype.merge = function(other) { var keys = other.keys(); for (var i = 0; i < keys.length; i++) { var key = keys[i]; this.set(key, other.get(key)); } return this; }; stringmap.prototype.map = function(fn) { var keys = this.keys(); for (var i = 0; i < keys.length; i++) { var key = keys[i]; keys[i] = fn(this.get(key), key); // re-use keys array for results } return keys; }; stringmap.prototype.forEach = function(fn) { var keys = this.keys(); for (var i = 0; i < keys.length; i++) { var key = keys[i]; fn(this.get(key), key); } }; stringmap.prototype.clone = function() { var other = stringmap(); return other.merge(this); }; stringmap.prototype.toString = function() { var self = this; return "{" + this.keys().map(function(key) { return JSON.stringify(key) + ":" + JSON.stringify(self.get(key)); }).join(",") + "}"; }; return stringmap; })(); if (typeof module !== "undefined" && typeof module.exports !== "undefined") { module.exports = StringMap; } },{}],457:[function(require,module,exports){ // stringset.js // MIT licensed, see LICENSE file // Copyright (c) 2013 Olov Lassus var StringSet = (function() { "use strict"; // to save us a few characters var hasOwnProperty = Object.prototype.hasOwnProperty; var create = (function() { function hasOwnEnumerableProps(obj) { for (var prop in obj) { if (hasOwnProperty.call(obj, prop)) { return true; } } return false; } // FF <= 3.6: // o = {}; o.hasOwnProperty("__proto__" or "__count__" or "__parent__") => true // o = {"__proto__": null}; Object.prototype.hasOwnProperty.call(o, "__proto__" or "__count__" or "__parent__") => false function hasOwnPollutedProps(obj) { return hasOwnProperty.call(obj, "__count__") || hasOwnProperty.call(obj, "__parent__"); } var useObjectCreate = false; if (typeof Object.create === "function") { if (!hasOwnEnumerableProps(Object.create(null))) { useObjectCreate = true; } } if (useObjectCreate === false) { if (hasOwnEnumerableProps({})) { throw new Error("StringSet environment error 0, please file a bug at https://github.com/olov/stringset/issues"); } } // no throw yet means we can create objects without own enumerable props (safe-guard against VMs and shims) var o = (useObjectCreate ? Object.create(null) : {}); var useProtoClear = false; if (hasOwnPollutedProps(o)) { o.__proto__ = null; if (hasOwnEnumerableProps(o) || hasOwnPollutedProps(o)) { throw new Error("StringSet environment error 1, please file a bug at https://github.com/olov/stringset/issues"); } useProtoClear = true; } // no throw yet means we can create objects without own polluted props (safe-guard against VMs and shims) return function() { var o = (useObjectCreate ? Object.create(null) : {}); if (useProtoClear) { o.__proto__ = null; } return o; }; })(); // stringset ctor function stringset(optional_array) { // use with or without new if (!(this instanceof stringset)) { return new stringset(optional_array); } this.obj = create(); this.hasProto = false; // false (no __proto__ item) or true (has __proto__ item) if (optional_array) { this.addMany(optional_array); } }; // primitive methods that deals with data representation stringset.prototype.has = function(item) { // The type-check of item in has, get, set and delete is important because otherwise an object // {toString: function() { return "__proto__"; }} can avoid the item === "__proto__" test. // The alternative to type-checking would be to force string conversion, i.e. item = String(item); if (typeof item !== "string") { throw new Error("StringSet expected string item"); } return (item === "__proto__" ? this.hasProto : hasOwnProperty.call(this.obj, item)); }; stringset.prototype.add = function(item) { if (typeof item !== "string") { throw new Error("StringSet expected string item"); } if (item === "__proto__") { this.hasProto = true; } else { this.obj[item] = true; } }; stringset.prototype.remove = function(item) { if (typeof item !== "string") { throw new Error("StringSet expected string item"); } var didExist = this.has(item); if (item === "__proto__") { this.hasProto = false; } else { delete this.obj[item]; } return didExist; }; // alias remove to delete but beware: // ss.delete("key"); // OK in ES5 and later // ss['delete']("key"); // OK in all ES versions // ss.remove("key"); // OK in all ES versions stringset.prototype['delete'] = stringset.prototype.remove; stringset.prototype.isEmpty = function() { for (var item in this.obj) { if (hasOwnProperty.call(this.obj, item)) { return false; } } return !this.hasProto; }; stringset.prototype.size = function() { var len = 0; for (var item in this.obj) { if (hasOwnProperty.call(this.obj, item)) { ++len; } } return (this.hasProto ? len + 1 : len); }; stringset.prototype.items = function() { var items = []; for (var item in this.obj) { if (hasOwnProperty.call(this.obj, item)) { items.push(item); } } if (this.hasProto) { items.push("__proto__"); } return items; }; // methods that rely on the above primitives stringset.prototype.addMany = function(items) { if (!Array.isArray(items)) { throw new Error("StringSet expected array"); } for (var i = 0; i < items.length; i++) { this.add(items[i]); } return this; }; stringset.prototype.merge = function(other) { this.addMany(other.items()); return this; }; stringset.prototype.clone = function() { var other = stringset(); return other.merge(this); }; stringset.prototype.toString = function() { return "{" + this.items().map(JSON.stringify).join(",") + "}"; }; return stringset; })(); if (typeof module !== "undefined" && typeof module.exports !== "undefined") { module.exports = StringSet; } },{}],458:[function(require,module,exports){ /* Copyright (C) 2013 Ariya Hidayat Copyright (C) 2013 Thaddee Tyl Copyright (C) 2012 Ariya Hidayat Copyright (C) 2012 Mathias Bynens Copyright (C) 2012 Joost-Wim Boekesteijn Copyright (C) 2012 Kris Kowal Copyright (C) 2012 Yusuke Suzuki Copyright (C) 2012 Arpad Borsos Copyright (C) 2011 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. */ (function (root, factory) { 'use strict'; // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, // Rhino, and plain browser loading. /* istanbul ignore next */ if (typeof define === 'function' && define.amd) { define(['exports'], factory); } else if (typeof exports !== 'undefined') { factory(exports); } else { factory((root.esprima = {})); } }(this, function (exports) { 'use strict'; var Token, TokenName, FnExprTokens, Syntax, PropertyKind, Messages, Regex, SyntaxTreeDelegate, XHTMLEntities, ClassPropertyType, source, strict, index, lineNumber, lineStart, length, delegate, lookahead, state, extra; Token = { BooleanLiteral: 1, EOF: 2, Identifier: 3, Keyword: 4, NullLiteral: 5, NumericLiteral: 6, Punctuator: 7, StringLiteral: 8, RegularExpression: 9, Template: 10, JSXIdentifier: 11, JSXText: 12 }; TokenName = {}; TokenName[Token.BooleanLiteral] = 'Boolean'; TokenName[Token.EOF] = ''; TokenName[Token.Identifier] = 'Identifier'; TokenName[Token.Keyword] = 'Keyword'; TokenName[Token.NullLiteral] = 'Null'; TokenName[Token.NumericLiteral] = 'Numeric'; TokenName[Token.Punctuator] = 'Punctuator'; TokenName[Token.StringLiteral] = 'String'; TokenName[Token.JSXIdentifier] = 'JSXIdentifier'; TokenName[Token.JSXText] = 'JSXText'; TokenName[Token.RegularExpression] = 'RegularExpression'; // A function following one of those tokens is an expression. FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new', 'return', 'case', 'delete', 'throw', 'void', // assignment operators '=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=', '&=', '|=', '^=', ',', // binary/unary operators '+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&', '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=', '<=', '<', '>', '!=', '!==']; Syntax = { AnyTypeAnnotation: 'AnyTypeAnnotation', ArrayExpression: 'ArrayExpression', ArrayPattern: 'ArrayPattern', ArrayTypeAnnotation: 'ArrayTypeAnnotation', ArrowFunctionExpression: 'ArrowFunctionExpression', AssignmentExpression: 'AssignmentExpression', BinaryExpression: 'BinaryExpression', BlockStatement: 'BlockStatement', BooleanTypeAnnotation: 'BooleanTypeAnnotation', BreakStatement: 'BreakStatement', CallExpression: 'CallExpression', CatchClause: 'CatchClause', ClassBody: 'ClassBody', ClassDeclaration: 'ClassDeclaration', ClassExpression: 'ClassExpression', ClassImplements: 'ClassImplements', ClassProperty: 'ClassProperty', ComprehensionBlock: 'ComprehensionBlock', ComprehensionExpression: 'ComprehensionExpression', ConditionalExpression: 'ConditionalExpression', ContinueStatement: 'ContinueStatement', DebuggerStatement: 'DebuggerStatement', DeclareClass: 'DeclareClass', DeclareFunction: 'DeclareFunction', DeclareModule: 'DeclareModule', DeclareVariable: 'DeclareVariable', DoWhileStatement: 'DoWhileStatement', EmptyStatement: 'EmptyStatement', ExportDeclaration: 'ExportDeclaration', ExportBatchSpecifier: 'ExportBatchSpecifier', ExportSpecifier: 'ExportSpecifier', ExpressionStatement: 'ExpressionStatement', ForInStatement: 'ForInStatement', ForOfStatement: 'ForOfStatement', ForStatement: 'ForStatement', FunctionDeclaration: 'FunctionDeclaration', FunctionExpression: 'FunctionExpression', FunctionTypeAnnotation: 'FunctionTypeAnnotation', FunctionTypeParam: 'FunctionTypeParam', GenericTypeAnnotation: 'GenericTypeAnnotation', Identifier: 'Identifier', IfStatement: 'IfStatement', ImportDeclaration: 'ImportDeclaration', ImportDefaultSpecifier: 'ImportDefaultSpecifier', ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', ImportSpecifier: 'ImportSpecifier', InterfaceDeclaration: 'InterfaceDeclaration', InterfaceExtends: 'InterfaceExtends', IntersectionTypeAnnotation: 'IntersectionTypeAnnotation', LabeledStatement: 'LabeledStatement', Literal: 'Literal', LogicalExpression: 'LogicalExpression', MemberExpression: 'MemberExpression', MethodDefinition: 'MethodDefinition', ModuleSpecifier: 'ModuleSpecifier', NewExpression: 'NewExpression', NullableTypeAnnotation: 'NullableTypeAnnotation', NumberTypeAnnotation: 'NumberTypeAnnotation', ObjectExpression: 'ObjectExpression', ObjectPattern: 'ObjectPattern', ObjectTypeAnnotation: 'ObjectTypeAnnotation', ObjectTypeCallProperty: 'ObjectTypeCallProperty', ObjectTypeIndexer: 'ObjectTypeIndexer', ObjectTypeProperty: 'ObjectTypeProperty', Program: 'Program', Property: 'Property', QualifiedTypeIdentifier: 'QualifiedTypeIdentifier', ReturnStatement: 'ReturnStatement', SequenceExpression: 'SequenceExpression', SpreadElement: 'SpreadElement', SpreadProperty: 'SpreadProperty', StringLiteralTypeAnnotation: 'StringLiteralTypeAnnotation', StringTypeAnnotation: 'StringTypeAnnotation', SwitchCase: 'SwitchCase', SwitchStatement: 'SwitchStatement', TaggedTemplateExpression: 'TaggedTemplateExpression', TemplateElement: 'TemplateElement', TemplateLiteral: 'TemplateLiteral', ThisExpression: 'ThisExpression', ThrowStatement: 'ThrowStatement', TupleTypeAnnotation: 'TupleTypeAnnotation', TryStatement: 'TryStatement', TypeAlias: 'TypeAlias', TypeAnnotation: 'TypeAnnotation', TypeCastExpression: 'TypeCastExpression', TypeofTypeAnnotation: 'TypeofTypeAnnotation', TypeParameterDeclaration: 'TypeParameterDeclaration', TypeParameterInstantiation: 'TypeParameterInstantiation', UnaryExpression: 'UnaryExpression', UnionTypeAnnotation: 'UnionTypeAnnotation', UpdateExpression: 'UpdateExpression', VariableDeclaration: 'VariableDeclaration', VariableDeclarator: 'VariableDeclarator', VoidTypeAnnotation: 'VoidTypeAnnotation', WhileStatement: 'WhileStatement', WithStatement: 'WithStatement', JSXIdentifier: 'JSXIdentifier', JSXNamespacedName: 'JSXNamespacedName', JSXMemberExpression: 'JSXMemberExpression', JSXEmptyExpression: 'JSXEmptyExpression', JSXExpressionContainer: 'JSXExpressionContainer', JSXElement: 'JSXElement', JSXClosingElement: 'JSXClosingElement', JSXOpeningElement: 'JSXOpeningElement', JSXAttribute: 'JSXAttribute', JSXSpreadAttribute: 'JSXSpreadAttribute', JSXText: 'JSXText', YieldExpression: 'YieldExpression', AwaitExpression: 'AwaitExpression' }; PropertyKind = { Data: 1, Get: 2, Set: 4 }; ClassPropertyType = { 'static': 'static', prototype: 'prototype' }; // Error messages should be identical to V8. Messages = { UnexpectedToken: 'Unexpected token %0', UnexpectedNumber: 'Unexpected number', UnexpectedString: 'Unexpected string', UnexpectedIdentifier: 'Unexpected identifier', UnexpectedReserved: 'Unexpected reserved word', UnexpectedTemplate: 'Unexpected quasi %0', UnexpectedEOS: 'Unexpected end of input', NewlineAfterThrow: 'Illegal newline after throw', InvalidRegExp: 'Invalid regular expression', 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', UnknownLabel: 'Undefined label \'%0\'', Redeclaration: '%0 \'%1\' has already been declared', IllegalContinue: 'Illegal continue statement', IllegalBreak: 'Illegal break statement', IllegalDuplicateClassProperty: 'Illegal duplicate property in class definition', IllegalClassConstructorProperty: 'Illegal constructor property in class definition', IllegalReturn: 'Illegal return statement', 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', PropertyAfterSpreadProperty: 'A rest property must be the final property of an object literal', 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.', StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode', AccessorDataProperty: 'Object literal may not have data and accessor property with the same name', AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name', StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode', StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode', StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode', StrictReservedWord: 'Use of future reserved word in strict mode', MissingFromClause: 'Missing from clause', NoAsAfterImportNamespace: 'Missing as after import *', InvalidModuleSpecifier: 'Invalid module specifier', IllegalImportDeclaration: 'Illegal import declaration', IllegalExportDeclaration: 'Illegal export declaration', NoUninitializedConst: 'Const must be initialized', ComprehensionRequiresBlock: 'Comprehension must have at least one block', ComprehensionError: 'Comprehension Error', EachNotAllowed: 'Each is not supported', InvalidJSXAttributeValue: 'JSX value should be either an expression or a quoted JSX text', ExpectedJSXClosingTag: 'Expected corresponding JSX closing tag for %0', AdjacentJSXElements: 'Adjacent JSX elements must be wrapped in an enclosing tag', ConfusedAboutFunctionType: 'Unexpected token =>. It looks like ' + 'you are trying to write a function type, but you ended up ' + 'writing a grouped type followed by an =>, which is a syntax ' + 'error. Remember, function type parameters are named so function ' + 'types look like (name1: type1, name2: type2) => returnType. You ' + 'probably wrote (type1) => returnType' }; // See also tools/generate-unicode-regex.py. Regex = { NonAsciiIdentifierStart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'), NonAsciiIdentifierPart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'), LeadingZeros: new RegExp('^0+(?!$)') }; // Ensure the condition is true, otherwise throw an error. // This is only to have a better contract semantic, i.e. another safety net // to catch a logic error. The condition shall be fulfilled in normal case. // Do NOT use this to enforce a certain condition on any user input. function assert(condition, message) { /* istanbul ignore if */ if (!condition) { throw new Error('ASSERT: ' + message); } } 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]; }; function isDecimalDigit(ch) { return (ch >= 48 && ch <= 57); // 0..9 } function isHexDigit(ch) { return '0123456789abcdefABCDEF'.indexOf(ch) >= 0; } function isOctalDigit(ch) { return '01234567'.indexOf(ch) >= 0; } // 7.2 White Space function isWhiteSpace(ch) { return (ch === 32) || // space (ch === 9) || // tab (ch === 0xB) || (ch === 0xC) || (ch === 0xA0) || (ch >= 0x1680 && '\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\uFEFF'.indexOf(String.fromCharCode(ch)) > 0); } // 7.3 Line Terminators function isLineTerminator(ch) { return (ch === 10) || (ch === 13) || (ch === 0x2028) || (ch === 0x2029); } // 7.6 Identifier Names and Identifiers function isIdentifierStart(ch) { return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore) (ch >= 65 && ch <= 90) || // A..Z (ch >= 97 && ch <= 122) || // a..z (ch === 92) || // \ (backslash) ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch))); } function isIdentifierPart(ch) { return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore) (ch >= 65 && ch <= 90) || // A..Z (ch >= 97 && ch <= 122) || // a..z (ch >= 48 && ch <= 57) || // 0..9 (ch === 92) || // \ (backslash) ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch))); } // 7.6.1.2 Future Reserved Words function isFutureReservedWord(id) { switch (id) { case 'class': case 'enum': case 'export': case 'extends': case 'import': case 'super': return true; default: return false; } } function isStrictModeReservedWord(id) { switch (id) { case 'implements': case 'interface': case 'package': case 'private': case 'protected': case 'public': case 'static': case 'yield': case 'let': return true; default: return false; } } function isRestrictedWord(id) { return id === 'eval' || id === 'arguments'; } // 7.6.1.1 Keywords function isKeyword(id) { if (strict && isStrictModeReservedWord(id)) { return true; } // 'const' is specialized as Keyword in V8. // 'yield' is only treated as a keyword in strict mode. // 'let' is for compatiblity with SpiderMonkey and ES.next. // Some others are from future reserved words. switch (id.length) { case 2: return (id === 'if') || (id === 'in') || (id === 'do'); case 3: return (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try') || (id === 'let'); case 4: return (id === 'this') || (id === 'else') || (id === 'case') || (id === 'void') || (id === 'with') || (id === 'enum'); case 5: return (id === 'while') || (id === 'break') || (id === 'catch') || (id === 'throw') || (id === 'const') || (id === 'class') || (id === 'super'); case 6: return (id === 'return') || (id === 'typeof') || (id === 'delete') || (id === 'switch') || (id === 'export') || (id === 'import'); case 7: return (id === 'default') || (id === 'finally') || (id === 'extends'); case 8: return (id === 'function') || (id === 'continue') || (id === 'debugger'); case 10: return (id === 'instanceof'); default: return false; } } // 7.4 Comments function addComment(type, value, start, end, loc) { var comment; assert(typeof start === 'number', 'Comment must have valid position'); // Because the way the actual token is scanned, often the comments // (if any) are skipped twice during the lexical analysis. // Thus, we need to skip adding a comment if the comment array already // handled it. if (state.lastCommentStart >= start) { return; } state.lastCommentStart = start; comment = { type: type, value: value }; if (extra.range) { comment.range = [start, end]; } if (extra.loc) { comment.loc = loc; } extra.comments.push(comment); if (extra.attachComment) { extra.leadingComments.push(comment); extra.trailingComments.push(comment); } } function skipSingleLineComment() { var start, loc, ch, comment; start = index - 2; loc = { start: { line: lineNumber, column: index - lineStart - 2 } }; while (index < length) { ch = source.charCodeAt(index); ++index; if (isLineTerminator(ch)) { if (extra.comments) { comment = source.slice(start + 2, index - 1); loc.end = { line: lineNumber, column: index - lineStart - 1 }; addComment('Line', comment, start, index - 1, loc); } if (ch === 13 && source.charCodeAt(index) === 10) { ++index; } ++lineNumber; lineStart = index; return; } } if (extra.comments) { comment = source.slice(start + 2, index); loc.end = { line: lineNumber, column: index - lineStart }; addComment('Line', comment, start, index, loc); } } function skipMultiLineComment() { var start, loc, ch, comment; if (extra.comments) { start = index - 2; loc = { start: { line: lineNumber, column: index - lineStart - 2 } }; } while (index < length) { ch = source.charCodeAt(index); if (isLineTerminator(ch)) { if (ch === 13 && source.charCodeAt(index + 1) === 10) { ++index; } ++lineNumber; ++index; lineStart = index; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } else if (ch === 42) { // Block comment ends with '*/' (char #42, char #47). if (source.charCodeAt(index + 1) === 47) { ++index; ++index; if (extra.comments) { comment = source.slice(start + 2, index - 2); loc.end = { line: lineNumber, column: index - lineStart }; addComment('Block', comment, start, index, loc); } return; } ++index; } else { ++index; } } throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } function skipComment() { var ch; while (index < length) { ch = source.charCodeAt(index); if (isWhiteSpace(ch)) { ++index; } else if (isLineTerminator(ch)) { ++index; if (ch === 13 && source.charCodeAt(index) === 10) { ++index; } ++lineNumber; lineStart = index; } else if (ch === 47) { // 47 is '/' ch = source.charCodeAt(index + 1); if (ch === 47) { ++index; ++index; skipSingleLineComment(); } else if (ch === 42) { // 42 is '*' ++index; ++index; skipMultiLineComment(); } else { break; } } else { break; } } } function scanHexEscape(prefix) { var i, len, ch, code = 0; len = (prefix === 'u') ? 4 : 2; for (i = 0; i < len; ++i) { if (index < length && isHexDigit(source[index])) { ch = source[index++]; code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); } else { return ''; } } return String.fromCharCode(code); } function scanUnicodeCodePointEscape() { var ch, code, cu1, cu2; ch = source[index]; code = 0; // At least, one hex digit is required. if (ch === '}') { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } while (index < length) { ch = source[index++]; if (!isHexDigit(ch)) { break; } code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); } if (code > 0x10FFFF || ch !== '}') { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } // UTF-16 Encoding if (code <= 0xFFFF) { return String.fromCharCode(code); } cu1 = ((code - 0x10000) >> 10) + 0xD800; cu2 = ((code - 0x10000) & 1023) + 0xDC00; return String.fromCharCode(cu1, cu2); } function getEscapedIdentifier() { var ch, id; ch = source.charCodeAt(index++); id = String.fromCharCode(ch); // '\u' (char #92, char #117) denotes an escaped character. if (ch === 92) { if (source.charCodeAt(index) !== 117) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } ++index; ch = scanHexEscape('u'); if (!ch || ch === '\\' || !isIdentifierStart(ch.charCodeAt(0))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } id = ch; } while (index < length) { ch = source.charCodeAt(index); if (!isIdentifierPart(ch)) { break; } ++index; id += String.fromCharCode(ch); // '\u' (char #92, char #117) denotes an escaped character. if (ch === 92) { id = id.substr(0, id.length - 1); if (source.charCodeAt(index) !== 117) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } ++index; ch = scanHexEscape('u'); if (!ch || ch === '\\' || !isIdentifierPart(ch.charCodeAt(0))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } id += ch; } } return id; } function getIdentifier() { var start, ch; start = index++; while (index < length) { ch = source.charCodeAt(index); if (ch === 92) { // Blackslash (char #92) marks Unicode escape sequence. index = start; return getEscapedIdentifier(); } if (isIdentifierPart(ch)) { ++index; } else { break; } } return source.slice(start, index); } function scanIdentifier() { var start, id, type; start = index; // Backslash (char #92) starts an escaped character. id = (source.charCodeAt(index) === 92) ? getEscapedIdentifier() : getIdentifier(); // There is no keyword or literal with only one character. // Thus, it must be an identifier. if (id.length === 1) { type = Token.Identifier; } else if (isKeyword(id)) { type = Token.Keyword; } else if (id === 'null') { type = Token.NullLiteral; } else if (id === 'true' || id === 'false') { type = Token.BooleanLiteral; } else { type = Token.Identifier; } return { type: type, value: id, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // 7.7 Punctuators function scanPunctuator() { var start = index, code = source.charCodeAt(index), code2, ch1 = source[index], ch2, ch3, ch4; if (state.inJSXTag || state.inJSXChild) { // Don't need to check for '{' and '}' as it's already handled // correctly by default. switch (code) { case 60: // < case 62: // > ++index; return { type: Token.Punctuator, value: String.fromCharCode(code), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } } switch (code) { // Check for most common single-character punctuators. case 40: // ( open bracket case 41: // ) close bracket case 59: // ; semicolon case 44: // , comma case 123: // { open curly brace case 125: // } close curly brace case 91: // [ case 93: // ] case 58: // : case 63: // ? case 126: // ~ ++index; if (extra.tokenize) { if (code === 40) { extra.openParenToken = extra.tokens.length; } else if (code === 123) { extra.openCurlyToken = extra.tokens.length; } } return { type: Token.Punctuator, value: String.fromCharCode(code), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; default: code2 = source.charCodeAt(index + 1); // '=' (char #61) marks an assignment or comparison operator. if (code2 === 61) { switch (code) { case 37: // % case 38: // & case 42: // *: case 43: // + case 45: // - case 47: // / case 60: // < case 62: // > case 94: // ^ case 124: // | index += 2; return { type: Token.Punctuator, value: String.fromCharCode(code) + String.fromCharCode(code2), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; case 33: // ! case 61: // = index += 2; // !== and === if (source.charCodeAt(index) === 61) { ++index; } return { type: Token.Punctuator, value: source.slice(start, index), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; default: break; } } break; } // Peek more characters. ch2 = source[index + 1]; ch3 = source[index + 2]; ch4 = source[index + 3]; // 4-character punctuator: >>>= if (ch1 === '>' && ch2 === '>' && ch3 === '>') { if (ch4 === '=') { index += 4; return { type: Token.Punctuator, value: '>>>=', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } } // 3-character punctuators: === !== >>> <<= >>= if (ch1 === '>' && ch2 === '>' && ch3 === '>') { index += 3; return { type: Token.Punctuator, value: '>>>', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '<' && ch2 === '<' && ch3 === '=') { index += 3; return { type: Token.Punctuator, value: '<<=', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '>' && ch2 === '>' && ch3 === '=') { index += 3; return { type: Token.Punctuator, value: '>>=', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '.' && ch2 === '.' && ch3 === '.') { index += 3; return { type: Token.Punctuator, value: '...', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // Other 2-character punctuators: ++ -- << >> && || // Don't match these tokens if we're in a type, since they never can // occur and can mess up types like Map> if (ch1 === ch2 && ('+-<>&|'.indexOf(ch1) >= 0) && !state.inType) { index += 2; return { type: Token.Punctuator, value: ch1 + ch2, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '=' && ch2 === '>') { index += 2; return { type: Token.Punctuator, value: '=>', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) { ++index; return { type: Token.Punctuator, value: ch1, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '.') { ++index; return { type: Token.Punctuator, value: ch1, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } // 7.8.3 Numeric Literals function scanHexLiteral(start) { var number = ''; while (index < length) { if (!isHexDigit(source[index])) { break; } number += source[index++]; } if (number.length === 0) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } if (isIdentifierStart(source.charCodeAt(index))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.NumericLiteral, value: parseInt('0x' + number, 16), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanBinaryLiteral(start) { var ch, number; number = ''; while (index < length) { ch = source[index]; if (ch !== '0' && ch !== '1') { break; } number += source[index++]; } if (number.length === 0) { // only 0b or 0B throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } if (index < length) { ch = source.charCodeAt(index); /* istanbul ignore else */ if (isIdentifierStart(ch) || isDecimalDigit(ch)) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } return { type: Token.NumericLiteral, value: parseInt(number, 2), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanOctalLiteral(prefix, start) { var number, octal; if (isOctalDigit(prefix)) { octal = true; number = '0' + source[index++]; } else { octal = false; ++index; number = ''; } while (index < length) { if (!isOctalDigit(source[index])) { break; } number += source[index++]; } if (!octal && number.length === 0) { // only 0o or 0O throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.NumericLiteral, value: parseInt(number, 8), octal: octal, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanNumericLiteral() { var number, start, ch; ch = source[index]; assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'), 'Numeric literal must start with a decimal digit or a decimal point'); start = index; number = ''; if (ch !== '.') { number = source[index++]; ch = source[index]; // Hex number starts with '0x'. // Octal number starts with '0'. // Octal number in ES6 starts with '0o'. // Binary number in ES6 starts with '0b'. if (number === '0') { if (ch === 'x' || ch === 'X') { ++index; return scanHexLiteral(start); } if (ch === 'b' || ch === 'B') { ++index; return scanBinaryLiteral(start); } if (ch === 'o' || ch === 'O' || isOctalDigit(ch)) { return scanOctalLiteral(ch, start); } // decimal number starts with '0' such as '09' is illegal. if (ch && isDecimalDigit(ch.charCodeAt(0))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } ch = source[index]; } if (ch === '.') { number += source[index++]; while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } ch = source[index]; } if (ch === 'e' || ch === 'E') { number += source[index++]; ch = source[index]; if (ch === '+' || ch === '-') { number += source[index++]; } if (isDecimalDigit(source.charCodeAt(index))) { while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } } else { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } if (isIdentifierStart(source.charCodeAt(index))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.NumericLiteral, value: parseFloat(number), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // 7.8.4 String Literals function scanStringLiteral() { var str = '', quote, start, ch, code, unescaped, restore, octal = false; quote = source[index]; assert((quote === '\'' || quote === '"'), 'String literal must starts with a quote'); start = index; ++index; while (index < length) { ch = source[index++]; if (ch === quote) { quote = ''; break; } else if (ch === '\\') { ch = source[index++]; if (!ch || !isLineTerminator(ch.charCodeAt(0))) { switch (ch) { case 'n': str += '\n'; break; case 'r': str += '\r'; break; case 't': str += '\t'; break; case 'u': case 'x': if (source[index] === '{') { ++index; str += scanUnicodeCodePointEscape(); } else { restore = index; unescaped = scanHexEscape(ch); if (unescaped) { str += unescaped; } else { index = restore; str += ch; } } break; case 'b': str += '\b'; break; case 'f': str += '\f'; break; case 'v': str += '\x0B'; break; default: if (isOctalDigit(ch)) { code = '01234567'.indexOf(ch); // \0 is not octal escape sequence if (code !== 0) { octal = true; } /* istanbul ignore else */ if (index < length && isOctalDigit(source[index])) { octal = true; code = code * 8 + '01234567'.indexOf(source[index++]); // 3 digits are only allowed when string starts // with 0, 1, 2, 3 if ('0123'.indexOf(ch) >= 0 && index < length && isOctalDigit(source[index])) { code = code * 8 + '01234567'.indexOf(source[index++]); } } str += String.fromCharCode(code); } else { str += ch; } break; } } else { ++lineNumber; if (ch === '\r' && source[index] === '\n') { ++index; } lineStart = index; } } else if (isLineTerminator(ch.charCodeAt(0))) { break; } else { str += ch; } } if (quote !== '') { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.StringLiteral, value: str, octal: octal, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanTemplate() { var cooked = '', ch, start, terminated, tail, restore, unescaped, code, octal; terminated = false; tail = false; start = index; ++index; while (index < length) { ch = source[index++]; if (ch === '`') { tail = true; terminated = true; break; } else if (ch === '$') { if (source[index] === '{') { ++index; terminated = true; break; } cooked += ch; } else if (ch === '\\') { ch = source[index++]; if (!isLineTerminator(ch.charCodeAt(0))) { switch (ch) { case 'n': cooked += '\n'; break; case 'r': cooked += '\r'; break; case 't': cooked += '\t'; break; case 'u': case 'x': if (source[index] === '{') { ++index; cooked += scanUnicodeCodePointEscape(); } else { restore = index; unescaped = scanHexEscape(ch); if (unescaped) { cooked += unescaped; } else { index = restore; cooked += ch; } } break; case 'b': cooked += '\b'; break; case 'f': cooked += '\f'; break; case 'v': cooked += '\v'; break; default: if (isOctalDigit(ch)) { code = '01234567'.indexOf(ch); // \0 is not octal escape sequence if (code !== 0) { octal = true; } /* istanbul ignore else */ if (index < length && isOctalDigit(source[index])) { octal = true; code = code * 8 + '01234567'.indexOf(source[index++]); // 3 digits are only allowed when string starts // with 0, 1, 2, 3 if ('0123'.indexOf(ch) >= 0 && index < length && isOctalDigit(source[index])) { code = code * 8 + '01234567'.indexOf(source[index++]); } } cooked += String.fromCharCode(code); } else { cooked += ch; } break; } } else { ++lineNumber; if (ch === '\r' && source[index] === '\n') { ++index; } lineStart = index; } } else if (isLineTerminator(ch.charCodeAt(0))) { ++lineNumber; if (ch === '\r' && source[index] === '\n') { ++index; } lineStart = index; cooked += '\n'; } else { cooked += ch; } } if (!terminated) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.Template, value: { cooked: cooked, raw: source.slice(start + 1, index - ((tail) ? 1 : 2)) }, tail: tail, octal: octal, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanTemplateElement(option) { var startsWith, template; lookahead = null; skipComment(); startsWith = (option.head) ? '`' : '}'; if (source[index] !== startsWith) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } template = scanTemplate(); peek(); return template; } function testRegExp(pattern, flags) { var tmp = pattern, value; if (flags.indexOf('u') >= 0) { // Replace each astral symbol and every Unicode code point // escape sequence with a single ASCII symbol to avoid throwing on // regular expressions that are only valid in combination with the // `/u` flag. // Note: replacing with the ASCII symbol `x` might cause false // negatives in unlikely scenarios. For example, `[\u{61}-b]` is a // perfectly valid pattern that is equivalent to `[a-b]`, but it // would be replaced by `[x-b]` which throws an error. tmp = tmp .replace(/\\u\{([0-9a-fA-F]+)\}/g, function ($0, $1) { if (parseInt($1, 16) <= 0x10FFFF) { return 'x'; } throwError({}, Messages.InvalidRegExp); }) .replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, 'x'); } // First, detect invalid regular expressions. try { value = new RegExp(tmp); } catch (e) { throwError({}, Messages.InvalidRegExp); } // Return a regular expression object for this pattern-flag pair, or // `null` in case the current environment doesn't support the flags it // uses. try { return new RegExp(pattern, flags); } catch (exception) { return null; } } function scanRegExpBody() { var ch, str, classMarker, terminated, body; ch = source[index]; assert(ch === '/', 'Regular expression literal must start with a slash'); str = source[index++]; classMarker = false; terminated = false; while (index < length) { ch = source[index++]; str += ch; if (ch === '\\') { ch = source[index++]; // ECMA-262 7.8.5 if (isLineTerminator(ch.charCodeAt(0))) { throwError({}, Messages.UnterminatedRegExp); } str += ch; } else if (isLineTerminator(ch.charCodeAt(0))) { throwError({}, Messages.UnterminatedRegExp); } else if (classMarker) { if (ch === ']') { classMarker = false; } } else { if (ch === '/') { terminated = true; break; } else if (ch === '[') { classMarker = true; } } } if (!terminated) { throwError({}, Messages.UnterminatedRegExp); } // Exclude leading and trailing slash. body = str.substr(1, str.length - 2); return { value: body, literal: str }; } function scanRegExpFlags() { var ch, str, flags, restore; str = ''; flags = ''; while (index < length) { ch = source[index]; if (!isIdentifierPart(ch.charCodeAt(0))) { break; } ++index; if (ch === '\\' && index < length) { ch = source[index]; if (ch === 'u') { ++index; restore = index; ch = scanHexEscape('u'); if (ch) { flags += ch; for (str += '\\u'; restore < index; ++restore) { str += source[restore]; } } else { index = restore; flags += 'u'; str += '\\u'; } throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL'); } else { str += '\\'; throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL'); } } else { flags += ch; str += ch; } } return { value: flags, literal: str }; } function scanRegExp() { var start, body, flags, value; lookahead = null; skipComment(); start = index; body = scanRegExpBody(); flags = scanRegExpFlags(); value = testRegExp(body.value, flags.value); if (extra.tokenize) { return { type: Token.RegularExpression, value: value, regex: { pattern: body.value, flags: flags.value }, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } return { literal: body.literal + flags.literal, value: value, regex: { pattern: body.value, flags: flags.value }, range: [start, index] }; } function isIdentifierName(token) { return token.type === Token.Identifier || token.type === Token.Keyword || token.type === Token.BooleanLiteral || token.type === Token.NullLiteral; } function advanceSlash() { var prevToken, checkToken; // Using the following algorithm: // https://github.com/mozilla/sweet.js/wiki/design prevToken = extra.tokens[extra.tokens.length - 1]; if (!prevToken) { // Nothing before that: it cannot be a division. return scanRegExp(); } if (prevToken.type === 'Punctuator') { if (prevToken.value === ')') { checkToken = extra.tokens[extra.openParenToken - 1]; if (checkToken && checkToken.type === 'Keyword' && (checkToken.value === 'if' || checkToken.value === 'while' || checkToken.value === 'for' || checkToken.value === 'with')) { return scanRegExp(); } return scanPunctuator(); } if (prevToken.value === '}') { // Dividing a function by anything makes little sense, // but we have to check for that. if (extra.tokens[extra.openCurlyToken - 3] && extra.tokens[extra.openCurlyToken - 3].type === 'Keyword') { // Anonymous function. checkToken = extra.tokens[extra.openCurlyToken - 4]; if (!checkToken) { return scanPunctuator(); } } else if (extra.tokens[extra.openCurlyToken - 4] && extra.tokens[extra.openCurlyToken - 4].type === 'Keyword') { // Named function. checkToken = extra.tokens[extra.openCurlyToken - 5]; if (!checkToken) { return scanRegExp(); } } else { return scanPunctuator(); } // checkToken determines whether the function is // a declaration or an expression. if (FnExprTokens.indexOf(checkToken.value) >= 0) { // It is an expression. return scanPunctuator(); } // It is a declaration. return scanRegExp(); } return scanRegExp(); } if (prevToken.type === 'Keyword' && prevToken.value !== 'this') { return scanRegExp(); } return scanPunctuator(); } function advance() { var ch; if (!state.inJSXChild) { skipComment(); } if (index >= length) { return { type: Token.EOF, lineNumber: lineNumber, lineStart: lineStart, range: [index, index] }; } if (state.inJSXChild) { return advanceJSXChild(); } ch = source.charCodeAt(index); // Very common: ( and ) and ; if (ch === 40 || ch === 41 || ch === 58) { return scanPunctuator(); } // String literal starts with single quote (#39) or double quote (#34). if (ch === 39 || ch === 34) { if (state.inJSXTag) { return scanJSXStringLiteral(); } return scanStringLiteral(); } if (state.inJSXTag && isJSXIdentifierStart(ch)) { return scanJSXIdentifier(); } if (ch === 96) { return scanTemplate(); } if (isIdentifierStart(ch)) { return scanIdentifier(); } // Dot (.) char #46 can also start a floating-point number, hence the need // to check the next character. if (ch === 46) { if (isDecimalDigit(source.charCodeAt(index + 1))) { return scanNumericLiteral(); } return scanPunctuator(); } if (isDecimalDigit(ch)) { return scanNumericLiteral(); } // Slash (/) char #47 can also start a regex. if (extra.tokenize && ch === 47) { return advanceSlash(); } return scanPunctuator(); } function lex() { var token; token = lookahead; index = token.range[1]; lineNumber = token.lineNumber; lineStart = token.lineStart; lookahead = advance(); index = token.range[1]; lineNumber = token.lineNumber; lineStart = token.lineStart; return token; } function peek() { var pos, line, start; pos = index; line = lineNumber; start = lineStart; lookahead = advance(); index = pos; lineNumber = line; lineStart = start; } function lookahead2() { var adv, pos, line, start, result; // If we are collecting the tokens, don't grab the next one yet. /* istanbul ignore next */ adv = (typeof extra.advance === 'function') ? extra.advance : advance; pos = index; line = lineNumber; start = lineStart; // Scan for the next immediate token. /* istanbul ignore if */ if (lookahead === null) { lookahead = adv(); } index = lookahead.range[1]; lineNumber = lookahead.lineNumber; lineStart = lookahead.lineStart; // Grab the token right after. result = adv(); index = pos; lineNumber = line; lineStart = start; return result; } function rewind(token) { index = token.range[0]; lineNumber = token.lineNumber; lineStart = token.lineStart; lookahead = token; } function markerCreate() { if (!extra.loc && !extra.range) { return undefined; } skipComment(); return {offset: index, line: lineNumber, col: index - lineStart}; } function markerCreatePreserveWhitespace() { if (!extra.loc && !extra.range) { return undefined; } return {offset: index, line: lineNumber, col: index - lineStart}; } function processComment(node) { var lastChild, trailingComments, bottomRight = extra.bottomRightStack, last = bottomRight[bottomRight.length - 1]; if (node.type === Syntax.Program) { /* istanbul ignore else */ if (node.body.length > 0) { return; } } if (extra.trailingComments.length > 0) { if (extra.trailingComments[0].range[0] >= node.range[1]) { trailingComments = extra.trailingComments; extra.trailingComments = []; } else { extra.trailingComments.length = 0; } } else { if (last && last.trailingComments && last.trailingComments[0].range[0] >= node.range[1]) { trailingComments = last.trailingComments; delete last.trailingComments; } } // Eating the stack. if (last) { while (last && last.range[0] >= node.range[0]) { lastChild = last; last = bottomRight.pop(); } } if (lastChild) { if (lastChild.leadingComments && lastChild.leadingComments[lastChild.leadingComments.length - 1].range[1] <= node.range[0]) { node.leadingComments = lastChild.leadingComments; delete lastChild.leadingComments; } } else if (extra.leadingComments.length > 0 && extra.leadingComments[extra.leadingComments.length - 1].range[1] <= node.range[0]) { node.leadingComments = extra.leadingComments; extra.leadingComments = []; } if (trailingComments) { node.trailingComments = trailingComments; } bottomRight.push(node); } function markerApply(marker, node) { if (extra.range) { node.range = [marker.offset, index]; } if (extra.loc) { node.loc = { start: { line: marker.line, column: marker.col }, end: { line: lineNumber, column: index - lineStart } }; node = delegate.postProcess(node); } if (extra.attachComment) { processComment(node); } return node; } SyntaxTreeDelegate = { name: 'SyntaxTree', postProcess: function (node) { return node; }, createArrayExpression: function (elements) { return { type: Syntax.ArrayExpression, elements: elements }; }, createAssignmentExpression: function (operator, left, right) { return { type: Syntax.AssignmentExpression, operator: operator, left: left, right: right }; }, createBinaryExpression: function (operator, left, right) { var type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression : Syntax.BinaryExpression; return { type: type, operator: operator, left: left, right: right }; }, createBlockStatement: function (body) { return { type: Syntax.BlockStatement, body: body }; }, createBreakStatement: function (label) { return { type: Syntax.BreakStatement, label: label }; }, createCallExpression: function (callee, args) { return { type: Syntax.CallExpression, callee: callee, 'arguments': args }; }, createCatchClause: function (param, body) { return { type: Syntax.CatchClause, param: param, body: body }; }, createConditionalExpression: function (test, consequent, alternate) { return { type: Syntax.ConditionalExpression, test: test, consequent: consequent, alternate: alternate }; }, createContinueStatement: function (label) { return { type: Syntax.ContinueStatement, label: label }; }, createDebuggerStatement: function () { return { type: Syntax.DebuggerStatement }; }, createDoWhileStatement: function (body, test) { return { type: Syntax.DoWhileStatement, body: body, test: test }; }, createEmptyStatement: function () { return { type: Syntax.EmptyStatement }; }, createExpressionStatement: function (expression) { return { type: Syntax.ExpressionStatement, expression: expression }; }, createForStatement: function (init, test, update, body) { return { type: Syntax.ForStatement, init: init, test: test, update: update, body: body }; }, createForInStatement: function (left, right, body) { return { type: Syntax.ForInStatement, left: left, right: right, body: body, each: false }; }, createForOfStatement: function (left, right, body) { return { type: Syntax.ForOfStatement, left: left, right: right, body: body }; }, createFunctionDeclaration: function (id, params, defaults, body, rest, generator, expression, isAsync, returnType, typeParameters) { var funDecl = { type: Syntax.FunctionDeclaration, id: id, params: params, defaults: defaults, body: body, rest: rest, generator: generator, expression: expression, returnType: returnType, typeParameters: typeParameters }; if (isAsync) { funDecl.async = true; } return funDecl; }, createFunctionExpression: function (id, params, defaults, body, rest, generator, expression, isAsync, returnType, typeParameters) { var funExpr = { type: Syntax.FunctionExpression, id: id, params: params, defaults: defaults, body: body, rest: rest, generator: generator, expression: expression, returnType: returnType, typeParameters: typeParameters }; if (isAsync) { funExpr.async = true; } return funExpr; }, createIdentifier: function (name) { return { type: Syntax.Identifier, name: name, // Only here to initialize the shape of the object to ensure // that the 'typeAnnotation' key is ordered before others that // are added later (like 'loc' and 'range'). This just helps // keep the shape of Identifier nodes consistent with everything // else. typeAnnotation: undefined, optional: undefined }; }, createTypeAnnotation: function (typeAnnotation) { return { type: Syntax.TypeAnnotation, typeAnnotation: typeAnnotation }; }, createTypeCast: function (expression, typeAnnotation) { return { type: Syntax.TypeCastExpression, expression: expression, typeAnnotation: typeAnnotation }; }, createFunctionTypeAnnotation: function (params, returnType, rest, typeParameters) { return { type: Syntax.FunctionTypeAnnotation, params: params, returnType: returnType, rest: rest, typeParameters: typeParameters }; }, createFunctionTypeParam: function (name, typeAnnotation, optional) { return { type: Syntax.FunctionTypeParam, name: name, typeAnnotation: typeAnnotation, optional: optional }; }, createNullableTypeAnnotation: function (typeAnnotation) { return { type: Syntax.NullableTypeAnnotation, typeAnnotation: typeAnnotation }; }, createArrayTypeAnnotation: function (elementType) { return { type: Syntax.ArrayTypeAnnotation, elementType: elementType }; }, createGenericTypeAnnotation: function (id, typeParameters) { return { type: Syntax.GenericTypeAnnotation, id: id, typeParameters: typeParameters }; }, createQualifiedTypeIdentifier: function (qualification, id) { return { type: Syntax.QualifiedTypeIdentifier, qualification: qualification, id: id }; }, createTypeParameterDeclaration: function (params) { return { type: Syntax.TypeParameterDeclaration, params: params }; }, createTypeParameterInstantiation: function (params) { return { type: Syntax.TypeParameterInstantiation, params: params }; }, createAnyTypeAnnotation: function () { return { type: Syntax.AnyTypeAnnotation }; }, createBooleanTypeAnnotation: function () { return { type: Syntax.BooleanTypeAnnotation }; }, createNumberTypeAnnotation: function () { return { type: Syntax.NumberTypeAnnotation }; }, createStringTypeAnnotation: function () { return { type: Syntax.StringTypeAnnotation }; }, createStringLiteralTypeAnnotation: function (token) { return { type: Syntax.StringLiteralTypeAnnotation, value: token.value, raw: source.slice(token.range[0], token.range[1]) }; }, createVoidTypeAnnotation: function () { return { type: Syntax.VoidTypeAnnotation }; }, createTypeofTypeAnnotation: function (argument) { return { type: Syntax.TypeofTypeAnnotation, argument: argument }; }, createTupleTypeAnnotation: function (types) { return { type: Syntax.TupleTypeAnnotation, types: types }; }, createObjectTypeAnnotation: function (properties, indexers, callProperties) { return { type: Syntax.ObjectTypeAnnotation, properties: properties, indexers: indexers, callProperties: callProperties }; }, createObjectTypeIndexer: function (id, key, value, isStatic) { return { type: Syntax.ObjectTypeIndexer, id: id, key: key, value: value, static: isStatic }; }, createObjectTypeCallProperty: function (value, isStatic) { return { type: Syntax.ObjectTypeCallProperty, value: value, static: isStatic }; }, createObjectTypeProperty: function (key, value, optional, isStatic) { return { type: Syntax.ObjectTypeProperty, key: key, value: value, optional: optional, static: isStatic }; }, createUnionTypeAnnotation: function (types) { return { type: Syntax.UnionTypeAnnotation, types: types }; }, createIntersectionTypeAnnotation: function (types) { return { type: Syntax.IntersectionTypeAnnotation, types: types }; }, createTypeAlias: function (id, typeParameters, right) { return { type: Syntax.TypeAlias, id: id, typeParameters: typeParameters, right: right }; }, createInterface: function (id, typeParameters, body, extended) { return { type: Syntax.InterfaceDeclaration, id: id, typeParameters: typeParameters, body: body, extends: extended }; }, createInterfaceExtends: function (id, typeParameters) { return { type: Syntax.InterfaceExtends, id: id, typeParameters: typeParameters }; }, createDeclareFunction: function (id) { return { type: Syntax.DeclareFunction, id: id }; }, createDeclareVariable: function (id) { return { type: Syntax.DeclareVariable, id: id }; }, createDeclareModule: function (id, body) { return { type: Syntax.DeclareModule, id: id, body: body }; }, createJSXAttribute: function (name, value) { return { type: Syntax.JSXAttribute, name: name, value: value || null }; }, createJSXSpreadAttribute: function (argument) { return { type: Syntax.JSXSpreadAttribute, argument: argument }; }, createJSXIdentifier: function (name) { return { type: Syntax.JSXIdentifier, name: name }; }, createJSXNamespacedName: function (namespace, name) { return { type: Syntax.JSXNamespacedName, namespace: namespace, name: name }; }, createJSXMemberExpression: function (object, property) { return { type: Syntax.JSXMemberExpression, object: object, property: property }; }, createJSXElement: function (openingElement, closingElement, children) { return { type: Syntax.JSXElement, openingElement: openingElement, closingElement: closingElement, children: children }; }, createJSXEmptyExpression: function () { return { type: Syntax.JSXEmptyExpression }; }, createJSXExpressionContainer: function (expression) { return { type: Syntax.JSXExpressionContainer, expression: expression }; }, createJSXOpeningElement: function (name, attributes, selfClosing) { return { type: Syntax.JSXOpeningElement, name: name, selfClosing: selfClosing, attributes: attributes }; }, createJSXClosingElement: function (name) { return { type: Syntax.JSXClosingElement, name: name }; }, createIfStatement: function (test, consequent, alternate) { return { type: Syntax.IfStatement, test: test, consequent: consequent, alternate: alternate }; }, createLabeledStatement: function (label, body) { return { type: Syntax.LabeledStatement, label: label, body: body }; }, createLiteral: function (token) { var object = { type: Syntax.Literal, value: token.value, raw: source.slice(token.range[0], token.range[1]) }; if (token.regex) { object.regex = token.regex; } return object; }, createMemberExpression: function (accessor, object, property) { return { type: Syntax.MemberExpression, computed: accessor === '[', object: object, property: property }; }, createNewExpression: function (callee, args) { return { type: Syntax.NewExpression, callee: callee, 'arguments': args }; }, createObjectExpression: function (properties) { return { type: Syntax.ObjectExpression, properties: properties }; }, createPostfixExpression: function (operator, argument) { return { type: Syntax.UpdateExpression, operator: operator, argument: argument, prefix: false }; }, createProgram: function (body) { return { type: Syntax.Program, body: body }; }, createProperty: function (kind, key, value, method, shorthand, computed) { return { type: Syntax.Property, key: key, value: value, kind: kind, method: method, shorthand: shorthand, computed: computed }; }, createReturnStatement: function (argument) { return { type: Syntax.ReturnStatement, argument: argument }; }, createSequenceExpression: function (expressions) { return { type: Syntax.SequenceExpression, expressions: expressions }; }, createSwitchCase: function (test, consequent) { return { type: Syntax.SwitchCase, test: test, consequent: consequent }; }, createSwitchStatement: function (discriminant, cases) { return { type: Syntax.SwitchStatement, discriminant: discriminant, cases: cases }; }, createThisExpression: function () { return { type: Syntax.ThisExpression }; }, createThrowStatement: function (argument) { return { type: Syntax.ThrowStatement, argument: argument }; }, createTryStatement: function (block, guardedHandlers, handlers, finalizer) { return { type: Syntax.TryStatement, block: block, guardedHandlers: guardedHandlers, handlers: handlers, finalizer: finalizer }; }, createUnaryExpression: function (operator, argument) { if (operator === '++' || operator === '--') { return { type: Syntax.UpdateExpression, operator: operator, argument: argument, prefix: true }; } return { type: Syntax.UnaryExpression, operator: operator, argument: argument, prefix: true }; }, createVariableDeclaration: function (declarations, kind) { return { type: Syntax.VariableDeclaration, declarations: declarations, kind: kind }; }, createVariableDeclarator: function (id, init) { return { type: Syntax.VariableDeclarator, id: id, init: init }; }, createWhileStatement: function (test, body) { return { type: Syntax.WhileStatement, test: test, body: body }; }, createWithStatement: function (object, body) { return { type: Syntax.WithStatement, object: object, body: body }; }, createTemplateElement: function (value, tail) { return { type: Syntax.TemplateElement, value: value, tail: tail }; }, createTemplateLiteral: function (quasis, expressions) { return { type: Syntax.TemplateLiteral, quasis: quasis, expressions: expressions }; }, createSpreadElement: function (argument) { return { type: Syntax.SpreadElement, argument: argument }; }, createSpreadProperty: function (argument) { return { type: Syntax.SpreadProperty, argument: argument }; }, createTaggedTemplateExpression: function (tag, quasi) { return { type: Syntax.TaggedTemplateExpression, tag: tag, quasi: quasi }; }, createArrowFunctionExpression: function (params, defaults, body, rest, expression, isAsync) { var arrowExpr = { type: Syntax.ArrowFunctionExpression, id: null, params: params, defaults: defaults, body: body, rest: rest, generator: false, expression: expression }; if (isAsync) { arrowExpr.async = true; } return arrowExpr; }, createMethodDefinition: function (propertyType, kind, key, value, computed) { return { type: Syntax.MethodDefinition, key: key, value: value, kind: kind, 'static': propertyType === ClassPropertyType.static, computed: computed }; }, createClassProperty: function (key, typeAnnotation, computed, isStatic) { return { type: Syntax.ClassProperty, key: key, typeAnnotation: typeAnnotation, computed: computed, static: isStatic }; }, createClassBody: function (body) { return { type: Syntax.ClassBody, body: body }; }, createClassImplements: function (id, typeParameters) { return { type: Syntax.ClassImplements, id: id, typeParameters: typeParameters }; }, createClassExpression: function (id, superClass, body, typeParameters, superTypeParameters, implemented) { return { type: Syntax.ClassExpression, id: id, superClass: superClass, body: body, typeParameters: typeParameters, superTypeParameters: superTypeParameters, implements: implemented }; }, createClassDeclaration: function (id, superClass, body, typeParameters, superTypeParameters, implemented) { return { type: Syntax.ClassDeclaration, id: id, superClass: superClass, body: body, typeParameters: typeParameters, superTypeParameters: superTypeParameters, implements: implemented }; }, createModuleSpecifier: function (token) { return { type: Syntax.ModuleSpecifier, value: token.value, raw: source.slice(token.range[0], token.range[1]) }; }, createExportSpecifier: function (id, name) { return { type: Syntax.ExportSpecifier, id: id, name: name }; }, createExportBatchSpecifier: function () { return { type: Syntax.ExportBatchSpecifier }; }, createImportDefaultSpecifier: function (id) { return { type: Syntax.ImportDefaultSpecifier, id: id }; }, createImportNamespaceSpecifier: function (id) { return { type: Syntax.ImportNamespaceSpecifier, id: id }; }, createExportDeclaration: function (isDefault, declaration, specifiers, src) { return { type: Syntax.ExportDeclaration, 'default': !!isDefault, declaration: declaration, specifiers: specifiers, source: src }; }, createImportSpecifier: function (id, name) { return { type: Syntax.ImportSpecifier, id: id, name: name }; }, createImportDeclaration: function (specifiers, src, isType) { return { type: Syntax.ImportDeclaration, specifiers: specifiers, source: src, isType: isType }; }, createYieldExpression: function (argument, dlg) { return { type: Syntax.YieldExpression, argument: argument, delegate: dlg }; }, createAwaitExpression: function (argument) { return { type: Syntax.AwaitExpression, argument: argument }; }, createComprehensionExpression: function (filter, blocks, body) { return { type: Syntax.ComprehensionExpression, filter: filter, blocks: blocks, body: body }; } }; // Return true if there is a line terminator before the next token. function peekLineTerminator() { var pos, line, start, found; pos = index; line = lineNumber; start = lineStart; skipComment(); found = lineNumber !== line; index = pos; lineNumber = line; lineStart = start; return found; } // Throw an exception function throwError(token, messageFormat) { var error, args = Array.prototype.slice.call(arguments, 2), msg = messageFormat.replace( /%(\d)/g, function (whole, idx) { assert(idx < args.length, 'Message reference must be in range'); return args[idx]; } ); if (typeof token.lineNumber === 'number') { error = new Error('Line ' + token.lineNumber + ': ' + msg); error.index = token.range[0]; error.lineNumber = token.lineNumber; error.column = token.range[0] - lineStart + 1; } else { error = new Error('Line ' + lineNumber + ': ' + msg); error.index = index; error.lineNumber = lineNumber; error.column = index - lineStart + 1; } error.description = msg; throw error; } function throwErrorTolerant() { try { throwError.apply(null, arguments); } catch (e) { if (extra.errors) { extra.errors.push(e); } else { throw e; } } } // Throw an exception because of the token. function throwUnexpected(token) { if (token.type === Token.EOF) { throwError(token, Messages.UnexpectedEOS); } if (token.type === Token.NumericLiteral) { throwError(token, Messages.UnexpectedNumber); } if (token.type === Token.StringLiteral || token.type === Token.JSXText) { throwError(token, Messages.UnexpectedString); } if (token.type === Token.Identifier) { throwError(token, Messages.UnexpectedIdentifier); } if (token.type === Token.Keyword) { if (isFutureReservedWord(token.value)) { throwError(token, Messages.UnexpectedReserved); } else if (strict && isStrictModeReservedWord(token.value)) { throwErrorTolerant(token, Messages.StrictReservedWord); return; } throwError(token, Messages.UnexpectedToken, token.value); } if (token.type === Token.Template) { throwError(token, Messages.UnexpectedTemplate, token.value.raw); } // BooleanLiteral, NullLiteral, or Punctuator. throwError(token, Messages.UnexpectedToken, token.value); } // Expect the next token to match the specified punctuator. // If not, an exception will be thrown. function expect(value) { var token = lex(); if (token.type !== Token.Punctuator || token.value !== value) { throwUnexpected(token); } } // Expect the next token to match the specified keyword. // If not, an exception will be thrown. function expectKeyword(keyword, contextual) { var token = lex(); if (token.type !== (contextual ? Token.Identifier : Token.Keyword) || token.value !== keyword) { throwUnexpected(token); } } // Expect the next token to match the specified contextual keyword. // If not, an exception will be thrown. function expectContextualKeyword(keyword) { return expectKeyword(keyword, true); } // Return true if the next token matches the specified punctuator. function match(value) { return lookahead.type === Token.Punctuator && lookahead.value === value; } // Return true if the next token matches the specified keyword function matchKeyword(keyword, contextual) { var expectedType = contextual ? Token.Identifier : Token.Keyword; return lookahead.type === expectedType && lookahead.value === keyword; } // Return true if the next token matches the specified contextual keyword function matchContextualKeyword(keyword) { return matchKeyword(keyword, true); } // Return true if the next token is an assignment operator function matchAssign() { var op; if (lookahead.type !== Token.Punctuator) { return false; } op = lookahead.value; return op === '=' || op === '*=' || op === '/=' || op === '%=' || op === '+=' || op === '-=' || op === '<<=' || op === '>>=' || op === '>>>=' || op === '&=' || op === '^=' || op === '|='; } // Note that 'yield' is treated as a keyword in strict mode, but a // contextual keyword (identifier) in non-strict mode, so we need to // use matchKeyword('yield', false) and matchKeyword('yield', true) // (i.e. matchContextualKeyword) appropriately. function matchYield() { return state.yieldAllowed && matchKeyword('yield', !strict); } function matchAsync() { var backtrackToken = lookahead, matches = false; if (matchContextualKeyword('async')) { lex(); // Make sure peekLineTerminator() starts after 'async'. matches = !peekLineTerminator(); rewind(backtrackToken); // Revert the lex(). } return matches; } function matchAwait() { return state.awaitAllowed && matchContextualKeyword('await'); } function consumeSemicolon() { var line, oldIndex = index, oldLineNumber = lineNumber, oldLineStart = lineStart, oldLookahead = lookahead; // Catch the very common case first: immediately a semicolon (char #59). if (source.charCodeAt(index) === 59) { lex(); return; } line = lineNumber; skipComment(); if (lineNumber !== line) { index = oldIndex; lineNumber = oldLineNumber; lineStart = oldLineStart; lookahead = oldLookahead; return; } if (match(';')) { lex(); return; } if (lookahead.type !== Token.EOF && !match('}')) { throwUnexpected(lookahead); } } // Return true if provided expression is LeftHandSideExpression function isLeftHandSide(expr) { return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression; } function isAssignableLeftHandSide(expr) { return isLeftHandSide(expr) || expr.type === Syntax.ObjectPattern || expr.type === Syntax.ArrayPattern; } // 11.1.4 Array Initialiser function parseArrayInitialiser() { var elements = [], blocks = [], filter = null, tmp, possiblecomprehension = true, marker = markerCreate(); expect('['); while (!match(']')) { if (lookahead.value === 'for' && lookahead.type === Token.Keyword) { if (!possiblecomprehension) { throwError({}, Messages.ComprehensionError); } matchKeyword('for'); tmp = parseForStatement({ignoreBody: true}); tmp.of = tmp.type === Syntax.ForOfStatement; tmp.type = Syntax.ComprehensionBlock; if (tmp.left.kind) { // can't be let or const throwError({}, Messages.ComprehensionError); } blocks.push(tmp); } else if (lookahead.value === 'if' && lookahead.type === Token.Keyword) { if (!possiblecomprehension) { throwError({}, Messages.ComprehensionError); } expectKeyword('if'); expect('('); filter = parseExpression(); expect(')'); } else if (lookahead.value === ',' && lookahead.type === Token.Punctuator) { possiblecomprehension = false; // no longer allowed. lex(); elements.push(null); } else { tmp = parseSpreadOrAssignmentExpression(); elements.push(tmp); if (tmp && tmp.type === Syntax.SpreadElement) { if (!match(']')) { throwError({}, Messages.ElementAfterSpreadElement); } } else if (!(match(']') || matchKeyword('for') || matchKeyword('if'))) { expect(','); // this lexes. possiblecomprehension = false; } } } expect(']'); if (filter && !blocks.length) { throwError({}, Messages.ComprehensionRequiresBlock); } if (blocks.length) { if (elements.length !== 1) { throwError({}, Messages.ComprehensionError); } return markerApply(marker, delegate.createComprehensionExpression(filter, blocks, elements[0])); } return markerApply(marker, delegate.createArrayExpression(elements)); } // 11.1.5 Object Initialiser function parsePropertyFunction(options) { var previousStrict, previousYieldAllowed, previousAwaitAllowed, params, defaults, body, marker = markerCreate(); previousStrict = strict; previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = options.generator; previousAwaitAllowed = state.awaitAllowed; state.awaitAllowed = options.async; params = options.params || []; defaults = options.defaults || []; body = parseConciseBody(); if (options.name && strict && isRestrictedWord(params[0].name)) { throwErrorTolerant(options.name, Messages.StrictParamName); } strict = previousStrict; state.yieldAllowed = previousYieldAllowed; state.awaitAllowed = previousAwaitAllowed; return markerApply(marker, delegate.createFunctionExpression( null, params, defaults, body, options.rest || null, options.generator, body.type !== Syntax.BlockStatement, options.async, options.returnType, options.typeParameters )); } function parsePropertyMethodFunction(options) { var previousStrict, tmp, method; previousStrict = strict; strict = true; tmp = parseParams(); if (tmp.stricted) { throwErrorTolerant(tmp.stricted, tmp.message); } method = parsePropertyFunction({ params: tmp.params, defaults: tmp.defaults, rest: tmp.rest, generator: options.generator, async: options.async, returnType: tmp.returnType, typeParameters: options.typeParameters }); strict = previousStrict; return method; } function parseObjectPropertyKey() { var marker = markerCreate(), token = lex(), propertyKey, result; // Note: This function is called only from parseObjectProperty(), where // EOF and Punctuator tokens are already filtered out. if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) { if (strict && token.octal) { throwErrorTolerant(token, Messages.StrictOctalLiteral); } return markerApply(marker, delegate.createLiteral(token)); } if (token.type === Token.Punctuator && token.value === '[') { // For computed properties we should skip the [ and ], and // capture in marker only the assignment expression itself. marker = markerCreate(); propertyKey = parseAssignmentExpression(); result = markerApply(marker, propertyKey); expect(']'); return result; } return markerApply(marker, delegate.createIdentifier(token.value)); } function parseObjectProperty() { var token, key, id, param, computed, marker = markerCreate(), returnType, typeParameters; token = lookahead; computed = (token.value === '[' && token.type === Token.Punctuator); if (token.type === Token.Identifier || computed || matchAsync()) { id = parseObjectPropertyKey(); if (match(':')) { lex(); return markerApply( marker, delegate.createProperty( 'init', id, parseAssignmentExpression(), false, false, computed ) ); } if (match('(') || match('<')) { if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } return markerApply( marker, delegate.createProperty( 'init', id, parsePropertyMethodFunction({ generator: false, async: false, typeParameters: typeParameters }), true, false, computed ) ); } // Property Assignment: Getter and Setter. if (token.value === 'get') { computed = (lookahead.value === '['); key = parseObjectPropertyKey(); expect('('); expect(')'); if (match(':')) { returnType = parseTypeAnnotation(); } return markerApply( marker, delegate.createProperty( 'get', key, parsePropertyFunction({ generator: false, async: false, returnType: returnType }), false, false, computed ) ); } if (token.value === 'set') { computed = (lookahead.value === '['); key = parseObjectPropertyKey(); expect('('); token = lookahead; param = [ parseTypeAnnotatableIdentifier() ]; expect(')'); if (match(':')) { returnType = parseTypeAnnotation(); } return markerApply( marker, delegate.createProperty( 'set', key, parsePropertyFunction({ params: param, generator: false, async: false, name: token, returnType: returnType }), false, false, computed ) ); } if (token.value === 'async') { computed = (lookahead.value === '['); key = parseObjectPropertyKey(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } return markerApply( marker, delegate.createProperty( 'init', key, parsePropertyMethodFunction({ generator: false, async: true, typeParameters: typeParameters }), true, false, computed ) ); } if (computed) { // Computed properties can only be used with full notation. throwUnexpected(lookahead); } return markerApply( marker, delegate.createProperty('init', id, id, false, true, false) ); } if (token.type === Token.EOF || token.type === Token.Punctuator) { if (!match('*')) { throwUnexpected(token); } lex(); computed = (lookahead.type === Token.Punctuator && lookahead.value === '['); id = parseObjectPropertyKey(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } if (!match('(')) { throwUnexpected(lex()); } return markerApply(marker, delegate.createProperty( 'init', id, parsePropertyMethodFunction({ generator: true, typeParameters: typeParameters }), true, false, computed )); } key = parseObjectPropertyKey(); if (match(':')) { lex(); return markerApply(marker, delegate.createProperty('init', key, parseAssignmentExpression(), false, false, false)); } if (match('(') || match('<')) { if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } return markerApply(marker, delegate.createProperty( 'init', key, parsePropertyMethodFunction({ generator: false, typeParameters: typeParameters }), true, false, false )); } throwUnexpected(lex()); } function parseObjectSpreadProperty() { var marker = markerCreate(); expect('...'); return markerApply(marker, delegate.createSpreadProperty(parseAssignmentExpression())); } function getFieldName(key) { var toString = String; if (key.type === Syntax.Identifier) { return key.name; } return toString(key.value); } function parseObjectInitialiser() { var properties = [], property, name, kind, storedKind, map = new StringMap(), marker = markerCreate(), toString = String; expect('{'); while (!match('}')) { if (match('...')) { property = parseObjectSpreadProperty(); } else { property = parseObjectProperty(); if (property.key.type === Syntax.Identifier) { name = property.key.name; } else { name = toString(property.key.value); } kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set; if (map.has(name)) { storedKind = map.get(name); if (storedKind === PropertyKind.Data) { if (strict && kind === PropertyKind.Data) { throwErrorTolerant({}, Messages.StrictDuplicateProperty); } else if (kind !== PropertyKind.Data) { throwErrorTolerant({}, Messages.AccessorDataProperty); } } else { if (kind === PropertyKind.Data) { throwErrorTolerant({}, Messages.AccessorDataProperty); } else if (storedKind & kind) { throwErrorTolerant({}, Messages.AccessorGetSet); } } map.set(name, storedKind | kind); } else { map.set(name, kind); } } properties.push(property); if (!match('}')) { expect(','); } } expect('}'); return markerApply(marker, delegate.createObjectExpression(properties)); } function parseTemplateElement(option) { var marker = markerCreate(), token = scanTemplateElement(option); if (strict && token.octal) { throwError(token, Messages.StrictOctalLiteral); } return markerApply(marker, delegate.createTemplateElement({ raw: token.value.raw, cooked: token.value.cooked }, token.tail)); } function parseTemplateLiteral() { var quasi, quasis, expressions, marker = markerCreate(); quasi = parseTemplateElement({ head: true }); quasis = [ quasi ]; expressions = []; while (!quasi.tail) { expressions.push(parseExpression()); quasi = parseTemplateElement({ head: false }); quasis.push(quasi); } return markerApply(marker, delegate.createTemplateLiteral(quasis, expressions)); } // 11.1.6 The Grouping Operator function parseGroupExpression() { var expr, marker, typeAnnotation; expect('('); ++state.parenthesizedCount; marker = markerCreate(); expr = parseExpression(); if (match(':')) { typeAnnotation = parseTypeAnnotation(); expr = markerApply(marker, delegate.createTypeCast( expr, typeAnnotation )); } expect(')'); return expr; } function matchAsyncFuncExprOrDecl() { var token; if (matchAsync()) { token = lookahead2(); if (token.type === Token.Keyword && token.value === 'function') { return true; } } return false; } // 11.1 Primary Expressions function parsePrimaryExpression() { var marker, type, token, expr; type = lookahead.type; if (type === Token.Identifier) { marker = markerCreate(); return markerApply(marker, delegate.createIdentifier(lex().value)); } if (type === Token.StringLiteral || type === Token.NumericLiteral) { if (strict && lookahead.octal) { throwErrorTolerant(lookahead, Messages.StrictOctalLiteral); } marker = markerCreate(); return markerApply(marker, delegate.createLiteral(lex())); } if (type === Token.Keyword) { if (matchKeyword('this')) { marker = markerCreate(); lex(); return markerApply(marker, delegate.createThisExpression()); } if (matchKeyword('function')) { return parseFunctionExpression(); } if (matchKeyword('class')) { return parseClassExpression(); } if (matchKeyword('super')) { marker = markerCreate(); lex(); return markerApply(marker, delegate.createIdentifier('super')); } } if (type === Token.BooleanLiteral) { marker = markerCreate(); token = lex(); token.value = (token.value === 'true'); return markerApply(marker, delegate.createLiteral(token)); } if (type === Token.NullLiteral) { marker = markerCreate(); token = lex(); token.value = null; return markerApply(marker, delegate.createLiteral(token)); } if (match('[')) { return parseArrayInitialiser(); } if (match('{')) { return parseObjectInitialiser(); } if (match('(')) { return parseGroupExpression(); } if (match('/') || match('/=')) { marker = markerCreate(); expr = delegate.createLiteral(scanRegExp()); peek(); return markerApply(marker, expr); } if (type === Token.Template) { return parseTemplateLiteral(); } if (match('<')) { return parseJSXElement(); } throwUnexpected(lex()); } // 11.2 Left-Hand-Side Expressions function parseArguments() { var args = [], arg; expect('('); if (!match(')')) { while (index < length) { arg = parseSpreadOrAssignmentExpression(); args.push(arg); if (match(')')) { break; } else if (arg.type === Syntax.SpreadElement) { throwError({}, Messages.ElementAfterSpreadElement); } expect(','); } } expect(')'); return args; } function parseSpreadOrAssignmentExpression() { if (match('...')) { var marker = markerCreate(); lex(); return markerApply(marker, delegate.createSpreadElement(parseAssignmentExpression())); } return parseAssignmentExpression(); } function parseNonComputedProperty() { var marker = markerCreate(), token = lex(); if (!isIdentifierName(token)) { throwUnexpected(token); } return markerApply(marker, delegate.createIdentifier(token.value)); } function parseNonComputedMember() { expect('.'); return parseNonComputedProperty(); } function parseComputedMember() { var expr; expect('['); expr = parseExpression(); expect(']'); return expr; } function parseNewExpression() { var callee, args, marker = markerCreate(); expectKeyword('new'); callee = parseLeftHandSideExpression(); args = match('(') ? parseArguments() : []; return markerApply(marker, delegate.createNewExpression(callee, args)); } function parseLeftHandSideExpressionAllowCall() { var expr, args, marker = markerCreate(); expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); while (match('.') || match('[') || match('(') || lookahead.type === Token.Template) { if (match('(')) { args = parseArguments(); expr = markerApply(marker, delegate.createCallExpression(expr, args)); } else if (match('[')) { expr = markerApply(marker, delegate.createMemberExpression('[', expr, parseComputedMember())); } else if (match('.')) { expr = markerApply(marker, delegate.createMemberExpression('.', expr, parseNonComputedMember())); } else { expr = markerApply(marker, delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral())); } } return expr; } function parseLeftHandSideExpression() { var expr, marker = markerCreate(); expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); while (match('.') || match('[') || lookahead.type === Token.Template) { if (match('[')) { expr = markerApply(marker, delegate.createMemberExpression('[', expr, parseComputedMember())); } else if (match('.')) { expr = markerApply(marker, delegate.createMemberExpression('.', expr, parseNonComputedMember())); } else { expr = markerApply(marker, delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral())); } } return expr; } // 11.3 Postfix Expressions function parsePostfixExpression() { var marker = markerCreate(), expr = parseLeftHandSideExpressionAllowCall(), token; if (lookahead.type !== Token.Punctuator) { return expr; } if ((match('++') || match('--')) && !peekLineTerminator()) { // 11.3.1, 11.3.2 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { throwErrorTolerant({}, Messages.StrictLHSPostfix); } if (!isLeftHandSide(expr)) { throwError({}, Messages.InvalidLHSInAssignment); } token = lex(); expr = markerApply(marker, delegate.createPostfixExpression(token.value, expr)); } return expr; } // 11.4 Unary Operators function parseUnaryExpression() { var marker, token, expr; if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) { return parsePostfixExpression(); } if (match('++') || match('--')) { marker = markerCreate(); token = lex(); expr = parseUnaryExpression(); // 11.4.4, 11.4.5 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { throwErrorTolerant({}, Messages.StrictLHSPrefix); } if (!isLeftHandSide(expr)) { throwError({}, Messages.InvalidLHSInAssignment); } return markerApply(marker, delegate.createUnaryExpression(token.value, expr)); } if (match('+') || match('-') || match('~') || match('!')) { marker = markerCreate(); token = lex(); expr = parseUnaryExpression(); return markerApply(marker, delegate.createUnaryExpression(token.value, expr)); } if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) { marker = markerCreate(); token = lex(); expr = parseUnaryExpression(); expr = markerApply(marker, delegate.createUnaryExpression(token.value, expr)); if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) { throwErrorTolerant({}, Messages.StrictDelete); } return expr; } return parsePostfixExpression(); } function binaryPrecedence(token, allowIn) { var prec = 0; if (token.type !== Token.Punctuator && token.type !== Token.Keyword) { return 0; } switch (token.value) { case '||': prec = 1; break; case '&&': prec = 2; break; case '|': prec = 3; break; case '^': prec = 4; break; case '&': prec = 5; break; case '==': case '!=': case '===': case '!==': prec = 6; break; case '<': case '>': case '<=': case '>=': case 'instanceof': prec = 7; break; case 'in': prec = allowIn ? 7 : 0; break; case '<<': case '>>': case '>>>': prec = 8; break; case '+': case '-': prec = 9; break; case '*': case '/': case '%': prec = 11; break; default: break; } return prec; } // 11.5 Multiplicative Operators // 11.6 Additive Operators // 11.7 Bitwise Shift Operators // 11.8 Relational Operators // 11.9 Equality Operators // 11.10 Binary Bitwise Operators // 11.11 Binary Logical Operators function parseBinaryExpression() { var expr, token, prec, previousAllowIn, stack, right, operator, left, i, marker, markers; previousAllowIn = state.allowIn; state.allowIn = true; marker = markerCreate(); left = parseUnaryExpression(); token = lookahead; prec = binaryPrecedence(token, previousAllowIn); if (prec === 0) { return left; } token.prec = prec; lex(); markers = [marker, markerCreate()]; right = parseUnaryExpression(); stack = [left, token, right]; while ((prec = binaryPrecedence(lookahead, previousAllowIn)) > 0) { // Reduce: make a binary expression from the three topmost entries. while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) { right = stack.pop(); operator = stack.pop().value; left = stack.pop(); expr = delegate.createBinaryExpression(operator, left, right); markers.pop(); marker = markers.pop(); markerApply(marker, expr); stack.push(expr); markers.push(marker); } // Shift. token = lex(); token.prec = prec; stack.push(token); markers.push(markerCreate()); expr = parseUnaryExpression(); stack.push(expr); } state.allowIn = previousAllowIn; // Final reduce to clean-up the stack. i = stack.length - 1; expr = stack[i]; markers.pop(); while (i > 1) { expr = delegate.createBinaryExpression(stack[i - 1].value, stack[i - 2], expr); i -= 2; marker = markers.pop(); markerApply(marker, expr); } return expr; } // 11.12 Conditional Operator function parseConditionalExpression() { var expr, previousAllowIn, consequent, alternate, marker = markerCreate(); expr = parseBinaryExpression(); if (match('?')) { lex(); previousAllowIn = state.allowIn; state.allowIn = true; consequent = parseAssignmentExpression(); state.allowIn = previousAllowIn; expect(':'); alternate = parseAssignmentExpression(); expr = markerApply(marker, delegate.createConditionalExpression(expr, consequent, alternate)); } return expr; } // 11.13 Assignment Operators // 12.14.5 AssignmentPattern function reinterpretAsAssignmentBindingPattern(expr) { var i, len, property, element; if (expr.type === Syntax.ObjectExpression) { expr.type = Syntax.ObjectPattern; for (i = 0, len = expr.properties.length; i < len; i += 1) { property = expr.properties[i]; if (property.type === Syntax.SpreadProperty) { if (i < len - 1) { throwError({}, Messages.PropertyAfterSpreadProperty); } reinterpretAsAssignmentBindingPattern(property.argument); } else { if (property.kind !== 'init') { throwError({}, Messages.InvalidLHSInAssignment); } reinterpretAsAssignmentBindingPattern(property.value); } } } else if (expr.type === Syntax.ArrayExpression) { expr.type = Syntax.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 === Syntax.Identifier) { if (isRestrictedWord(expr.name)) { throwError({}, Messages.InvalidLHSInAssignment); } } else if (expr.type === Syntax.SpreadElement) { reinterpretAsAssignmentBindingPattern(expr.argument); if (expr.argument.type === Syntax.ObjectPattern) { throwError({}, Messages.ObjectPatternAsSpread); } } else { /* istanbul ignore else */ if (expr.type !== Syntax.MemberExpression && expr.type !== Syntax.CallExpression && expr.type !== Syntax.NewExpression) { throwError({}, Messages.InvalidLHSInAssignment); } } } // 13.2.3 BindingPattern function reinterpretAsDestructuredParameter(options, expr) { var i, len, property, element; if (expr.type === Syntax.ObjectExpression) { expr.type = Syntax.ObjectPattern; for (i = 0, len = expr.properties.length; i < len; i += 1) { property = expr.properties[i]; if (property.type === Syntax.SpreadProperty) { if (i < len - 1) { throwError({}, Messages.PropertyAfterSpreadProperty); } reinterpretAsDestructuredParameter(options, property.argument); } else { if (property.kind !== 'init') { throwError({}, Messages.InvalidLHSInFormalsList); } reinterpretAsDestructuredParameter(options, property.value); } } } else if (expr.type === Syntax.ArrayExpression) { expr.type = Syntax.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 === Syntax.Identifier) { validateParam(options, expr, expr.name); } else if (expr.type === Syntax.SpreadElement) { // BindingRestElement only allows BindingIdentifier if (expr.argument.type !== Syntax.Identifier) { throwError({}, Messages.InvalidLHSInFormalsList); } validateParam(options, expr.argument, expr.argument.name); } else { throwError({}, Messages.InvalidLHSInFormalsList); } } 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 === Syntax.Identifier) { params.push(param); defaults.push(null); validateParam(options, param, param.name); } else if (param.type === Syntax.ObjectExpression || param.type === Syntax.ArrayExpression) { reinterpretAsDestructuredParameter(options, param); params.push(param); defaults.push(null); } else if (param.type === Syntax.SpreadElement) { assert(i === len - 1, 'It is guaranteed that SpreadElement is last element by parseExpression'); if (param.argument.type !== Syntax.Identifier) { throwError({}, Messages.InvalidLHSInFormalsList); } reinterpretAsDestructuredParameter(options, param.argument); rest = param.argument; } else if (param.type === Syntax.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 ); } 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, previousYieldAllowed, previousAwaitAllowed, body; expect('=>'); previousStrict = strict; previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = false; previousAwaitAllowed = state.awaitAllowed; state.awaitAllowed = !!options.async; body = parseConciseBody(); if (strict && options.firstRestricted) { throwError(options.firstRestricted, options.message); } if (strict && options.stricted) { throwErrorTolerant(options.stricted, options.message); } strict = previousStrict; state.yieldAllowed = previousYieldAllowed; state.awaitAllowed = previousAwaitAllowed; return markerApply(marker, delegate.createArrowFunctionExpression( options.params, options.defaults, body, options.rest, body.type !== Syntax.BlockStatement, !!options.async )); } function parseAssignmentExpression() { var marker, expr, token, params, oldParenthesizedCount, startsWithParen = false, backtrackToken = lookahead, possiblyAsync = false; if (matchYield()) { return parseYieldExpression(); } if (matchAwait()) { return parseAwaitExpression(); } oldParenthesizedCount = state.parenthesizedCount; marker = markerCreate(); if (matchAsyncFuncExprOrDecl()) { return parseFunctionExpression(); } if (matchAsync()) { // We can't be completely sure that this 'async' token is // actually a contextual keyword modifying a function // expression, so we might have to un-lex() it later by // calling rewind(backtrackToken). possiblyAsync = true; lex(); } if (match('(')) { token = lookahead2(); if ((token.type === Token.Punctuator && token.value === ')') || token.value === '...') { params = parseParams(); if (!match('=>')) { throwUnexpected(lex()); } params.async = possiblyAsync; return parseArrowFunctionExpression(params, marker); } startsWithParen = true; } token = lookahead; // If the 'async' keyword is not followed by a '(' character or an // identifier, then it can't be an arrow function modifier, and we // should interpret it as a normal identifer. if (possiblyAsync && !match('(') && token.type !== Token.Identifier) { possiblyAsync = false; rewind(backtrackToken); } expr = parseConditionalExpression(); if (match('=>') && (state.parenthesizedCount === oldParenthesizedCount || state.parenthesizedCount === (oldParenthesizedCount + 1))) { if (expr.type === Syntax.Identifier) { params = reinterpretAsCoverFormalsList([ expr ]); } else if (expr.type === Syntax.AssignmentExpression || expr.type === Syntax.ArrayExpression || expr.type === Syntax.ObjectExpression) { if (!startsWithParen) { throwUnexpected(lex()); } params = reinterpretAsCoverFormalsList([ expr ]); } else if (expr.type === Syntax.SequenceExpression) { params = reinterpretAsCoverFormalsList(expr.expressions); } if (params) { params.async = possiblyAsync; return parseArrowFunctionExpression(params, marker); } } // If we haven't returned by now, then the 'async' keyword was not // a function modifier, and we should rewind and interpret it as a // normal identifier. if (possiblyAsync) { possiblyAsync = false; rewind(backtrackToken); expr = parseConditionalExpression(); } if (matchAssign()) { // 11.13.1 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { throwErrorTolerant(token, Messages.StrictLHSAssignment); } // ES.next draf 11.13 Runtime Semantics step 1 if (match('=') && (expr.type === Syntax.ObjectExpression || expr.type === Syntax.ArrayExpression)) { reinterpretAsAssignmentBindingPattern(expr); } else if (!isLeftHandSide(expr)) { throwError({}, Messages.InvalidLHSInAssignment); } expr = markerApply(marker, delegate.createAssignmentExpression(lex().value, expr, parseAssignmentExpression())); } return expr; } // 11.14 Comma Operator function parseExpression() { var marker, expr, expressions, sequence, spreadFound; marker = markerCreate(); expr = parseAssignmentExpression(); expressions = [ expr ]; if (match(',')) { while (index < length) { if (!match(',')) { break; } lex(); expr = parseSpreadOrAssignmentExpression(); expressions.push(expr); if (expr.type === Syntax.SpreadElement) { spreadFound = true; if (!match(')')) { throwError({}, Messages.ElementAfterSpreadElement); } break; } } sequence = markerApply(marker, delegate.createSequenceExpression(expressions)); } if (spreadFound && lookahead2().value !== '=>') { throwError({}, Messages.IllegalSpread); } return sequence || expr; } // 12.1 Block function parseStatementList() { var list = [], statement; while (index < length) { if (match('}')) { break; } statement = parseSourceElement(); if (typeof statement === 'undefined') { break; } list.push(statement); } return list; } function parseBlock() { var block, marker = markerCreate(); expect('{'); block = parseStatementList(); expect('}'); return markerApply(marker, delegate.createBlockStatement(block)); } // 12.2 Variable Statement function parseTypeParameterDeclaration() { var marker = markerCreate(), paramTypes = []; expect('<'); while (!match('>')) { paramTypes.push(parseVariableIdentifier()); if (!match('>')) { expect(','); } } expect('>'); return markerApply(marker, delegate.createTypeParameterDeclaration( paramTypes )); } function parseTypeParameterInstantiation() { var marker = markerCreate(), oldInType = state.inType, paramTypes = []; state.inType = true; expect('<'); while (!match('>')) { paramTypes.push(parseType()); if (!match('>')) { expect(','); } } expect('>'); state.inType = oldInType; return markerApply(marker, delegate.createTypeParameterInstantiation( paramTypes )); } function parseObjectTypeIndexer(marker, isStatic) { var id, key, value; expect('['); id = parseObjectPropertyKey(); expect(':'); key = parseType(); expect(']'); expect(':'); value = parseType(); return markerApply(marker, delegate.createObjectTypeIndexer( id, key, value, isStatic )); } function parseObjectTypeMethodish(marker) { var params = [], rest = null, returnType, typeParameters = null; if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } expect('('); while (lookahead.type === Token.Identifier) { params.push(parseFunctionTypeParam()); if (!match(')')) { expect(','); } } if (match('...')) { lex(); rest = parseFunctionTypeParam(); } expect(')'); expect(':'); returnType = parseType(); return markerApply(marker, delegate.createFunctionTypeAnnotation( params, returnType, rest, typeParameters )); } function parseObjectTypeMethod(marker, isStatic, key) { var optional = false, value; value = parseObjectTypeMethodish(marker); return markerApply(marker, delegate.createObjectTypeProperty( key, value, optional, isStatic )); } function parseObjectTypeCallProperty(marker, isStatic) { var valueMarker = markerCreate(); return markerApply(marker, delegate.createObjectTypeCallProperty( parseObjectTypeMethodish(valueMarker), isStatic )); } function parseObjectType(allowStatic) { var callProperties = [], indexers = [], marker, optional = false, properties = [], propertyKey, propertyTypeAnnotation, token, isStatic, matchStatic; expect('{'); while (!match('}')) { marker = markerCreate(); matchStatic = strict ? matchKeyword('static') : matchContextualKeyword('static'); if (allowStatic && matchStatic) { token = lex(); isStatic = true; } if (match('[')) { indexers.push(parseObjectTypeIndexer(marker, isStatic)); } else if (match('(') || match('<')) { callProperties.push(parseObjectTypeCallProperty(marker, allowStatic)); } else { if (isStatic && match(':')) { propertyKey = markerApply(marker, delegate.createIdentifier(token)); throwErrorTolerant(token, Messages.StrictReservedWord); } else { propertyKey = parseObjectPropertyKey(); } if (match('<') || match('(')) { // This is a method property properties.push(parseObjectTypeMethod(marker, isStatic, propertyKey)); } else { if (match('?')) { lex(); optional = true; } expect(':'); propertyTypeAnnotation = parseType(); properties.push(markerApply(marker, delegate.createObjectTypeProperty( propertyKey, propertyTypeAnnotation, optional, isStatic ))); } } if (match(';')) { lex(); } else if (!match('}')) { throwUnexpected(lookahead); } } expect('}'); return delegate.createObjectTypeAnnotation( properties, indexers, callProperties ); } function parseGenericType() { var marker = markerCreate(), typeParameters = null, typeIdentifier; typeIdentifier = parseVariableIdentifier(); while (match('.')) { expect('.'); typeIdentifier = markerApply(marker, delegate.createQualifiedTypeIdentifier( typeIdentifier, parseVariableIdentifier() )); } if (match('<')) { typeParameters = parseTypeParameterInstantiation(); } return markerApply(marker, delegate.createGenericTypeAnnotation( typeIdentifier, typeParameters )); } function parseVoidType() { var marker = markerCreate(); expectKeyword('void'); return markerApply(marker, delegate.createVoidTypeAnnotation()); } function parseTypeofType() { var argument, marker = markerCreate(); expectKeyword('typeof'); argument = parsePrimaryType(); return markerApply(marker, delegate.createTypeofTypeAnnotation( argument )); } function parseTupleType() { var marker = markerCreate(), types = []; expect('['); // We allow trailing commas while (index < length && !match(']')) { types.push(parseType()); if (match(']')) { break; } expect(','); } expect(']'); return markerApply(marker, delegate.createTupleTypeAnnotation( types )); } function parseFunctionTypeParam() { var marker = markerCreate(), name, optional = false, typeAnnotation; name = parseVariableIdentifier(); if (match('?')) { lex(); optional = true; } expect(':'); typeAnnotation = parseType(); return markerApply(marker, delegate.createFunctionTypeParam( name, typeAnnotation, optional )); } function parseFunctionTypeParams() { var ret = { params: [], rest: null }; while (lookahead.type === Token.Identifier) { ret.params.push(parseFunctionTypeParam()); if (!match(')')) { expect(','); } } if (match('...')) { lex(); ret.rest = parseFunctionTypeParam(); } return ret; } // The parsing of types roughly parallels the parsing of expressions, and // primary types are kind of like primary expressions...they're the // primitives with which other types are constructed. function parsePrimaryType() { var params = null, returnType = null, marker = markerCreate(), rest = null, tmp, typeParameters, token, type, isGroupedType = false; switch (lookahead.type) { case Token.Identifier: switch (lookahead.value) { case 'any': lex(); return markerApply(marker, delegate.createAnyTypeAnnotation()); case 'bool': // fallthrough case 'boolean': lex(); return markerApply(marker, delegate.createBooleanTypeAnnotation()); case 'number': lex(); return markerApply(marker, delegate.createNumberTypeAnnotation()); case 'string': lex(); return markerApply(marker, delegate.createStringTypeAnnotation()); } return markerApply(marker, parseGenericType()); case Token.Punctuator: switch (lookahead.value) { case '{': return markerApply(marker, parseObjectType()); case '[': return parseTupleType(); case '<': typeParameters = parseTypeParameterDeclaration(); expect('('); tmp = parseFunctionTypeParams(); params = tmp.params; rest = tmp.rest; expect(')'); expect('=>'); returnType = parseType(); return markerApply(marker, delegate.createFunctionTypeAnnotation( params, returnType, rest, typeParameters )); case '(': lex(); // Check to see if this is actually a grouped type if (!match(')') && !match('...')) { if (lookahead.type === Token.Identifier) { token = lookahead2(); isGroupedType = token.value !== '?' && token.value !== ':'; } else { isGroupedType = true; } } if (isGroupedType) { type = parseType(); expect(')'); // If we see a => next then someone was probably confused about // function types, so we can provide a better error message if (match('=>')) { throwError({}, Messages.ConfusedAboutFunctionType); } return type; } tmp = parseFunctionTypeParams(); params = tmp.params; rest = tmp.rest; expect(')'); expect('=>'); returnType = parseType(); return markerApply(marker, delegate.createFunctionTypeAnnotation( params, returnType, rest, null /* typeParameters */ )); } break; case Token.Keyword: switch (lookahead.value) { case 'void': return markerApply(marker, parseVoidType()); case 'typeof': return markerApply(marker, parseTypeofType()); } break; case Token.StringLiteral: token = lex(); if (token.octal) { throwError(token, Messages.StrictOctalLiteral); } return markerApply(marker, delegate.createStringLiteralTypeAnnotation( token )); } throwUnexpected(lookahead); } function parsePostfixType() { var marker = markerCreate(), t = parsePrimaryType(); if (match('[')) { expect('['); expect(']'); return markerApply(marker, delegate.createArrayTypeAnnotation(t)); } return t; } function parsePrefixType() { var marker = markerCreate(); if (match('?')) { lex(); return markerApply(marker, delegate.createNullableTypeAnnotation( parsePrefixType() )); } return parsePostfixType(); } function parseIntersectionType() { var marker = markerCreate(), type, types; type = parsePrefixType(); types = [type]; while (match('&')) { lex(); types.push(parsePrefixType()); } return types.length === 1 ? type : markerApply(marker, delegate.createIntersectionTypeAnnotation( types )); } function parseUnionType() { var marker = markerCreate(), type, types; type = parseIntersectionType(); types = [type]; while (match('|')) { lex(); types.push(parseIntersectionType()); } return types.length === 1 ? type : markerApply(marker, delegate.createUnionTypeAnnotation( types )); } function parseType() { var oldInType = state.inType, type; state.inType = true; type = parseUnionType(); state.inType = oldInType; return type; } function parseTypeAnnotation() { var marker = markerCreate(), type; expect(':'); type = parseType(); return markerApply(marker, delegate.createTypeAnnotation(type)); } function parseVariableIdentifier() { var marker = markerCreate(), token = lex(); if (token.type !== Token.Identifier) { throwUnexpected(token); } return markerApply(marker, delegate.createIdentifier(token.value)); } function parseTypeAnnotatableIdentifier(requireTypeAnnotation, canBeOptionalParam) { var marker = markerCreate(), ident = parseVariableIdentifier(), isOptionalParam = false; if (canBeOptionalParam && match('?')) { expect('?'); isOptionalParam = true; } if (requireTypeAnnotation || match(':')) { ident.typeAnnotation = parseTypeAnnotation(); ident = markerApply(marker, ident); } if (isOptionalParam) { ident.optional = true; ident = markerApply(marker, ident); } return ident; } function parseVariableDeclaration(kind) { var id, marker = markerCreate(), init = null, typeAnnotationMarker = markerCreate(); if (match('{')) { id = parseObjectInitialiser(); reinterpretAsAssignmentBindingPattern(id); if (match(':')) { id.typeAnnotation = parseTypeAnnotation(); markerApply(typeAnnotationMarker, id); } } else if (match('[')) { id = parseArrayInitialiser(); reinterpretAsAssignmentBindingPattern(id); if (match(':')) { id.typeAnnotation = parseTypeAnnotation(); markerApply(typeAnnotationMarker, id); } } else { /* istanbul ignore next */ id = state.allowKeyword ? parseNonComputedProperty() : parseTypeAnnotatableIdentifier(); // 12.2.1 if (strict && isRestrictedWord(id.name)) { throwErrorTolerant({}, Messages.StrictVarName); } } if (kind === 'const') { if (!match('=')) { throwError({}, Messages.NoUninitializedConst); } expect('='); init = parseAssignmentExpression(); } else if (match('=')) { lex(); init = parseAssignmentExpression(); } return markerApply(marker, delegate.createVariableDeclarator(id, init)); } function parseVariableDeclarationList(kind) { var list = []; do { list.push(parseVariableDeclaration(kind)); if (!match(',')) { break; } lex(); } while (index < length); return list; } function parseVariableStatement() { var declarations, marker = markerCreate(); expectKeyword('var'); declarations = parseVariableDeclarationList(); consumeSemicolon(); return markerApply(marker, delegate.createVariableDeclaration(declarations, 'var')); } // kind may be `const` or `let` // Both are experimental and not in the specification yet. // see http://wiki.ecmascript.org/doku.php?id=harmony:const // and http://wiki.ecmascript.org/doku.php?id=harmony:let function parseConstLetDeclaration(kind) { var declarations, marker = markerCreate(); expectKeyword(kind); declarations = parseVariableDeclarationList(kind); consumeSemicolon(); return markerApply(marker, delegate.createVariableDeclaration(declarations, kind)); } // people.mozilla.org/~jorendorff/es6-draft.html function parseModuleSpecifier() { var marker = markerCreate(), specifier; if (lookahead.type !== Token.StringLiteral) { throwError({}, Messages.InvalidModuleSpecifier); } specifier = delegate.createModuleSpecifier(lookahead); lex(); return markerApply(marker, specifier); } function parseExportBatchSpecifier() { var marker = markerCreate(); expect('*'); return markerApply(marker, delegate.createExportBatchSpecifier()); } function parseExportSpecifier() { var id, name = null, marker = markerCreate(), from; if (matchKeyword('default')) { lex(); id = markerApply(marker, delegate.createIdentifier('default')); // export {default} from "something"; } else { id = parseVariableIdentifier(); } if (matchContextualKeyword('as')) { lex(); name = parseNonComputedProperty(); } return markerApply(marker, delegate.createExportSpecifier(id, name)); } function parseExportDeclaration() { var declaration = null, possibleIdentifierToken, sourceElement, isExportFromIdentifier, src = null, specifiers = [], marker = markerCreate(); expectKeyword('export'); if (matchKeyword('default')) { // covers: // export default ... lex(); if (matchKeyword('function') || matchKeyword('class')) { possibleIdentifierToken = lookahead2(); if (isIdentifierName(possibleIdentifierToken)) { // covers: // export default function foo () {} // export default class foo {} sourceElement = parseSourceElement(); return markerApply(marker, delegate.createExportDeclaration(true, sourceElement, [sourceElement.id], null)); } // covers: // export default function () {} // export default class {} switch (lookahead.value) { case 'class': return markerApply(marker, delegate.createExportDeclaration(true, parseClassExpression(), [], null)); case 'function': return markerApply(marker, delegate.createExportDeclaration(true, parseFunctionExpression(), [], null)); } } if (matchContextualKeyword('from')) { throwError({}, Messages.UnexpectedToken, lookahead.value); } // covers: // export default {}; // export default []; if (match('{')) { declaration = parseObjectInitialiser(); } else if (match('[')) { declaration = parseArrayInitialiser(); } else { declaration = parseAssignmentExpression(); } consumeSemicolon(); return markerApply(marker, delegate.createExportDeclaration(true, declaration, [], null)); } // non-default export if (lookahead.type === Token.Keyword || matchContextualKeyword('type')) { // covers: // export var f = 1; switch (lookahead.value) { case 'type': case 'let': case 'const': case 'var': case 'class': case 'function': return markerApply(marker, delegate.createExportDeclaration(false, parseSourceElement(), specifiers, null)); } } if (match('*')) { // covers: // export * from "foo"; specifiers.push(parseExportBatchSpecifier()); if (!matchContextualKeyword('from')) { throwError({}, lookahead.value ? Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value); } lex(); src = parseModuleSpecifier(); consumeSemicolon(); return markerApply(marker, delegate.createExportDeclaration(false, null, specifiers, src)); } expect('{'); if (!match('}')) { do { isExportFromIdentifier = isExportFromIdentifier || matchKeyword('default'); specifiers.push(parseExportSpecifier()); } while (match(',') && lex()); } expect('}'); if (matchContextualKeyword('from')) { // covering: // export {default} from "foo"; // export {foo} from "foo"; lex(); src = parseModuleSpecifier(); consumeSemicolon(); } else if (isExportFromIdentifier) { // covering: // export {default}; // missing fromClause throwError({}, lookahead.value ? Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value); } else { // cover // export {foo}; consumeSemicolon(); } return markerApply(marker, delegate.createExportDeclaration(false, declaration, specifiers, src)); } function parseImportSpecifier() { // import {} ...; var id, name = null, marker = markerCreate(); id = parseNonComputedProperty(); if (matchContextualKeyword('as')) { lex(); name = parseVariableIdentifier(); } return markerApply(marker, delegate.createImportSpecifier(id, name)); } function parseNamedImports() { var specifiers = []; // {foo, bar as bas} expect('{'); if (!match('}')) { do { specifiers.push(parseImportSpecifier()); } while (match(',') && lex()); } expect('}'); return specifiers; } function parseImportDefaultSpecifier() { // import ...; var id, marker = markerCreate(); id = parseNonComputedProperty(); return markerApply(marker, delegate.createImportDefaultSpecifier(id)); } function parseImportNamespaceSpecifier() { // import <* as foo> ...; var id, marker = markerCreate(); expect('*'); if (!matchContextualKeyword('as')) { throwError({}, Messages.NoAsAfterImportNamespace); } lex(); id = parseNonComputedProperty(); return markerApply(marker, delegate.createImportNamespaceSpecifier(id)); } function parseImportDeclaration() { var specifiers, src, marker = markerCreate(), isType = false, token2; expectKeyword('import'); if (matchContextualKeyword('type')) { token2 = lookahead2(); if ((token2.type === Token.Identifier && token2.value !== 'from') || (token2.type === Token.Punctuator && (token2.value === '{' || token2.value === '*'))) { isType = true; lex(); } } specifiers = []; if (lookahead.type === Token.StringLiteral) { // covers: // import "foo"; src = parseModuleSpecifier(); consumeSemicolon(); return markerApply(marker, delegate.createImportDeclaration(specifiers, src, isType)); } if (!matchKeyword('default') && isIdentifierName(lookahead)) { // covers: // import foo // import foo, ... specifiers.push(parseImportDefaultSpecifier()); if (match(',')) { lex(); } } if (match('*')) { // covers: // import foo, * as foo // import * as foo specifiers.push(parseImportNamespaceSpecifier()); } else if (match('{')) { // covers: // import foo, {bar} // import {bar} specifiers = specifiers.concat(parseNamedImports()); } if (!matchContextualKeyword('from')) { throwError({}, lookahead.value ? Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value); } lex(); src = parseModuleSpecifier(); consumeSemicolon(); return markerApply(marker, delegate.createImportDeclaration(specifiers, src, isType)); } // 12.3 Empty Statement function parseEmptyStatement() { var marker = markerCreate(); expect(';'); return markerApply(marker, delegate.createEmptyStatement()); } // 12.4 Expression Statement function parseExpressionStatement() { var marker = markerCreate(), expr = parseExpression(); consumeSemicolon(); return markerApply(marker, delegate.createExpressionStatement(expr)); } // 12.5 If statement function parseIfStatement() { var test, consequent, alternate, marker = markerCreate(); expectKeyword('if'); expect('('); test = parseExpression(); expect(')'); consequent = parseStatement(); if (matchKeyword('else')) { lex(); alternate = parseStatement(); } else { alternate = null; } return markerApply(marker, delegate.createIfStatement(test, consequent, alternate)); } // 12.6 Iteration Statements function parseDoWhileStatement() { var body, test, oldInIteration, marker = markerCreate(); expectKeyword('do'); oldInIteration = state.inIteration; state.inIteration = true; body = parseStatement(); state.inIteration = oldInIteration; expectKeyword('while'); expect('('); test = parseExpression(); expect(')'); if (match(';')) { lex(); } return markerApply(marker, delegate.createDoWhileStatement(body, test)); } function parseWhileStatement() { var test, body, oldInIteration, marker = markerCreate(); expectKeyword('while'); expect('('); test = parseExpression(); expect(')'); oldInIteration = state.inIteration; state.inIteration = true; body = parseStatement(); state.inIteration = oldInIteration; return markerApply(marker, delegate.createWhileStatement(test, body)); } function parseForVariableDeclaration() { var marker = markerCreate(), token = lex(), declarations = parseVariableDeclarationList(); return markerApply(marker, delegate.createVariableDeclaration(declarations, token.value)); } function parseForStatement(opts) { var init, test, update, left, right, body, operator, oldInIteration, marker = markerCreate(); init = test = update = null; expectKeyword('for'); // http://wiki.ecmascript.org/doku.php?id=proposals:iterators_and_generators&s=each if (matchContextualKeyword('each')) { throwError({}, Messages.EachNotAllowed); } expect('('); if (match(';')) { lex(); } else { if (matchKeyword('var') || matchKeyword('let') || matchKeyword('const')) { state.allowIn = false; init = parseForVariableDeclaration(); state.allowIn = true; if (init.declarations.length === 1) { if (matchKeyword('in') || matchContextualKeyword('of')) { operator = lookahead; if (!((operator.value === 'in' || init.kind !== 'var') && init.declarations[0].init)) { lex(); left = init; right = parseExpression(); init = null; } } } } else { state.allowIn = false; init = parseExpression(); state.allowIn = true; if (matchContextualKeyword('of')) { operator = lex(); left = init; right = parseExpression(); init = null; } else if (matchKeyword('in')) { // LeftHandSideExpression if (!isAssignableLeftHandSide(init)) { throwError({}, Messages.InvalidLHSInForIn); } operator = lex(); left = init; right = parseExpression(); init = null; } } if (typeof left === 'undefined') { expect(';'); } } if (typeof left === 'undefined') { if (!match(';')) { test = parseExpression(); } expect(';'); if (!match(')')) { update = parseExpression(); } } expect(')'); oldInIteration = state.inIteration; state.inIteration = true; if (!(opts !== undefined && opts.ignoreBody)) { body = parseStatement(); } state.inIteration = oldInIteration; if (typeof left === 'undefined') { return markerApply(marker, delegate.createForStatement(init, test, update, body)); } if (operator.value === 'in') { return markerApply(marker, delegate.createForInStatement(left, right, body)); } return markerApply(marker, delegate.createForOfStatement(left, right, body)); } // 12.7 The continue statement function parseContinueStatement() { var label = null, marker = markerCreate(); expectKeyword('continue'); // Optimize the most common form: 'continue;'. if (source.charCodeAt(index) === 59) { lex(); if (!state.inIteration) { throwError({}, Messages.IllegalContinue); } return markerApply(marker, delegate.createContinueStatement(null)); } if (peekLineTerminator()) { if (!state.inIteration) { throwError({}, Messages.IllegalContinue); } return markerApply(marker, delegate.createContinueStatement(null)); } if (lookahead.type === Token.Identifier) { label = parseVariableIdentifier(); if (!state.labelSet.has(label.name)) { throwError({}, Messages.UnknownLabel, label.name); } } consumeSemicolon(); if (label === null && !state.inIteration) { throwError({}, Messages.IllegalContinue); } return markerApply(marker, delegate.createContinueStatement(label)); } // 12.8 The break statement function parseBreakStatement() { var label = null, marker = markerCreate(); expectKeyword('break'); // Catch the very common case first: immediately a semicolon (char #59). if (source.charCodeAt(index) === 59) { lex(); if (!(state.inIteration || state.inSwitch)) { throwError({}, Messages.IllegalBreak); } return markerApply(marker, delegate.createBreakStatement(null)); } if (peekLineTerminator()) { if (!(state.inIteration || state.inSwitch)) { throwError({}, Messages.IllegalBreak); } return markerApply(marker, delegate.createBreakStatement(null)); } if (lookahead.type === Token.Identifier) { label = parseVariableIdentifier(); if (!state.labelSet.has(label.name)) { throwError({}, Messages.UnknownLabel, label.name); } } consumeSemicolon(); if (label === null && !(state.inIteration || state.inSwitch)) { throwError({}, Messages.IllegalBreak); } return markerApply(marker, delegate.createBreakStatement(label)); } // 12.9 The return statement function parseReturnStatement() { var argument = null, marker = markerCreate(); expectKeyword('return'); if (!state.inFunctionBody) { throwErrorTolerant({}, Messages.IllegalReturn); } // 'return' followed by a space and an identifier is very common. if (source.charCodeAt(index) === 32) { if (isIdentifierStart(source.charCodeAt(index + 1))) { argument = parseExpression(); consumeSemicolon(); return markerApply(marker, delegate.createReturnStatement(argument)); } } if (peekLineTerminator()) { return markerApply(marker, delegate.createReturnStatement(null)); } if (!match(';')) { if (!match('}') && lookahead.type !== Token.EOF) { argument = parseExpression(); } } consumeSemicolon(); return markerApply(marker, delegate.createReturnStatement(argument)); } // 12.10 The with statement function parseWithStatement() { var object, body, marker = markerCreate(); if (strict) { throwErrorTolerant({}, Messages.StrictModeWith); } expectKeyword('with'); expect('('); object = parseExpression(); expect(')'); body = parseStatement(); return markerApply(marker, delegate.createWithStatement(object, body)); } // 12.10 The swith statement function parseSwitchCase() { var test, consequent = [], sourceElement, marker = markerCreate(); if (matchKeyword('default')) { lex(); test = null; } else { expectKeyword('case'); test = parseExpression(); } expect(':'); while (index < length) { if (match('}') || matchKeyword('default') || matchKeyword('case')) { break; } sourceElement = parseSourceElement(); if (typeof sourceElement === 'undefined') { break; } consequent.push(sourceElement); } return markerApply(marker, delegate.createSwitchCase(test, consequent)); } function parseSwitchStatement() { var discriminant, cases, clause, oldInSwitch, defaultFound, marker = markerCreate(); expectKeyword('switch'); expect('('); discriminant = parseExpression(); expect(')'); expect('{'); cases = []; if (match('}')) { lex(); return markerApply(marker, delegate.createSwitchStatement(discriminant, cases)); } oldInSwitch = state.inSwitch; state.inSwitch = true; defaultFound = false; while (index < length) { if (match('}')) { break; } clause = parseSwitchCase(); if (clause.test === null) { if (defaultFound) { throwError({}, Messages.MultipleDefaultsInSwitch); } defaultFound = true; } cases.push(clause); } state.inSwitch = oldInSwitch; expect('}'); return markerApply(marker, delegate.createSwitchStatement(discriminant, cases)); } // 12.13 The throw statement function parseThrowStatement() { var argument, marker = markerCreate(); expectKeyword('throw'); if (peekLineTerminator()) { throwError({}, Messages.NewlineAfterThrow); } argument = parseExpression(); consumeSemicolon(); return markerApply(marker, delegate.createThrowStatement(argument)); } // 12.14 The try statement function parseCatchClause() { var param, body, marker = markerCreate(); expectKeyword('catch'); expect('('); if (match(')')) { throwUnexpected(lookahead); } param = parseExpression(); // 12.14.1 if (strict && param.type === Syntax.Identifier && isRestrictedWord(param.name)) { throwErrorTolerant({}, Messages.StrictCatchVariable); } expect(')'); body = parseBlock(); return markerApply(marker, delegate.createCatchClause(param, body)); } function parseTryStatement() { var block, handlers = [], finalizer = null, marker = markerCreate(); expectKeyword('try'); block = parseBlock(); if (matchKeyword('catch')) { handlers.push(parseCatchClause()); } if (matchKeyword('finally')) { lex(); finalizer = parseBlock(); } if (handlers.length === 0 && !finalizer) { throwError({}, Messages.NoCatchOrFinally); } return markerApply(marker, delegate.createTryStatement(block, [], handlers, finalizer)); } // 12.15 The debugger statement function parseDebuggerStatement() { var marker = markerCreate(); expectKeyword('debugger'); consumeSemicolon(); return markerApply(marker, delegate.createDebuggerStatement()); } // 12 Statements function parseStatement() { var type = lookahead.type, marker, expr, labeledBody; if (type === Token.EOF) { throwUnexpected(lookahead); } if (type === Token.Punctuator) { switch (lookahead.value) { case ';': return parseEmptyStatement(); case '{': return parseBlock(); case '(': return parseExpressionStatement(); default: break; } } if (type === Token.Keyword) { switch (lookahead.value) { case 'break': return parseBreakStatement(); case 'continue': return parseContinueStatement(); case 'debugger': return parseDebuggerStatement(); case 'do': return parseDoWhileStatement(); case 'for': return parseForStatement(); case 'function': return parseFunctionDeclaration(); case 'class': return parseClassDeclaration(); case 'if': return parseIfStatement(); case 'return': return parseReturnStatement(); case 'switch': return parseSwitchStatement(); case 'throw': return parseThrowStatement(); case 'try': return parseTryStatement(); case 'var': return parseVariableStatement(); case 'while': return parseWhileStatement(); case 'with': return parseWithStatement(); default: break; } } if (matchAsyncFuncExprOrDecl()) { return parseFunctionDeclaration(); } marker = markerCreate(); expr = parseExpression(); // 12.12 Labelled Statements if ((expr.type === Syntax.Identifier) && match(':')) { lex(); if (state.labelSet.has(expr.name)) { throwError({}, Messages.Redeclaration, 'Label', expr.name); } state.labelSet.set(expr.name, true); labeledBody = parseStatement(); state.labelSet.delete(expr.name); return markerApply(marker, delegate.createLabeledStatement(expr, labeledBody)); } consumeSemicolon(); return markerApply(marker, delegate.createExpressionStatement(expr)); } // 13 Function Definition function parseConciseBody() { if (match('{')) { return parseFunctionSourceElements(); } return parseAssignmentExpression(); } function parseFunctionSourceElements() { var sourceElement, sourceElements = [], token, directive, firstRestricted, oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, oldParenthesizedCount, marker = markerCreate(); expect('{'); while (index < length) { if (lookahead.type !== Token.StringLiteral) { break; } token = lookahead; sourceElement = parseSourceElement(); sourceElements.push(sourceElement); if (sourceElement.expression.type !== Syntax.Literal) { // this is not directive break; } directive = source.slice(token.range[0] + 1, token.range[1] - 1); if (directive === 'use strict') { strict = true; if (firstRestricted) { throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral); } } else { if (!firstRestricted && token.octal) { firstRestricted = token; } } } oldLabelSet = state.labelSet; oldInIteration = state.inIteration; oldInSwitch = state.inSwitch; oldInFunctionBody = state.inFunctionBody; oldParenthesizedCount = state.parenthesizedCount; state.labelSet = new StringMap(); state.inIteration = false; state.inSwitch = false; state.inFunctionBody = true; state.parenthesizedCount = 0; while (index < length) { if (match('}')) { break; } sourceElement = parseSourceElement(); if (typeof sourceElement === 'undefined') { break; } sourceElements.push(sourceElement); } expect('}'); state.labelSet = oldLabelSet; state.inIteration = oldInIteration; state.inSwitch = oldInSwitch; state.inFunctionBody = oldInFunctionBody; state.parenthesizedCount = oldParenthesizedCount; return markerApply(marker, delegate.createBlockStatement(sourceElements)); } function validateParam(options, param, name) { if (strict) { if (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 (isRestrictedWord(name)) { options.firstRestricted = param; options.message = Messages.StrictParamName; } else if (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 marker, token, rest, param, def; token = lookahead; if (token.value === '...') { token = lex(); rest = true; } if (match('[')) { marker = markerCreate(); param = parseArrayInitialiser(); reinterpretAsDestructuredParameter(options, param); if (match(':')) { param.typeAnnotation = parseTypeAnnotation(); markerApply(marker, param); } } else if (match('{')) { marker = markerCreate(); if (rest) { throwError({}, Messages.ObjectPatternAsRestParameter); } param = parseObjectInitialiser(); reinterpretAsDestructuredParameter(options, param); if (match(':')) { param.typeAnnotation = parseTypeAnnotation(); markerApply(marker, param); } } else { param = rest ? parseTypeAnnotatableIdentifier( false, /* requireTypeAnnotation */ false /* canBeOptionalParam */ ) : parseTypeAnnotatableIdentifier( false, /* requireTypeAnnotation */ true /* canBeOptionalParam */ ); validateParam(options, token, token.value); } if (match('=')) { if (rest) { throwErrorTolerant(lookahead, Messages.DefaultRestParameter); } 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); return !match(')'); } function parseParams(firstRestricted) { var options, marker = markerCreate(); options = { params: [], defaultCount: 0, defaults: [], rest: null, firstRestricted: firstRestricted }; expect('('); if (!match(')')) { options.paramSet = new StringMap(); while (index < length) { if (!parseParam(options)) { break; } expect(','); } } expect(')'); if (options.defaultCount === 0) { options.defaults = []; } if (match(':')) { options.returnType = parseTypeAnnotation(); } return markerApply(marker, options); } function parseFunctionDeclaration() { var id, body, token, tmp, firstRestricted, message, generator, isAsync, previousStrict, previousYieldAllowed, previousAwaitAllowed, marker = markerCreate(), typeParameters; isAsync = false; if (matchAsync()) { lex(); isAsync = true; } expectKeyword('function'); generator = false; if (match('*')) { lex(); generator = true; } token = lookahead; id = parseVariableIdentifier(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } if (strict) { if (isRestrictedWord(token.value)) { throwErrorTolerant(token, Messages.StrictFunctionName); } } else { if (isRestrictedWord(token.value)) { firstRestricted = token; message = Messages.StrictFunctionName; } else if (isStrictModeReservedWord(token.value)) { firstRestricted = token; message = Messages.StrictReservedWord; } } tmp = parseParams(firstRestricted); firstRestricted = tmp.firstRestricted; if (tmp.message) { message = tmp.message; } previousStrict = strict; previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = generator; previousAwaitAllowed = state.awaitAllowed; state.awaitAllowed = isAsync; body = parseFunctionSourceElements(); if (strict && firstRestricted) { throwError(firstRestricted, message); } if (strict && tmp.stricted) { throwErrorTolerant(tmp.stricted, message); } strict = previousStrict; state.yieldAllowed = previousYieldAllowed; state.awaitAllowed = previousAwaitAllowed; return markerApply( marker, delegate.createFunctionDeclaration( id, tmp.params, tmp.defaults, body, tmp.rest, generator, false, isAsync, tmp.returnType, typeParameters ) ); } function parseFunctionExpression() { var token, id = null, firstRestricted, message, tmp, body, generator, isAsync, previousStrict, previousYieldAllowed, previousAwaitAllowed, marker = markerCreate(), typeParameters; isAsync = false; if (matchAsync()) { lex(); isAsync = true; } expectKeyword('function'); generator = false; if (match('*')) { lex(); generator = true; } if (!match('(')) { if (!match('<')) { token = lookahead; id = parseVariableIdentifier(); if (strict) { if (isRestrictedWord(token.value)) { throwErrorTolerant(token, Messages.StrictFunctionName); } } else { if (isRestrictedWord(token.value)) { firstRestricted = token; message = Messages.StrictFunctionName; } else if (isStrictModeReservedWord(token.value)) { firstRestricted = token; message = Messages.StrictReservedWord; } } } if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } } tmp = parseParams(firstRestricted); firstRestricted = tmp.firstRestricted; if (tmp.message) { message = tmp.message; } previousStrict = strict; previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = generator; previousAwaitAllowed = state.awaitAllowed; state.awaitAllowed = isAsync; body = parseFunctionSourceElements(); if (strict && firstRestricted) { throwError(firstRestricted, message); } if (strict && tmp.stricted) { throwErrorTolerant(tmp.stricted, message); } strict = previousStrict; state.yieldAllowed = previousYieldAllowed; state.awaitAllowed = previousAwaitAllowed; return markerApply( marker, delegate.createFunctionExpression( id, tmp.params, tmp.defaults, body, tmp.rest, generator, false, isAsync, tmp.returnType, typeParameters ) ); } function parseYieldExpression() { var delegateFlag, expr, marker = markerCreate(); expectKeyword('yield', !strict); delegateFlag = false; if (match('*')) { lex(); delegateFlag = true; } expr = parseAssignmentExpression(); return markerApply(marker, delegate.createYieldExpression(expr, delegateFlag)); } function parseAwaitExpression() { var expr, marker = markerCreate(); expectContextualKeyword('await'); expr = parseAssignmentExpression(); return markerApply(marker, delegate.createAwaitExpression(expr)); } // 14 Functions and classes // 14.1 Functions is defined above (13 in ES5) // 14.2 Arrow Functions Definitions is defined in (7.3 assignments) // 14.3 Method Definitions // 14.3.7 function specialMethod(methodDefinition) { return methodDefinition.kind === 'get' || methodDefinition.kind === 'set' || methodDefinition.value.generator; } function parseMethodDefinition(key, isStatic, generator, computed) { var token, param, propType, isAsync, typeParameters, tokenValue, returnType; propType = isStatic ? ClassPropertyType.static : ClassPropertyType.prototype; if (generator) { return delegate.createMethodDefinition( propType, '', key, parsePropertyMethodFunction({ generator: true }), computed ); } tokenValue = key.type === 'Identifier' && key.name; if (tokenValue === 'get' && !match('(')) { key = parseObjectPropertyKey(); expect('('); expect(')'); if (match(':')) { returnType = parseTypeAnnotation(); } return delegate.createMethodDefinition( propType, 'get', key, parsePropertyFunction({ generator: false, returnType: returnType }), computed ); } if (tokenValue === 'set' && !match('(')) { key = parseObjectPropertyKey(); expect('('); token = lookahead; param = [ parseTypeAnnotatableIdentifier() ]; expect(')'); if (match(':')) { returnType = parseTypeAnnotation(); } return delegate.createMethodDefinition( propType, 'set', key, parsePropertyFunction({ params: param, generator: false, name: token, returnType: returnType }), computed ); } if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } isAsync = tokenValue === 'async' && !match('('); if (isAsync) { key = parseObjectPropertyKey(); } return delegate.createMethodDefinition( propType, '', key, parsePropertyMethodFunction({ generator: false, async: isAsync, typeParameters: typeParameters }), computed ); } function parseClassProperty(key, computed, isStatic) { var typeAnnotation; typeAnnotation = parseTypeAnnotation(); expect(';'); return delegate.createClassProperty( key, typeAnnotation, computed, isStatic ); } function parseClassElement() { var computed = false, generator = false, key, marker = markerCreate(), isStatic = false, possiblyOpenBracketToken; if (match(';')) { lex(); return undefined; } if (lookahead.value === 'static') { lex(); isStatic = true; } if (match('*')) { lex(); generator = true; } possiblyOpenBracketToken = lookahead; if (matchContextualKeyword('get') || matchContextualKeyword('set')) { possiblyOpenBracketToken = lookahead2(); } if (possiblyOpenBracketToken.type === Token.Punctuator && possiblyOpenBracketToken.value === '[') { computed = true; } key = parseObjectPropertyKey(); if (!generator && lookahead.value === ':') { return markerApply(marker, parseClassProperty(key, computed, isStatic)); } return markerApply(marker, parseMethodDefinition( key, isStatic, generator, computed )); } function parseClassBody() { var classElement, classElements = [], existingProps = {}, marker = markerCreate(), propName, propType; existingProps[ClassPropertyType.static] = new StringMap(); existingProps[ClassPropertyType.prototype] = new StringMap(); expect('{'); while (index < length) { if (match('}')) { break; } classElement = parseClassElement(existingProps); if (typeof classElement !== 'undefined') { classElements.push(classElement); propName = !classElement.computed && getFieldName(classElement.key); if (propName !== false) { propType = classElement.static ? ClassPropertyType.static : ClassPropertyType.prototype; if (classElement.type === Syntax.MethodDefinition) { if (propName === 'constructor' && !classElement.static) { if (specialMethod(classElement)) { throwError(classElement, Messages.IllegalClassConstructorProperty); } if (existingProps[ClassPropertyType.prototype].has('constructor')) { throwError(classElement.key, Messages.IllegalDuplicateClassProperty); } } existingProps[propType].set(propName, true); } } } } expect('}'); return markerApply(marker, delegate.createClassBody(classElements)); } function parseClassImplements() { var id, implemented = [], marker, typeParameters; if (strict) { expectKeyword('implements'); } else { expectContextualKeyword('implements'); } while (index < length) { marker = markerCreate(); id = parseVariableIdentifier(); if (match('<')) { typeParameters = parseTypeParameterInstantiation(); } else { typeParameters = null; } implemented.push(markerApply(marker, delegate.createClassImplements( id, typeParameters ))); if (!match(',')) { break; } expect(','); } return implemented; } function parseClassExpression() { var id, implemented, previousYieldAllowed, superClass = null, superTypeParameters, marker = markerCreate(), typeParameters, matchImplements; expectKeyword('class'); matchImplements = strict ? matchKeyword('implements') : matchContextualKeyword('implements'); if (!matchKeyword('extends') && !matchImplements && !match('{')) { id = parseVariableIdentifier(); } if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } if (matchKeyword('extends')) { expectKeyword('extends'); previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = false; superClass = parseLeftHandSideExpressionAllowCall(); if (match('<')) { superTypeParameters = parseTypeParameterInstantiation(); } state.yieldAllowed = previousYieldAllowed; } if (strict ? matchKeyword('implements') : matchContextualKeyword('implements')) { implemented = parseClassImplements(); } return markerApply(marker, delegate.createClassExpression( id, superClass, parseClassBody(), typeParameters, superTypeParameters, implemented )); } function parseClassDeclaration() { var id, implemented, previousYieldAllowed, superClass = null, superTypeParameters, marker = markerCreate(), typeParameters; expectKeyword('class'); id = parseVariableIdentifier(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } if (matchKeyword('extends')) { expectKeyword('extends'); previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = false; superClass = parseLeftHandSideExpressionAllowCall(); if (match('<')) { superTypeParameters = parseTypeParameterInstantiation(); } state.yieldAllowed = previousYieldAllowed; } if (strict ? matchKeyword('implements') : matchContextualKeyword('implements')) { implemented = parseClassImplements(); } return markerApply(marker, delegate.createClassDeclaration( id, superClass, parseClassBody(), typeParameters, superTypeParameters, implemented )); } // 15 Program function parseSourceElement() { var token; if (lookahead.type === Token.Keyword) { switch (lookahead.value) { case 'const': case 'let': return parseConstLetDeclaration(lookahead.value); case 'function': return parseFunctionDeclaration(); case 'export': throwErrorTolerant({}, Messages.IllegalExportDeclaration); return parseExportDeclaration(); case 'import': throwErrorTolerant({}, Messages.IllegalImportDeclaration); return parseImportDeclaration(); case 'interface': if (lookahead2().type === Token.Identifier) { return parseInterface(); } return parseStatement(); default: return parseStatement(); } } if (matchContextualKeyword('type') && lookahead2().type === Token.Identifier) { return parseTypeAlias(); } if (matchContextualKeyword('interface') && lookahead2().type === Token.Identifier) { return parseInterface(); } if (matchContextualKeyword('declare')) { token = lookahead2(); if (token.type === Token.Keyword) { switch (token.value) { case 'class': return parseDeclareClass(); case 'function': return parseDeclareFunction(); case 'var': return parseDeclareVariable(); } } else if (token.type === Token.Identifier && token.value === 'module') { return parseDeclareModule(); } } if (lookahead.type !== Token.EOF) { return parseStatement(); } } function parseProgramElement() { var isModule = extra.sourceType === 'module' || extra.sourceType === 'nonStrictModule'; if (isModule && lookahead.type === Token.Keyword) { switch (lookahead.value) { case 'export': return parseExportDeclaration(); case 'import': return parseImportDeclaration(); } } return parseSourceElement(); } function parseProgramElements() { var sourceElement, sourceElements = [], token, directive, firstRestricted; while (index < length) { token = lookahead; if (token.type !== Token.StringLiteral) { break; } sourceElement = parseProgramElement(); sourceElements.push(sourceElement); if (sourceElement.expression.type !== Syntax.Literal) { // this is not directive break; } directive = source.slice(token.range[0] + 1, token.range[1] - 1); if (directive === 'use strict') { strict = true; if (firstRestricted) { throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral); } } else { if (!firstRestricted && token.octal) { firstRestricted = token; } } } while (index < length) { sourceElement = parseProgramElement(); if (typeof sourceElement === 'undefined') { break; } sourceElements.push(sourceElement); } return sourceElements; } function parseProgram() { var body, marker = markerCreate(); strict = extra.sourceType === 'module'; peek(); body = parseProgramElements(); return markerApply(marker, delegate.createProgram(body)); } // 16 JSX XHTMLEntities = { quot: '\u0022', amp: '&', apos: '\u0027', lt: '<', gt: '>', nbsp: '\u00A0', iexcl: '\u00A1', cent: '\u00A2', pound: '\u00A3', curren: '\u00A4', yen: '\u00A5', brvbar: '\u00A6', sect: '\u00A7', uml: '\u00A8', copy: '\u00A9', ordf: '\u00AA', laquo: '\u00AB', not: '\u00AC', shy: '\u00AD', reg: '\u00AE', macr: '\u00AF', deg: '\u00B0', plusmn: '\u00B1', sup2: '\u00B2', sup3: '\u00B3', acute: '\u00B4', micro: '\u00B5', para: '\u00B6', middot: '\u00B7', cedil: '\u00B8', sup1: '\u00B9', ordm: '\u00BA', raquo: '\u00BB', frac14: '\u00BC', frac12: '\u00BD', frac34: '\u00BE', iquest: '\u00BF', Agrave: '\u00C0', Aacute: '\u00C1', Acirc: '\u00C2', Atilde: '\u00C3', Auml: '\u00C4', Aring: '\u00C5', AElig: '\u00C6', Ccedil: '\u00C7', Egrave: '\u00C8', Eacute: '\u00C9', Ecirc: '\u00CA', Euml: '\u00CB', Igrave: '\u00CC', Iacute: '\u00CD', Icirc: '\u00CE', Iuml: '\u00CF', ETH: '\u00D0', Ntilde: '\u00D1', Ograve: '\u00D2', Oacute: '\u00D3', Ocirc: '\u00D4', Otilde: '\u00D5', Ouml: '\u00D6', times: '\u00D7', Oslash: '\u00D8', Ugrave: '\u00D9', Uacute: '\u00DA', Ucirc: '\u00DB', Uuml: '\u00DC', Yacute: '\u00DD', THORN: '\u00DE', szlig: '\u00DF', agrave: '\u00E0', aacute: '\u00E1', acirc: '\u00E2', atilde: '\u00E3', auml: '\u00E4', aring: '\u00E5', aelig: '\u00E6', ccedil: '\u00E7', egrave: '\u00E8', eacute: '\u00E9', ecirc: '\u00EA', euml: '\u00EB', igrave: '\u00EC', iacute: '\u00ED', icirc: '\u00EE', iuml: '\u00EF', eth: '\u00F0', ntilde: '\u00F1', ograve: '\u00F2', oacute: '\u00F3', ocirc: '\u00F4', otilde: '\u00F5', ouml: '\u00F6', divide: '\u00F7', oslash: '\u00F8', ugrave: '\u00F9', uacute: '\u00FA', ucirc: '\u00FB', uuml: '\u00FC', yacute: '\u00FD', thorn: '\u00FE', yuml: '\u00FF', OElig: '\u0152', oelig: '\u0153', Scaron: '\u0160', scaron: '\u0161', Yuml: '\u0178', fnof: '\u0192', circ: '\u02C6', tilde: '\u02DC', Alpha: '\u0391', Beta: '\u0392', Gamma: '\u0393', Delta: '\u0394', Epsilon: '\u0395', Zeta: '\u0396', Eta: '\u0397', Theta: '\u0398', Iota: '\u0399', Kappa: '\u039A', Lambda: '\u039B', Mu: '\u039C', Nu: '\u039D', Xi: '\u039E', Omicron: '\u039F', Pi: '\u03A0', Rho: '\u03A1', Sigma: '\u03A3', Tau: '\u03A4', Upsilon: '\u03A5', Phi: '\u03A6', Chi: '\u03A7', Psi: '\u03A8', Omega: '\u03A9', alpha: '\u03B1', beta: '\u03B2', gamma: '\u03B3', delta: '\u03B4', epsilon: '\u03B5', zeta: '\u03B6', eta: '\u03B7', theta: '\u03B8', iota: '\u03B9', kappa: '\u03BA', lambda: '\u03BB', mu: '\u03BC', nu: '\u03BD', xi: '\u03BE', omicron: '\u03BF', pi: '\u03C0', rho: '\u03C1', sigmaf: '\u03C2', sigma: '\u03C3', tau: '\u03C4', upsilon: '\u03C5', phi: '\u03C6', chi: '\u03C7', psi: '\u03C8', omega: '\u03C9', thetasym: '\u03D1', upsih: '\u03D2', piv: '\u03D6', ensp: '\u2002', emsp: '\u2003', thinsp: '\u2009', zwnj: '\u200C', zwj: '\u200D', lrm: '\u200E', rlm: '\u200F', ndash: '\u2013', mdash: '\u2014', lsquo: '\u2018', rsquo: '\u2019', sbquo: '\u201A', ldquo: '\u201C', rdquo: '\u201D', bdquo: '\u201E', dagger: '\u2020', Dagger: '\u2021', bull: '\u2022', hellip: '\u2026', permil: '\u2030', prime: '\u2032', Prime: '\u2033', lsaquo: '\u2039', rsaquo: '\u203A', oline: '\u203E', frasl: '\u2044', euro: '\u20AC', image: '\u2111', weierp: '\u2118', real: '\u211C', trade: '\u2122', alefsym: '\u2135', larr: '\u2190', uarr: '\u2191', rarr: '\u2192', darr: '\u2193', harr: '\u2194', crarr: '\u21B5', lArr: '\u21D0', uArr: '\u21D1', rArr: '\u21D2', dArr: '\u21D3', hArr: '\u21D4', forall: '\u2200', part: '\u2202', exist: '\u2203', empty: '\u2205', nabla: '\u2207', isin: '\u2208', notin: '\u2209', ni: '\u220B', prod: '\u220F', sum: '\u2211', minus: '\u2212', lowast: '\u2217', radic: '\u221A', prop: '\u221D', infin: '\u221E', ang: '\u2220', and: '\u2227', or: '\u2228', cap: '\u2229', cup: '\u222A', 'int': '\u222B', there4: '\u2234', sim: '\u223C', cong: '\u2245', asymp: '\u2248', ne: '\u2260', equiv: '\u2261', le: '\u2264', ge: '\u2265', sub: '\u2282', sup: '\u2283', nsub: '\u2284', sube: '\u2286', supe: '\u2287', oplus: '\u2295', otimes: '\u2297', perp: '\u22A5', sdot: '\u22C5', lceil: '\u2308', rceil: '\u2309', lfloor: '\u230A', rfloor: '\u230B', lang: '\u2329', rang: '\u232A', loz: '\u25CA', spades: '\u2660', clubs: '\u2663', hearts: '\u2665', diams: '\u2666' }; function getQualifiedJSXName(object) { if (object.type === Syntax.JSXIdentifier) { return object.name; } if (object.type === Syntax.JSXNamespacedName) { return object.namespace.name + ':' + object.name.name; } /* istanbul ignore else */ if (object.type === Syntax.JSXMemberExpression) { return ( getQualifiedJSXName(object.object) + '.' + getQualifiedJSXName(object.property) ); } /* istanbul ignore next */ throwUnexpected(object); } function isJSXIdentifierStart(ch) { // exclude backslash (\) return (ch !== 92) && isIdentifierStart(ch); } function isJSXIdentifierPart(ch) { // exclude backslash (\) and add hyphen (-) return (ch !== 92) && (ch === 45 || isIdentifierPart(ch)); } function scanJSXIdentifier() { var ch, start, value = ''; start = index; while (index < length) { ch = source.charCodeAt(index); if (!isJSXIdentifierPart(ch)) { break; } value += source[index++]; } return { type: Token.JSXIdentifier, value: value, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanJSXEntity() { var ch, str = '', start = index, count = 0, code; ch = source[index]; assert(ch === '&', 'Entity must start with an ampersand'); index++; while (index < length && count++ < 10) { ch = source[index++]; if (ch === ';') { break; } str += ch; } // Well-formed entity (ending was found). if (ch === ';') { // Numeric entity. if (str[0] === '#') { if (str[1] === 'x') { code = +('0' + str.substr(1)); } else { // Removing leading zeros in order to avoid treating as octal in old browsers. code = +str.substr(1).replace(Regex.LeadingZeros, ''); } if (!isNaN(code)) { return String.fromCharCode(code); } /* istanbul ignore else */ } else if (XHTMLEntities[str]) { return XHTMLEntities[str]; } } // Treat non-entity sequences as regular text. index = start + 1; return '&'; } function scanJSXText(stopChars) { var ch, str = '', start; start = index; while (index < length) { ch = source[index]; if (stopChars.indexOf(ch) !== -1) { break; } if (ch === '&') { str += scanJSXEntity(); } else { index++; if (ch === '\r' && source[index] === '\n') { str += ch; ch = source[index]; index++; } if (isLineTerminator(ch.charCodeAt(0))) { ++lineNumber; lineStart = index; } str += ch; } } return { type: Token.JSXText, value: str, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanJSXStringLiteral() { var innerToken, quote, start; quote = source[index]; assert((quote === '\'' || quote === '"'), 'String literal must starts with a quote'); start = index; ++index; innerToken = scanJSXText([quote]); if (quote !== source[index]) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } ++index; innerToken.range = [start, index]; return innerToken; } /** * Between JSX opening and closing tags (e.g. HERE), anything that * is not another JSX tag and is not an expression wrapped by {} is text. */ function advanceJSXChild() { var ch = source.charCodeAt(index); // '<' 60, '>' 62, '{' 123, '}' 125 if (ch !== 60 && ch !== 62 && ch !== 123 && ch !== 125) { return scanJSXText(['<', '>', '{', '}']); } return scanPunctuator(); } function parseJSXIdentifier() { var token, marker = markerCreate(); if (lookahead.type !== Token.JSXIdentifier) { throwUnexpected(lookahead); } token = lex(); return markerApply(marker, delegate.createJSXIdentifier(token.value)); } function parseJSXNamespacedName() { var namespace, name, marker = markerCreate(); namespace = parseJSXIdentifier(); expect(':'); name = parseJSXIdentifier(); return markerApply(marker, delegate.createJSXNamespacedName(namespace, name)); } function parseJSXMemberExpression() { var marker = markerCreate(), expr = parseJSXIdentifier(); while (match('.')) { lex(); expr = markerApply(marker, delegate.createJSXMemberExpression(expr, parseJSXIdentifier())); } return expr; } function parseJSXElementName() { if (lookahead2().value === ':') { return parseJSXNamespacedName(); } if (lookahead2().value === '.') { return parseJSXMemberExpression(); } return parseJSXIdentifier(); } function parseJSXAttributeName() { if (lookahead2().value === ':') { return parseJSXNamespacedName(); } return parseJSXIdentifier(); } function parseJSXAttributeValue() { var value, marker; if (match('{')) { value = parseJSXExpressionContainer(); if (value.expression.type === Syntax.JSXEmptyExpression) { throwError( value, 'JSX attributes must only be assigned a non-empty ' + 'expression' ); } } else if (match('<')) { value = parseJSXElement(); } else if (lookahead.type === Token.JSXText) { marker = markerCreate(); value = markerApply(marker, delegate.createLiteral(lex())); } else { throwError({}, Messages.InvalidJSXAttributeValue); } return value; } function parseJSXEmptyExpression() { var marker = markerCreatePreserveWhitespace(); while (source.charAt(index) !== '}') { index++; } return markerApply(marker, delegate.createJSXEmptyExpression()); } function parseJSXExpressionContainer() { var expression, origInJSXChild, origInJSXTag, marker = markerCreate(); origInJSXChild = state.inJSXChild; origInJSXTag = state.inJSXTag; state.inJSXChild = false; state.inJSXTag = false; expect('{'); if (match('}')) { expression = parseJSXEmptyExpression(); } else { expression = parseExpression(); } state.inJSXChild = origInJSXChild; state.inJSXTag = origInJSXTag; expect('}'); return markerApply(marker, delegate.createJSXExpressionContainer(expression)); } function parseJSXSpreadAttribute() { var expression, origInJSXChild, origInJSXTag, marker = markerCreate(); origInJSXChild = state.inJSXChild; origInJSXTag = state.inJSXTag; state.inJSXChild = false; state.inJSXTag = false; expect('{'); expect('...'); expression = parseAssignmentExpression(); state.inJSXChild = origInJSXChild; state.inJSXTag = origInJSXTag; expect('}'); return markerApply(marker, delegate.createJSXSpreadAttribute(expression)); } function parseJSXAttribute() { var name, marker; if (match('{')) { return parseJSXSpreadAttribute(); } marker = markerCreate(); name = parseJSXAttributeName(); // HTML empty attribute if (match('=')) { lex(); return markerApply(marker, delegate.createJSXAttribute(name, parseJSXAttributeValue())); } return markerApply(marker, delegate.createJSXAttribute(name)); } function parseJSXChild() { var token, marker; if (match('{')) { token = parseJSXExpressionContainer(); } else if (lookahead.type === Token.JSXText) { marker = markerCreatePreserveWhitespace(); token = markerApply(marker, delegate.createLiteral(lex())); } else if (match('<')) { token = parseJSXElement(); } else { throwUnexpected(lookahead); } return token; } function parseJSXClosingElement() { var name, origInJSXChild, origInJSXTag, marker = markerCreate(); origInJSXChild = state.inJSXChild; origInJSXTag = state.inJSXTag; state.inJSXChild = false; state.inJSXTag = true; expect('<'); expect('/'); name = parseJSXElementName(); // Because advance() (called by lex() called by expect()) expects there // to be a valid token after >, it needs to know whether to look for a // standard JS token or an JSX text node state.inJSXChild = origInJSXChild; state.inJSXTag = origInJSXTag; expect('>'); return markerApply(marker, delegate.createJSXClosingElement(name)); } function parseJSXOpeningElement() { var name, attributes = [], selfClosing = false, origInJSXChild, origInJSXTag, marker = markerCreate(); origInJSXChild = state.inJSXChild; origInJSXTag = state.inJSXTag; state.inJSXChild = false; state.inJSXTag = true; expect('<'); name = parseJSXElementName(); while (index < length && lookahead.value !== '/' && lookahead.value !== '>') { attributes.push(parseJSXAttribute()); } state.inJSXTag = origInJSXTag; if (lookahead.value === '/') { expect('/'); // Because advance() (called by lex() called by expect()) expects // there to be a valid token after >, it needs to know whether to // look for a standard JS token or an JSX text node state.inJSXChild = origInJSXChild; expect('>'); selfClosing = true; } else { state.inJSXChild = true; expect('>'); } return markerApply(marker, delegate.createJSXOpeningElement(name, attributes, selfClosing)); } function parseJSXElement() { var openingElement, closingElement = null, children = [], origInJSXChild, origInJSXTag, marker = markerCreate(); origInJSXChild = state.inJSXChild; origInJSXTag = state.inJSXTag; openingElement = parseJSXOpeningElement(); if (!openingElement.selfClosing) { while (index < length) { state.inJSXChild = false; // Call lookahead2() with inJSXChild = false because one
two
; // // the default error message is a bit incomprehensible. Since it's // rarely (never?) useful to write a less-than sign after an JSX // element, we disallow it here in the parser in order to provide a // better error message. (In the rare case that the less-than operator // was intended, the left tag can be wrapped in parentheses.) if (!origInJSXChild && match('<')) { throwError(lookahead, Messages.AdjacentJSXElements); } return markerApply(marker, delegate.createJSXElement(openingElement, closingElement, children)); } function parseTypeAlias() { var id, marker = markerCreate(), typeParameters = null, right; expectContextualKeyword('type'); id = parseVariableIdentifier(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } expect('='); right = parseType(); consumeSemicolon(); return markerApply(marker, delegate.createTypeAlias(id, typeParameters, right)); } function parseInterfaceExtends() { var marker = markerCreate(), id, typeParameters = null; id = parseVariableIdentifier(); if (match('<')) { typeParameters = parseTypeParameterInstantiation(); } return markerApply(marker, delegate.createInterfaceExtends( id, typeParameters )); } function parseInterfaceish(marker, allowStatic) { var body, bodyMarker, extended = [], id, typeParameters = null; id = parseVariableIdentifier(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } if (matchKeyword('extends')) { expectKeyword('extends'); while (index < length) { extended.push(parseInterfaceExtends()); if (!match(',')) { break; } expect(','); } } bodyMarker = markerCreate(); body = markerApply(bodyMarker, parseObjectType(allowStatic)); return markerApply(marker, delegate.createInterface( id, typeParameters, body, extended )); } function parseInterface() { var marker = markerCreate(); if (strict) { expectKeyword('interface'); } else { expectContextualKeyword('interface'); } return parseInterfaceish(marker, /* allowStatic */false); } function parseDeclareClass() { var marker = markerCreate(), ret; expectContextualKeyword('declare'); expectKeyword('class'); ret = parseInterfaceish(marker, /* allowStatic */true); ret.type = Syntax.DeclareClass; return ret; } function parseDeclareFunction() { var id, idMarker, marker = markerCreate(), params, returnType, rest, tmp, typeParameters = null, value, valueMarker; expectContextualKeyword('declare'); expectKeyword('function'); idMarker = markerCreate(); id = parseVariableIdentifier(); valueMarker = markerCreate(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } expect('('); tmp = parseFunctionTypeParams(); params = tmp.params; rest = tmp.rest; expect(')'); expect(':'); returnType = parseType(); value = markerApply(valueMarker, delegate.createFunctionTypeAnnotation( params, returnType, rest, typeParameters )); id.typeAnnotation = markerApply(valueMarker, delegate.createTypeAnnotation( value )); markerApply(idMarker, id); consumeSemicolon(); return markerApply(marker, delegate.createDeclareFunction( id )); } function parseDeclareVariable() { var id, marker = markerCreate(); expectContextualKeyword('declare'); expectKeyword('var'); id = parseTypeAnnotatableIdentifier(); consumeSemicolon(); return markerApply(marker, delegate.createDeclareVariable( id )); } function parseDeclareModule() { var body = [], bodyMarker, id, idMarker, marker = markerCreate(), token; expectContextualKeyword('declare'); expectContextualKeyword('module'); if (lookahead.type === Token.StringLiteral) { if (strict && lookahead.octal) { throwErrorTolerant(lookahead, Messages.StrictOctalLiteral); } idMarker = markerCreate(); id = markerApply(idMarker, delegate.createLiteral(lex())); } else { id = parseVariableIdentifier(); } bodyMarker = markerCreate(); expect('{'); while (index < length && !match('}')) { token = lookahead2(); switch (token.value) { case 'class': body.push(parseDeclareClass()); break; case 'function': body.push(parseDeclareFunction()); break; case 'var': body.push(parseDeclareVariable()); break; default: throwUnexpected(lookahead); } } expect('}'); return markerApply(marker, delegate.createDeclareModule( id, markerApply(bodyMarker, delegate.createBlockStatement(body)) )); } function collectToken() { var loc, token, range, value, entry; /* istanbul ignore else */ if (!state.inJSXChild) { skipComment(); } loc = { start: { line: lineNumber, column: index - lineStart } }; token = extra.advance(); loc.end = { line: lineNumber, column: index - lineStart }; if (token.type !== Token.EOF) { range = [token.range[0], token.range[1]]; value = source.slice(token.range[0], token.range[1]); entry = { type: TokenName[token.type], value: value, range: range, loc: loc }; if (token.regex) { entry.regex = { pattern: token.regex.pattern, flags: token.regex.flags }; } extra.tokens.push(entry); } return token; } function collectRegex() { var pos, loc, regex, token; skipComment(); pos = index; loc = { start: { line: lineNumber, column: index - lineStart } }; regex = extra.scanRegExp(); loc.end = { line: lineNumber, column: index - lineStart }; if (!extra.tokenize) { /* istanbul ignore next */ // Pop the previous token, which is likely '/' or '/=' if (extra.tokens.length > 0) { token = extra.tokens[extra.tokens.length - 1]; if (token.range[0] === pos && token.type === 'Punctuator') { if (token.value === '/' || token.value === '/=') { extra.tokens.pop(); } } } extra.tokens.push({ type: 'RegularExpression', value: regex.literal, regex: regex.regex, range: [pos, index], loc: loc }); } return regex; } function filterTokenLocation() { var i, entry, token, tokens = []; for (i = 0; i < extra.tokens.length; ++i) { entry = extra.tokens[i]; token = { type: entry.type, value: entry.value }; if (entry.regex) { token.regex = { pattern: entry.regex.pattern, flags: entry.regex.flags }; } if (extra.range) { token.range = entry.range; } if (extra.loc) { token.loc = entry.loc; } tokens.push(token); } extra.tokens = tokens; } function patch() { if (typeof extra.tokens !== 'undefined') { extra.advance = advance; extra.scanRegExp = scanRegExp; advance = collectToken; scanRegExp = collectRegex; } } function unpatch() { if (typeof extra.scanRegExp === 'function') { advance = extra.advance; scanRegExp = extra.scanRegExp; } } // This is used to modify the delegate. function extend(object, properties) { var entry, result = {}; for (entry in object) { /* istanbul ignore else */ if (object.hasOwnProperty(entry)) { result[entry] = object[entry]; } } for (entry in properties) { /* istanbul ignore else */ if (properties.hasOwnProperty(entry)) { result[entry] = properties[entry]; } } return result; } function tokenize(code, options) { var toString, token, tokens; toString = String; if (typeof code !== 'string' && !(code instanceof String)) { code = toString(code); } delegate = SyntaxTreeDelegate; source = code; index = 0; lineNumber = (source.length > 0) ? 1 : 0; lineStart = 0; length = source.length; lookahead = null; state = { allowKeyword: true, allowIn: true, labelSet: new StringMap(), inFunctionBody: false, inIteration: false, inSwitch: false, lastCommentStart: -1 }; extra = {}; // Options matching. options = options || {}; // Of course we collect tokens here. 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; extra.range = (typeof options.range === 'boolean') && options.range; extra.loc = (typeof options.loc === 'boolean') && options.loc; if (typeof options.comment === 'boolean' && options.comment) { extra.comments = []; } if (typeof options.tolerant === 'boolean' && options.tolerant) { extra.errors = []; } patch(); try { peek(); if (lookahead.type === Token.EOF) { return extra.tokens; } token = lex(); while (lookahead.type !== Token.EOF) { try { token = lex(); } catch (lexError) { token = lookahead; if (extra.errors) { extra.errors.push(lexError); // We have to break on the first error // to avoid infinite loops. break; } else { throw lexError; } } } filterTokenLocation(); tokens = extra.tokens; if (typeof extra.comments !== 'undefined') { tokens.comments = extra.comments; } if (typeof extra.errors !== 'undefined') { tokens.errors = extra.errors; } } catch (e) { throw e; } finally { unpatch(); extra = {}; } return tokens; } function parse(code, options) { var program, toString; toString = String; if (typeof code !== 'string' && !(code instanceof String)) { code = toString(code); } delegate = SyntaxTreeDelegate; source = code; index = 0; lineNumber = (source.length > 0) ? 1 : 0; lineStart = 0; length = source.length; lookahead = null; state = { allowKeyword: false, allowIn: true, labelSet: new StringMap(), parenthesizedCount: 0, inFunctionBody: false, inIteration: false, inSwitch: false, inJSXChild: false, inJSXTag: false, inType: false, lastCommentStart: -1, yieldAllowed: false, awaitAllowed: false }; extra = {}; if (typeof options !== 'undefined') { extra.range = (typeof options.range === 'boolean') && options.range; extra.loc = (typeof options.loc === 'boolean') && options.loc; extra.attachComment = (typeof options.attachComment === 'boolean') && options.attachComment; if (extra.loc && options.source !== null && options.source !== undefined) { delegate = extend(delegate, { 'postProcess': function (node) { node.loc.source = toString(options.source); return node; } }); } extra.sourceType = options.sourceType; if (typeof options.tokens === 'boolean' && options.tokens) { extra.tokens = []; } if (typeof options.comment === 'boolean' && options.comment) { extra.comments = []; } if (typeof options.tolerant === 'boolean' && options.tolerant) { extra.errors = []; } if (extra.attachComment) { extra.range = true; extra.comments = []; extra.bottomRightStack = []; extra.trailingComments = []; extra.leadingComments = []; } } patch(); try { program = parseProgram(); if (typeof extra.comments !== 'undefined') { program.comments = extra.comments; } if (typeof extra.tokens !== 'undefined') { filterTokenLocation(); program.tokens = extra.tokens; } if (typeof extra.errors !== 'undefined') { program.errors = extra.errors; } } catch (e) { throw e; } finally { unpatch(); extra = {}; } return program; } // Sync with *.json manifests. exports.version = '13001.1.0-dev-harmony-fb'; exports.tokenize = tokenize; exports.parse = parse; // Deep copy. /* istanbul ignore next */ exports.Syntax = (function () { var name, types = {}; if (typeof Object.create === 'function') { types = Object.create(null); } for (name in Syntax) { if (Syntax.hasOwnProperty(name)) { types[name] = Syntax[name]; } } if (typeof Object.freeze === 'function') { Object.freeze(types); } return types; }()); })); /* vim: set sw=4 ts=4 et tw=80 : */ },{}],459:[function(require,module,exports){ var assert = require("assert"); var types = require("./types"); var n = types.namedTypes; var isArray = types.builtInTypes.array; var isObject = types.builtInTypes.object; var linesModule = require("./lines"); var fromString = linesModule.fromString; var Lines = linesModule.Lines; var concat = linesModule.concat; var util = require("./util"); var comparePos = util.comparePos; var childNodesCacheKey = require("private").makeUniqueKey(); // TODO Move a non-caching implementation of this function into ast-types, // and implement a caching wrapper function here. function getSortedChildNodes(node, resultArray) { if (!node) { return; } // The .loc checks below are sensitive to some of the problems that // are fixed by this utility function. Specifically, if it decides to // set node.loc to null, indicating that the node's .loc information // is unreliable, then we don't want to add node to the resultArray. util.fixFaultyLocations(node); if (resultArray) { if (n.Node.check(node) && n.SourceLocation.check(node.loc)) { // This reverse insertion sort almost always takes constant // time because we almost always (maybe always?) append the // nodes in order anyway. for (var i = resultArray.length - 1; i >= 0; --i) { if (comparePos(resultArray[i].loc.end, node.loc.start) <= 0) { break; } } resultArray.splice(i + 1, 0, node); return; } } else if (node[childNodesCacheKey]) { return node[childNodesCacheKey]; } var names; if (isArray.check(node)) { names = Object.keys(node); } else if (isObject.check(node)) { names = types.getFieldNames(node); } else { return; } if (!resultArray) { Object.defineProperty(node, childNodesCacheKey, { value: resultArray = [], enumerable: false }); } for (var i = 0, nameCount = names.length; i < nameCount; ++i) { getSortedChildNodes(node[names[i]], resultArray); } return resultArray; } // As efficiently as possible, decorate the comment object with // .precedingNode, .enclosingNode, and/or .followingNode properties, at // least one of which is guaranteed to be defined. function decorateComment(node, comment) { var childNodes = getSortedChildNodes(node); // Time to dust off the old binary search robes and wizard hat. var left = 0, right = childNodes.length; while (left < right) { var middle = (left + right) >> 1; var child = childNodes[middle]; if (comparePos(child.loc.start, comment.loc.start) <= 0 && comparePos(comment.loc.end, child.loc.end) <= 0) { // The comment is completely contained by this child node. decorateComment(comment.enclosingNode = child, comment); return; // Abandon the binary search at this level. } if (comparePos(child.loc.end, comment.loc.start) <= 0) { // This child node falls completely before the comment. // Because we will never consider this node or any nodes // before it again, this node must be the closest preceding // node we have encountered so far. var precedingNode = child; left = middle + 1; continue; } if (comparePos(comment.loc.end, child.loc.start) <= 0) { // This child node falls completely after the comment. // Because we will never consider this node or any nodes after // it again, this node must be the closest following node we // have encountered so far. var followingNode = child; right = middle; continue; } throw new Error("Comment location overlaps with node location"); } if (precedingNode) { comment.precedingNode = precedingNode; } if (followingNode) { comment.followingNode = followingNode; } } exports.attach = function(comments, ast, lines) { if (!isArray.check(comments)) { return; } var tiesToBreak = []; comments.forEach(function(comment) { comment.loc.lines = lines; decorateComment(ast, comment); var pn = comment.precedingNode; var en = comment.enclosingNode; var fn = comment.followingNode; if (pn && fn) { var tieCount = tiesToBreak.length; if (tieCount > 0) { var lastTie = tiesToBreak[tieCount - 1]; assert.strictEqual( lastTie.precedingNode === comment.precedingNode, lastTie.followingNode === comment.followingNode ); if (lastTie.followingNode !== comment.followingNode) { breakTies(tiesToBreak, lines); } } tiesToBreak.push(comment); } else if (pn) { // No contest: we have a trailing comment. breakTies(tiesToBreak, lines); addTrailingComment(pn, comment); } else if (fn) { // No contest: we have a leading comment. breakTies(tiesToBreak, lines); addLeadingComment(fn, comment); } else if (en) { // The enclosing node has no child nodes at all, so what we // have here is a dangling comment, e.g. [/* crickets */]. breakTies(tiesToBreak, lines); addDanglingComment(en, comment); } else { throw new Error("AST contains no nodes at all?"); } }); breakTies(tiesToBreak, lines); comments.forEach(function(comment) { // These node references were useful for breaking ties, but we // don't need them anymore, and they create cycles in the AST that // may lead to infinite recursion if we don't delete them here. delete comment.precedingNode; delete comment.enclosingNode; delete comment.followingNode; }); }; function breakTies(tiesToBreak, lines) { var tieCount = tiesToBreak.length; if (tieCount === 0) { return; } var pn = tiesToBreak[0].precedingNode; var fn = tiesToBreak[0].followingNode; var gapEndPos = fn.loc.start; // Iterate backwards through tiesToBreak, examining the gaps // between the tied comments. In order to qualify as leading, a // comment must be separated from fn by an unbroken series of // whitespace-only gaps (or other comments). for (var indexOfFirstLeadingComment = tieCount; indexOfFirstLeadingComment > 0; --indexOfFirstLeadingComment) { var comment = tiesToBreak[indexOfFirstLeadingComment - 1]; assert.strictEqual(comment.precedingNode, pn); assert.strictEqual(comment.followingNode, fn); var gap = lines.sliceString(comment.loc.end, gapEndPos); if (/\S/.test(gap)) { // The gap string contained something other than whitespace. break; } gapEndPos = comment.loc.start; } while (indexOfFirstLeadingComment <= tieCount && (comment = tiesToBreak[indexOfFirstLeadingComment]) && // If the comment is a //-style comment and indented more // deeply than the node itself, reconsider it as trailing. comment.type === "Line" && comment.loc.start.column > fn.loc.start.column) { ++indexOfFirstLeadingComment; } tiesToBreak.forEach(function(comment, i) { if (i < indexOfFirstLeadingComment) { addTrailingComment(pn, comment); } else { addLeadingComment(fn, comment); } }); tiesToBreak.length = 0; } function addCommentHelper(node, comment) { var comments = node.comments || (node.comments = []); comments.push(comment); } function addLeadingComment(node, comment) { comment.leading = true; comment.trailing = false; addCommentHelper(node, comment); } function addDanglingComment(node, comment) { comment.leading = false; comment.trailing = false; addCommentHelper(node, comment); } function addTrailingComment(node, comment) { comment.leading = false; comment.trailing = true; addCommentHelper(node, comment); } function printLeadingComment(commentPath, print) { var comment = commentPath.getValue(); n.Comment.assert(comment); var loc = comment.loc; var lines = loc && loc.lines; var parts = [print(commentPath)]; if (comment.trailing) { // When we print trailing comments as leading comments, we don't // want to bring any trailing spaces along. parts.push("\n"); } else if (lines instanceof Lines) { var trailingSpace = lines.slice( loc.end, lines.skipSpaces(loc.end) ); if (trailingSpace.length === 1) { // If the trailing space contains no newlines, then we want to // preserve it exactly as we found it. parts.push(trailingSpace); } else { // If the trailing space contains newlines, then replace it // with just that many newlines, with all other spaces removed. parts.push(new Array(trailingSpace.length).join("\n")); } } else { parts.push("\n"); } return concat(parts); } function printTrailingComment(commentPath, print) { var comment = commentPath.getValue(commentPath); n.Comment.assert(comment); var loc = comment.loc; var lines = loc && loc.lines; var parts = []; if (lines instanceof Lines) { var fromPos = lines.skipSpaces(loc.start, true) || lines.firstPos(); var leadingSpace = lines.slice(fromPos, loc.start); if (leadingSpace.length === 1) { // If the leading space contains no newlines, then we want to // preserve it exactly as we found it. parts.push(leadingSpace); } else { // If the leading space contains newlines, then replace it // with just that many newlines, sans all other spaces. parts.push(new Array(leadingSpace.length).join("\n")); } } parts.push(print(commentPath)); return concat(parts); } exports.printComments = function(path, print) { var value = path.getValue(); var innerLines = print(path); var comments = n.Node.check(value) && types.getFieldValue(value, "comments"); if (!comments || comments.length === 0) { return innerLines; } var leadingParts = []; var trailingParts = [innerLines]; path.each(function(commentPath) { var comment = commentPath.getValue(); var leading = types.getFieldValue(comment, "leading"); var trailing = types.getFieldValue(comment, "trailing"); if (leading || (trailing && comment.type !== "Block")) { leadingParts.push(printLeadingComment(commentPath, print)); } else if (trailing) { assert.strictEqual(comment.type, "Block"); trailingParts.push(printTrailingComment(commentPath, print)); } }, "comments"); leadingParts.push.apply(leadingParts, trailingParts); return concat(leadingParts); }; },{"./lines":461,"./types":467,"./util":468,"assert":190,"private":435}],460:[function(require,module,exports){ var assert = require("assert"); var types = require("./types"); var n = types.namedTypes; var Node = n.Node; var isArray = types.builtInTypes.array; var isNumber = types.builtInTypes.number; function FastPath(value) { assert.ok(this instanceof FastPath); this.stack = [value]; } var FPp = FastPath.prototype; module.exports = FastPath; // Static convenience function for coercing a value to a FastPath. FastPath.from = function(obj) { if (obj instanceof FastPath) { // Return a defensive copy of any existing FastPath instances. return obj.copy(); } if (obj instanceof types.NodePath) { // For backwards compatibility, unroll NodePath instances into // lightweight FastPath [..., name, value] stacks. var copy = Object.create(FastPath.prototype); var stack = [obj.value]; for (var pp; (pp = obj.parentPath); obj = pp) stack.push(obj.name, pp.value); copy.stack = stack.reverse(); return copy; } // Otherwise use obj as the value of the new FastPath instance. return new FastPath(obj); }; FPp.copy = function copy() { var copy = Object.create(FastPath.prototype); copy.stack = this.stack.slice(0); return copy; }; // The name of the current property is always the penultimate element of // this.stack, and always a String. FPp.getName = function getName() { var s = this.stack; var len = s.length; if (len > 1) { return s[len - 2]; } // Since the name is always a string, null is a safe sentinel value to // return if we do not know the name of the (root) value. return null; }; // The value of the current property is always the final element of // this.stack. FPp.getValue = function getValue() { var s = this.stack; return s[s.length - 1]; }; function getNodeHelper(path, count) { var s = path.stack; for (var i = s.length - 1; i >= 0; i -= 2) { var value = s[i]; if (n.Node.check(value) && --count < 0) { return value; } } return null; } FPp.getNode = function getNode(count) { return getNodeHelper(this, ~~count); }; FPp.getParentNode = function getParentNode(count) { return getNodeHelper(this, ~~count + 1); }; // The length of the stack can be either even or odd, depending on whether // or not we have a name for the root value. The difference between the // index of the root value and the index of the final value is always // even, though, which allows us to return the root value in constant time // (i.e. without iterating backwards through the stack). FPp.getRootValue = function getRootValue() { var s = this.stack; if (s.length % 2 === 0) { return s[1]; } return s[0]; }; // Temporarily push properties named by string arguments given after the // callback function onto this.stack, then call the callback with a // reference to this (modified) FastPath object. Note that the stack will // be restored to its original state after the callback is finished, so it // is probably a mistake to retain a reference to the path. FPp.call = function call(callback/*, name1, name2, ... */) { var s = this.stack; var origLen = s.length; var value = s[origLen - 1]; var argc = arguments.length; for (var i = 1; i < argc; ++i) { var name = arguments[i]; value = value[name]; s.push(name, value); } var result = callback(this); s.length = origLen; return result; }; // Similar to FastPath.prototype.call, except that the value obtained by // accessing this.getValue()[name1][name2]... should be array-like. The // callback will be called with a reference to this path object for each // element of the array. FPp.each = function each(callback/*, name1, name2, ... */) { var s = this.stack; var origLen = s.length; var value = s[origLen - 1]; var argc = arguments.length; for (var i = 1; i < argc; ++i) { var name = arguments[i]; value = value[name]; s.push(name, value); } for (var i = 0; i < value.length; ++i) { if (i in value) { s.push(i, value[i]); // If the callback needs to know the value of i, call // path.getName(), assuming path is the parameter name. callback(this); s.length -= 2; } } s.length = origLen; }; // Similar to FastPath.prototype.each, except that the results of the // callback function invocations are stored in an array and returned at // the end of the iteration. FPp.map = function map(callback/*, name1, name2, ... */) { var s = this.stack; var origLen = s.length; var value = s[origLen - 1]; var argc = arguments.length; for (var i = 1; i < argc; ++i) { var name = arguments[i]; value = value[name]; s.push(name, value); } var result = new Array(value.length); for (var i = 0; i < value.length; ++i) { if (i in value) { s.push(i, value[i]); result[i] = callback(this, i); s.length -= 2; } } s.length = origLen; return result; }; // Inspired by require("ast-types").NodePath.prototype.needsParens, but // more efficient because we're iterating backwards through a stack. FPp.needsParens = function(assumeExpressionContext) { var parent = this.getParentNode(); if (!parent) { return false; } var name = this.getName(); var node = this.getNode(); // If the value of this path is some child of a Node and not a Node // itself, then it doesn't need parentheses. Only Node objects (in // fact, only Expression nodes) need parentheses. if (this.getValue() !== node) { return false; } // Only expressions need parentheses. if (!n.Expression.check(node)) { return false; } // Identifiers never need parentheses. if (node.type === "Identifier") { return false; } switch (node.type) { case "UnaryExpression": case "SpreadElement": case "SpreadProperty": return parent.type === "MemberExpression" && name === "object" && parent.object === node; case "BinaryExpression": case "LogicalExpression": switch (parent.type) { case "CallExpression": return name === "callee" && parent.callee === node; case "UnaryExpression": case "SpreadElement": case "SpreadProperty": return true; case "MemberExpression": return name === "object" && parent.object === node; case "BinaryExpression": case "LogicalExpression": var po = parent.operator; var pp = PRECEDENCE[po]; var no = node.operator; var np = PRECEDENCE[no]; if (pp > np) { return true; } if (pp === np && name === "right") { assert.strictEqual(parent.right, node); return true; } default: return false; } case "SequenceExpression": switch (parent.type) { case "ForStatement": // Although parentheses wouldn't hurt around sequence // expressions in the head of for loops, traditional style // dictates that e.g. i++, j++ should not be wrapped with // parentheses. return false; case "ExpressionStatement": return name !== "expression"; default: // Otherwise err on the side of overparenthesization, adding // explicit exceptions above if this proves overzealous. return true; } case "YieldExpression": switch (parent.type) { case "BinaryExpression": case "LogicalExpression": case "UnaryExpression": case "SpreadElement": case "SpreadProperty": case "CallExpression": case "MemberExpression": case "NewExpression": case "ConditionalExpression": case "YieldExpression": return true; default: return false; } case "Literal": return parent.type === "MemberExpression" && isNumber.check(node.value) && name === "object" && parent.object === node; case "AssignmentExpression": case "ConditionalExpression": switch (parent.type) { case "UnaryExpression": case "SpreadElement": case "SpreadProperty": case "BinaryExpression": case "LogicalExpression": return true; case "CallExpression": return name === "callee" && parent.callee === node; case "ConditionalExpression": return name === "test" && parent.test === node; case "MemberExpression": return name === "object" && parent.object === node; default: return false; } case "ArrowFunctionExpression": return isBinary(parent); case "ObjectExpression": if (parent.type === "ArrowFunctionExpression" && name === "body") { return true; } default: if (parent.type === "NewExpression" && name === "callee" && parent.callee === node) { return containsCallExpression(node); } } if (assumeExpressionContext !== true && !this.canBeFirstInStatement() && this.firstInStatement()) return true; return false; }; function isBinary(node) { return n.BinaryExpression.check(node) || n.LogicalExpression.check(node); } function isUnaryLike(node) { return n.UnaryExpression.check(node) // I considered making SpreadElement and SpreadProperty subtypes // of UnaryExpression, but they're not really Expression nodes. || (n.SpreadElement && n.SpreadElement.check(node)) || (n.SpreadProperty && n.SpreadProperty.check(node)); } var PRECEDENCE = {}; [["||"], ["&&"], ["|"], ["^"], ["&"], ["==", "===", "!=", "!=="], ["<", ">", "<=", ">=", "in", "instanceof"], [">>", "<<", ">>>"], ["+", "-"], ["*", "/", "%"] ].forEach(function(tier, i) { tier.forEach(function(op) { PRECEDENCE[op] = i; }); }); function containsCallExpression(node) { if (n.CallExpression.check(node)) { return true; } if (isArray.check(node)) { return node.some(containsCallExpression); } if (n.Node.check(node)) { return types.someField(node, function(name, child) { return containsCallExpression(child); }); } return false; } FPp.canBeFirstInStatement = function() { var node = this.getNode(); return !n.FunctionExpression.check(node) && !n.ObjectExpression.check(node); }; FPp.firstInStatement = function() { var s = this.stack; var parentName, parent; var childName, child; for (var i = s.length - 1; i >= 0; i -= 2) { if (n.Node.check(s[i])) { childName = parentName; child = parent; parentName = s[i - 1]; parent = s[i]; } if (!parent || !child) { continue; } if (n.BlockStatement.check(parent) && parentName === "body" && childName === 0) { assert.strictEqual(parent.body[0], child); return true; } if (n.ExpressionStatement.check(parent) && childName === "expression") { assert.strictEqual(parent.expression, child); return true; } if (n.SequenceExpression.check(parent) && parentName === "expressions" && childName === 0) { assert.strictEqual(parent.expressions[0], child); continue; } if (n.CallExpression.check(parent) && childName === "callee") { assert.strictEqual(parent.callee, child); continue; } if (n.MemberExpression.check(parent) && childName === "object") { assert.strictEqual(parent.object, child); continue; } if (n.ConditionalExpression.check(parent) && childName === "test") { assert.strictEqual(parent.test, child); continue; } if (isBinary(parent) && childName === "left") { assert.strictEqual(parent.left, child); continue; } if (n.UnaryExpression.check(parent) && !parent.prefix && childName === "argument") { assert.strictEqual(parent.argument, child); continue; } return false; } return true; }; },{"./types":467,"assert":190}],461:[function(require,module,exports){ var assert = require("assert"); var sourceMap = require("source-map"); var normalizeOptions = require("./options").normalize; var secretKey = require("private").makeUniqueKey(); var types = require("./types"); var isString = types.builtInTypes.string; var comparePos = require("./util").comparePos; var Mapping = require("./mapping"); // Goals: // 1. Minimize new string creation. // 2. Keep (de)identation O(lines) time. // 3. Permit negative indentations. // 4. Enforce immutability. // 5. No newline characters. function getSecret(lines) { return lines[secretKey]; } function Lines(infos, sourceFileName) { assert.ok(this instanceof Lines); assert.ok(infos.length > 0); if (sourceFileName) { isString.assert(sourceFileName); } else { sourceFileName = null; } Object.defineProperty(this, secretKey, { value: { infos: infos, mappings: [], name: sourceFileName, cachedSourceMap: null } }); if (sourceFileName) { getSecret(this).mappings.push(new Mapping(this, { start: this.firstPos(), end: this.lastPos() })); } } // Exposed for instanceof checks. The fromString function should be used // to create new Lines objects. exports.Lines = Lines; var Lp = Lines.prototype; // These properties used to be assigned to each new object in the Lines // constructor, but we can more efficiently stuff them into the secret and // let these lazy accessors compute their values on-the-fly. Object.defineProperties(Lp, { length: { get: function() { return getSecret(this).infos.length; } }, name: { get: function() { return getSecret(this).name; } } }); function copyLineInfo(info) { return { line: info.line, indent: info.indent, sliceStart: info.sliceStart, sliceEnd: info.sliceEnd }; } var fromStringCache = {}; var hasOwn = fromStringCache.hasOwnProperty; var maxCacheKeyLen = 10; function countSpaces(spaces, tabWidth) { var count = 0; var len = spaces.length; for (var i = 0; i < len; ++i) { switch (spaces.charCodeAt(i)) { case 9: // '\t' assert.strictEqual(typeof tabWidth, "number"); assert.ok(tabWidth > 0); var next = Math.ceil(count / tabWidth) * tabWidth; if (next === count) { count += tabWidth; } else { count = next; } break; case 11: // '\v' case 12: // '\f' case 13: // '\r' case 0xfeff: // zero-width non-breaking space // These characters contribute nothing to indentation. break; case 32: // ' ' default: // Treat all other whitespace like ' '. count += 1; break; } } return count; } exports.countSpaces = countSpaces; var leadingSpaceExp = /^\s*/; /** * @param {Object} options - Options object that configures printing. */ function fromString(string, options) { if (string instanceof Lines) return string; string += ""; var tabWidth = options && options.tabWidth; var tabless = string.indexOf("\t") < 0; var cacheable = !options && tabless && (string.length <= maxCacheKeyLen); assert.ok(tabWidth || tabless, "No tab width specified but encountered tabs in string\n" + string); if (cacheable && hasOwn.call(fromStringCache, string)) return fromStringCache[string]; var lines = new Lines(string.split("\n").map(function(line) { var spaces = leadingSpaceExp.exec(line)[0]; return { line: line, indent: countSpaces(spaces, tabWidth), sliceStart: spaces.length, sliceEnd: line.length }; }), normalizeOptions(options).sourceFileName); if (cacheable) fromStringCache[string] = lines; return lines; } exports.fromString = fromString; function isOnlyWhitespace(string) { return !/\S/.test(string); } Lp.toString = function(options) { return this.sliceString(this.firstPos(), this.lastPos(), options); }; Lp.getSourceMap = function(sourceMapName, sourceRoot) { if (!sourceMapName) { // Although we could make up a name or generate an anonymous // source map, instead we assume that any consumer who does not // provide a name does not actually want a source map. return null; } var targetLines = this; function updateJSON(json) { json = json || {}; isString.assert(sourceMapName); json.file = sourceMapName; if (sourceRoot) { isString.assert(sourceRoot); json.sourceRoot = sourceRoot; } return json; } var secret = getSecret(targetLines); if (secret.cachedSourceMap) { // Since Lines objects are immutable, we can reuse any source map // that was previously generated. Nevertheless, we return a new // JSON object here to protect the cached source map from outside // modification. return updateJSON(secret.cachedSourceMap.toJSON()); } var smg = new sourceMap.SourceMapGenerator(updateJSON()); var sourcesToContents = {}; secret.mappings.forEach(function(mapping) { var sourceCursor = mapping.sourceLines.skipSpaces( mapping.sourceLoc.start ) || mapping.sourceLines.lastPos(); var targetCursor = targetLines.skipSpaces( mapping.targetLoc.start ) || targetLines.lastPos(); while (comparePos(sourceCursor, mapping.sourceLoc.end) < 0 && comparePos(targetCursor, mapping.targetLoc.end) < 0) { var sourceChar = mapping.sourceLines.charAt(sourceCursor); var targetChar = targetLines.charAt(targetCursor); assert.strictEqual(sourceChar, targetChar); var sourceName = mapping.sourceLines.name; // Add mappings one character at a time for maximum resolution. smg.addMapping({ source: sourceName, original: { line: sourceCursor.line, column: sourceCursor.column }, generated: { line: targetCursor.line, column: targetCursor.column } }); if (!hasOwn.call(sourcesToContents, sourceName)) { var sourceContent = mapping.sourceLines.toString(); smg.setSourceContent(sourceName, sourceContent); sourcesToContents[sourceName] = sourceContent; } targetLines.nextPos(targetCursor, true); mapping.sourceLines.nextPos(sourceCursor, true); } }); secret.cachedSourceMap = smg; return smg.toJSON(); }; Lp.bootstrapCharAt = function(pos) { assert.strictEqual(typeof pos, "object"); assert.strictEqual(typeof pos.line, "number"); assert.strictEqual(typeof pos.column, "number"); var line = pos.line, column = pos.column, strings = this.toString().split("\n"), string = strings[line - 1]; if (typeof string === "undefined") return ""; if (column === string.length && line < strings.length) return "\n"; if (column >= string.length) return ""; return string.charAt(column); }; Lp.charAt = function(pos) { assert.strictEqual(typeof pos, "object"); assert.strictEqual(typeof pos.line, "number"); assert.strictEqual(typeof pos.column, "number"); var line = pos.line, column = pos.column, secret = getSecret(this), infos = secret.infos, info = infos[line - 1], c = column; if (typeof info === "undefined" || c < 0) return ""; var indent = this.getIndentAt(line); if (c < indent) return " "; c += info.sliceStart - indent; if (c === info.sliceEnd && line < this.length) return "\n"; if (c >= info.sliceEnd) return ""; return info.line.charAt(c); }; Lp.stripMargin = function(width, skipFirstLine) { if (width === 0) return this; assert.ok(width > 0, "negative margin: " + width); if (skipFirstLine && this.length === 1) return this; var secret = getSecret(this); var lines = new Lines(secret.infos.map(function(info, i) { if (info.line && (i > 0 || !skipFirstLine)) { info = copyLineInfo(info); info.indent = Math.max(0, info.indent - width); } return info; })); if (secret.mappings.length > 0) { var newMappings = getSecret(lines).mappings; assert.strictEqual(newMappings.length, 0); secret.mappings.forEach(function(mapping) { newMappings.push(mapping.indent(width, skipFirstLine, true)); }); } return lines; }; Lp.indent = function(by) { if (by === 0) return this; var secret = getSecret(this); var lines = new Lines(secret.infos.map(function(info) { if (info.line) { info = copyLineInfo(info); info.indent += by; } return info })); if (secret.mappings.length > 0) { var newMappings = getSecret(lines).mappings; assert.strictEqual(newMappings.length, 0); secret.mappings.forEach(function(mapping) { newMappings.push(mapping.indent(by)); }); } return lines; }; Lp.indentTail = function(by) { if (by === 0) return this; if (this.length < 2) return this; var secret = getSecret(this); var lines = new Lines(secret.infos.map(function(info, i) { if (i > 0 && info.line) { info = copyLineInfo(info); info.indent += by; } return info; })); if (secret.mappings.length > 0) { var newMappings = getSecret(lines).mappings; assert.strictEqual(newMappings.length, 0); secret.mappings.forEach(function(mapping) { newMappings.push(mapping.indent(by, true)); }); } return lines; }; Lp.getIndentAt = function(line) { assert.ok(line >= 1, "no line " + line + " (line numbers start from 1)"); var secret = getSecret(this), info = secret.infos[line - 1]; return Math.max(info.indent, 0); }; Lp.guessTabWidth = function() { var secret = getSecret(this); if (hasOwn.call(secret, "cachedTabWidth")) { return secret.cachedTabWidth; } var counts = []; // Sparse array. var lastIndent = 0; for (var line = 1, last = this.length; line <= last; ++line) { var info = secret.infos[line - 1]; var sliced = info.line.slice(info.sliceStart, info.sliceEnd); // Whitespace-only lines don't tell us much about the likely tab // width of this code. if (isOnlyWhitespace(sliced)) { continue; } var diff = Math.abs(info.indent - lastIndent); counts[diff] = ~~counts[diff] + 1; lastIndent = info.indent; } var maxCount = -1; var result = 2; for (var tabWidth = 1; tabWidth < counts.length; tabWidth += 1) { if (hasOwn.call(counts, tabWidth) && counts[tabWidth] > maxCount) { maxCount = counts[tabWidth]; result = tabWidth; } } return secret.cachedTabWidth = result; }; Lp.isOnlyWhitespace = function() { return isOnlyWhitespace(this.toString()); }; Lp.isPrecededOnlyByWhitespace = function(pos) { var secret = getSecret(this); var info = secret.infos[pos.line - 1]; var indent = Math.max(info.indent, 0); var diff = pos.column - indent; if (diff <= 0) { // If pos.column does not exceed the indentation amount, then // there must be only whitespace before it. return true; } var start = info.sliceStart; var end = Math.min(start + diff, info.sliceEnd); var prefix = info.line.slice(start, end); return isOnlyWhitespace(prefix); }; Lp.getLineLength = function(line) { var secret = getSecret(this), info = secret.infos[line - 1]; return this.getIndentAt(line) + info.sliceEnd - info.sliceStart; }; Lp.nextPos = function(pos, skipSpaces) { var l = Math.max(pos.line, 0), c = Math.max(pos.column, 0); if (c < this.getLineLength(l)) { pos.column += 1; return skipSpaces ? !!this.skipSpaces(pos, false, true) : true; } if (l < this.length) { pos.line += 1; pos.column = 0; return skipSpaces ? !!this.skipSpaces(pos, false, true) : true; } return false; }; Lp.prevPos = function(pos, skipSpaces) { var l = pos.line, c = pos.column; if (c < 1) { l -= 1; if (l < 1) return false; c = this.getLineLength(l); } else { c = Math.min(c - 1, this.getLineLength(l)); } pos.line = l; pos.column = c; return skipSpaces ? !!this.skipSpaces(pos, true, true) : true; }; Lp.firstPos = function() { // Trivial, but provided for completeness. return { line: 1, column: 0 }; }; Lp.lastPos = function() { return { line: this.length, column: this.getLineLength(this.length) }; }; Lp.skipSpaces = function(pos, backward, modifyInPlace) { if (pos) { pos = modifyInPlace ? pos : { line: pos.line, column: pos.column }; } else if (backward) { pos = this.lastPos(); } else { pos = this.firstPos(); } if (backward) { while (this.prevPos(pos)) { if (!isOnlyWhitespace(this.charAt(pos)) && this.nextPos(pos)) { return pos; } } return null; } else { while (isOnlyWhitespace(this.charAt(pos))) { if (!this.nextPos(pos)) { return null; } } return pos; } }; Lp.trimLeft = function() { var pos = this.skipSpaces(this.firstPos(), false, true); return pos ? this.slice(pos) : emptyLines; }; Lp.trimRight = function() { var pos = this.skipSpaces(this.lastPos(), true, true); return pos ? this.slice(this.firstPos(), pos) : emptyLines; }; Lp.trim = function() { var start = this.skipSpaces(this.firstPos(), false, true); if (start === null) return emptyLines; var end = this.skipSpaces(this.lastPos(), true, true); assert.notStrictEqual(end, null); return this.slice(start, end); }; Lp.eachPos = function(callback, startPos, skipSpaces) { var pos = this.firstPos(); if (startPos) { pos.line = startPos.line, pos.column = startPos.column } if (skipSpaces && !this.skipSpaces(pos, false, true)) { return; // Encountered nothing but spaces. } do callback.call(this, pos); while (this.nextPos(pos, skipSpaces)); }; Lp.bootstrapSlice = function(start, end) { var strings = this.toString().split("\n").slice( start.line - 1, end.line); strings.push(strings.pop().slice(0, end.column)); strings[0] = strings[0].slice(start.column); return fromString(strings.join("\n")); }; Lp.slice = function(start, end) { if (!end) { if (!start) { // The client seems to want a copy of this Lines object, but // Lines objects are immutable, so it's perfectly adequate to // return the same object. return this; } // Slice to the end if no end position was provided. end = this.lastPos(); } var secret = getSecret(this); var sliced = secret.infos.slice(start.line - 1, end.line); if (start.line === end.line) { sliced[0] = sliceInfo(sliced[0], start.column, end.column); } else { assert.ok(start.line < end.line); sliced[0] = sliceInfo(sliced[0], start.column); sliced.push(sliceInfo(sliced.pop(), 0, end.column)); } var lines = new Lines(sliced); if (secret.mappings.length > 0) { var newMappings = getSecret(lines).mappings; assert.strictEqual(newMappings.length, 0); secret.mappings.forEach(function(mapping) { var sliced = mapping.slice(this, start, end); if (sliced) { newMappings.push(sliced); } }, this); } return lines; }; function sliceInfo(info, startCol, endCol) { var sliceStart = info.sliceStart; var sliceEnd = info.sliceEnd; var indent = Math.max(info.indent, 0); var lineLength = indent + sliceEnd - sliceStart; if (typeof endCol === "undefined") { endCol = lineLength; } startCol = Math.max(startCol, 0); endCol = Math.min(endCol, lineLength); endCol = Math.max(endCol, startCol); if (endCol < indent) { indent = endCol; sliceEnd = sliceStart; } else { sliceEnd -= lineLength - endCol; } lineLength = endCol; lineLength -= startCol; if (startCol < indent) { indent -= startCol; } else { startCol -= indent; indent = 0; sliceStart += startCol; } assert.ok(indent >= 0); assert.ok(sliceStart <= sliceEnd); assert.strictEqual(lineLength, indent + sliceEnd - sliceStart); if (info.indent === indent && info.sliceStart === sliceStart && info.sliceEnd === sliceEnd) { return info; } return { line: info.line, indent: indent, sliceStart: sliceStart, sliceEnd: sliceEnd }; } Lp.bootstrapSliceString = function(start, end, options) { return this.slice(start, end).toString(options); }; Lp.sliceString = function(start, end, options) { if (!end) { if (!start) { // The client seems to want a copy of this Lines object, but // Lines objects are immutable, so it's perfectly adequate to // return the same object. return this; } // Slice to the end if no end position was provided. end = this.lastPos(); } options = normalizeOptions(options); var infos = getSecret(this).infos; var parts = []; var tabWidth = options.tabWidth; for (var line = start.line; line <= end.line; ++line) { var info = infos[line - 1]; if (line === start.line) { if (line === end.line) { info = sliceInfo(info, start.column, end.column); } else { info = sliceInfo(info, start.column); } } else if (line === end.line) { info = sliceInfo(info, 0, end.column); } var indent = Math.max(info.indent, 0); var before = info.line.slice(0, info.sliceStart); if (options.reuseWhitespace && isOnlyWhitespace(before) && countSpaces(before, options.tabWidth) === indent) { // Reuse original spaces if the indentation is correct. parts.push(info.line.slice(0, info.sliceEnd)); continue; } var tabs = 0; var spaces = indent; if (options.useTabs) { tabs = Math.floor(indent / tabWidth); spaces -= tabs * tabWidth; } var result = ""; if (tabs > 0) { result += new Array(tabs + 1).join("\t"); } if (spaces > 0) { result += new Array(spaces + 1).join(" "); } result += info.line.slice(info.sliceStart, info.sliceEnd); parts.push(result); } return parts.join("\n"); }; Lp.isEmpty = function() { return this.length < 2 && this.getLineLength(1) < 1; }; Lp.join = function(elements) { var separator = this; var separatorSecret = getSecret(separator); var infos = []; var mappings = []; var prevInfo; function appendSecret(secret) { if (secret === null) return; if (prevInfo) { var info = secret.infos[0]; var indent = new Array(info.indent + 1).join(" "); var prevLine = infos.length; var prevColumn = Math.max(prevInfo.indent, 0) + prevInfo.sliceEnd - prevInfo.sliceStart; prevInfo.line = prevInfo.line.slice( 0, prevInfo.sliceEnd) + indent + info.line.slice( info.sliceStart, info.sliceEnd); prevInfo.sliceEnd = prevInfo.line.length; if (secret.mappings.length > 0) { secret.mappings.forEach(function(mapping) { mappings.push(mapping.add(prevLine, prevColumn)); }); } } else if (secret.mappings.length > 0) { mappings.push.apply(mappings, secret.mappings); } secret.infos.forEach(function(info, i) { if (!prevInfo || i > 0) { prevInfo = copyLineInfo(info); infos.push(prevInfo); } }); } function appendWithSeparator(secret, i) { if (i > 0) appendSecret(separatorSecret); appendSecret(secret); } elements.map(function(elem) { var lines = fromString(elem); if (lines.isEmpty()) return null; return getSecret(lines); }).forEach(separator.isEmpty() ? appendSecret : appendWithSeparator); if (infos.length < 1) return emptyLines; var lines = new Lines(infos); getSecret(lines).mappings = mappings; return lines; }; exports.concat = function(elements) { return emptyLines.join(elements); }; Lp.concat = function(other) { var args = arguments, list = [this]; list.push.apply(list, args); assert.strictEqual(list.length, args.length + 1); return emptyLines.join(list); }; // The emptyLines object needs to be created all the way down here so that // Lines.prototype will be fully populated. var emptyLines = fromString(""); },{"./mapping":462,"./options":463,"./types":467,"./util":468,"assert":190,"private":435,"source-map":483}],462:[function(require,module,exports){ var assert = require("assert"); var types = require("./types"); var isString = types.builtInTypes.string; var isNumber = types.builtInTypes.number; var SourceLocation = types.namedTypes.SourceLocation; var Position = types.namedTypes.Position; var linesModule = require("./lines"); var comparePos = require("./util").comparePos; function Mapping(sourceLines, sourceLoc, targetLoc) { assert.ok(this instanceof Mapping); assert.ok(sourceLines instanceof linesModule.Lines); SourceLocation.assert(sourceLoc); if (targetLoc) { // In certain cases it's possible for targetLoc.{start,end}.column // values to be negative, which technically makes them no longer // valid SourceLocation nodes, so we need to be more forgiving. assert.ok( isNumber.check(targetLoc.start.line) && isNumber.check(targetLoc.start.column) && isNumber.check(targetLoc.end.line) && isNumber.check(targetLoc.end.column) ); } else { // Assume identity mapping if no targetLoc specified. targetLoc = sourceLoc; } Object.defineProperties(this, { sourceLines: { value: sourceLines }, sourceLoc: { value: sourceLoc }, targetLoc: { value: targetLoc } }); } var Mp = Mapping.prototype; module.exports = Mapping; Mp.slice = function(lines, start, end) { assert.ok(lines instanceof linesModule.Lines); Position.assert(start); if (end) { Position.assert(end); } else { end = lines.lastPos(); } var sourceLines = this.sourceLines; var sourceLoc = this.sourceLoc; var targetLoc = this.targetLoc; function skip(name) { var sourceFromPos = sourceLoc[name]; var targetFromPos = targetLoc[name]; var targetToPos = start; if (name === "end") { targetToPos = end; } else { assert.strictEqual(name, "start"); } return skipChars( sourceLines, sourceFromPos, lines, targetFromPos, targetToPos ); } if (comparePos(start, targetLoc.start) <= 0) { if (comparePos(targetLoc.end, end) <= 0) { targetLoc = { start: subtractPos(targetLoc.start, start.line, start.column), end: subtractPos(targetLoc.end, start.line, start.column) }; // The sourceLoc can stay the same because the contents of the // targetLoc have not changed. } else if (comparePos(end, targetLoc.start) <= 0) { return null; } else { sourceLoc = { start: sourceLoc.start, end: skip("end") }; targetLoc = { start: subtractPos(targetLoc.start, start.line, start.column), end: subtractPos(end, start.line, start.column) }; } } else { if (comparePos(targetLoc.end, start) <= 0) { return null; } if (comparePos(targetLoc.end, end) <= 0) { sourceLoc = { start: skip("start"), end: sourceLoc.end }; targetLoc = { // Same as subtractPos(start, start.line, start.column): start: { line: 1, column: 0 }, end: subtractPos(targetLoc.end, start.line, start.column) }; } else { sourceLoc = { start: skip("start"), end: skip("end") }; targetLoc = { // Same as subtractPos(start, start.line, start.column): start: { line: 1, column: 0 }, end: subtractPos(end, start.line, start.column) }; } } return new Mapping(this.sourceLines, sourceLoc, targetLoc); }; Mp.add = function(line, column) { return new Mapping(this.sourceLines, this.sourceLoc, { start: addPos(this.targetLoc.start, line, column), end: addPos(this.targetLoc.end, line, column) }); }; function addPos(toPos, line, column) { return { line: toPos.line + line - 1, column: (toPos.line === 1) ? toPos.column + column : toPos.column }; } Mp.subtract = function(line, column) { return new Mapping(this.sourceLines, this.sourceLoc, { start: subtractPos(this.targetLoc.start, line, column), end: subtractPos(this.targetLoc.end, line, column) }); }; function subtractPos(fromPos, line, column) { return { line: fromPos.line - line + 1, column: (fromPos.line === line) ? fromPos.column - column : fromPos.column }; } Mp.indent = function(by, skipFirstLine, noNegativeColumns) { if (by === 0) { return this; } var targetLoc = this.targetLoc; var startLine = targetLoc.start.line; var endLine = targetLoc.end.line; if (skipFirstLine && startLine === 1 && endLine === 1) { return this; } targetLoc = { start: targetLoc.start, end: targetLoc.end }; if (!skipFirstLine || startLine > 1) { var startColumn = targetLoc.start.column + by; targetLoc.start = { line: startLine, column: noNegativeColumns ? Math.max(0, startColumn) : startColumn }; } if (!skipFirstLine || endLine > 1) { var endColumn = targetLoc.end.column + by; targetLoc.end = { line: endLine, column: noNegativeColumns ? Math.max(0, endColumn) : endColumn }; } return new Mapping(this.sourceLines, this.sourceLoc, targetLoc); }; function skipChars( sourceLines, sourceFromPos, targetLines, targetFromPos, targetToPos ) { assert.ok(sourceLines instanceof linesModule.Lines); assert.ok(targetLines instanceof linesModule.Lines); Position.assert(sourceFromPos); Position.assert(targetFromPos); Position.assert(targetToPos); var targetComparison = comparePos(targetFromPos, targetToPos); if (targetComparison === 0) { // Trivial case: no characters to skip. return sourceFromPos; } if (targetComparison < 0) { // Skipping forward. var sourceCursor = sourceLines.skipSpaces(sourceFromPos); var targetCursor = targetLines.skipSpaces(targetFromPos); var lineDiff = targetToPos.line - targetCursor.line; sourceCursor.line += lineDiff; targetCursor.line += lineDiff; if (lineDiff > 0) { // If jumping to later lines, reset columns to the beginnings // of those lines. sourceCursor.column = 0; targetCursor.column = 0; } else { assert.strictEqual(lineDiff, 0); } while (comparePos(targetCursor, targetToPos) < 0 && targetLines.nextPos(targetCursor, true)) { assert.ok(sourceLines.nextPos(sourceCursor, true)); assert.strictEqual( sourceLines.charAt(sourceCursor), targetLines.charAt(targetCursor) ); } } else { // Skipping backward. var sourceCursor = sourceLines.skipSpaces(sourceFromPos, true); var targetCursor = targetLines.skipSpaces(targetFromPos, true); var lineDiff = targetToPos.line - targetCursor.line; sourceCursor.line += lineDiff; targetCursor.line += lineDiff; if (lineDiff < 0) { // If jumping to earlier lines, reset columns to the ends of // those lines. sourceCursor.column = sourceLines.getLineLength(sourceCursor.line); targetCursor.column = targetLines.getLineLength(targetCursor.line); } else { assert.strictEqual(lineDiff, 0); } while (comparePos(targetToPos, targetCursor) < 0 && targetLines.prevPos(targetCursor, true)) { assert.ok(sourceLines.prevPos(sourceCursor, true)); assert.strictEqual( sourceLines.charAt(sourceCursor), targetLines.charAt(targetCursor) ); } } return sourceCursor; } },{"./lines":461,"./types":467,"./util":468,"assert":190}],463:[function(require,module,exports){ var defaults = { // If you want to use a different branch of esprima, or any other // module that supports a .parse function, pass that module object to // recast.parse as options.esprima. esprima: require("esprima-fb"), // Number of spaces the pretty-printer should use per tab for // indentation. If you do not pass this option explicitly, it will be // (quite reliably!) inferred from the original code. tabWidth: 4, // If you really want the pretty-printer to use tabs instead of // spaces, make this option true. useTabs: false, // The reprinting code leaves leading whitespace untouched unless it // has to reindent a line, or you pass false for this option. reuseWhitespace: true, // Some of the pretty-printer code (such as that for printing function // parameter lists) makes a valiant attempt to prevent really long // lines. You can adjust the limit by changing this option; however, // there is no guarantee that line length will fit inside this limit. wrapColumn: 74, // Aspirational for now. // Pass a string as options.sourceFileName to recast.parse to tell the // reprinter to keep track of reused code so that it can construct a // source map automatically. sourceFileName: null, // Pass a string as options.sourceMapName to recast.print, and // (provided you passed options.sourceFileName earlier) the // PrintResult of recast.print will have a .map property for the // generated source map. sourceMapName: null, // If provided, this option will be passed along to the source map // generator as a root directory for relative source file paths. sourceRoot: null, // If you provide a source map that was generated from a previous call // to recast.print as options.inputSourceMap, the old source map will // be composed with the new source map. inputSourceMap: null, // If you want esprima to generate .range information (recast only // uses .loc internally), pass true for this option. range: false, // If you want esprima not to throw exceptions when it encounters // non-fatal errors, keep this option true. tolerant: true, // If you want to override the quotes used in string literals, specify // either "single", "double", or "auto" here ("auto" will select the one // which results in the shorter literal) // Otherwise, the input marks will be preserved quote: null, }, hasOwn = defaults.hasOwnProperty; // Copy options and fill in default values. exports.normalize = function(options) { options = options || defaults; function get(key) { return hasOwn.call(options, key) ? options[key] : defaults[key]; } return { tabWidth: +get("tabWidth"), useTabs: !!get("useTabs"), reuseWhitespace: !!get("reuseWhitespace"), wrapColumn: Math.max(get("wrapColumn"), 0), sourceFileName: get("sourceFileName"), sourceMapName: get("sourceMapName"), sourceRoot: get("sourceRoot"), inputSourceMap: get("inputSourceMap"), esprima: get("esprima"), range: get("range"), tolerant: get("tolerant"), quote: get("quote"), }; }; },{"esprima-fb":470}],464:[function(require,module,exports){ var assert = require("assert"); var types = require("./types"); var n = types.namedTypes; var b = types.builders; var isObject = types.builtInTypes.object; var isArray = types.builtInTypes.array; var isFunction = types.builtInTypes.function; var Patcher = require("./patcher").Patcher; var normalizeOptions = require("./options").normalize; var fromString = require("./lines").fromString; var attachComments = require("./comments").attach; var util = require("./util"); exports.parse = function parse(source, options) { options = normalizeOptions(options); var lines = fromString(source, options); var sourceWithoutTabs = lines.toString({ tabWidth: options.tabWidth, reuseWhitespace: false, useTabs: false }); var program = options.esprima.parse(sourceWithoutTabs, { loc: true, range: options.range, comment: true, tolerant: options.tolerant, sourceType: 'module' }); // Expand the Program node's .loc to include all comments, since // typically its .loc.start and .loc.end will coincide with those of // the first and last statements, respectively, excluding any comments // that fall outside that region. program.loc = util.getTrueLoc(program); var comments = program.comments; delete program.comments; // In order to ensure we reprint leading and trailing program // comments, wrap the original Program node with a File node. var file = b.file(program); file.loc = { lines: lines, indent: 0, start: lines.firstPos(), end: lines.lastPos() }; // Passing file.program here instead of just file means that initial // comments will be attached to program.body[0] instead of program. attachComments( comments, program.body.length ? file.program : file, lines ); // Return a copy of the original AST so that any changes made may be // compared to the original. return new TreeCopier(lines).copy(file); }; function TreeCopier(lines) { assert.ok(this instanceof TreeCopier); this.lines = lines; this.indent = 0; } var TCp = TreeCopier.prototype; TCp.copy = function(node) { if (isArray.check(node)) { return node.map(this.copy, this); } if (!isObject.check(node)) { return node; } util.fixFaultyLocations(node); var copy = Object.create(Object.getPrototypeOf(node), { original: { // Provide a link from the copy to the original. value: node, configurable: false, enumerable: false, writable: true } }); var loc = node.loc; var oldIndent = this.indent; var newIndent = oldIndent; if (loc) { // When node is a comment, we set node.loc.indent to // node.loc.start.column so that, when/if we print the comment by // itself, we can strip that much whitespace from the left margin // of the comment. This only really matters for multiline Block // comments, but it doesn't hurt for Line comments. if (node.type === "Block" || node.type === "Line" || this.lines.isPrecededOnlyByWhitespace(loc.start)) { newIndent = this.indent = loc.start.column; } loc.lines = this.lines; loc.indent = newIndent; } var keys = Object.keys(node); var keyCount = keys.length; for (var i = 0; i < keyCount; ++i) { var key = keys[i]; if (key === "loc") { copy[key] = node[key]; } else { copy[key] = this.copy(node[key]); } } this.indent = oldIndent; return copy; }; },{"./comments":459,"./lines":461,"./options":463,"./patcher":465,"./types":467,"./util":468,"assert":190}],465:[function(require,module,exports){ var assert = require("assert"); var linesModule = require("./lines"); var types = require("./types"); var getFieldValue = types.getFieldValue; var Printable = types.namedTypes.Printable; var Expression = types.namedTypes.Expression; var SourceLocation = types.namedTypes.SourceLocation; var util = require("./util"); var comparePos = util.comparePos; var FastPath = require("./fast-path"); var isObject = types.builtInTypes.object; var isArray = types.builtInTypes.array; var isString = types.builtInTypes.string; var riskyAdjoiningCharExp = /[0-9a-z_$]/i; function Patcher(lines) { assert.ok(this instanceof Patcher); assert.ok(lines instanceof linesModule.Lines); var self = this, replacements = []; self.replace = function(loc, lines) { if (isString.check(lines)) lines = linesModule.fromString(lines); replacements.push({ lines: lines, start: loc.start, end: loc.end }); }; self.get = function(loc) { // If no location is provided, return the complete Lines object. loc = loc || { start: { line: 1, column: 0 }, end: { line: lines.length, column: lines.getLineLength(lines.length) } }; var sliceFrom = loc.start, toConcat = []; function pushSlice(from, to) { assert.ok(comparePos(from, to) <= 0); toConcat.push(lines.slice(from, to)); } replacements.sort(function(a, b) { return comparePos(a.start, b.start); }).forEach(function(rep) { if (comparePos(sliceFrom, rep.start) > 0) { // Ignore nested replacement ranges. } else { pushSlice(sliceFrom, rep.start); toConcat.push(rep.lines); sliceFrom = rep.end; } }); pushSlice(sliceFrom, loc.end); return linesModule.concat(toConcat); }; } exports.Patcher = Patcher; var Pp = Patcher.prototype; Pp.tryToReprintComments = function(newNode, oldNode, print) { var patcher = this; if (!newNode.comments && !oldNode.comments) { // We were (vacuously) able to reprint all the comments! return true; } var newPath = FastPath.from(newNode); var oldPath = FastPath.from(oldNode); newPath.stack.push("comments", getSurroundingComments(newNode)); oldPath.stack.push("comments", getSurroundingComments(oldNode)); var reprints = []; var ableToReprintComments = findArrayReprints(newPath, oldPath, reprints); // No need to pop anything from newPath.stack or oldPath.stack, since // newPath and oldPath are fresh local variables. if (ableToReprintComments && reprints.length > 0) { reprints.forEach(function(reprint) { var oldComment = reprint.oldPath.getValue(); assert.ok(oldComment.leading || oldComment.trailing); patcher.replace( oldComment.loc, // Comments can't have .comments, so it doesn't matter // whether we print with comments or without. print(reprint.newPath).indentTail(oldComment.loc.indent) ); }); } return ableToReprintComments; }; // Get all comments that are either leading or trailing, ignoring any // comments that occur inside node.loc. Returns an empty array for nodes // with no leading or trailing comments. function getSurroundingComments(node) { var result = []; if (node.comments && node.comments.length > 0) { node.comments.forEach(function(comment) { if (comment.leading || comment.trailing) { result.push(comment); } }); } return result; } Pp.deleteComments = function(node) { if (!node.comments) { return; } var patcher = this; node.comments.forEach(function(comment) { if (comment.leading) { // Delete leading comments along with any trailing whitespace // they might have. patcher.replace({ start: comment.loc.start, end: node.loc.lines.skipSpaces( comment.loc.end, false, false) }, ""); } else if (comment.trailing) { // Delete trailing comments along with any leading whitespace // they might have. patcher.replace({ start: node.loc.lines.skipSpaces( comment.loc.start, true, false), end: comment.loc.end }, ""); } }); }; exports.getReprinter = function(path) { assert.ok(path instanceof FastPath); // Make sure that this path refers specifically to a Node, rather than // some non-Node subproperty of a Node. var node = path.getValue(); if (!Printable.check(node)) return; var orig = node.original; var origLoc = orig && orig.loc; var lines = origLoc && origLoc.lines; var reprints = []; if (!lines || !findReprints(path, reprints)) return; return function(print) { var patcher = new Patcher(lines); reprints.forEach(function(reprint) { var newNode = reprint.newPath.getValue(); var oldNode = reprint.oldPath.getValue(); SourceLocation.assert(oldNode.loc, true); var needToPrintNewPathWithComments = !patcher.tryToReprintComments(newNode, oldNode, print) if (needToPrintNewPathWithComments) { // Since we were not able to preserve all leading/trailing // comments, we delete oldNode's comments, print newPath // with comments, and then patch the resulting lines where // oldNode used to be. patcher.deleteComments(oldNode); } var pos = util.copyPos(oldNode.loc.start); var needsLeadingSpace = lines.prevPos(pos) && riskyAdjoiningCharExp.test(lines.charAt(pos)); var newLines = print( reprint.newPath, needToPrintNewPathWithComments ).indentTail(oldNode.loc.indent); var needsTrailingSpace = riskyAdjoiningCharExp.test(lines.charAt(oldNode.loc.end)); // If we try to replace the argument of a ReturnStatement like // return"asdf" with e.g. a literal null expression, we run // the risk of ending up with returnnull, so we need to add an // extra leading space in situations where that might // happen. Likewise for "asdf"in obj. See #170. if (needsLeadingSpace || needsTrailingSpace) { var newParts = []; needsLeadingSpace && newParts.push(" "); newParts.push(newLines); needsTrailingSpace && newParts.push(" "); newLines = linesModule.concat(newParts); } patcher.replace(oldNode.loc, newLines); }); // Recall that origLoc is the .loc of an ancestor node that is // guaranteed to contain all the reprinted nodes and comments. return patcher.get(origLoc).indentTail(-orig.loc.indent); }; }; function findReprints(newPath, reprints) { var newNode = newPath.getValue(); Printable.assert(newNode); var oldNode = newNode.original; Printable.assert(oldNode); assert.deepEqual(reprints, []); if (newNode.type !== oldNode.type) { return false; } var oldPath = new FastPath(oldNode); var canReprint = findChildReprints(newPath, oldPath, reprints); if (!canReprint) { // Make absolutely sure the calling code does not attempt to reprint // any nodes. reprints.length = 0; } return canReprint; } function findAnyReprints(newPath, oldPath, reprints) { var newNode = newPath.getValue(); var oldNode = oldPath.getValue(); if (newNode === oldNode) return true; if (isArray.check(newNode)) return findArrayReprints(newPath, oldPath, reprints); if (isObject.check(newNode)) return findObjectReprints(newPath, oldPath, reprints); return false; } function findArrayReprints(newPath, oldPath, reprints) { var newNode = newPath.getValue(); var oldNode = oldPath.getValue(); isArray.assert(newNode); var len = newNode.length; if (!(isArray.check(oldNode) && oldNode.length === len)) return false; for (var i = 0; i < len; ++i) { newPath.stack.push(i, newNode[i]); oldPath.stack.push(i, oldNode[i]); var canReprint = findAnyReprints(newPath, oldPath, reprints); newPath.stack.length -= 2; oldPath.stack.length -= 2; if (!canReprint) { return false; } } return true; } function findObjectReprints(newPath, oldPath, reprints) { var newNode = newPath.getValue(); isObject.assert(newNode); if (newNode.original === null) { // If newNode.original node was set to null, reprint the node. return false; } var oldNode = oldPath.getValue(); if (!isObject.check(oldNode)) return false; if (Printable.check(newNode)) { if (!Printable.check(oldNode)) { return false; } // Here we need to decide whether the reprinted code for newNode // is appropriate for patching into the location of oldNode. if (newNode.type === oldNode.type) { var childReprints = []; if (findChildReprints(newPath, oldPath, childReprints)) { reprints.push.apply(reprints, childReprints); } else if (oldNode.loc) { // If we have no .loc information for oldNode, then we // won't be able to reprint it. reprints.push({ oldPath: oldPath.copy(), newPath: newPath.copy() }); } else { return false; } return true; } if (Expression.check(newNode) && Expression.check(oldNode) && // If we have no .loc information for oldNode, then we won't // be able to reprint it. oldNode.loc) { // If both nodes are subtypes of Expression, then we should be // able to fill the location occupied by the old node with // code printed for the new node with no ill consequences. reprints.push({ oldPath: oldPath.copy(), newPath: newPath.copy() }); return true; } // The nodes have different types, and at least one of the types // is not a subtype of the Expression type, so we cannot safely // assume the nodes are syntactically interchangeable. return false; } return findChildReprints(newPath, oldPath, reprints); } // This object is reused in hasOpeningParen and hasClosingParen to avoid // having to allocate a temporary object. var reusablePos = { line: 1, column: 0 }; var nonSpaceExp = /\S/; function hasOpeningParen(oldPath) { var oldNode = oldPath.getValue(); var loc = oldNode.loc; var lines = loc && loc.lines; if (lines) { var pos = reusablePos; pos.line = loc.start.line; pos.column = loc.start.column; while (lines.prevPos(pos)) { var ch = lines.charAt(pos); if (ch === "(") { // If we found an opening parenthesis but it occurred before // the start of the original subtree for this reprinting, then // we must not return true for hasOpeningParen(oldPath). return comparePos(oldPath.getRootValue().loc.start, pos) <= 0; } if (nonSpaceExp.test(ch)) { return false; } } } return false; } function hasClosingParen(oldPath) { var oldNode = oldPath.getValue(); var loc = oldNode.loc; var lines = loc && loc.lines; if (lines) { var pos = reusablePos; pos.line = loc.end.line; pos.column = loc.end.column; do { var ch = lines.charAt(pos); if (ch === ")") { // If we found a closing parenthesis but it occurred after the // end of the original subtree for this reprinting, then we // must not return true for hasClosingParen(oldPath). return comparePos(pos, oldPath.getRootValue().loc.end) <= 0; } if (nonSpaceExp.test(ch)) { return false; } } while (lines.nextPos(pos)); } return false; } function hasParens(oldPath) { // This logic can technically be fooled if the node has parentheses // but there are comments intervening between the parentheses and the // node. In such cases the node will be harmlessly wrapped in an // additional layer of parentheses. return hasOpeningParen(oldPath) && hasClosingParen(oldPath); } function findChildReprints(newPath, oldPath, reprints) { var newNode = newPath.getValue(); var oldNode = oldPath.getValue(); isObject.assert(newNode); isObject.assert(oldNode); if (newNode.original === null) { // If newNode.original node was set to null, reprint the node. return false; } // If this type of node cannot come lexically first in its enclosing // statement (e.g. a function expression or object literal), and it // seems to be doing so, then the only way we can ignore this problem // and save ourselves from falling back to the pretty printer is if an // opening parenthesis happens to precede the node. For example, // (function(){ ... }()); does not need to be reprinted, even though // the FunctionExpression comes lexically first in the enclosing // ExpressionStatement and fails the hasParens test, because the // parent CallExpression passes the hasParens test. If we relied on // the path.needsParens() && !hasParens(oldNode) check below, the // absence of a closing parenthesis after the FunctionExpression would // trigger pretty-printing unnecessarily. if (!newPath.canBeFirstInStatement() && newPath.firstInStatement() && !hasOpeningParen(oldPath)) return false; // If this node needs parentheses and will not be wrapped with // parentheses when reprinted, then return false to skip reprinting // and let it be printed generically. if (newPath.needsParens(true) && !hasParens(oldPath)) { return false; } for (var k in util.getUnionOfKeys(newNode, oldNode)) { if (k === "loc") continue; newPath.stack.push(k, types.getFieldValue(newNode, k)); oldPath.stack.push(k, types.getFieldValue(oldNode, k)); var canReprint = findAnyReprints(newPath, oldPath, reprints); newPath.stack.length -= 2; oldPath.stack.length -= 2; if (!canReprint) { return false; } } return true; } },{"./fast-path":460,"./lines":461,"./types":467,"./util":468,"assert":190}],466:[function(require,module,exports){ var assert = require("assert"); var sourceMap = require("source-map"); var printComments = require("./comments").printComments; var linesModule = require("./lines"); var fromString = linesModule.fromString; var concat = linesModule.concat; var normalizeOptions = require("./options").normalize; var getReprinter = require("./patcher").getReprinter; var types = require("./types"); var namedTypes = types.namedTypes; var isString = types.builtInTypes.string; var isObject = types.builtInTypes.object; var FastPath = require("./fast-path"); var util = require("./util"); function PrintResult(code, sourceMap) { assert.ok(this instanceof PrintResult); isString.assert(code); this.code = code; if (sourceMap) { isObject.assert(sourceMap); this.map = sourceMap; } } var PRp = PrintResult.prototype; var warnedAboutToString = false; PRp.toString = function() { if (!warnedAboutToString) { console.warn( "Deprecation warning: recast.print now returns an object with " + "a .code property. You appear to be treating the object as a " + "string, which might still work but is strongly discouraged." ); warnedAboutToString = true; } return this.code; }; var emptyPrintResult = new PrintResult(""); function Printer(originalOptions) { assert.ok(this instanceof Printer); var explicitTabWidth = originalOptions && originalOptions.tabWidth; var options = normalizeOptions(originalOptions); assert.notStrictEqual(options, originalOptions); // It's common for client code to pass the same options into both // recast.parse and recast.print, but the Printer doesn't need (and // can be confused by) options.sourceFileName, so we null it out. options.sourceFileName = null; function printWithComments(path) { assert.ok(path instanceof FastPath); return printComments(path, print); } function print(path, includeComments) { if (includeComments) return printWithComments(path); assert.ok(path instanceof FastPath); if (!explicitTabWidth) { var oldTabWidth = options.tabWidth; var loc = path.getNode().loc; if (loc && loc.lines && loc.lines.guessTabWidth) { options.tabWidth = loc.lines.guessTabWidth(); var lines = maybeReprint(path); options.tabWidth = oldTabWidth; return lines; } } return maybeReprint(path); } function maybeReprint(path) { var reprinter = getReprinter(path); if (reprinter) return maybeAddParens(path, reprinter(print)); return printRootGenerically(path); } // Print the root node generically, but then resume reprinting its // children non-generically. function printRootGenerically(path) { return genericPrint(path, options, printWithComments); } // Print the entire AST generically. function printGenerically(path) { return genericPrint(path, options, printGenerically); } this.print = function(ast) { if (!ast) { return emptyPrintResult; } var lines = print(FastPath.from(ast), true); return new PrintResult( lines.toString(options), util.composeSourceMaps( options.inputSourceMap, lines.getSourceMap( options.sourceMapName, options.sourceRoot ) ) ); }; this.printGenerically = function(ast) { if (!ast) { return emptyPrintResult; } var path = FastPath.from(ast); var oldReuseWhitespace = options.reuseWhitespace; // Do not reuse whitespace (or anything else, for that matter) // when printing generically. options.reuseWhitespace = false; // TODO Allow printing of comments? var pr = new PrintResult(printGenerically(path).toString(options)); options.reuseWhitespace = oldReuseWhitespace; return pr; }; } exports.Printer = Printer; function maybeAddParens(path, lines) { return path.needsParens() ? concat(["(", lines, ")"]) : lines; } function genericPrint(path, options, printPath) { assert.ok(path instanceof FastPath); return maybeAddParens(path, genericPrintNoParens(path, options, printPath)); } function genericPrintNoParens(path, options, print) { var n = path.getValue(); if (!n) { return fromString(""); } if (typeof n === "string") { return fromString(n, options); } namedTypes.Printable.assert(n); switch (n.type) { case "File": return path.call(print, "program"); case "Program": return maybeAddSemicolon(path.call(function(bodyPath) { return printStatementSequence(bodyPath, options, print); }, "body")); case "EmptyStatement": return fromString(""); case "ExpressionStatement": return concat([path.call(print, "expression"), ";"]); case "BinaryExpression": case "LogicalExpression": case "AssignmentExpression": return fromString(" ").join([ path.call(print, "left"), n.operator, path.call(print, "right") ]); case "AssignmentPattern": return concat([ path.call(print, "left"), "=", path.call(print, "right") ]); case "MemberExpression": var parts = [path.call(print, "object")]; var property = path.call(print, "property"); if (n.computed) { parts.push("[", property, "]"); } else { parts.push(".", property); } return concat(parts); case "Path": return fromString(".").join(n.body); case "Identifier": return concat([ fromString(n.name, options), path.call(print, "typeAnnotation") ]); case "SpreadElement": case "SpreadElementPattern": case "SpreadProperty": case "SpreadPropertyPattern": case "RestElement": return concat(["...", path.call(print, "argument")]); case "FunctionDeclaration": case "FunctionExpression": var parts = []; if (n.async) parts.push("async "); parts.push("function"); if (n.generator) parts.push("*"); if (n.id) { parts.push( " ", path.call(print, "id"), path.call(print, "typeParameters") ); } parts.push( "(", printFunctionParams(path, options, print), ")", path.call(print, "returnType"), " ", path.call(print, "body") ); return concat(parts); case "ArrowFunctionExpression": var parts = []; if (n.async) parts.push("async "); if (n.params.length === 1 && !n.rest) { parts.push(path.call(print, "params", 0)); } else { parts.push( "(", printFunctionParams(path, options, print), ")" ); } parts.push(" => ", path.call(print, "body")); return concat(parts); case "MethodDefinition": var parts = []; if (n.static) { parts.push("static "); } parts.push(printMethod(path, options, print)); return concat(parts); case "YieldExpression": var parts = ["yield"]; if (n.delegate) parts.push("*"); if (n.argument) parts.push(" ", path.call(print, "argument")); return concat(parts); case "AwaitExpression": var parts = ["await"]; if (n.all) parts.push("*"); if (n.argument) parts.push(" ", path.call(print, "argument")); return concat(parts); case "ModuleDeclaration": var parts = ["module", path.call(print, "id")]; if (n.source) { assert.ok(!n.body); parts.push("from", path.call(print, "source")); } else { parts.push(path.call(print, "body")); } return fromString(" ").join(parts); case "ImportSpecifier": case "ExportSpecifier": var parts = [path.call(print, "id")]; if (n.name) parts.push(" as ", path.call(print, "name")); return concat(parts); case "ExportBatchSpecifier": return fromString("*"); case "ImportNamespaceSpecifier": return concat(["* as ", path.call(print, "id")]); case "ImportDefaultSpecifier": return path.call(print, "id"); case "ExportDeclaration": var parts = ["export"]; if (n["default"]) { parts.push(" default"); } else if (n.specifiers && n.specifiers.length > 0) { if (n.specifiers.length === 1 && n.specifiers[0].type === "ExportBatchSpecifier") { parts.push(" *"); } else { parts.push( " { ", fromString(", ").join(path.map(print, "specifiers")), " }" ); } if (n.source) parts.push(" from ", path.call(print, "source")); parts.push(";"); return concat(parts); } if (n.declaration) { if (!namedTypes.Node.check(n.declaration)) { console.log(JSON.stringify(n, null, 2)); } var decLines = path.call(print, "declaration"); parts.push(" ", decLines); if (lastNonSpaceCharacter(decLines) !== ";") { parts.push(";"); } } return concat(parts); case "ImportDeclaration": var parts = ["import "]; if (n.specifiers && n.specifiers.length > 0) { var foundImportSpecifier = false; path.each(function(specifierPath) { var i = specifierPath.getName(); if (i > 0) { parts.push(", "); } var value = specifierPath.getValue(); if (namedTypes.ImportDefaultSpecifier.check(value) || namedTypes.ImportNamespaceSpecifier.check(value)) { assert.strictEqual(foundImportSpecifier, false); } else { namedTypes.ImportSpecifier.assert(value); if (!foundImportSpecifier) { foundImportSpecifier = true; parts.push("{"); } } parts.push(print(specifierPath)); }, "specifiers"); if (foundImportSpecifier) { parts.push("}"); } parts.push(" from "); } parts.push(path.call(print, "source"), ";"); return concat(parts); case "BlockStatement": var naked = path.call(function(bodyPath) { return printStatementSequence(bodyPath, options, print); }, "body"); if (naked.isEmpty()) { return fromString("{}"); } return concat([ "{\n", naked.indent(options.tabWidth), "\n}" ]); case "ReturnStatement": var parts = ["return"]; if (n.argument) { var argLines = path.call(print, "argument"); if (argLines.length > 1 && (namedTypes.XJSElement && namedTypes.XJSElement.check(n.argument) || namedTypes.JSXElement && namedTypes.JSXElement.check(n.argument))) { parts.push( " (\n", argLines.indent(options.tabWidth), "\n)" ); } else { parts.push(" ", argLines); } } parts.push(";"); return concat(parts); case "CallExpression": return concat([ path.call(print, "callee"), printArgumentsList(path, options, print) ]); case "ObjectExpression": case "ObjectPattern": case "ObjectTypeAnnotation": var allowBreak = false; var isTypeAnnotation = n.type === "ObjectTypeAnnotation"; var separator = isTypeAnnotation ? ';' : ','; var fields = []; if (isTypeAnnotation) { fields.push("indexers", "callProperties"); } fields.push("properties"); var len = 0; fields.forEach(function(field) { len += n[field].length; }); var oneLine = (isTypeAnnotation && len === 1) || len === 0; var parts = [oneLine ? "{" : "{\n"]; fields.forEach(function(field) { path.map(function(childPath) { var i = childPath.getName(); var prop = childPath.getValue(); var lines = print(childPath); if (!oneLine) { lines = lines.indent(options.tabWidth); } var multiLine = !isTypeAnnotation && lines.length > 1; if (multiLine && allowBreak) { // Similar to the logic for BlockStatement. parts.push("\n"); } parts.push(lines); if (i < len - 1) { // Add an extra line break if the previous object property // had a multi-line value. parts.push(separator + (multiLine ? "\n\n" : "\n")); allowBreak = !multiLine; } else if (len !== 1 && isTypeAnnotation) { parts.push(separator); } }, field); }); parts.push(oneLine ? "}" : "\n}"); return concat(parts); case "PropertyPattern": return concat([ path.call(print, "key"), ": ", path.call(print, "pattern") ]); case "Property": // Non-standard AST node type. if (n.method || n.kind === "get" || n.kind === "set") { return printMethod(path, options, print); } var key = path.call(print, "key"); if (n.computed) { key = concat(["[", key, "]"]); } if (n.shorthand) { return key; } return concat([key, ": ", path.call(print, "value")]); case "ArrayExpression": case "ArrayPattern": var elems = n.elements, len = elems.length, parts = ["["]; path.each(function(elemPath) { var i = elemPath.getName(); var elem = elemPath.getValue(); if (!elem) { // If the array expression ends with a hole, that hole // will be ignored by the interpreter, but if it ends with // two (or more) holes, we need to write out two (or more) // commas so that the resulting code is interpreted with // both (all) of the holes. parts.push(","); } else { if (i > 0) parts.push(" "); parts.push(print(elemPath)); if (i < len - 1) parts.push(","); } }, "elements"); parts.push("]"); return concat(parts); case "SequenceExpression": return fromString(", ").join(path.map(print, "expressions")); case "ThisExpression": return fromString("this"); case "Literal": if (typeof n.value !== "string") return fromString(n.value, options); // intentionally fall through... case "ModuleSpecifier": return fromString(nodeStr(n.value, options), options); case "UnaryExpression": var parts = [n.operator]; if (/[a-z]$/.test(n.operator)) parts.push(" "); parts.push(path.call(print, "argument")); return concat(parts); case "UpdateExpression": var parts = [path.call(print, "argument"), n.operator]; if (n.prefix) parts.reverse(); return concat(parts); case "ConditionalExpression": return concat([ "(", path.call(print, "test"), " ? ", path.call(print, "consequent"), " : ", path.call(print, "alternate"), ")" ]); case "NewExpression": var parts = ["new ", path.call(print, "callee")]; var args = n.arguments; if (args) { parts.push(printArgumentsList(path, options, print)); } return concat(parts); case "VariableDeclaration": var parts = [n.kind, " "]; var maxLen = 0; var printed = path.map(function(childPath) { var lines = print(childPath); maxLen = Math.max(lines.length, maxLen); return lines; }, "declarations"); if (maxLen === 1) { parts.push(fromString(", ").join(printed)); } else if (printed.length > 1 ) { parts.push( fromString(",\n").join(printed) .indentTail(n.kind.length + 1) ); } else { parts.push(printed[0]); } // We generally want to terminate all variable declarations with a // semicolon, except when they are children of for loops. var parentNode = path.getParentNode(); if (!namedTypes.ForStatement.check(parentNode) && !namedTypes.ForInStatement.check(parentNode) && !(namedTypes.ForOfStatement && namedTypes.ForOfStatement.check(parentNode))) { parts.push(";"); } return concat(parts); case "VariableDeclarator": return n.init ? fromString(" = ").join([ path.call(print, "id"), path.call(print, "init") ]) : path.call(print, "id"); case "WithStatement": return concat([ "with (", path.call(print, "object"), ") ", path.call(print, "body") ]); case "IfStatement": var con = adjustClause(path.call(print, "consequent"), options), parts = ["if (", path.call(print, "test"), ")", con]; if (n.alternate) parts.push( endsWithBrace(con) ? " else" : "\nelse", adjustClause(path.call(print, "alternate"), options)); return concat(parts); case "ForStatement": // TODO Get the for (;;) case right. var init = path.call(print, "init"), sep = init.length > 1 ? ";\n" : "; ", forParen = "for (", indented = fromString(sep).join([ init, path.call(print, "test"), path.call(print, "update") ]).indentTail(forParen.length), head = concat([forParen, indented, ")"]), clause = adjustClause(path.call(print, "body"), options), parts = [head]; if (head.length > 1) { parts.push("\n"); clause = clause.trimLeft(); } parts.push(clause); return concat(parts); case "WhileStatement": return concat([ "while (", path.call(print, "test"), ")", adjustClause(path.call(print, "body"), options) ]); case "ForInStatement": // Note: esprima can't actually parse "for each (". return concat([ n.each ? "for each (" : "for (", path.call(print, "left"), " in ", path.call(print, "right"), ")", adjustClause(path.call(print, "body"), options) ]); case "ForOfStatement": return concat([ "for (", path.call(print, "left"), " of ", path.call(print, "right"), ")", adjustClause(path.call(print, "body"), options) ]); case "DoWhileStatement": var doBody = concat([ "do", adjustClause(path.call(print, "body"), options) ]), parts = [doBody]; if (endsWithBrace(doBody)) parts.push(" while"); else parts.push("\nwhile"); parts.push(" (", path.call(print, "test"), ");"); return concat(parts); case "BreakStatement": var parts = ["break"]; if (n.label) parts.push(" ", path.call(print, "label")); parts.push(";"); return concat(parts); case "ContinueStatement": var parts = ["continue"]; if (n.label) parts.push(" ", path.call(print, "label")); parts.push(";"); return concat(parts); case "LabeledStatement": return concat([ path.call(print, "label"), ":\n", path.call(print, "body") ]); case "TryStatement": var parts = [ "try ", path.call(print, "block") ]; if (n.handler) { parts.push(" ", path.call(print, "handler")); } else if (n.handlers) { path.each(function(handlerPath) { parts.push(" ", print(handlerPath)); }, "handlers"); } if (n.finalizer) { parts.push(" finally ", path.call(print, "finalizer")); } return concat(parts); case "CatchClause": var parts = ["catch (", path.call(print, "param")]; if (n.guard) // Note: esprima does not recognize conditional catch clauses. parts.push(" if ", path.call(print, "guard")); parts.push(") ", path.call(print, "body")); return concat(parts); case "ThrowStatement": return concat(["throw ", path.call(print, "argument"), ";"]); case "SwitchStatement": return concat([ "switch (", path.call(print, "discriminant"), ") {\n", fromString("\n").join(path.map(print, "cases")), "\n}" ]); // Note: ignoring n.lexical because it has no printing consequences. case "SwitchCase": var parts = []; if (n.test) parts.push("case ", path.call(print, "test"), ":"); else parts.push("default:"); if (n.consequent.length > 0) { parts.push("\n", path.call(function(consequentPath) { return printStatementSequence(consequentPath, options, print); }, "consequent").indent(options.tabWidth)); } return concat(parts); case "DebuggerStatement": return fromString("debugger;"); // JSX extensions below. case "XJSAttribute": case "JSXAttribute": var parts = [path.call(print, "name")]; if (n.value) parts.push("=", path.call(print, "value")); return concat(parts); case "XJSIdentifier": case "JSXIdentifier": return fromString(n.name, options); case "XJSNamespacedName": case "JSXNamespacedName": return fromString(":").join([ path.call(print, "namespace"), path.call(print, "name") ]); case "XJSMemberExpression": case "JSXMemberExpression": return fromString(".").join([ path.call(print, "object"), path.call(print, "property") ]); case "XJSSpreadAttribute": case "JSXSpreadAttribute": return concat(["{...", path.call(print, "argument"), "}"]); case "XJSExpressionContainer": case "JSXExpressionContainer": return concat(["{", path.call(print, "expression"), "}"]); case "XJSElement": case "JSXElement": var openingLines = path.call(print, "openingElement"); if (n.openingElement.selfClosing) { assert.ok(!n.closingElement); return openingLines; } var childLines = concat( path.map(function(childPath) { var child = childPath.getValue(); if (namedTypes.Literal.check(child) && typeof child.value === "string") { if (/\S/.test(child.value)) { return child.value.replace(/^\s+|\s+$/g, ""); } else if (/\n/.test(child.value)) { return "\n"; } } return print(childPath); }, "children") ).indentTail(options.tabWidth); var closingLines = path.call(print, "closingElement"); return concat([ openingLines, childLines, closingLines ]); case "XJSOpeningElement": case "JSXOpeningElement": var parts = ["<", path.call(print, "name")]; var attrParts = []; path.each(function(attrPath) { attrParts.push(" ", print(attrPath)); }, "attributes"); var attrLines = concat(attrParts); var needLineWrap = ( attrLines.length > 1 || attrLines.getLineLength(1) > options.wrapColumn ); if (needLineWrap) { attrParts.forEach(function(part, i) { if (part === " ") { assert.strictEqual(i % 2, 0); attrParts[i] = "\n"; } }); attrLines = concat(attrParts).indentTail(options.tabWidth); } parts.push(attrLines, n.selfClosing ? " />" : ">"); return concat(parts); case "XJSClosingElement": case "JSXClosingElement": return concat([""]); case "XJSText": case "JSXText": return fromString(n.value, options); case "XJSEmptyExpression": case "JSXEmptyExpression": return fromString(""); case "TypeAnnotatedIdentifier": return concat([ path.call(print, "annotation"), " ", path.call(print, "identifier") ]); case "ClassBody": if (n.body.length === 0) { return fromString("{}"); } return concat([ "{\n", path.call(function(bodyPath) { return printStatementSequence(bodyPath, options, print); }, "body").indent(options.tabWidth), "\n}" ]); case "ClassPropertyDefinition": var parts = ["static ", path.call(print, "definition")]; if (!namedTypes.MethodDefinition.check(n.definition)) parts.push(";"); return concat(parts); case "ClassProperty": return concat([ path.call(print, "key"), path.call(print, "typeAnnotation"), ";" ]); case "ClassDeclaration": case "ClassExpression": var parts = ["class"]; if (n.id) { parts.push( " ", path.call(print, "id"), path.call(print, "typeParameters") ); } if (n.superClass) { parts.push( " extends ", path.call(print, "superClass"), path.call(print, "superTypeParameters") ); } if (n["implements"]) { parts.push( " implements ", fromString(", ").join(path.map(print, "implements")) ); } parts.push(" ", path.call(print, "body")); return concat(parts); // These types are unprintable because they serve as abstract // supertypes for other (printable) types. case "Node": case "Printable": case "SourceLocation": case "Position": case "Statement": case "Function": case "Pattern": case "Expression": case "Declaration": case "Specifier": case "NamedSpecifier": case "Comment": // Supertype of Block and Line. case "MemberTypeAnnotation": // Flow case "TupleTypeAnnotation": // Flow case "Type": // Flow throw new Error("unprintable type: " + JSON.stringify(n.type)); case "Block": // Block comment. return concat(["/*", fromString(n.value, options), "*/"]); case "Line": // Line comment. return concat(["//", fromString(n.value, options)]); // Type Annotations for Facebook Flow, typically stripped out or // transformed away before printing. case "TypeAnnotation": var parts = []; if (n.typeAnnotation) { if (n.typeAnnotation.type !== "FunctionTypeAnnotation") { parts.push(": "); } parts.push(path.call(print, "typeAnnotation")); return concat(parts); } return fromString(""); case "AnyTypeAnnotation": return fromString("any", options); case "ArrayTypeAnnotation": return concat([ path.call(print, "elementType"), "[]" ]); case "BooleanTypeAnnotation": return fromString("boolean", options); case "DeclareClass": return concat([ fromString("declare class ", options), path.call(print, "id"), " ", path.call(print, "body"), ]); case "DeclareFunction": return concat([ fromString("declare function ", options), path.call(print, "id") ]); case "DeclareModule": return concat([ fromString("declare module ", options), path.call(print, "id"), " ", path.call(print, "body"), ]); case "DeclareVariable": return concat([ fromString("declare var ", options), path.call(print, "id") ]); case "FunctionTypeAnnotation": // FunctionTypeAnnotation is ambiguous: // declare function(a: B): void; OR // var A: (a: B) => void; var parts = []; var parent = path.getParentNode(0); var isArrowFunctionTypeAnnotation = !( namedTypes.ObjectTypeCallProperty.check(parent) || namedTypes.DeclareFunction.check(path.getParentNode(2)) ); var needsColon = isArrowFunctionTypeAnnotation && !namedTypes.FunctionTypeParam.check(parent); if (needsColon) { parts.push(": "); } parts.push( "(", fromString(", ").join(path.map(print, "params")), ")" ); // The returnType is not wrapped in a TypeAnnotation, so the colon // needs to be added separately. if (n.returnType) { parts.push( isArrowFunctionTypeAnnotation ? " => " : ": ", path.call(print, "returnType") ); } return concat(parts); case "FunctionTypeParam": return concat([ path.call(print, "name"), ": ", path.call(print, "typeAnnotation"), ]); case "GenericTypeAnnotation": return concat([ path.call(print, "id"), path.call(print, "typeParameters") ]); case "InterfaceDeclaration": var parts = [ fromString("interface ", options), path.call(print, "id"), path.call(print, "typeParameters"), " " ]; if (n["extends"]) { parts.push( "extends ", fromString(", ").join(path.map(print, "extends")) ); } parts.push(path.call(print, "body")); return concat(parts); case "ClassImplements": case "InterfaceExtends": return concat([ path.call(print, "id"), path.call(print, "typeParameters") ]); case "IntersectionTypeAnnotation": return fromString(" & ").join(path.map(print, "types")); case "NullableTypeAnnotation": return concat([ "?", path.call(print, "typeAnnotation") ]); case "NumberTypeAnnotation": return fromString("number", options); case "ObjectTypeCallProperty": return path.call(print, "value"); case "ObjectTypeIndexer": return concat([ "[", path.call(print, "id"), ": ", path.call(print, "key"), "]: ", path.call(print, "value") ]); case "ObjectTypeProperty": return concat([ path.call(print, "key"), ": ", path.call(print, "value") ]); case "QualifiedTypeIdentifier": return concat([ path.call(print, "qualification"), ".", path.call(print, "id") ]); case "StringLiteralTypeAnnotation": return fromString(nodeStr(n.value, options), options); case "StringTypeAnnotation": return fromString("string", options); case "TypeAlias": return concat([ "type ", path.call(print, "id"), " = ", path.call(print, "right") ]); case "TypeCastExpression": return concat([ "(", path.call(print, "expression"), path.call(print, "typeAnnotation"), ")" ]); case "TypeParameterDeclaration": case "TypeParameterInstantiation": return concat([ "<", fromString(", ").join(path.map(print, "params")), ">" ]); case "TypeofTypeAnnotation": return concat([ fromString("typeof ", options), path.call(print, "argument") ]); case "UnionTypeAnnotation": return fromString(" | ").join(path.map(print, "types")); case "VoidTypeAnnotation": return fromString("void", options); // Unhandled types below. If encountered, nodes of these types should // be either left alone or desugared into AST types that are fully // supported by the pretty-printer. case "ClassHeritage": // TODO case "ComprehensionBlock": // TODO case "ComprehensionExpression": // TODO case "Glob": // TODO case "TaggedTemplateExpression": // TODO case "TemplateElement": // TODO case "TemplateLiteral": // TODO case "GeneratorExpression": // TODO case "LetStatement": // TODO case "LetExpression": // TODO case "GraphExpression": // TODO case "GraphIndexExpression": // TODO // XML types that nobody cares about or needs to print. case "XMLDefaultDeclaration": case "XMLAnyName": case "XMLQualifiedIdentifier": case "XMLFunctionQualifiedIdentifier": case "XMLAttributeSelector": case "XMLFilterExpression": case "XML": case "XMLElement": case "XMLList": case "XMLEscape": case "XMLText": case "XMLStartTag": case "XMLEndTag": case "XMLPointTag": case "XMLName": case "XMLAttribute": case "XMLCdata": case "XMLComment": case "XMLProcessingInstruction": default: debugger; throw new Error("unknown type: " + JSON.stringify(n.type)); } return p; } function printStatementSequence(path, options, print) { var inClassBody = namedTypes.ClassBody && namedTypes.ClassBody.check(path.getParentNode()); var filtered = []; path.each(function(stmtPath) { var i = stmtPath.getName(); var stmt = stmtPath.getValue(); // Just in case the AST has been modified to contain falsy // "statements," it's safer simply to skip them. if (!stmt) { return; } // Skip printing EmptyStatement nodes to avoid leaving stray // semicolons lying around. if (stmt.type === "EmptyStatement") { return; } if (!inClassBody) { namedTypes.Statement.assert(stmt); } // We can't hang onto stmtPath outside of this function, because // it's just a reference to a mutable FastPath object, so we have // to go ahead and print it here. filtered.push({ node: stmt, printed: print(stmtPath) }); }); var prevTrailingSpace = null; var len = filtered.length; var parts = []; filtered.forEach(function(info, i) { var printed = info.printed; var stmt = info.node; var needSemicolon = true; var multiLine = printed.length > 1; var notFirst = i > 0; var notLast = i < len - 1; var leadingSpace; var trailingSpace; if (inClassBody) { if (namedTypes.MethodDefinition.check(stmt) || (namedTypes.ClassPropertyDefinition.check(stmt) && namedTypes.MethodDefinition.check(stmt.definition))) { needSemicolon = false; } } if (needSemicolon) { // Try to add a semicolon to anything that isn't a method in a // class body. printed = maybeAddSemicolon(printed); } var trueLoc = options.reuseWhitespace && util.getTrueLoc(stmt); var lines = trueLoc && trueLoc.lines; if (notFirst) { if (lines) { var beforeStart = lines.skipSpaces(trueLoc.start, true); var beforeStartLine = beforeStart ? beforeStart.line : 1; var leadingGap = trueLoc.start.line - beforeStartLine; leadingSpace = Array(leadingGap + 1).join("\n"); } else { leadingSpace = multiLine ? "\n\n" : "\n"; } } else { leadingSpace = ""; } if (notLast) { if (lines) { var afterEnd = lines.skipSpaces(trueLoc.end); var afterEndLine = afterEnd ? afterEnd.line : lines.length; var trailingGap = afterEndLine - trueLoc.end.line; trailingSpace = Array(trailingGap + 1).join("\n"); } else { trailingSpace = multiLine ? "\n\n" : "\n"; } } else { trailingSpace = ""; } parts.push( maxSpace(prevTrailingSpace, leadingSpace), printed ); if (notLast) { prevTrailingSpace = trailingSpace; } else if (trailingSpace) { parts.push(trailingSpace); } }); return concat(parts); } function maxSpace(s1, s2) { if (!s1 && !s2) { return fromString(""); } if (!s1) { return fromString(s2); } if (!s2) { return fromString(s1); } var spaceLines1 = fromString(s1); var spaceLines2 = fromString(s2); if (spaceLines2.length > spaceLines1.length) { return spaceLines2; } return spaceLines1; } function printMethod(path, options, print) { var node = path.getNode(); var kind = node.kind; var parts = []; namedTypes.FunctionExpression.assert(node.value); if (node.value.async) { parts.push("async "); } if (!kind || kind === "init") { if (node.value.generator) { parts.push("*"); } } else { assert.ok(kind === "get" || kind === "set"); parts.push(kind, " "); } var key = path.call(print, "key"); if (node.computed) { key = concat(["[", key, "]"]); } parts.push( key, path.call(print, "value", "typeParameters"), "(", path.call(function(valuePath) { return printFunctionParams(valuePath, options, print); }, "value"), ")", path.call(print, "value", "returnType"), " ", path.call(print, "value", "body") ); return concat(parts); } function printArgumentsList(path, options, print) { var printed = path.map(print, "arguments"); var joined = fromString(", ").join(printed); if (joined.getLineLength(1) > options.wrapColumn) { joined = fromString(",\n").join(printed); return concat(["(\n", joined.indent(options.tabWidth), "\n)"]); } return concat(["(", joined, ")"]); } function printFunctionParams(path, options, print) { var fun = path.getValue(); namedTypes.Function.assert(fun); var printed = path.map(print, "params"); if (fun.defaults) { path.each(function(defExprPath) { var i = defExprPath.getName(); var p = printed[i]; if (p && defExprPath.getValue()) { printed[i] = concat([p, "=", print(defExprPath)]); } }, "defaults"); } if (fun.rest) { printed.push(concat(["...", path.call(print, "rest")])); } var joined = fromString(", ").join(printed); if (joined.length > 1 || joined.getLineLength(1) > options.wrapColumn) { joined = fromString(",\n").join(printed); return concat(["\n", joined.indent(options.tabWidth)]); } return joined; } function adjustClause(clause, options) { if (clause.length > 1) return concat([" ", clause]); return concat([ "\n", maybeAddSemicolon(clause).indent(options.tabWidth) ]); } function lastNonSpaceCharacter(lines) { var pos = lines.lastPos(); do { var ch = lines.charAt(pos); if (/\S/.test(ch)) return ch; } while (lines.prevPos(pos)); } function endsWithBrace(lines) { return lastNonSpaceCharacter(lines) === "}"; } function swapQuotes(str) { return str.replace(/['"]/g, function(m) { return m === '"' ? '\'' : '"'; }); } function nodeStr(str, options) { isString.assert(str); switch (options.quote) { case "auto": var double = JSON.stringify(str); var single = swapQuotes(JSON.stringify(swapQuotes(str))); return double.length > single.length ? single : double; case "single": return swapQuotes(JSON.stringify(swapQuotes(str))); case "double": default: return JSON.stringify(str); } } function maybeAddSemicolon(lines) { var eoc = lastNonSpaceCharacter(lines); if (!eoc || "\n};".indexOf(eoc) < 0) return concat([lines, ";"]); return lines; } },{"./comments":459,"./fast-path":460,"./lines":461,"./options":463,"./patcher":465,"./types":467,"./util":468,"assert":190,"source-map":483}],467:[function(require,module,exports){ var types = require("ast-types"); var def = types.Type.def; def("File") .bases("Node") .build("program") .field("program", def("Program")); types.finalize(); module.exports = types; },{"ast-types":188}],468:[function(require,module,exports){ var assert = require("assert"); var types = require("./types"); var getFieldValue = types.getFieldValue; var n = types.namedTypes; var sourceMap = require("source-map"); var SourceMapConsumer = sourceMap.SourceMapConsumer; var SourceMapGenerator = sourceMap.SourceMapGenerator; var hasOwn = Object.prototype.hasOwnProperty; function getUnionOfKeys() { var result = {}; var argc = arguments.length; for (var i = 0; i < argc; ++i) { var keys = Object.keys(arguments[i]); var keyCount = keys.length; for (var j = 0; j < keyCount; ++j) { result[keys[j]] = true; } } return result; } exports.getUnionOfKeys = getUnionOfKeys; function comparePos(pos1, pos2) { return (pos1.line - pos2.line) || (pos1.column - pos2.column); } exports.comparePos = comparePos; function copyPos(pos) { return { line: pos.line, column: pos.column }; } exports.copyPos = copyPos; exports.composeSourceMaps = function(formerMap, latterMap) { if (formerMap) { if (!latterMap) { return formerMap; } } else { return latterMap || null; } var smcFormer = new SourceMapConsumer(formerMap); var smcLatter = new SourceMapConsumer(latterMap); var smg = new SourceMapGenerator({ file: latterMap.file, sourceRoot: latterMap.sourceRoot }); var sourcesToContents = {}; smcLatter.eachMapping(function(mapping) { var origPos = smcFormer.originalPositionFor({ line: mapping.originalLine, column: mapping.originalColumn }); var sourceName = origPos.source; if (sourceName === null) { return; } smg.addMapping({ source: sourceName, original: copyPos(origPos), generated: { line: mapping.generatedLine, column: mapping.generatedColumn }, name: mapping.name }); var sourceContent = smcFormer.sourceContentFor(sourceName); if (sourceContent && !hasOwn.call(sourcesToContents, sourceName)) { sourcesToContents[sourceName] = sourceContent; smg.setSourceContent(sourceName, sourceContent); } }); return smg.toJSON(); }; exports.getTrueLoc = function(node) { // It's possible that node is newly-created (not parsed by Esprima), // in which case it probably won't have a .loc property (or an // .original property for that matter). That's fine; we'll just // pretty-print it as usual. if (!node.loc) { return null; } if (!node.comments) { // If the node has no comments, regard node.loc as true. return node.loc; } var start = node.loc.start; var end = node.loc.end; // If the node has any comments, their locations might contribute to // the true start/end positions of the node. node.comments.forEach(function(comment) { if (comment.loc) { if (comparePos(comment.loc.start, start) < 0) { start = comment.loc.start; } if (comparePos(end, comment.loc.end) < 0) { end = comment.loc.end; } } }); return { lines: node.loc.lines, start: start, end: end }; }; exports.fixFaultyLocations = function(node) { if ((n.MethodDefinition && n.MethodDefinition.check(node)) || (n.Property.check(node) && (node.method || node.shorthand))) { // If the node is a MethodDefinition or a .method or .shorthand // Property, then the location information stored in // node.value.loc is very likely untrustworthy (just the {body} // part of a method, or nothing in the case of shorthand // properties), so we null out that information to prevent // accidental reuse of bogus source code during reprinting. node.value.loc = null; if (n.FunctionExpression.check(node.value)) { // FunctionExpression method values should be anonymous, // because their .id fields are ignored anyway. node.value.id = null; } } var loc = node.loc; if (loc) { if (loc.start.line < 1) { loc.start.line = 1; } if (loc.end.line < 1) { loc.end.line = 1; } } }; },{"./types":467,"assert":190,"source-map":483}],469:[function(require,module,exports){ (function (process){ var types = require("./lib/types"); var parse = require("./lib/parser").parse; var Printer = require("./lib/printer").Printer; function print(node, options) { return new Printer(options).print(node); } function prettyPrint(node, options) { return new Printer(options).printGenerically(node); } function run(transformer, options) { return runFile(process.argv[2], transformer, options); } function runFile(path, transformer, options) { require("fs").readFile(path, "utf-8", function(err, code) { if (err) { console.error(err); return; } runString(code, transformer, options); }); } function defaultWriteback(output) { process.stdout.write(output); } function runString(code, transformer, options) { var writeback = options && options.writeback || defaultWriteback; transformer(parse(code, options), function(node) { writeback(print(node, options).code); }); } Object.defineProperties(exports, { /** * Parse a string of code into an augmented syntax tree suitable for * arbitrary modification and reprinting. */ parse: { enumerable: true, value: parse }, /** * Traverse and potentially modify an abstract syntax tree using a * convenient visitor syntax: * * recast.visit(ast, { * names: [], * visitIdentifier: function(path) { * var node = path.value; * this.visitor.names.push(node.name); * this.traverse(path); * } * }); */ visit: { enumerable: true, value: types.visit }, /** * Reprint a modified syntax tree using as much of the original source * code as possible. */ print: { enumerable: true, value: print }, /** * Print without attempting to reuse any original source code. */ prettyPrint: { enumerable: false, value: prettyPrint }, /** * Customized version of require("ast-types"). */ types: { enumerable: false, value: types }, /** * Convenient command-line interface (see e.g. example/add-braces). */ run: { enumerable: false, value: run } }); }).call(this,require('_process')) },{"./lib/parser":464,"./lib/printer":466,"./lib/types":467,"_process":200,"fs":189}],470:[function(require,module,exports){ /* Copyright (C) 2013 Ariya Hidayat Copyright (C) 2013 Thaddee Tyl Copyright (C) 2012 Ariya Hidayat Copyright (C) 2012 Mathias Bynens Copyright (C) 2012 Joost-Wim Boekesteijn Copyright (C) 2012 Kris Kowal Copyright (C) 2012 Yusuke Suzuki Copyright (C) 2012 Arpad Borsos Copyright (C) 2011 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. */ (function (root, factory) { 'use strict'; // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, // Rhino, and plain browser loading. /* istanbul ignore next */ if (typeof define === 'function' && define.amd) { define(['exports'], factory); } else if (typeof exports !== 'undefined') { factory(exports); } else { factory((root.esprima = {})); } }(this, function (exports) { 'use strict'; var Token, TokenName, FnExprTokens, Syntax, PropertyKind, Messages, Regex, SyntaxTreeDelegate, XHTMLEntities, ClassPropertyType, source, strict, index, lineNumber, lineStart, length, delegate, lookahead, state, extra; Token = { BooleanLiteral: 1, EOF: 2, Identifier: 3, Keyword: 4, NullLiteral: 5, NumericLiteral: 6, Punctuator: 7, StringLiteral: 8, RegularExpression: 9, Template: 10, JSXIdentifier: 11, JSXText: 12 }; TokenName = {}; TokenName[Token.BooleanLiteral] = 'Boolean'; TokenName[Token.EOF] = ''; TokenName[Token.Identifier] = 'Identifier'; TokenName[Token.Keyword] = 'Keyword'; TokenName[Token.NullLiteral] = 'Null'; TokenName[Token.NumericLiteral] = 'Numeric'; TokenName[Token.Punctuator] = 'Punctuator'; TokenName[Token.StringLiteral] = 'String'; TokenName[Token.JSXIdentifier] = 'JSXIdentifier'; TokenName[Token.JSXText] = 'JSXText'; TokenName[Token.RegularExpression] = 'RegularExpression'; TokenName[Token.Template] = 'Template'; // A function following one of those tokens is an expression. FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new', 'return', 'case', 'delete', 'throw', 'void', // assignment operators '=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=', '&=', '|=', '^=', ',', // binary/unary operators '+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&', '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=', '<=', '<', '>', '!=', '!==']; Syntax = { AnyTypeAnnotation: 'AnyTypeAnnotation', ArrayExpression: 'ArrayExpression', ArrayPattern: 'ArrayPattern', ArrayTypeAnnotation: 'ArrayTypeAnnotation', ArrowFunctionExpression: 'ArrowFunctionExpression', AssignmentExpression: 'AssignmentExpression', BinaryExpression: 'BinaryExpression', BlockStatement: 'BlockStatement', BooleanTypeAnnotation: 'BooleanTypeAnnotation', BreakStatement: 'BreakStatement', CallExpression: 'CallExpression', CatchClause: 'CatchClause', ClassBody: 'ClassBody', ClassDeclaration: 'ClassDeclaration', ClassExpression: 'ClassExpression', ClassImplements: 'ClassImplements', ClassProperty: 'ClassProperty', ComprehensionBlock: 'ComprehensionBlock', ComprehensionExpression: 'ComprehensionExpression', ConditionalExpression: 'ConditionalExpression', ContinueStatement: 'ContinueStatement', DebuggerStatement: 'DebuggerStatement', DeclareClass: 'DeclareClass', DeclareFunction: 'DeclareFunction', DeclareModule: 'DeclareModule', DeclareVariable: 'DeclareVariable', DoWhileStatement: 'DoWhileStatement', EmptyStatement: 'EmptyStatement', ExportDeclaration: 'ExportDeclaration', ExportBatchSpecifier: 'ExportBatchSpecifier', ExportSpecifier: 'ExportSpecifier', ExpressionStatement: 'ExpressionStatement', ForInStatement: 'ForInStatement', ForOfStatement: 'ForOfStatement', ForStatement: 'ForStatement', FunctionDeclaration: 'FunctionDeclaration', FunctionExpression: 'FunctionExpression', FunctionTypeAnnotation: 'FunctionTypeAnnotation', FunctionTypeParam: 'FunctionTypeParam', GenericTypeAnnotation: 'GenericTypeAnnotation', Identifier: 'Identifier', IfStatement: 'IfStatement', ImportDeclaration: 'ImportDeclaration', ImportDefaultSpecifier: 'ImportDefaultSpecifier', ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', ImportSpecifier: 'ImportSpecifier', InterfaceDeclaration: 'InterfaceDeclaration', InterfaceExtends: 'InterfaceExtends', IntersectionTypeAnnotation: 'IntersectionTypeAnnotation', LabeledStatement: 'LabeledStatement', Literal: 'Literal', LogicalExpression: 'LogicalExpression', MemberExpression: 'MemberExpression', MethodDefinition: 'MethodDefinition', NewExpression: 'NewExpression', NullableTypeAnnotation: 'NullableTypeAnnotation', NumberTypeAnnotation: 'NumberTypeAnnotation', ObjectExpression: 'ObjectExpression', ObjectPattern: 'ObjectPattern', ObjectTypeAnnotation: 'ObjectTypeAnnotation', ObjectTypeCallProperty: 'ObjectTypeCallProperty', ObjectTypeIndexer: 'ObjectTypeIndexer', ObjectTypeProperty: 'ObjectTypeProperty', Program: 'Program', Property: 'Property', QualifiedTypeIdentifier: 'QualifiedTypeIdentifier', ReturnStatement: 'ReturnStatement', SequenceExpression: 'SequenceExpression', SpreadElement: 'SpreadElement', SpreadProperty: 'SpreadProperty', StringLiteralTypeAnnotation: 'StringLiteralTypeAnnotation', StringTypeAnnotation: 'StringTypeAnnotation', SwitchCase: 'SwitchCase', SwitchStatement: 'SwitchStatement', TaggedTemplateExpression: 'TaggedTemplateExpression', TemplateElement: 'TemplateElement', TemplateLiteral: 'TemplateLiteral', ThisExpression: 'ThisExpression', ThrowStatement: 'ThrowStatement', TupleTypeAnnotation: 'TupleTypeAnnotation', TryStatement: 'TryStatement', TypeAlias: 'TypeAlias', TypeAnnotation: 'TypeAnnotation', TypeCastExpression: 'TypeCastExpression', TypeofTypeAnnotation: 'TypeofTypeAnnotation', TypeParameterDeclaration: 'TypeParameterDeclaration', TypeParameterInstantiation: 'TypeParameterInstantiation', UnaryExpression: 'UnaryExpression', UnionTypeAnnotation: 'UnionTypeAnnotation', UpdateExpression: 'UpdateExpression', VariableDeclaration: 'VariableDeclaration', VariableDeclarator: 'VariableDeclarator', VoidTypeAnnotation: 'VoidTypeAnnotation', WhileStatement: 'WhileStatement', WithStatement: 'WithStatement', JSXIdentifier: 'JSXIdentifier', JSXNamespacedName: 'JSXNamespacedName', JSXMemberExpression: 'JSXMemberExpression', JSXEmptyExpression: 'JSXEmptyExpression', JSXExpressionContainer: 'JSXExpressionContainer', JSXElement: 'JSXElement', JSXClosingElement: 'JSXClosingElement', JSXOpeningElement: 'JSXOpeningElement', JSXAttribute: 'JSXAttribute', JSXSpreadAttribute: 'JSXSpreadAttribute', JSXText: 'JSXText', YieldExpression: 'YieldExpression', AwaitExpression: 'AwaitExpression' }; PropertyKind = { Data: 1, Get: 2, Set: 4 }; ClassPropertyType = { 'static': 'static', prototype: 'prototype' }; // Error messages should be identical to V8. Messages = { UnexpectedToken: 'Unexpected token %0', UnexpectedNumber: 'Unexpected number', UnexpectedString: 'Unexpected string', UnexpectedIdentifier: 'Unexpected identifier', UnexpectedReserved: 'Unexpected reserved word', UnexpectedTemplate: 'Unexpected quasi %0', UnexpectedEOS: 'Unexpected end of input', NewlineAfterThrow: 'Illegal newline after throw', InvalidRegExp: 'Invalid regular expression', 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', UnknownLabel: 'Undefined label \'%0\'', Redeclaration: '%0 \'%1\' has already been declared', IllegalContinue: 'Illegal continue statement', IllegalBreak: 'Illegal break statement', IllegalDuplicateClassProperty: 'Illegal duplicate property in class definition', IllegalClassConstructorProperty: 'Illegal constructor property in class definition', IllegalReturn: 'Illegal return statement', 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', PropertyAfterSpreadProperty: 'A rest property must be the final property of an object literal', 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.', StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode', AccessorDataProperty: 'Object literal may not have data and accessor property with the same name', AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name', StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode', StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode', StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode', StrictReservedWord: 'Use of future reserved word in strict mode', MissingFromClause: 'Missing from clause', NoAsAfterImportNamespace: 'Missing as after import *', InvalidModuleSpecifier: 'Invalid module specifier', IllegalImportDeclaration: 'Illegal import declaration', IllegalExportDeclaration: 'Illegal export declaration', NoUninitializedConst: 'Const must be initialized', ComprehensionRequiresBlock: 'Comprehension must have at least one block', ComprehensionError: 'Comprehension Error', EachNotAllowed: 'Each is not supported', InvalidJSXAttributeValue: 'JSX value should be either an expression or a quoted JSX text', ExpectedJSXClosingTag: 'Expected corresponding JSX closing tag for %0', AdjacentJSXElements: 'Adjacent JSX elements must be wrapped in an enclosing tag', ConfusedAboutFunctionType: 'Unexpected token =>. It looks like ' + 'you are trying to write a function type, but you ended up ' + 'writing a grouped type followed by an =>, which is a syntax ' + 'error. Remember, function type parameters are named so function ' + 'types look like (name1: type1, name2: type2) => returnType. You ' + 'probably wrote (type1) => returnType' }; // See also tools/generate-unicode-regex.py. Regex = { NonAsciiIdentifierStart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'), NonAsciiIdentifierPart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'), LeadingZeros: new RegExp('^0+(?!$)') }; // Ensure the condition is true, otherwise throw an error. // This is only to have a better contract semantic, i.e. another safety net // to catch a logic error. The condition shall be fulfilled in normal case. // Do NOT use this to enforce a certain condition on any user input. function assert(condition, message) { /* istanbul ignore if */ if (!condition) { throw new Error('ASSERT: ' + message); } } 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]; }; function isDecimalDigit(ch) { return (ch >= 48 && ch <= 57); // 0..9 } function isHexDigit(ch) { return '0123456789abcdefABCDEF'.indexOf(ch) >= 0; } function isOctalDigit(ch) { return '01234567'.indexOf(ch) >= 0; } // 7.2 White Space function isWhiteSpace(ch) { return (ch === 32) || // space (ch === 9) || // tab (ch === 0xB) || (ch === 0xC) || (ch === 0xA0) || (ch >= 0x1680 && '\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\uFEFF'.indexOf(String.fromCharCode(ch)) > 0); } // 7.3 Line Terminators function isLineTerminator(ch) { return (ch === 10) || (ch === 13) || (ch === 0x2028) || (ch === 0x2029); } // 7.6 Identifier Names and Identifiers function isIdentifierStart(ch) { return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore) (ch >= 65 && ch <= 90) || // A..Z (ch >= 97 && ch <= 122) || // a..z (ch === 92) || // \ (backslash) ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch))); } function isIdentifierPart(ch) { return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore) (ch >= 65 && ch <= 90) || // A..Z (ch >= 97 && ch <= 122) || // a..z (ch >= 48 && ch <= 57) || // 0..9 (ch === 92) || // \ (backslash) ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch))); } // 7.6.1.2 Future Reserved Words function isFutureReservedWord(id) { switch (id) { case 'class': case 'enum': case 'export': case 'extends': case 'import': case 'super': return true; default: return false; } } function isStrictModeReservedWord(id) { switch (id) { case 'implements': case 'interface': case 'package': case 'private': case 'protected': case 'public': case 'static': case 'yield': case 'let': return true; default: return false; } } function isRestrictedWord(id) { return id === 'eval' || id === 'arguments'; } // 7.6.1.1 Keywords function isKeyword(id) { if (strict && isStrictModeReservedWord(id)) { return true; } // 'const' is specialized as Keyword in V8. // 'yield' is only treated as a keyword in strict mode. // 'let' is for compatiblity with SpiderMonkey and ES.next. // Some others are from future reserved words. switch (id.length) { case 2: return (id === 'if') || (id === 'in') || (id === 'do'); case 3: return (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try') || (id === 'let'); case 4: return (id === 'this') || (id === 'else') || (id === 'case') || (id === 'void') || (id === 'with') || (id === 'enum'); case 5: return (id === 'while') || (id === 'break') || (id === 'catch') || (id === 'throw') || (id === 'const') || (id === 'class') || (id === 'super'); case 6: return (id === 'return') || (id === 'typeof') || (id === 'delete') || (id === 'switch') || (id === 'export') || (id === 'import'); case 7: return (id === 'default') || (id === 'finally') || (id === 'extends'); case 8: return (id === 'function') || (id === 'continue') || (id === 'debugger'); case 10: return (id === 'instanceof'); default: return false; } } // 7.4 Comments function addComment(type, value, start, end, loc) { var comment; assert(typeof start === 'number', 'Comment must have valid position'); // Because the way the actual token is scanned, often the comments // (if any) are skipped twice during the lexical analysis. // Thus, we need to skip adding a comment if the comment array already // handled it. if (state.lastCommentStart >= start) { return; } state.lastCommentStart = start; comment = { type: type, value: value }; if (extra.range) { comment.range = [start, end]; } if (extra.loc) { comment.loc = loc; } extra.comments.push(comment); if (extra.attachComment) { extra.leadingComments.push(comment); extra.trailingComments.push(comment); } } function skipSingleLineComment() { var start, loc, ch, comment; start = index - 2; loc = { start: { line: lineNumber, column: index - lineStart - 2 } }; while (index < length) { ch = source.charCodeAt(index); ++index; if (isLineTerminator(ch)) { if (extra.comments) { comment = source.slice(start + 2, index - 1); loc.end = { line: lineNumber, column: index - lineStart - 1 }; addComment('Line', comment, start, index - 1, loc); } if (ch === 13 && source.charCodeAt(index) === 10) { ++index; } ++lineNumber; lineStart = index; return; } } if (extra.comments) { comment = source.slice(start + 2, index); loc.end = { line: lineNumber, column: index - lineStart }; addComment('Line', comment, start, index, loc); } } function skipMultiLineComment() { var start, loc, ch, comment; if (extra.comments) { start = index - 2; loc = { start: { line: lineNumber, column: index - lineStart - 2 } }; } while (index < length) { ch = source.charCodeAt(index); if (isLineTerminator(ch)) { if (ch === 13 && source.charCodeAt(index + 1) === 10) { ++index; } ++lineNumber; ++index; lineStart = index; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } else if (ch === 42) { // Block comment ends with '*/' (char #42, char #47). if (source.charCodeAt(index + 1) === 47) { ++index; ++index; if (extra.comments) { comment = source.slice(start + 2, index - 2); loc.end = { line: lineNumber, column: index - lineStart }; addComment('Block', comment, start, index, loc); } return; } ++index; } else { ++index; } } throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } function skipComment() { var ch; while (index < length) { ch = source.charCodeAt(index); if (isWhiteSpace(ch)) { ++index; } else if (isLineTerminator(ch)) { ++index; if (ch === 13 && source.charCodeAt(index) === 10) { ++index; } ++lineNumber; lineStart = index; } else if (ch === 47) { // 47 is '/' ch = source.charCodeAt(index + 1); if (ch === 47) { ++index; ++index; skipSingleLineComment(); } else if (ch === 42) { // 42 is '*' ++index; ++index; skipMultiLineComment(); } else { break; } } else { break; } } } function scanHexEscape(prefix) { var i, len, ch, code = 0; len = (prefix === 'u') ? 4 : 2; for (i = 0; i < len; ++i) { if (index < length && isHexDigit(source[index])) { ch = source[index++]; code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); } else { return ''; } } return String.fromCharCode(code); } function scanUnicodeCodePointEscape() { var ch, code, cu1, cu2; ch = source[index]; code = 0; // At least, one hex digit is required. if (ch === '}') { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } while (index < length) { ch = source[index++]; if (!isHexDigit(ch)) { break; } code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); } if (code > 0x10FFFF || ch !== '}') { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } // UTF-16 Encoding if (code <= 0xFFFF) { return String.fromCharCode(code); } cu1 = ((code - 0x10000) >> 10) + 0xD800; cu2 = ((code - 0x10000) & 1023) + 0xDC00; return String.fromCharCode(cu1, cu2); } function getEscapedIdentifier() { var ch, id; ch = source.charCodeAt(index++); id = String.fromCharCode(ch); // '\u' (char #92, char #117) denotes an escaped character. if (ch === 92) { if (source.charCodeAt(index) !== 117) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } ++index; ch = scanHexEscape('u'); if (!ch || ch === '\\' || !isIdentifierStart(ch.charCodeAt(0))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } id = ch; } while (index < length) { ch = source.charCodeAt(index); if (!isIdentifierPart(ch)) { break; } ++index; id += String.fromCharCode(ch); // '\u' (char #92, char #117) denotes an escaped character. if (ch === 92) { id = id.substr(0, id.length - 1); if (source.charCodeAt(index) !== 117) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } ++index; ch = scanHexEscape('u'); if (!ch || ch === '\\' || !isIdentifierPart(ch.charCodeAt(0))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } id += ch; } } return id; } function getIdentifier() { var start, ch; start = index++; while (index < length) { ch = source.charCodeAt(index); if (ch === 92) { // Blackslash (char #92) marks Unicode escape sequence. index = start; return getEscapedIdentifier(); } if (isIdentifierPart(ch)) { ++index; } else { break; } } return source.slice(start, index); } function scanIdentifier() { var start, id, type; start = index; // Backslash (char #92) starts an escaped character. id = (source.charCodeAt(index) === 92) ? getEscapedIdentifier() : getIdentifier(); // There is no keyword or literal with only one character. // Thus, it must be an identifier. if (id.length === 1) { type = Token.Identifier; } else if (isKeyword(id)) { type = Token.Keyword; } else if (id === 'null') { type = Token.NullLiteral; } else if (id === 'true' || id === 'false') { type = Token.BooleanLiteral; } else { type = Token.Identifier; } return { type: type, value: id, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // 7.7 Punctuators function scanPunctuator() { var start = index, code = source.charCodeAt(index), code2, ch1 = source[index], ch2, ch3, ch4; if (state.inJSXTag || state.inJSXChild) { // Don't need to check for '{' and '}' as it's already handled // correctly by default. switch (code) { case 60: // < case 62: // > ++index; return { type: Token.Punctuator, value: String.fromCharCode(code), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } } switch (code) { // Check for most common single-character punctuators. case 40: // ( open bracket case 41: // ) close bracket case 59: // ; semicolon case 44: // , comma case 91: // [ case 93: // ] case 58: // : case 63: // ? case 126: // ~ ++index; if (extra.tokenize && code === 40) { extra.openParenToken = extra.tokens.length; } return { type: Token.Punctuator, value: String.fromCharCode(code), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; case 123: // { open curly brace case 125: // } close curly brace ++index; if (extra.tokenize && code === 123) { extra.openCurlyToken = extra.tokens.length; } // lookahead2 function can cause tokens to be scanned twice and in doing so // would wreck the curly stack by pushing the same token onto the stack twice. // curlyLastIndex ensures each token is pushed or popped exactly once if (index > state.curlyLastIndex) { state.curlyLastIndex = index; if (code === 123) { state.curlyStack.push('{'); } else { state.curlyStack.pop(); } } return { type: Token.Punctuator, value: String.fromCharCode(code), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; default: code2 = source.charCodeAt(index + 1); // '=' (char #61) marks an assignment or comparison operator. if (code2 === 61) { switch (code) { case 37: // % case 38: // & case 42: // *: case 43: // + case 45: // - case 47: // / case 60: // < case 62: // > case 94: // ^ case 124: // | index += 2; return { type: Token.Punctuator, value: String.fromCharCode(code) + String.fromCharCode(code2), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; case 33: // ! case 61: // = index += 2; // !== and === if (source.charCodeAt(index) === 61) { ++index; } return { type: Token.Punctuator, value: source.slice(start, index), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; default: break; } } break; } // Peek more characters. ch2 = source[index + 1]; ch3 = source[index + 2]; ch4 = source[index + 3]; // 4-character punctuator: >>>= if (ch1 === '>' && ch2 === '>' && ch3 === '>') { if (ch4 === '=') { index += 4; return { type: Token.Punctuator, value: '>>>=', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } } // 3-character punctuators: === !== >>> <<= >>= if (ch1 === '>' && ch2 === '>' && ch3 === '>' && !state.inType) { index += 3; return { type: Token.Punctuator, value: '>>>', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '<' && ch2 === '<' && ch3 === '=') { index += 3; return { type: Token.Punctuator, value: '<<=', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '>' && ch2 === '>' && ch3 === '=') { index += 3; return { type: Token.Punctuator, value: '>>=', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '.' && ch2 === '.' && ch3 === '.') { index += 3; return { type: Token.Punctuator, value: '...', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // Other 2-character punctuators: ++ -- << >> && || // Don't match these tokens if we're in a type, since they never can // occur and can mess up types like Map> if (ch1 === ch2 && ('+-<>&|'.indexOf(ch1) >= 0) && !state.inType) { index += 2; return { type: Token.Punctuator, value: ch1 + ch2, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '=' && ch2 === '>') { index += 2; return { type: Token.Punctuator, value: '=>', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) { ++index; return { type: Token.Punctuator, value: ch1, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '.') { ++index; return { type: Token.Punctuator, value: ch1, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } // 7.8.3 Numeric Literals function scanHexLiteral(start) { var number = ''; while (index < length) { if (!isHexDigit(source[index])) { break; } number += source[index++]; } if (number.length === 0) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } if (isIdentifierStart(source.charCodeAt(index))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.NumericLiteral, value: parseInt('0x' + number, 16), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanBinaryLiteral(start) { var ch, number; number = ''; while (index < length) { ch = source[index]; if (ch !== '0' && ch !== '1') { break; } number += source[index++]; } if (number.length === 0) { // only 0b or 0B throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } if (index < length) { ch = source.charCodeAt(index); /* istanbul ignore else */ if (isIdentifierStart(ch) || isDecimalDigit(ch)) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } return { type: Token.NumericLiteral, value: parseInt(number, 2), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanOctalLiteral(prefix, start) { var number, octal; if (isOctalDigit(prefix)) { octal = true; number = '0' + source[index++]; } else { octal = false; ++index; number = ''; } while (index < length) { if (!isOctalDigit(source[index])) { break; } number += source[index++]; } if (!octal && number.length === 0) { // only 0o or 0O throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.NumericLiteral, value: parseInt(number, 8), octal: octal, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanNumericLiteral() { var number, start, ch; ch = source[index]; assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'), 'Numeric literal must start with a decimal digit or a decimal point'); start = index; number = ''; if (ch !== '.') { number = source[index++]; ch = source[index]; // Hex number starts with '0x'. // Octal number starts with '0'. // Octal number in ES6 starts with '0o'. // Binary number in ES6 starts with '0b'. if (number === '0') { if (ch === 'x' || ch === 'X') { ++index; return scanHexLiteral(start); } if (ch === 'b' || ch === 'B') { ++index; return scanBinaryLiteral(start); } if (ch === 'o' || ch === 'O' || isOctalDigit(ch)) { return scanOctalLiteral(ch, start); } // decimal number starts with '0' such as '09' is illegal. if (ch && isDecimalDigit(ch.charCodeAt(0))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } ch = source[index]; } if (ch === '.') { number += source[index++]; while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } ch = source[index]; } if (ch === 'e' || ch === 'E') { number += source[index++]; ch = source[index]; if (ch === '+' || ch === '-') { number += source[index++]; } if (isDecimalDigit(source.charCodeAt(index))) { while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } } else { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } if (isIdentifierStart(source.charCodeAt(index))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.NumericLiteral, value: parseFloat(number), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // 7.8.4 String Literals function scanStringLiteral() { var str = '', quote, start, ch, code, unescaped, restore, octal = false; quote = source[index]; assert((quote === '\'' || quote === '"'), 'String literal must starts with a quote'); start = index; ++index; while (index < length) { ch = source[index++]; if (ch === quote) { quote = ''; break; } else if (ch === '\\') { ch = source[index++]; if (!ch || !isLineTerminator(ch.charCodeAt(0))) { switch (ch) { case 'n': str += '\n'; break; case 'r': str += '\r'; break; case 't': str += '\t'; break; case 'u': case 'x': if (source[index] === '{') { ++index; str += scanUnicodeCodePointEscape(); } else { restore = index; unescaped = scanHexEscape(ch); if (unescaped) { str += unescaped; } else { index = restore; str += ch; } } break; case 'b': str += '\b'; break; case 'f': str += '\f'; break; case 'v': str += '\x0B'; break; default: if (isOctalDigit(ch)) { code = '01234567'.indexOf(ch); // \0 is not octal escape sequence if (code !== 0) { octal = true; } /* istanbul ignore else */ if (index < length && isOctalDigit(source[index])) { octal = true; code = code * 8 + '01234567'.indexOf(source[index++]); // 3 digits are only allowed when string starts // with 0, 1, 2, 3 if ('0123'.indexOf(ch) >= 0 && index < length && isOctalDigit(source[index])) { code = code * 8 + '01234567'.indexOf(source[index++]); } } str += String.fromCharCode(code); } else { str += ch; } break; } } else { ++lineNumber; if (ch === '\r' && source[index] === '\n') { ++index; } lineStart = index; } } else if (isLineTerminator(ch.charCodeAt(0))) { break; } else { str += ch; } } if (quote !== '') { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.StringLiteral, value: str, octal: octal, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanTemplate() { var cooked = '', ch, start, terminated, head, tail, restore, unescaped, code, octal; terminated = false; tail = false; start = index; head = (source[index] === '`'); ++index; while (index < length) { ch = source[index++]; if (ch === '`') { tail = true; terminated = true; break; } else if (ch === '$') { if (source[index] === '{') { ++index; terminated = true; break; } cooked += ch; } else if (ch === '\\') { ch = source[index++]; if (!isLineTerminator(ch.charCodeAt(0))) { switch (ch) { case 'n': cooked += '\n'; break; case 'r': cooked += '\r'; break; case 't': cooked += '\t'; break; case 'u': case 'x': if (source[index] === '{') { ++index; cooked += scanUnicodeCodePointEscape(); } else { restore = index; unescaped = scanHexEscape(ch); if (unescaped) { cooked += unescaped; } else { index = restore; cooked += ch; } } break; case 'b': cooked += '\b'; break; case 'f': cooked += '\f'; break; case 'v': cooked += '\v'; break; default: if (isOctalDigit(ch)) { code = '01234567'.indexOf(ch); // \0 is not octal escape sequence if (code !== 0) { octal = true; } /* istanbul ignore else */ if (index < length && isOctalDigit(source[index])) { octal = true; code = code * 8 + '01234567'.indexOf(source[index++]); // 3 digits are only allowed when string starts // with 0, 1, 2, 3 if ('0123'.indexOf(ch) >= 0 && index < length && isOctalDigit(source[index])) { code = code * 8 + '01234567'.indexOf(source[index++]); } } cooked += String.fromCharCode(code); } else { cooked += ch; } break; } } else { ++lineNumber; if (ch === '\r' && source[index] === '\n') { ++index; } lineStart = index; } } else if (isLineTerminator(ch.charCodeAt(0))) { ++lineNumber; if (ch === '\r' && source[index] === '\n') { ++index; } lineStart = index; cooked += '\n'; } else { cooked += ch; } } if (!terminated) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } if (index > state.curlyLastIndex) { state.curlyLastIndex = index; if (!tail) { state.curlyStack.push('template'); } if (!head) { state.curlyStack.pop(); } } return { type: Token.Template, value: { cooked: cooked, raw: source.slice(start + 1, index - ((tail) ? 1 : 2)) }, head: head, tail: tail, octal: octal, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function testRegExp(pattern, flags) { var tmp = pattern, value; if (flags.indexOf('u') >= 0) { // Replace each astral symbol and every Unicode code point // escape sequence with a single ASCII symbol to avoid throwing on // regular expressions that are only valid in combination with the // `/u` flag. // Note: replacing with the ASCII symbol `x` might cause false // negatives in unlikely scenarios. For example, `[\u{61}-b]` is a // perfectly valid pattern that is equivalent to `[a-b]`, but it // would be replaced by `[x-b]` which throws an error. tmp = tmp .replace(/\\u\{([0-9a-fA-F]+)\}/g, function ($0, $1) { if (parseInt($1, 16) <= 0x10FFFF) { return 'x'; } throwError({}, Messages.InvalidRegExp); }) .replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, 'x'); } // First, detect invalid regular expressions. try { value = new RegExp(tmp); } catch (e) { throwError({}, Messages.InvalidRegExp); } // Return a regular expression object for this pattern-flag pair, or // `null` in case the current environment doesn't support the flags it // uses. try { return new RegExp(pattern, flags); } catch (exception) { return null; } } function scanRegExpBody() { var ch, str, classMarker, terminated, body; ch = source[index]; assert(ch === '/', 'Regular expression literal must start with a slash'); str = source[index++]; classMarker = false; terminated = false; while (index < length) { ch = source[index++]; str += ch; if (ch === '\\') { ch = source[index++]; // ECMA-262 7.8.5 if (isLineTerminator(ch.charCodeAt(0))) { throwError({}, Messages.UnterminatedRegExp); } str += ch; } else if (isLineTerminator(ch.charCodeAt(0))) { throwError({}, Messages.UnterminatedRegExp); } else if (classMarker) { if (ch === ']') { classMarker = false; } } else { if (ch === '/') { terminated = true; break; } else if (ch === '[') { classMarker = true; } } } if (!terminated) { throwError({}, Messages.UnterminatedRegExp); } // Exclude leading and trailing slash. body = str.substr(1, str.length - 2); return { value: body, literal: str }; } function scanRegExpFlags() { var ch, str, flags, restore; str = ''; flags = ''; while (index < length) { ch = source[index]; if (!isIdentifierPart(ch.charCodeAt(0))) { break; } ++index; if (ch === '\\' && index < length) { ch = source[index]; if (ch === 'u') { ++index; restore = index; ch = scanHexEscape('u'); if (ch) { flags += ch; for (str += '\\u'; restore < index; ++restore) { str += source[restore]; } } else { index = restore; flags += 'u'; str += '\\u'; } throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL'); } else { str += '\\'; throwErrorTolerant({}, Messages.UnexpectedToken, 'ILLEGAL'); } } else { flags += ch; str += ch; } } return { value: flags, literal: str }; } function scanRegExp() { var start, body, flags, value; lookahead = null; skipComment(); start = index; body = scanRegExpBody(); flags = scanRegExpFlags(); value = testRegExp(body.value, flags.value); if (extra.tokenize) { return { type: Token.RegularExpression, value: value, regex: { pattern: body.value, flags: flags.value }, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } return { literal: body.literal + flags.literal, value: value, regex: { pattern: body.value, flags: flags.value }, range: [start, index] }; } function isIdentifierName(token) { return token.type === Token.Identifier || token.type === Token.Keyword || token.type === Token.BooleanLiteral || token.type === Token.NullLiteral; } function advanceSlash() { var prevToken, checkToken; // Using the following algorithm: // https://github.com/mozilla/sweet.js/wiki/design prevToken = extra.tokens[extra.tokens.length - 1]; if (!prevToken) { // Nothing before that: it cannot be a division. return scanRegExp(); } if (prevToken.type === 'Punctuator') { if (prevToken.value === ')') { checkToken = extra.tokens[extra.openParenToken - 1]; if (checkToken && checkToken.type === 'Keyword' && (checkToken.value === 'if' || checkToken.value === 'while' || checkToken.value === 'for' || checkToken.value === 'with')) { return scanRegExp(); } return scanPunctuator(); } if (prevToken.value === '}') { // Dividing a function by anything makes little sense, // but we have to check for that. if (extra.tokens[extra.openCurlyToken - 3] && extra.tokens[extra.openCurlyToken - 3].type === 'Keyword') { // Anonymous function. checkToken = extra.tokens[extra.openCurlyToken - 4]; if (!checkToken) { return scanPunctuator(); } } else if (extra.tokens[extra.openCurlyToken - 4] && extra.tokens[extra.openCurlyToken - 4].type === 'Keyword') { // Named function. checkToken = extra.tokens[extra.openCurlyToken - 5]; if (!checkToken) { return scanRegExp(); } } else { return scanPunctuator(); } // checkToken determines whether the function is // a declaration or an expression. if (FnExprTokens.indexOf(checkToken.value) >= 0) { // It is an expression. return scanPunctuator(); } // It is a declaration. return scanRegExp(); } return scanRegExp(); } if (prevToken.type === 'Keyword' && prevToken.value !== 'this') { return scanRegExp(); } return scanPunctuator(); } function advance() { var ch; if (!state.inJSXChild) { skipComment(); } if (index >= length) { return { type: Token.EOF, lineNumber: lineNumber, lineStart: lineStart, range: [index, index] }; } if (state.inJSXChild) { return advanceJSXChild(); } ch = source.charCodeAt(index); // Very common: ( and ) and ; if (ch === 40 || ch === 41 || ch === 58) { return scanPunctuator(); } // String literal starts with single quote (#39) or double quote (#34). if (ch === 39 || ch === 34) { if (state.inJSXTag) { return scanJSXStringLiteral(); } return scanStringLiteral(); } if (state.inJSXTag && isJSXIdentifierStart(ch)) { return scanJSXIdentifier(); } // Template literals start with backtick (#96) for template head // or close curly (#125) for template middle or template tail. if (ch === 96 || (ch === 125 && state.curlyStack[state.curlyStack.length - 1] === 'template')) { return scanTemplate(); } if (isIdentifierStart(ch)) { return scanIdentifier(); } // Dot (.) char #46 can also start a floating-point number, hence the need // to check the next character. if (ch === 46) { if (isDecimalDigit(source.charCodeAt(index + 1))) { return scanNumericLiteral(); } return scanPunctuator(); } if (isDecimalDigit(ch)) { return scanNumericLiteral(); } // Slash (/) char #47 can also start a regex. if (extra.tokenize && ch === 47) { return advanceSlash(); } return scanPunctuator(); } function lex() { var token; token = lookahead; index = token.range[1]; lineNumber = token.lineNumber; lineStart = token.lineStart; lookahead = advance(); index = token.range[1]; lineNumber = token.lineNumber; lineStart = token.lineStart; return token; } function peek() { var pos, line, start; pos = index; line = lineNumber; start = lineStart; lookahead = advance(); index = pos; lineNumber = line; lineStart = start; } function lookahead2() { var adv, pos, line, start, result; // If we are collecting the tokens, don't grab the next one yet. /* istanbul ignore next */ adv = (typeof extra.advance === 'function') ? extra.advance : advance; pos = index; line = lineNumber; start = lineStart; // Scan for the next immediate token. /* istanbul ignore if */ if (lookahead === null) { lookahead = adv(); } index = lookahead.range[1]; lineNumber = lookahead.lineNumber; lineStart = lookahead.lineStart; // Grab the token right after. result = adv(); index = pos; lineNumber = line; lineStart = start; return result; } function rewind(token) { index = token.range[0]; lineNumber = token.lineNumber; lineStart = token.lineStart; lookahead = token; } function markerCreate() { if (!extra.loc && !extra.range) { return undefined; } skipComment(); return {offset: index, line: lineNumber, col: index - lineStart}; } function markerCreatePreserveWhitespace() { if (!extra.loc && !extra.range) { return undefined; } return {offset: index, line: lineNumber, col: index - lineStart}; } function processComment(node) { var lastChild, trailingComments, bottomRight = extra.bottomRightStack, last = bottomRight[bottomRight.length - 1]; if (node.type === Syntax.Program) { /* istanbul ignore else */ if (node.body.length > 0) { return; } } if (extra.trailingComments.length > 0) { if (extra.trailingComments[0].range[0] >= node.range[1]) { trailingComments = extra.trailingComments; extra.trailingComments = []; } else { extra.trailingComments.length = 0; } } else { if (last && last.trailingComments && last.trailingComments[0].range[0] >= node.range[1]) { trailingComments = last.trailingComments; delete last.trailingComments; } } // Eating the stack. if (last) { while (last && last.range[0] >= node.range[0]) { lastChild = last; last = bottomRight.pop(); } } if (lastChild) { if (lastChild.leadingComments && lastChild.leadingComments[lastChild.leadingComments.length - 1].range[1] <= node.range[0]) { node.leadingComments = lastChild.leadingComments; delete lastChild.leadingComments; } } else if (extra.leadingComments.length > 0 && extra.leadingComments[extra.leadingComments.length - 1].range[1] <= node.range[0]) { node.leadingComments = extra.leadingComments; extra.leadingComments = []; } if (trailingComments) { node.trailingComments = trailingComments; } bottomRight.push(node); } function markerApply(marker, node) { if (extra.range) { node.range = [marker.offset, index]; } if (extra.loc) { node.loc = { start: { line: marker.line, column: marker.col }, end: { line: lineNumber, column: index - lineStart } }; node = delegate.postProcess(node); } if (extra.attachComment) { processComment(node); } return node; } SyntaxTreeDelegate = { name: 'SyntaxTree', postProcess: function (node) { return node; }, createArrayExpression: function (elements) { return { type: Syntax.ArrayExpression, elements: elements }; }, createAssignmentExpression: function (operator, left, right) { return { type: Syntax.AssignmentExpression, operator: operator, left: left, right: right }; }, createBinaryExpression: function (operator, left, right) { var type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression : Syntax.BinaryExpression; return { type: type, operator: operator, left: left, right: right }; }, createBlockStatement: function (body) { return { type: Syntax.BlockStatement, body: body }; }, createBreakStatement: function (label) { return { type: Syntax.BreakStatement, label: label }; }, createCallExpression: function (callee, args) { return { type: Syntax.CallExpression, callee: callee, 'arguments': args }; }, createCatchClause: function (param, body) { return { type: Syntax.CatchClause, param: param, body: body }; }, createConditionalExpression: function (test, consequent, alternate) { return { type: Syntax.ConditionalExpression, test: test, consequent: consequent, alternate: alternate }; }, createContinueStatement: function (label) { return { type: Syntax.ContinueStatement, label: label }; }, createDebuggerStatement: function () { return { type: Syntax.DebuggerStatement }; }, createDoWhileStatement: function (body, test) { return { type: Syntax.DoWhileStatement, body: body, test: test }; }, createEmptyStatement: function () { return { type: Syntax.EmptyStatement }; }, createExpressionStatement: function (expression) { return { type: Syntax.ExpressionStatement, expression: expression }; }, createForStatement: function (init, test, update, body) { return { type: Syntax.ForStatement, init: init, test: test, update: update, body: body }; }, createForInStatement: function (left, right, body) { return { type: Syntax.ForInStatement, left: left, right: right, body: body, each: false }; }, createForOfStatement: function (left, right, body) { return { type: Syntax.ForOfStatement, left: left, right: right, body: body }; }, createFunctionDeclaration: function (id, params, defaults, body, rest, generator, expression, isAsync, returnType, typeParameters) { var funDecl = { type: Syntax.FunctionDeclaration, id: id, params: params, defaults: defaults, body: body, rest: rest, generator: generator, expression: expression, returnType: returnType, typeParameters: typeParameters }; if (isAsync) { funDecl.async = true; } return funDecl; }, createFunctionExpression: function (id, params, defaults, body, rest, generator, expression, isAsync, returnType, typeParameters) { var funExpr = { type: Syntax.FunctionExpression, id: id, params: params, defaults: defaults, body: body, rest: rest, generator: generator, expression: expression, returnType: returnType, typeParameters: typeParameters }; if (isAsync) { funExpr.async = true; } return funExpr; }, createIdentifier: function (name) { return { type: Syntax.Identifier, name: name, // Only here to initialize the shape of the object to ensure // that the 'typeAnnotation' key is ordered before others that // are added later (like 'loc' and 'range'). This just helps // keep the shape of Identifier nodes consistent with everything // else. typeAnnotation: undefined, optional: undefined }; }, createTypeAnnotation: function (typeAnnotation) { return { type: Syntax.TypeAnnotation, typeAnnotation: typeAnnotation }; }, createTypeCast: function (expression, typeAnnotation) { return { type: Syntax.TypeCastExpression, expression: expression, typeAnnotation: typeAnnotation }; }, createFunctionTypeAnnotation: function (params, returnType, rest, typeParameters) { return { type: Syntax.FunctionTypeAnnotation, params: params, returnType: returnType, rest: rest, typeParameters: typeParameters }; }, createFunctionTypeParam: function (name, typeAnnotation, optional) { return { type: Syntax.FunctionTypeParam, name: name, typeAnnotation: typeAnnotation, optional: optional }; }, createNullableTypeAnnotation: function (typeAnnotation) { return { type: Syntax.NullableTypeAnnotation, typeAnnotation: typeAnnotation }; }, createArrayTypeAnnotation: function (elementType) { return { type: Syntax.ArrayTypeAnnotation, elementType: elementType }; }, createGenericTypeAnnotation: function (id, typeParameters) { return { type: Syntax.GenericTypeAnnotation, id: id, typeParameters: typeParameters }; }, createQualifiedTypeIdentifier: function (qualification, id) { return { type: Syntax.QualifiedTypeIdentifier, qualification: qualification, id: id }; }, createTypeParameterDeclaration: function (params) { return { type: Syntax.TypeParameterDeclaration, params: params }; }, createTypeParameterInstantiation: function (params) { return { type: Syntax.TypeParameterInstantiation, params: params }; }, createAnyTypeAnnotation: function () { return { type: Syntax.AnyTypeAnnotation }; }, createBooleanTypeAnnotation: function () { return { type: Syntax.BooleanTypeAnnotation }; }, createNumberTypeAnnotation: function () { return { type: Syntax.NumberTypeAnnotation }; }, createStringTypeAnnotation: function () { return { type: Syntax.StringTypeAnnotation }; }, createStringLiteralTypeAnnotation: function (token) { return { type: Syntax.StringLiteralTypeAnnotation, value: token.value, raw: source.slice(token.range[0], token.range[1]) }; }, createVoidTypeAnnotation: function () { return { type: Syntax.VoidTypeAnnotation }; }, createTypeofTypeAnnotation: function (argument) { return { type: Syntax.TypeofTypeAnnotation, argument: argument }; }, createTupleTypeAnnotation: function (types) { return { type: Syntax.TupleTypeAnnotation, types: types }; }, createObjectTypeAnnotation: function (properties, indexers, callProperties) { return { type: Syntax.ObjectTypeAnnotation, properties: properties, indexers: indexers, callProperties: callProperties }; }, createObjectTypeIndexer: function (id, key, value, isStatic) { return { type: Syntax.ObjectTypeIndexer, id: id, key: key, value: value, static: isStatic }; }, createObjectTypeCallProperty: function (value, isStatic) { return { type: Syntax.ObjectTypeCallProperty, value: value, static: isStatic }; }, createObjectTypeProperty: function (key, value, optional, isStatic) { return { type: Syntax.ObjectTypeProperty, key: key, value: value, optional: optional, static: isStatic }; }, createUnionTypeAnnotation: function (types) { return { type: Syntax.UnionTypeAnnotation, types: types }; }, createIntersectionTypeAnnotation: function (types) { return { type: Syntax.IntersectionTypeAnnotation, types: types }; }, createTypeAlias: function (id, typeParameters, right) { return { type: Syntax.TypeAlias, id: id, typeParameters: typeParameters, right: right }; }, createInterface: function (id, typeParameters, body, extended) { return { type: Syntax.InterfaceDeclaration, id: id, typeParameters: typeParameters, body: body, extends: extended }; }, createInterfaceExtends: function (id, typeParameters) { return { type: Syntax.InterfaceExtends, id: id, typeParameters: typeParameters }; }, createDeclareFunction: function (id) { return { type: Syntax.DeclareFunction, id: id }; }, createDeclareVariable: function (id) { return { type: Syntax.DeclareVariable, id: id }; }, createDeclareModule: function (id, body) { return { type: Syntax.DeclareModule, id: id, body: body }; }, createJSXAttribute: function (name, value) { return { type: Syntax.JSXAttribute, name: name, value: value || null }; }, createJSXSpreadAttribute: function (argument) { return { type: Syntax.JSXSpreadAttribute, argument: argument }; }, createJSXIdentifier: function (name) { return { type: Syntax.JSXIdentifier, name: name }; }, createJSXNamespacedName: function (namespace, name) { return { type: Syntax.JSXNamespacedName, namespace: namespace, name: name }; }, createJSXMemberExpression: function (object, property) { return { type: Syntax.JSXMemberExpression, object: object, property: property }; }, createJSXElement: function (openingElement, closingElement, children) { return { type: Syntax.JSXElement, openingElement: openingElement, closingElement: closingElement, children: children }; }, createJSXEmptyExpression: function () { return { type: Syntax.JSXEmptyExpression }; }, createJSXExpressionContainer: function (expression) { return { type: Syntax.JSXExpressionContainer, expression: expression }; }, createJSXOpeningElement: function (name, attributes, selfClosing) { return { type: Syntax.JSXOpeningElement, name: name, selfClosing: selfClosing, attributes: attributes }; }, createJSXClosingElement: function (name) { return { type: Syntax.JSXClosingElement, name: name }; }, createIfStatement: function (test, consequent, alternate) { return { type: Syntax.IfStatement, test: test, consequent: consequent, alternate: alternate }; }, createLabeledStatement: function (label, body) { return { type: Syntax.LabeledStatement, label: label, body: body }; }, createLiteral: function (token) { var object = { type: Syntax.Literal, value: token.value, raw: source.slice(token.range[0], token.range[1]) }; if (token.regex) { object.regex = token.regex; } return object; }, createMemberExpression: function (accessor, object, property) { return { type: Syntax.MemberExpression, computed: accessor === '[', object: object, property: property }; }, createNewExpression: function (callee, args) { return { type: Syntax.NewExpression, callee: callee, 'arguments': args }; }, createObjectExpression: function (properties) { return { type: Syntax.ObjectExpression, properties: properties }; }, createPostfixExpression: function (operator, argument) { return { type: Syntax.UpdateExpression, operator: operator, argument: argument, prefix: false }; }, createProgram: function (body) { return { type: Syntax.Program, body: body }; }, createProperty: function (kind, key, value, method, shorthand, computed) { return { type: Syntax.Property, key: key, value: value, kind: kind, method: method, shorthand: shorthand, computed: computed }; }, createReturnStatement: function (argument) { return { type: Syntax.ReturnStatement, argument: argument }; }, createSequenceExpression: function (expressions) { return { type: Syntax.SequenceExpression, expressions: expressions }; }, createSwitchCase: function (test, consequent) { return { type: Syntax.SwitchCase, test: test, consequent: consequent }; }, createSwitchStatement: function (discriminant, cases) { return { type: Syntax.SwitchStatement, discriminant: discriminant, cases: cases }; }, createThisExpression: function () { return { type: Syntax.ThisExpression }; }, createThrowStatement: function (argument) { return { type: Syntax.ThrowStatement, argument: argument }; }, createTryStatement: function (block, guardedHandlers, handlers, finalizer) { return { type: Syntax.TryStatement, block: block, guardedHandlers: guardedHandlers, handlers: handlers, finalizer: finalizer }; }, createUnaryExpression: function (operator, argument) { if (operator === '++' || operator === '--') { return { type: Syntax.UpdateExpression, operator: operator, argument: argument, prefix: true }; } return { type: Syntax.UnaryExpression, operator: operator, argument: argument, prefix: true }; }, createVariableDeclaration: function (declarations, kind) { return { type: Syntax.VariableDeclaration, declarations: declarations, kind: kind }; }, createVariableDeclarator: function (id, init) { return { type: Syntax.VariableDeclarator, id: id, init: init }; }, createWhileStatement: function (test, body) { return { type: Syntax.WhileStatement, test: test, body: body }; }, createWithStatement: function (object, body) { return { type: Syntax.WithStatement, object: object, body: body }; }, createTemplateElement: function (value, tail) { return { type: Syntax.TemplateElement, value: value, tail: tail }; }, createTemplateLiteral: function (quasis, expressions) { return { type: Syntax.TemplateLiteral, quasis: quasis, expressions: expressions }; }, createSpreadElement: function (argument) { return { type: Syntax.SpreadElement, argument: argument }; }, createSpreadProperty: function (argument) { return { type: Syntax.SpreadProperty, argument: argument }; }, createTaggedTemplateExpression: function (tag, quasi) { return { type: Syntax.TaggedTemplateExpression, tag: tag, quasi: quasi }; }, createArrowFunctionExpression: function (params, defaults, body, rest, expression, isAsync) { var arrowExpr = { type: Syntax.ArrowFunctionExpression, id: null, params: params, defaults: defaults, body: body, rest: rest, generator: false, expression: expression }; if (isAsync) { arrowExpr.async = true; } return arrowExpr; }, createMethodDefinition: function (propertyType, kind, key, value, computed) { return { type: Syntax.MethodDefinition, key: key, value: value, kind: kind, 'static': propertyType === ClassPropertyType.static, computed: computed }; }, createClassProperty: function (key, typeAnnotation, computed, isStatic) { return { type: Syntax.ClassProperty, key: key, typeAnnotation: typeAnnotation, computed: computed, static: isStatic }; }, createClassBody: function (body) { return { type: Syntax.ClassBody, body: body }; }, createClassImplements: function (id, typeParameters) { return { type: Syntax.ClassImplements, id: id, typeParameters: typeParameters }; }, createClassExpression: function (id, superClass, body, typeParameters, superTypeParameters, implemented) { return { type: Syntax.ClassExpression, id: id, superClass: superClass, body: body, typeParameters: typeParameters, superTypeParameters: superTypeParameters, implements: implemented }; }, createClassDeclaration: function (id, superClass, body, typeParameters, superTypeParameters, implemented) { return { type: Syntax.ClassDeclaration, id: id, superClass: superClass, body: body, typeParameters: typeParameters, superTypeParameters: superTypeParameters, implements: implemented }; }, createExportSpecifier: function (id, name) { return { type: Syntax.ExportSpecifier, id: id, name: name }; }, createExportBatchSpecifier: function () { return { type: Syntax.ExportBatchSpecifier }; }, createImportDefaultSpecifier: function (id) { return { type: Syntax.ImportDefaultSpecifier, id: id }; }, createImportNamespaceSpecifier: function (id) { return { type: Syntax.ImportNamespaceSpecifier, id: id }; }, createExportDeclaration: function (isDefault, declaration, specifiers, src) { return { type: Syntax.ExportDeclaration, 'default': !!isDefault, declaration: declaration, specifiers: specifiers, source: src }; }, createImportSpecifier: function (id, name) { return { type: Syntax.ImportSpecifier, id: id, name: name }; }, createImportDeclaration: function (specifiers, src, isType) { return { type: Syntax.ImportDeclaration, specifiers: specifiers, source: src, isType: isType }; }, createYieldExpression: function (argument, dlg) { return { type: Syntax.YieldExpression, argument: argument, delegate: dlg }; }, createAwaitExpression: function (argument) { return { type: Syntax.AwaitExpression, argument: argument }; }, createComprehensionExpression: function (filter, blocks, body) { return { type: Syntax.ComprehensionExpression, filter: filter, blocks: blocks, body: body }; } }; // Return true if there is a line terminator before the next token. function peekLineTerminator() { var pos, line, start, found; pos = index; line = lineNumber; start = lineStart; skipComment(); found = lineNumber !== line; index = pos; lineNumber = line; lineStart = start; return found; } // Throw an exception function throwError(token, messageFormat) { var error, args = Array.prototype.slice.call(arguments, 2), msg = messageFormat.replace( /%(\d)/g, function (whole, idx) { assert(idx < args.length, 'Message reference must be in range'); return args[idx]; } ); if (typeof token.lineNumber === 'number') { error = new Error('Line ' + token.lineNumber + ': ' + msg); error.index = token.range[0]; error.lineNumber = token.lineNumber; error.column = token.range[0] - lineStart + 1; } else { error = new Error('Line ' + lineNumber + ': ' + msg); error.index = index; error.lineNumber = lineNumber; error.column = index - lineStart + 1; } error.description = msg; throw error; } function throwErrorTolerant() { try { throwError.apply(null, arguments); } catch (e) { if (extra.errors) { extra.errors.push(e); } else { throw e; } } } // Throw an exception because of the token. function throwUnexpected(token) { if (token.type === Token.EOF) { throwError(token, Messages.UnexpectedEOS); } if (token.type === Token.NumericLiteral) { throwError(token, Messages.UnexpectedNumber); } if (token.type === Token.StringLiteral || token.type === Token.JSXText) { throwError(token, Messages.UnexpectedString); } if (token.type === Token.Identifier) { throwError(token, Messages.UnexpectedIdentifier); } if (token.type === Token.Keyword) { if (isFutureReservedWord(token.value)) { throwError(token, Messages.UnexpectedReserved); } else if (strict && isStrictModeReservedWord(token.value)) { throwErrorTolerant(token, Messages.StrictReservedWord); return; } throwError(token, Messages.UnexpectedToken, token.value); } if (token.type === Token.Template) { throwError(token, Messages.UnexpectedTemplate, token.value.raw); } // BooleanLiteral, NullLiteral, or Punctuator. throwError(token, Messages.UnexpectedToken, token.value); } // Expect the next token to match the specified punctuator. // If not, an exception will be thrown. function expect(value) { var token = lex(); if (token.type !== Token.Punctuator || token.value !== value) { throwUnexpected(token); } } // Expect the next token to match the specified keyword. // If not, an exception will be thrown. function expectKeyword(keyword, contextual) { var token = lex(); if (token.type !== (contextual ? Token.Identifier : Token.Keyword) || token.value !== keyword) { throwUnexpected(token); } } // Expect the next token to match the specified contextual keyword. // If not, an exception will be thrown. function expectContextualKeyword(keyword) { return expectKeyword(keyword, true); } // Return true if the next token matches the specified punctuator. function match(value) { return lookahead.type === Token.Punctuator && lookahead.value === value; } // Return true if the next token matches the specified keyword function matchKeyword(keyword, contextual) { var expectedType = contextual ? Token.Identifier : Token.Keyword; return lookahead.type === expectedType && lookahead.value === keyword; } // Return true if the next token matches the specified contextual keyword function matchContextualKeyword(keyword) { return matchKeyword(keyword, true); } // Return true if the next token is an assignment operator function matchAssign() { var op; if (lookahead.type !== Token.Punctuator) { return false; } op = lookahead.value; return op === '=' || op === '*=' || op === '/=' || op === '%=' || op === '+=' || op === '-=' || op === '<<=' || op === '>>=' || op === '>>>=' || op === '&=' || op === '^=' || op === '|='; } // Note that 'yield' is treated as a keyword in strict mode, but a // contextual keyword (identifier) in non-strict mode, so we need to // use matchKeyword('yield', false) and matchKeyword('yield', true) // (i.e. matchContextualKeyword) appropriately. function matchYield() { return state.yieldAllowed && matchKeyword('yield', !strict); } function matchAsync() { var backtrackToken = lookahead, matches = false; if (matchContextualKeyword('async')) { lex(); // Make sure peekLineTerminator() starts after 'async'. matches = !peekLineTerminator(); rewind(backtrackToken); // Revert the lex(). } return matches; } function matchAwait() { return state.awaitAllowed && matchContextualKeyword('await'); } function consumeSemicolon() { var line, oldIndex = index, oldLineNumber = lineNumber, oldLineStart = lineStart, oldLookahead = lookahead; // Catch the very common case first: immediately a semicolon (char #59). if (source.charCodeAt(index) === 59) { lex(); return; } line = lineNumber; skipComment(); if (lineNumber !== line) { index = oldIndex; lineNumber = oldLineNumber; lineStart = oldLineStart; lookahead = oldLookahead; return; } if (match(';')) { lex(); return; } if (lookahead.type !== Token.EOF && !match('}')) { throwUnexpected(lookahead); } } // Return true if provided expression is LeftHandSideExpression function isLeftHandSide(expr) { return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression; } function isAssignableLeftHandSide(expr) { return isLeftHandSide(expr) || expr.type === Syntax.ObjectPattern || expr.type === Syntax.ArrayPattern; } // 11.1.4 Array Initialiser function parseArrayInitialiser() { var elements = [], blocks = [], filter = null, tmp, possiblecomprehension = true, marker = markerCreate(); expect('['); while (!match(']')) { if (lookahead.value === 'for' && lookahead.type === Token.Keyword) { if (!possiblecomprehension) { throwError({}, Messages.ComprehensionError); } matchKeyword('for'); tmp = parseForStatement({ignoreBody: true}); tmp.of = tmp.type === Syntax.ForOfStatement; tmp.type = Syntax.ComprehensionBlock; if (tmp.left.kind) { // can't be let or const throwError({}, Messages.ComprehensionError); } blocks.push(tmp); } else if (lookahead.value === 'if' && lookahead.type === Token.Keyword) { if (!possiblecomprehension) { throwError({}, Messages.ComprehensionError); } expectKeyword('if'); expect('('); filter = parseExpression(); expect(')'); } else if (lookahead.value === ',' && lookahead.type === Token.Punctuator) { possiblecomprehension = false; // no longer allowed. lex(); elements.push(null); } else { tmp = parseSpreadOrAssignmentExpression(); elements.push(tmp); if (tmp && tmp.type === Syntax.SpreadElement) { if (!match(']')) { throwError({}, Messages.ElementAfterSpreadElement); } } else if (!(match(']') || matchKeyword('for') || matchKeyword('if'))) { expect(','); // this lexes. possiblecomprehension = false; } } } expect(']'); if (filter && !blocks.length) { throwError({}, Messages.ComprehensionRequiresBlock); } if (blocks.length) { if (elements.length !== 1) { throwError({}, Messages.ComprehensionError); } return markerApply(marker, delegate.createComprehensionExpression(filter, blocks, elements[0])); } return markerApply(marker, delegate.createArrayExpression(elements)); } // 11.1.5 Object Initialiser function parsePropertyFunction(options) { var previousStrict, previousYieldAllowed, previousAwaitAllowed, params, defaults, body, marker = markerCreate(); previousStrict = strict; previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = options.generator; previousAwaitAllowed = state.awaitAllowed; state.awaitAllowed = options.async; params = options.params || []; defaults = options.defaults || []; body = parseConciseBody(); if (options.name && strict && isRestrictedWord(params[0].name)) { throwErrorTolerant(options.name, Messages.StrictParamName); } strict = previousStrict; state.yieldAllowed = previousYieldAllowed; state.awaitAllowed = previousAwaitAllowed; return markerApply(marker, delegate.createFunctionExpression( null, params, defaults, body, options.rest || null, options.generator, body.type !== Syntax.BlockStatement, options.async, options.returnType, options.typeParameters )); } function parsePropertyMethodFunction(options) { var previousStrict, tmp, method; previousStrict = strict; strict = true; tmp = parseParams(); if (tmp.stricted) { throwErrorTolerant(tmp.stricted, tmp.message); } method = parsePropertyFunction({ params: tmp.params, defaults: tmp.defaults, rest: tmp.rest, generator: options.generator, async: options.async, returnType: tmp.returnType, typeParameters: options.typeParameters }); strict = previousStrict; return method; } function parseObjectPropertyKey() { var marker = markerCreate(), token = lex(), propertyKey, result; // Note: This function is called only from parseObjectProperty(), where // EOF and Punctuator tokens are already filtered out. if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) { if (strict && token.octal) { throwErrorTolerant(token, Messages.StrictOctalLiteral); } return markerApply(marker, delegate.createLiteral(token)); } if (token.type === Token.Punctuator && token.value === '[') { // For computed properties we should skip the [ and ], and // capture in marker only the assignment expression itself. marker = markerCreate(); propertyKey = parseAssignmentExpression(); result = markerApply(marker, propertyKey); expect(']'); return result; } return markerApply(marker, delegate.createIdentifier(token.value)); } function parseObjectProperty() { var token, key, id, param, computed, marker = markerCreate(), returnType, typeParameters; token = lookahead; computed = (token.value === '[' && token.type === Token.Punctuator); if (token.type === Token.Identifier || computed || matchAsync()) { id = parseObjectPropertyKey(); if (match(':')) { lex(); return markerApply( marker, delegate.createProperty( 'init', id, parseAssignmentExpression(), false, false, computed ) ); } if (match('(') || match('<')) { if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } return markerApply( marker, delegate.createProperty( 'init', id, parsePropertyMethodFunction({ generator: false, async: false, typeParameters: typeParameters }), true, false, computed ) ); } // Property Assignment: Getter and Setter. if (token.value === 'get') { computed = (lookahead.value === '['); key = parseObjectPropertyKey(); expect('('); expect(')'); if (match(':')) { returnType = parseTypeAnnotation(); } return markerApply( marker, delegate.createProperty( 'get', key, parsePropertyFunction({ generator: false, async: false, returnType: returnType }), false, false, computed ) ); } if (token.value === 'set') { computed = (lookahead.value === '['); key = parseObjectPropertyKey(); expect('('); token = lookahead; param = [ parseTypeAnnotatableIdentifier() ]; expect(')'); if (match(':')) { returnType = parseTypeAnnotation(); } return markerApply( marker, delegate.createProperty( 'set', key, parsePropertyFunction({ params: param, generator: false, async: false, name: token, returnType: returnType }), false, false, computed ) ); } if (token.value === 'async') { computed = (lookahead.value === '['); key = parseObjectPropertyKey(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } return markerApply( marker, delegate.createProperty( 'init', key, parsePropertyMethodFunction({ generator: false, async: true, typeParameters: typeParameters }), true, false, computed ) ); } if (computed) { // Computed properties can only be used with full notation. throwUnexpected(lookahead); } return markerApply( marker, delegate.createProperty('init', id, id, false, true, false) ); } if (token.type === Token.EOF || token.type === Token.Punctuator) { if (!match('*')) { throwUnexpected(token); } lex(); computed = (lookahead.type === Token.Punctuator && lookahead.value === '['); id = parseObjectPropertyKey(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } if (!match('(')) { throwUnexpected(lex()); } return markerApply(marker, delegate.createProperty( 'init', id, parsePropertyMethodFunction({ generator: true, typeParameters: typeParameters }), true, false, computed )); } key = parseObjectPropertyKey(); if (match(':')) { lex(); return markerApply(marker, delegate.createProperty('init', key, parseAssignmentExpression(), false, false, false)); } if (match('(') || match('<')) { if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } return markerApply(marker, delegate.createProperty( 'init', key, parsePropertyMethodFunction({ generator: false, typeParameters: typeParameters }), true, false, false )); } throwUnexpected(lex()); } function parseObjectSpreadProperty() { var marker = markerCreate(); expect('...'); return markerApply(marker, delegate.createSpreadProperty(parseAssignmentExpression())); } function getFieldName(key) { var toString = String; if (key.type === Syntax.Identifier) { return key.name; } return toString(key.value); } function parseObjectInitialiser() { var properties = [], property, name, kind, storedKind, map = new StringMap(), marker = markerCreate(), toString = String; expect('{'); while (!match('}')) { if (match('...')) { property = parseObjectSpreadProperty(); } else { property = parseObjectProperty(); if (property.key.type === Syntax.Identifier) { name = property.key.name; } else { name = toString(property.key.value); } kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set; if (map.has(name)) { storedKind = map.get(name); if (storedKind === PropertyKind.Data) { if (strict && kind === PropertyKind.Data) { throwErrorTolerant({}, Messages.StrictDuplicateProperty); } else if (kind !== PropertyKind.Data) { throwErrorTolerant({}, Messages.AccessorDataProperty); } } else { if (kind === PropertyKind.Data) { throwErrorTolerant({}, Messages.AccessorDataProperty); } else if (storedKind & kind) { throwErrorTolerant({}, Messages.AccessorGetSet); } } map.set(name, storedKind | kind); } else { map.set(name, kind); } } properties.push(property); if (!match('}')) { expect(','); } } expect('}'); return markerApply(marker, delegate.createObjectExpression(properties)); } function parseTemplateElement(option) { var marker, token; if (lookahead.type !== Token.Template || (option.head && !lookahead.head)) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } marker = markerCreate(); token = lex(); if (strict && token.octal) { throwError(token, Messages.StrictOctalLiteral); } return markerApply(marker, delegate.createTemplateElement({ raw: token.value.raw, cooked: token.value.cooked }, token.tail)); } function parseTemplateLiteral() { var quasi, quasis, expressions, marker = markerCreate(); quasi = parseTemplateElement({ head: true }); quasis = [ quasi ]; expressions = []; while (!quasi.tail) { expressions.push(parseExpression()); quasi = parseTemplateElement({ head: false }); quasis.push(quasi); } return markerApply(marker, delegate.createTemplateLiteral(quasis, expressions)); } // 11.1.6 The Grouping Operator function parseGroupExpression() { var expr, marker, typeAnnotation; expect('('); ++state.parenthesizedCount; marker = markerCreate(); expr = parseExpression(); if (match(':')) { typeAnnotation = parseTypeAnnotation(); expr = markerApply(marker, delegate.createTypeCast( expr, typeAnnotation )); } expect(')'); return expr; } function matchAsyncFuncExprOrDecl() { var token; if (matchAsync()) { token = lookahead2(); if (token.type === Token.Keyword && token.value === 'function') { return true; } } return false; } // 11.1 Primary Expressions function parsePrimaryExpression() { var marker, type, token, expr; type = lookahead.type; if (type === Token.Identifier) { marker = markerCreate(); return markerApply(marker, delegate.createIdentifier(lex().value)); } if (type === Token.StringLiteral || type === Token.NumericLiteral) { if (strict && lookahead.octal) { throwErrorTolerant(lookahead, Messages.StrictOctalLiteral); } marker = markerCreate(); return markerApply(marker, delegate.createLiteral(lex())); } if (type === Token.Keyword) { if (matchKeyword('this')) { marker = markerCreate(); lex(); return markerApply(marker, delegate.createThisExpression()); } if (matchKeyword('function')) { return parseFunctionExpression(); } if (matchKeyword('class')) { return parseClassExpression(); } if (matchKeyword('super')) { marker = markerCreate(); lex(); return markerApply(marker, delegate.createIdentifier('super')); } } if (type === Token.BooleanLiteral) { marker = markerCreate(); token = lex(); token.value = (token.value === 'true'); return markerApply(marker, delegate.createLiteral(token)); } if (type === Token.NullLiteral) { marker = markerCreate(); token = lex(); token.value = null; return markerApply(marker, delegate.createLiteral(token)); } if (match('[')) { return parseArrayInitialiser(); } if (match('{')) { return parseObjectInitialiser(); } if (match('(')) { return parseGroupExpression(); } if (match('/') || match('/=')) { marker = markerCreate(); expr = delegate.createLiteral(scanRegExp()); peek(); return markerApply(marker, expr); } if (type === Token.Template) { return parseTemplateLiteral(); } if (match('<')) { return parseJSXElement(); } throwUnexpected(lex()); } // 11.2 Left-Hand-Side Expressions function parseArguments() { var args = [], arg; expect('('); if (!match(')')) { while (index < length) { arg = parseSpreadOrAssignmentExpression(); args.push(arg); if (arg.type === Syntax.SpreadElement) { if (match(')')) { break; } else { throwError({}, Messages.ElementAfterSpreadElement); } } if (match(')')) { break; } else { expect(','); if (match(')')) { break; } } } } expect(')'); return args; } function parseSpreadOrAssignmentExpression() { if (match('...')) { var marker = markerCreate(); lex(); return markerApply(marker, delegate.createSpreadElement(parseAssignmentExpression())); } return parseAssignmentExpression(); } function parseNonComputedProperty() { var marker = markerCreate(), token = lex(); if (!isIdentifierName(token)) { throwUnexpected(token); } return markerApply(marker, delegate.createIdentifier(token.value)); } function parseNonComputedMember() { expect('.'); return parseNonComputedProperty(); } function parseComputedMember() { var expr; expect('['); expr = parseExpression(); expect(']'); return expr; } function parseNewExpression() { var callee, args, marker = markerCreate(); expectKeyword('new'); callee = parseLeftHandSideExpression(); args = match('(') ? parseArguments() : []; return markerApply(marker, delegate.createNewExpression(callee, args)); } function parseLeftHandSideExpressionAllowCall() { var expr, args, marker = markerCreate(); expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); while (match('.') || match('[') || match('(') || (lookahead.type === Token.Template && lookahead.head)) { if (match('(')) { args = parseArguments(); expr = markerApply(marker, delegate.createCallExpression(expr, args)); } else if (match('[')) { expr = markerApply(marker, delegate.createMemberExpression('[', expr, parseComputedMember())); } else if (match('.')) { expr = markerApply(marker, delegate.createMemberExpression('.', expr, parseNonComputedMember())); } else { expr = markerApply(marker, delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral())); } } return expr; } function parseLeftHandSideExpression() { var expr, marker = markerCreate(); expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); while (match('.') || match('[') || (lookahead.type === Token.Template && lookahead.head)) { if (match('[')) { expr = markerApply(marker, delegate.createMemberExpression('[', expr, parseComputedMember())); } else if (match('.')) { expr = markerApply(marker, delegate.createMemberExpression('.', expr, parseNonComputedMember())); } else { expr = markerApply(marker, delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral())); } } return expr; } // 11.3 Postfix Expressions function parsePostfixExpression() { var marker = markerCreate(), expr = parseLeftHandSideExpressionAllowCall(), token; if (lookahead.type !== Token.Punctuator) { return expr; } if ((match('++') || match('--')) && !peekLineTerminator()) { // 11.3.1, 11.3.2 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { throwErrorTolerant({}, Messages.StrictLHSPostfix); } if (!isLeftHandSide(expr)) { throwError({}, Messages.InvalidLHSInAssignment); } token = lex(); expr = markerApply(marker, delegate.createPostfixExpression(token.value, expr)); } return expr; } // 11.4 Unary Operators function parseUnaryExpression() { var marker, token, expr; if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) { return parsePostfixExpression(); } if (match('++') || match('--')) { marker = markerCreate(); token = lex(); expr = parseUnaryExpression(); // 11.4.4, 11.4.5 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { throwErrorTolerant({}, Messages.StrictLHSPrefix); } if (!isLeftHandSide(expr)) { throwError({}, Messages.InvalidLHSInAssignment); } return markerApply(marker, delegate.createUnaryExpression(token.value, expr)); } if (match('+') || match('-') || match('~') || match('!')) { marker = markerCreate(); token = lex(); expr = parseUnaryExpression(); return markerApply(marker, delegate.createUnaryExpression(token.value, expr)); } if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) { marker = markerCreate(); token = lex(); expr = parseUnaryExpression(); expr = markerApply(marker, delegate.createUnaryExpression(token.value, expr)); if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) { throwErrorTolerant({}, Messages.StrictDelete); } return expr; } return parsePostfixExpression(); } function binaryPrecedence(token, allowIn) { var prec = 0; if (token.type !== Token.Punctuator && token.type !== Token.Keyword) { return 0; } switch (token.value) { case '||': prec = 1; break; case '&&': prec = 2; break; case '|': prec = 3; break; case '^': prec = 4; break; case '&': prec = 5; break; case '==': case '!=': case '===': case '!==': prec = 6; break; case '<': case '>': case '<=': case '>=': case 'instanceof': prec = 7; break; case 'in': prec = allowIn ? 7 : 0; break; case '<<': case '>>': case '>>>': prec = 8; break; case '+': case '-': prec = 9; break; case '*': case '/': case '%': prec = 11; break; default: break; } return prec; } // 11.5 Multiplicative Operators // 11.6 Additive Operators // 11.7 Bitwise Shift Operators // 11.8 Relational Operators // 11.9 Equality Operators // 11.10 Binary Bitwise Operators // 11.11 Binary Logical Operators function parseBinaryExpression() { var expr, token, prec, previousAllowIn, stack, right, operator, left, i, marker, markers; previousAllowIn = state.allowIn; state.allowIn = true; marker = markerCreate(); left = parseUnaryExpression(); token = lookahead; prec = binaryPrecedence(token, previousAllowIn); if (prec === 0) { return left; } token.prec = prec; lex(); markers = [marker, markerCreate()]; right = parseUnaryExpression(); stack = [left, token, right]; while ((prec = binaryPrecedence(lookahead, previousAllowIn)) > 0) { // Reduce: make a binary expression from the three topmost entries. while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) { right = stack.pop(); operator = stack.pop().value; left = stack.pop(); expr = delegate.createBinaryExpression(operator, left, right); markers.pop(); marker = markers.pop(); markerApply(marker, expr); stack.push(expr); markers.push(marker); } // Shift. token = lex(); token.prec = prec; stack.push(token); markers.push(markerCreate()); expr = parseUnaryExpression(); stack.push(expr); } state.allowIn = previousAllowIn; // Final reduce to clean-up the stack. i = stack.length - 1; expr = stack[i]; markers.pop(); while (i > 1) { expr = delegate.createBinaryExpression(stack[i - 1].value, stack[i - 2], expr); i -= 2; marker = markers.pop(); markerApply(marker, expr); } return expr; } // 11.12 Conditional Operator function parseConditionalExpression() { var expr, previousAllowIn, consequent, alternate, marker = markerCreate(); expr = parseBinaryExpression(); if (match('?')) { lex(); previousAllowIn = state.allowIn; state.allowIn = true; consequent = parseAssignmentExpression(); state.allowIn = previousAllowIn; expect(':'); alternate = parseAssignmentExpression(); expr = markerApply(marker, delegate.createConditionalExpression(expr, consequent, alternate)); } return expr; } // 11.13 Assignment Operators // 12.14.5 AssignmentPattern function reinterpretAsAssignmentBindingPattern(expr) { var i, len, property, element; if (expr.type === Syntax.ObjectExpression) { expr.type = Syntax.ObjectPattern; for (i = 0, len = expr.properties.length; i < len; i += 1) { property = expr.properties[i]; if (property.type === Syntax.SpreadProperty) { if (i < len - 1) { throwError({}, Messages.PropertyAfterSpreadProperty); } reinterpretAsAssignmentBindingPattern(property.argument); } else { if (property.kind !== 'init') { throwError({}, Messages.InvalidLHSInAssignment); } reinterpretAsAssignmentBindingPattern(property.value); } } } else if (expr.type === Syntax.ArrayExpression) { expr.type = Syntax.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 === Syntax.Identifier) { if (isRestrictedWord(expr.name)) { throwError({}, Messages.InvalidLHSInAssignment); } } else if (expr.type === Syntax.SpreadElement) { reinterpretAsAssignmentBindingPattern(expr.argument); if (expr.argument.type === Syntax.ObjectPattern) { throwError({}, Messages.ObjectPatternAsSpread); } } else { /* istanbul ignore else */ if (expr.type !== Syntax.MemberExpression && expr.type !== Syntax.CallExpression && expr.type !== Syntax.NewExpression) { throwError({}, Messages.InvalidLHSInAssignment); } } } // 13.2.3 BindingPattern function reinterpretAsDestructuredParameter(options, expr) { var i, len, property, element; if (expr.type === Syntax.ObjectExpression) { expr.type = Syntax.ObjectPattern; for (i = 0, len = expr.properties.length; i < len; i += 1) { property = expr.properties[i]; if (property.type === Syntax.SpreadProperty) { if (i < len - 1) { throwError({}, Messages.PropertyAfterSpreadProperty); } reinterpretAsDestructuredParameter(options, property.argument); } else { if (property.kind !== 'init') { throwError({}, Messages.InvalidLHSInFormalsList); } reinterpretAsDestructuredParameter(options, property.value); } } } else if (expr.type === Syntax.ArrayExpression) { expr.type = Syntax.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 === Syntax.Identifier) { validateParam(options, expr, expr.name); } else if (expr.type === Syntax.SpreadElement) { // BindingRestElement only allows BindingIdentifier if (expr.argument.type !== Syntax.Identifier) { throwError({}, Messages.InvalidLHSInFormalsList); } validateParam(options, expr.argument, expr.argument.name); } else { throwError({}, Messages.InvalidLHSInFormalsList); } } 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 === Syntax.Identifier) { params.push(param); defaults.push(null); validateParam(options, param, param.name); } else if (param.type === Syntax.ObjectExpression || param.type === Syntax.ArrayExpression) { reinterpretAsDestructuredParameter(options, param); params.push(param); defaults.push(null); } else if (param.type === Syntax.SpreadElement) { assert(i === len - 1, 'It is guaranteed that SpreadElement is last element by parseExpression'); if (param.argument.type !== Syntax.Identifier) { throwError({}, Messages.InvalidLHSInFormalsList); } reinterpretAsDestructuredParameter(options, param.argument); rest = param.argument; } else if (param.type === Syntax.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 ); } 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, previousYieldAllowed, previousAwaitAllowed, body; expect('=>'); previousStrict = strict; previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = false; previousAwaitAllowed = state.awaitAllowed; state.awaitAllowed = !!options.async; body = parseConciseBody(); if (strict && options.firstRestricted) { throwError(options.firstRestricted, options.message); } if (strict && options.stricted) { throwErrorTolerant(options.stricted, options.message); } strict = previousStrict; state.yieldAllowed = previousYieldAllowed; state.awaitAllowed = previousAwaitAllowed; return markerApply(marker, delegate.createArrowFunctionExpression( options.params, options.defaults, body, options.rest, body.type !== Syntax.BlockStatement, !!options.async )); } function parseAssignmentExpression() { var marker, expr, token, params, oldParenthesizedCount, startsWithParen = false, backtrackToken = lookahead, possiblyAsync = false; if (matchYield()) { return parseYieldExpression(); } if (matchAwait()) { return parseAwaitExpression(); } oldParenthesizedCount = state.parenthesizedCount; marker = markerCreate(); if (matchAsyncFuncExprOrDecl()) { return parseFunctionExpression(); } if (matchAsync()) { // We can't be completely sure that this 'async' token is // actually a contextual keyword modifying a function // expression, so we might have to un-lex() it later by // calling rewind(backtrackToken). possiblyAsync = true; lex(); } if (match('(')) { token = lookahead2(); if ((token.type === Token.Punctuator && token.value === ')') || token.value === '...') { params = parseParams(); if (!match('=>')) { throwUnexpected(lex()); } params.async = possiblyAsync; return parseArrowFunctionExpression(params, marker); } startsWithParen = true; } token = lookahead; // If the 'async' keyword is not followed by a '(' character or an // identifier, then it can't be an arrow function modifier, and we // should interpret it as a normal identifer. if (possiblyAsync && !match('(') && token.type !== Token.Identifier) { possiblyAsync = false; rewind(backtrackToken); } expr = parseConditionalExpression(); if (match('=>') && (state.parenthesizedCount === oldParenthesizedCount || state.parenthesizedCount === (oldParenthesizedCount + 1))) { if (expr.type === Syntax.Identifier) { params = reinterpretAsCoverFormalsList([ expr ]); } else if (expr.type === Syntax.AssignmentExpression || expr.type === Syntax.ArrayExpression || expr.type === Syntax.ObjectExpression) { if (!startsWithParen) { throwUnexpected(lex()); } params = reinterpretAsCoverFormalsList([ expr ]); } else if (expr.type === Syntax.SequenceExpression) { params = reinterpretAsCoverFormalsList(expr.expressions); } if (params) { params.async = possiblyAsync; return parseArrowFunctionExpression(params, marker); } } // If we haven't returned by now, then the 'async' keyword was not // a function modifier, and we should rewind and interpret it as a // normal identifier. if (possiblyAsync) { possiblyAsync = false; rewind(backtrackToken); expr = parseConditionalExpression(); } if (matchAssign()) { // 11.13.1 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { throwErrorTolerant(token, Messages.StrictLHSAssignment); } // ES.next draf 11.13 Runtime Semantics step 1 if (match('=') && (expr.type === Syntax.ObjectExpression || expr.type === Syntax.ArrayExpression)) { reinterpretAsAssignmentBindingPattern(expr); } else if (!isLeftHandSide(expr)) { throwError({}, Messages.InvalidLHSInAssignment); } expr = markerApply(marker, delegate.createAssignmentExpression(lex().value, expr, parseAssignmentExpression())); } return expr; } // 11.14 Comma Operator function parseExpression() { var marker, expr, expressions, sequence, spreadFound, possibleArrow; marker = markerCreate(); expr = parseAssignmentExpression(); expressions = [ expr ]; if (match(',')) { while (index < length) { if (!match(',')) { break; } lex(); if (match(')')) { possibleArrow = lookahead2(); if ( possibleArrow.type === Token.Punctuator && possibleArrow.value === '=>' ) { break; } } expr = parseSpreadOrAssignmentExpression(); expressions.push(expr); if (expr.type === Syntax.SpreadElement) { spreadFound = true; if (!match(')')) { throwError({}, Messages.ElementAfterSpreadElement); } break; } } if (expressions.length > 1) { sequence = markerApply(marker, delegate.createSequenceExpression(expressions)); } } if (spreadFound && lookahead2().value !== '=>') { throwError({}, Messages.IllegalSpread); } return sequence || expr; } // 12.1 Block function parseStatementList() { var list = [], statement; while (index < length) { if (match('}')) { break; } statement = parseSourceElement(); if (typeof statement === 'undefined') { break; } list.push(statement); } return list; } function parseBlock() { var block, marker = markerCreate(); expect('{'); block = parseStatementList(); expect('}'); return markerApply(marker, delegate.createBlockStatement(block)); } // 12.2 Variable Statement function parseTypeParameterDeclaration() { var marker = markerCreate(), paramTypes = []; expect('<'); while (!match('>')) { paramTypes.push(parseTypeAnnotatableIdentifier()); if (!match('>')) { expect(','); } } expect('>'); return markerApply(marker, delegate.createTypeParameterDeclaration( paramTypes )); } function parseTypeParameterInstantiation() { var marker = markerCreate(), oldInType = state.inType, paramTypes = []; state.inType = true; expect('<'); while (!match('>')) { paramTypes.push(parseType()); if (!match('>')) { expect(','); } } expect('>'); state.inType = oldInType; return markerApply(marker, delegate.createTypeParameterInstantiation( paramTypes )); } function parseObjectTypeIndexer(marker, isStatic) { var id, key, value; expect('['); id = parseObjectPropertyKey(); expect(':'); key = parseType(); expect(']'); expect(':'); value = parseType(); return markerApply(marker, delegate.createObjectTypeIndexer( id, key, value, isStatic )); } function parseObjectTypeMethodish(marker) { var params = [], rest = null, returnType, typeParameters = null; if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } expect('('); while (lookahead.type === Token.Identifier) { params.push(parseFunctionTypeParam()); if (!match(')')) { expect(','); } } if (match('...')) { lex(); rest = parseFunctionTypeParam(); } expect(')'); expect(':'); returnType = parseType(); return markerApply(marker, delegate.createFunctionTypeAnnotation( params, returnType, rest, typeParameters )); } function parseObjectTypeMethod(marker, isStatic, key) { var optional = false, value; value = parseObjectTypeMethodish(marker); return markerApply(marker, delegate.createObjectTypeProperty( key, value, optional, isStatic )); } function parseObjectTypeCallProperty(marker, isStatic) { var valueMarker = markerCreate(); return markerApply(marker, delegate.createObjectTypeCallProperty( parseObjectTypeMethodish(valueMarker), isStatic )); } function parseObjectType(allowStatic) { var callProperties = [], indexers = [], marker, optional = false, properties = [], propertyKey, propertyTypeAnnotation, token, isStatic, matchStatic; expect('{'); while (!match('}')) { marker = markerCreate(); matchStatic = strict ? matchKeyword('static') : matchContextualKeyword('static'); if (allowStatic && matchStatic) { token = lex(); isStatic = true; } if (match('[')) { indexers.push(parseObjectTypeIndexer(marker, isStatic)); } else if (match('(') || match('<')) { callProperties.push(parseObjectTypeCallProperty(marker, allowStatic)); } else { if (isStatic && match(':')) { propertyKey = markerApply(marker, delegate.createIdentifier(token)); throwErrorTolerant(token, Messages.StrictReservedWord); } else { propertyKey = parseObjectPropertyKey(); } if (match('<') || match('(')) { // This is a method property properties.push(parseObjectTypeMethod(marker, isStatic, propertyKey)); } else { if (match('?')) { lex(); optional = true; } expect(':'); propertyTypeAnnotation = parseType(); properties.push(markerApply(marker, delegate.createObjectTypeProperty( propertyKey, propertyTypeAnnotation, optional, isStatic ))); } } if (match(';') || match(',')) { lex(); } else if (!match('}')) { throwUnexpected(lookahead); } } expect('}'); return delegate.createObjectTypeAnnotation( properties, indexers, callProperties ); } function parseGenericType() { var marker = markerCreate(), typeParameters = null, typeIdentifier; typeIdentifier = parseVariableIdentifier(); while (match('.')) { expect('.'); typeIdentifier = markerApply(marker, delegate.createQualifiedTypeIdentifier( typeIdentifier, parseVariableIdentifier() )); } if (match('<')) { typeParameters = parseTypeParameterInstantiation(); } return markerApply(marker, delegate.createGenericTypeAnnotation( typeIdentifier, typeParameters )); } function parseVoidType() { var marker = markerCreate(); expectKeyword('void'); return markerApply(marker, delegate.createVoidTypeAnnotation()); } function parseTypeofType() { var argument, marker = markerCreate(); expectKeyword('typeof'); argument = parsePrimaryType(); return markerApply(marker, delegate.createTypeofTypeAnnotation( argument )); } function parseTupleType() { var marker = markerCreate(), types = []; expect('['); // We allow trailing commas while (index < length && !match(']')) { types.push(parseType()); if (match(']')) { break; } expect(','); } expect(']'); return markerApply(marker, delegate.createTupleTypeAnnotation( types )); } function parseFunctionTypeParam() { var marker = markerCreate(), name, optional = false, typeAnnotation; name = parseVariableIdentifier(); if (match('?')) { lex(); optional = true; } expect(':'); typeAnnotation = parseType(); return markerApply(marker, delegate.createFunctionTypeParam( name, typeAnnotation, optional )); } function parseFunctionTypeParams() { var ret = { params: [], rest: null }; while (lookahead.type === Token.Identifier) { ret.params.push(parseFunctionTypeParam()); if (!match(')')) { expect(','); } } if (match('...')) { lex(); ret.rest = parseFunctionTypeParam(); } return ret; } // The parsing of types roughly parallels the parsing of expressions, and // primary types are kind of like primary expressions...they're the // primitives with which other types are constructed. function parsePrimaryType() { var params = null, returnType = null, marker = markerCreate(), rest = null, tmp, typeParameters, token, type, isGroupedType = false; switch (lookahead.type) { case Token.Identifier: switch (lookahead.value) { case 'any': lex(); return markerApply(marker, delegate.createAnyTypeAnnotation()); case 'bool': // fallthrough case 'boolean': lex(); return markerApply(marker, delegate.createBooleanTypeAnnotation()); case 'number': lex(); return markerApply(marker, delegate.createNumberTypeAnnotation()); case 'string': lex(); return markerApply(marker, delegate.createStringTypeAnnotation()); } return markerApply(marker, parseGenericType()); case Token.Punctuator: switch (lookahead.value) { case '{': return markerApply(marker, parseObjectType()); case '[': return parseTupleType(); case '<': typeParameters = parseTypeParameterDeclaration(); expect('('); tmp = parseFunctionTypeParams(); params = tmp.params; rest = tmp.rest; expect(')'); expect('=>'); returnType = parseType(); return markerApply(marker, delegate.createFunctionTypeAnnotation( params, returnType, rest, typeParameters )); case '(': lex(); // Check to see if this is actually a grouped type if (!match(')') && !match('...')) { if (lookahead.type === Token.Identifier) { token = lookahead2(); isGroupedType = token.value !== '?' && token.value !== ':'; } else { isGroupedType = true; } } if (isGroupedType) { type = parseType(); expect(')'); // If we see a => next then someone was probably confused about // function types, so we can provide a better error message if (match('=>')) { throwError({}, Messages.ConfusedAboutFunctionType); } return type; } tmp = parseFunctionTypeParams(); params = tmp.params; rest = tmp.rest; expect(')'); expect('=>'); returnType = parseType(); return markerApply(marker, delegate.createFunctionTypeAnnotation( params, returnType, rest, null /* typeParameters */ )); } break; case Token.Keyword: switch (lookahead.value) { case 'void': return markerApply(marker, parseVoidType()); case 'typeof': return markerApply(marker, parseTypeofType()); } break; case Token.StringLiteral: token = lex(); if (token.octal) { throwError(token, Messages.StrictOctalLiteral); } return markerApply(marker, delegate.createStringLiteralTypeAnnotation( token )); } throwUnexpected(lookahead); } function parsePostfixType() { var marker = markerCreate(), t = parsePrimaryType(); if (match('[')) { expect('['); expect(']'); return markerApply(marker, delegate.createArrayTypeAnnotation(t)); } return t; } function parsePrefixType() { var marker = markerCreate(); if (match('?')) { lex(); return markerApply(marker, delegate.createNullableTypeAnnotation( parsePrefixType() )); } return parsePostfixType(); } function parseIntersectionType() { var marker = markerCreate(), type, types; type = parsePrefixType(); types = [type]; while (match('&')) { lex(); types.push(parsePrefixType()); } return types.length === 1 ? type : markerApply(marker, delegate.createIntersectionTypeAnnotation( types )); } function parseUnionType() { var marker = markerCreate(), type, types; type = parseIntersectionType(); types = [type]; while (match('|')) { lex(); types.push(parseIntersectionType()); } return types.length === 1 ? type : markerApply(marker, delegate.createUnionTypeAnnotation( types )); } function parseType() { var oldInType = state.inType, type; state.inType = true; type = parseUnionType(); state.inType = oldInType; return type; } function parseTypeAnnotation() { var marker = markerCreate(), type; expect(':'); type = parseType(); return markerApply(marker, delegate.createTypeAnnotation(type)); } function parseVariableIdentifier() { var marker = markerCreate(), token = lex(); if (token.type !== Token.Identifier) { throwUnexpected(token); } return markerApply(marker, delegate.createIdentifier(token.value)); } function parseTypeAnnotatableIdentifier(requireTypeAnnotation, canBeOptionalParam) { var marker = markerCreate(), ident = parseVariableIdentifier(), isOptionalParam = false; if (canBeOptionalParam && match('?')) { expect('?'); isOptionalParam = true; } if (requireTypeAnnotation || match(':')) { ident.typeAnnotation = parseTypeAnnotation(); ident = markerApply(marker, ident); } if (isOptionalParam) { ident.optional = true; ident = markerApply(marker, ident); } return ident; } function parseVariableDeclaration(kind) { var id, marker = markerCreate(), init = null, typeAnnotationMarker = markerCreate(); if (match('{')) { id = parseObjectInitialiser(); reinterpretAsAssignmentBindingPattern(id); if (match(':')) { id.typeAnnotation = parseTypeAnnotation(); markerApply(typeAnnotationMarker, id); } } else if (match('[')) { id = parseArrayInitialiser(); reinterpretAsAssignmentBindingPattern(id); if (match(':')) { id.typeAnnotation = parseTypeAnnotation(); markerApply(typeAnnotationMarker, id); } } else { /* istanbul ignore next */ id = state.allowKeyword ? parseNonComputedProperty() : parseTypeAnnotatableIdentifier(); // 12.2.1 if (strict && isRestrictedWord(id.name)) { throwErrorTolerant({}, Messages.StrictVarName); } } if (kind === 'const') { if (!match('=')) { throwError({}, Messages.NoUninitializedConst); } expect('='); init = parseAssignmentExpression(); } else if (match('=')) { lex(); init = parseAssignmentExpression(); } return markerApply(marker, delegate.createVariableDeclarator(id, init)); } function parseVariableDeclarationList(kind) { var list = []; do { list.push(parseVariableDeclaration(kind)); if (!match(',')) { break; } lex(); } while (index < length); return list; } function parseVariableStatement() { var declarations, marker = markerCreate(); expectKeyword('var'); declarations = parseVariableDeclarationList(); consumeSemicolon(); return markerApply(marker, delegate.createVariableDeclaration(declarations, 'var')); } // kind may be `const` or `let` // Both are experimental and not in the specification yet. // see http://wiki.ecmascript.org/doku.php?id=harmony:const // and http://wiki.ecmascript.org/doku.php?id=harmony:let function parseConstLetDeclaration(kind) { var declarations, marker = markerCreate(); expectKeyword(kind); declarations = parseVariableDeclarationList(kind); consumeSemicolon(); return markerApply(marker, delegate.createVariableDeclaration(declarations, kind)); } // people.mozilla.org/~jorendorff/es6-draft.html function parseModuleSpecifier() { var marker = markerCreate(), specifier; if (lookahead.type !== Token.StringLiteral) { throwError({}, Messages.InvalidModuleSpecifier); } specifier = delegate.createLiteral(lex()); return markerApply(marker, specifier); } function parseExportBatchSpecifier() { var marker = markerCreate(); expect('*'); return markerApply(marker, delegate.createExportBatchSpecifier()); } function parseExportSpecifier() { var id, name = null, marker = markerCreate(); if (matchKeyword('default')) { lex(); id = markerApply(marker, delegate.createIdentifier('default')); // export {default} from "something"; } else { id = parseVariableIdentifier(); } if (matchContextualKeyword('as')) { lex(); name = parseNonComputedProperty(); } return markerApply(marker, delegate.createExportSpecifier(id, name)); } function parseExportDeclaration() { var declaration = null, possibleIdentifierToken, sourceElement, isExportFromIdentifier, src = null, specifiers = [], marker = markerCreate(); expectKeyword('export'); if (matchKeyword('default')) { // covers: // export default ... lex(); if (matchKeyword('function') || matchKeyword('class')) { possibleIdentifierToken = lookahead2(); if (isIdentifierName(possibleIdentifierToken)) { // covers: // export default function foo () {} // export default class foo {} sourceElement = parseSourceElement(); return markerApply(marker, delegate.createExportDeclaration(true, sourceElement, [sourceElement.id], null)); } // covers: // export default function () {} // export default class {} switch (lookahead.value) { case 'class': return markerApply(marker, delegate.createExportDeclaration(true, parseClassExpression(), [], null)); case 'function': return markerApply(marker, delegate.createExportDeclaration(true, parseFunctionExpression(), [], null)); } } if (matchContextualKeyword('from')) { throwError({}, Messages.UnexpectedToken, lookahead.value); } // covers: // export default {}; // export default []; if (match('{')) { declaration = parseObjectInitialiser(); } else if (match('[')) { declaration = parseArrayInitialiser(); } else { declaration = parseAssignmentExpression(); } consumeSemicolon(); return markerApply(marker, delegate.createExportDeclaration(true, declaration, [], null)); } // non-default export if (lookahead.type === Token.Keyword || matchContextualKeyword('type')) { // covers: // export var f = 1; switch (lookahead.value) { case 'type': case 'let': case 'const': case 'var': case 'class': case 'function': return markerApply(marker, delegate.createExportDeclaration(false, parseSourceElement(), specifiers, null)); } } if (match('*')) { // covers: // export * from "foo"; specifiers.push(parseExportBatchSpecifier()); if (!matchContextualKeyword('from')) { throwError({}, lookahead.value ? Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value); } lex(); src = parseModuleSpecifier(); consumeSemicolon(); return markerApply(marker, delegate.createExportDeclaration(false, null, specifiers, src)); } expect('{'); if (!match('}')) { do { isExportFromIdentifier = isExportFromIdentifier || matchKeyword('default'); specifiers.push(parseExportSpecifier()); } while (match(',') && lex()); } expect('}'); if (matchContextualKeyword('from')) { // covering: // export {default} from "foo"; // export {foo} from "foo"; lex(); src = parseModuleSpecifier(); consumeSemicolon(); } else if (isExportFromIdentifier) { // covering: // export {default}; // missing fromClause throwError({}, lookahead.value ? Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value); } else { // cover // export {foo}; consumeSemicolon(); } return markerApply(marker, delegate.createExportDeclaration(false, declaration, specifiers, src)); } function parseImportSpecifier() { // import {} ...; var id, name = null, marker = markerCreate(); id = parseNonComputedProperty(); if (matchContextualKeyword('as')) { lex(); name = parseVariableIdentifier(); } return markerApply(marker, delegate.createImportSpecifier(id, name)); } function parseNamedImports() { var specifiers = []; // {foo, bar as bas} expect('{'); if (!match('}')) { do { specifiers.push(parseImportSpecifier()); } while (match(',') && lex()); } expect('}'); return specifiers; } function parseImportDefaultSpecifier() { // import ...; var id, marker = markerCreate(); id = parseNonComputedProperty(); return markerApply(marker, delegate.createImportDefaultSpecifier(id)); } function parseImportNamespaceSpecifier() { // import <* as foo> ...; var id, marker = markerCreate(); expect('*'); if (!matchContextualKeyword('as')) { throwError({}, Messages.NoAsAfterImportNamespace); } lex(); id = parseNonComputedProperty(); return markerApply(marker, delegate.createImportNamespaceSpecifier(id)); } function parseImportDeclaration() { var specifiers, src, marker = markerCreate(), isType = false, token2; expectKeyword('import'); if (matchContextualKeyword('type')) { token2 = lookahead2(); if ((token2.type === Token.Identifier && token2.value !== 'from') || (token2.type === Token.Punctuator && (token2.value === '{' || token2.value === '*'))) { isType = true; lex(); } } specifiers = []; if (lookahead.type === Token.StringLiteral) { // covers: // import "foo"; src = parseModuleSpecifier(); consumeSemicolon(); return markerApply(marker, delegate.createImportDeclaration(specifiers, src, isType)); } if (!matchKeyword('default') && isIdentifierName(lookahead)) { // covers: // import foo // import foo, ... specifiers.push(parseImportDefaultSpecifier()); if (match(',')) { lex(); } } if (match('*')) { // covers: // import foo, * as foo // import * as foo specifiers.push(parseImportNamespaceSpecifier()); } else if (match('{')) { // covers: // import foo, {bar} // import {bar} specifiers = specifiers.concat(parseNamedImports()); } if (!matchContextualKeyword('from')) { throwError({}, lookahead.value ? Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value); } lex(); src = parseModuleSpecifier(); consumeSemicolon(); return markerApply(marker, delegate.createImportDeclaration(specifiers, src, isType)); } // 12.3 Empty Statement function parseEmptyStatement() { var marker = markerCreate(); expect(';'); return markerApply(marker, delegate.createEmptyStatement()); } // 12.4 Expression Statement function parseExpressionStatement() { var marker = markerCreate(), expr = parseExpression(); consumeSemicolon(); return markerApply(marker, delegate.createExpressionStatement(expr)); } // 12.5 If statement function parseIfStatement() { var test, consequent, alternate, marker = markerCreate(); expectKeyword('if'); expect('('); test = parseExpression(); expect(')'); consequent = parseStatement(); if (matchKeyword('else')) { lex(); alternate = parseStatement(); } else { alternate = null; } return markerApply(marker, delegate.createIfStatement(test, consequent, alternate)); } // 12.6 Iteration Statements function parseDoWhileStatement() { var body, test, oldInIteration, marker = markerCreate(); expectKeyword('do'); oldInIteration = state.inIteration; state.inIteration = true; body = parseStatement(); state.inIteration = oldInIteration; expectKeyword('while'); expect('('); test = parseExpression(); expect(')'); if (match(';')) { lex(); } return markerApply(marker, delegate.createDoWhileStatement(body, test)); } function parseWhileStatement() { var test, body, oldInIteration, marker = markerCreate(); expectKeyword('while'); expect('('); test = parseExpression(); expect(')'); oldInIteration = state.inIteration; state.inIteration = true; body = parseStatement(); state.inIteration = oldInIteration; return markerApply(marker, delegate.createWhileStatement(test, body)); } function parseForVariableDeclaration() { var marker = markerCreate(), token = lex(), declarations = parseVariableDeclarationList(); return markerApply(marker, delegate.createVariableDeclaration(declarations, token.value)); } function parseForStatement(opts) { var init, test, update, left, right, body, operator, oldInIteration, marker = markerCreate(); init = test = update = null; expectKeyword('for'); // http://wiki.ecmascript.org/doku.php?id=proposals:iterators_and_generators&s=each if (matchContextualKeyword('each')) { throwError({}, Messages.EachNotAllowed); } expect('('); if (match(';')) { lex(); } else { if (matchKeyword('var') || matchKeyword('let') || matchKeyword('const')) { state.allowIn = false; init = parseForVariableDeclaration(); state.allowIn = true; if (init.declarations.length === 1) { if (matchKeyword('in') || matchContextualKeyword('of')) { operator = lookahead; if (!((operator.value === 'in' || init.kind !== 'var') && init.declarations[0].init)) { lex(); left = init; right = parseExpression(); init = null; } } } } else { state.allowIn = false; init = parseExpression(); state.allowIn = true; if (matchContextualKeyword('of')) { operator = lex(); left = init; right = parseExpression(); init = null; } else if (matchKeyword('in')) { // LeftHandSideExpression if (!isAssignableLeftHandSide(init)) { throwError({}, Messages.InvalidLHSInForIn); } operator = lex(); left = init; right = parseExpression(); init = null; } } if (typeof left === 'undefined') { expect(';'); } } if (typeof left === 'undefined') { if (!match(';')) { test = parseExpression(); } expect(';'); if (!match(')')) { update = parseExpression(); } } expect(')'); oldInIteration = state.inIteration; state.inIteration = true; if (!(opts !== undefined && opts.ignoreBody)) { body = parseStatement(); } state.inIteration = oldInIteration; if (typeof left === 'undefined') { return markerApply(marker, delegate.createForStatement(init, test, update, body)); } if (operator.value === 'in') { return markerApply(marker, delegate.createForInStatement(left, right, body)); } return markerApply(marker, delegate.createForOfStatement(left, right, body)); } // 12.7 The continue statement function parseContinueStatement() { var label = null, marker = markerCreate(); expectKeyword('continue'); // Optimize the most common form: 'continue;'. if (source.charCodeAt(index) === 59) { lex(); if (!state.inIteration) { throwError({}, Messages.IllegalContinue); } return markerApply(marker, delegate.createContinueStatement(null)); } if (peekLineTerminator()) { if (!state.inIteration) { throwError({}, Messages.IllegalContinue); } return markerApply(marker, delegate.createContinueStatement(null)); } if (lookahead.type === Token.Identifier) { label = parseVariableIdentifier(); if (!state.labelSet.has(label.name)) { throwError({}, Messages.UnknownLabel, label.name); } } consumeSemicolon(); if (label === null && !state.inIteration) { throwError({}, Messages.IllegalContinue); } return markerApply(marker, delegate.createContinueStatement(label)); } // 12.8 The break statement function parseBreakStatement() { var label = null, marker = markerCreate(); expectKeyword('break'); // Catch the very common case first: immediately a semicolon (char #59). if (source.charCodeAt(index) === 59) { lex(); if (!(state.inIteration || state.inSwitch)) { throwError({}, Messages.IllegalBreak); } return markerApply(marker, delegate.createBreakStatement(null)); } if (peekLineTerminator()) { if (!(state.inIteration || state.inSwitch)) { throwError({}, Messages.IllegalBreak); } return markerApply(marker, delegate.createBreakStatement(null)); } if (lookahead.type === Token.Identifier) { label = parseVariableIdentifier(); if (!state.labelSet.has(label.name)) { throwError({}, Messages.UnknownLabel, label.name); } } consumeSemicolon(); if (label === null && !(state.inIteration || state.inSwitch)) { throwError({}, Messages.IllegalBreak); } return markerApply(marker, delegate.createBreakStatement(label)); } // 12.9 The return statement function parseReturnStatement() { var argument = null, marker = markerCreate(); expectKeyword('return'); if (!state.inFunctionBody) { throwErrorTolerant({}, Messages.IllegalReturn); } // 'return' followed by a space and an identifier is very common. if (source.charCodeAt(index) === 32) { if (isIdentifierStart(source.charCodeAt(index + 1))) { argument = parseExpression(); consumeSemicolon(); return markerApply(marker, delegate.createReturnStatement(argument)); } } if (peekLineTerminator()) { return markerApply(marker, delegate.createReturnStatement(null)); } if (!match(';')) { if (!match('}') && lookahead.type !== Token.EOF) { argument = parseExpression(); } } consumeSemicolon(); return markerApply(marker, delegate.createReturnStatement(argument)); } // 12.10 The with statement function parseWithStatement() { var object, body, marker = markerCreate(); if (strict) { throwErrorTolerant({}, Messages.StrictModeWith); } expectKeyword('with'); expect('('); object = parseExpression(); expect(')'); body = parseStatement(); return markerApply(marker, delegate.createWithStatement(object, body)); } // 12.10 The swith statement function parseSwitchCase() { var test, consequent = [], sourceElement, marker = markerCreate(); if (matchKeyword('default')) { lex(); test = null; } else { expectKeyword('case'); test = parseExpression(); } expect(':'); while (index < length) { if (match('}') || matchKeyword('default') || matchKeyword('case')) { break; } sourceElement = parseSourceElement(); if (typeof sourceElement === 'undefined') { break; } consequent.push(sourceElement); } return markerApply(marker, delegate.createSwitchCase(test, consequent)); } function parseSwitchStatement() { var discriminant, cases, clause, oldInSwitch, defaultFound, marker = markerCreate(); expectKeyword('switch'); expect('('); discriminant = parseExpression(); expect(')'); expect('{'); cases = []; if (match('}')) { lex(); return markerApply(marker, delegate.createSwitchStatement(discriminant, cases)); } oldInSwitch = state.inSwitch; state.inSwitch = true; defaultFound = false; while (index < length) { if (match('}')) { break; } clause = parseSwitchCase(); if (clause.test === null) { if (defaultFound) { throwError({}, Messages.MultipleDefaultsInSwitch); } defaultFound = true; } cases.push(clause); } state.inSwitch = oldInSwitch; expect('}'); return markerApply(marker, delegate.createSwitchStatement(discriminant, cases)); } // 12.13 The throw statement function parseThrowStatement() { var argument, marker = markerCreate(); expectKeyword('throw'); if (peekLineTerminator()) { throwError({}, Messages.NewlineAfterThrow); } argument = parseExpression(); consumeSemicolon(); return markerApply(marker, delegate.createThrowStatement(argument)); } // 12.14 The try statement function parseCatchClause() { var param, body, marker = markerCreate(); expectKeyword('catch'); expect('('); if (match(')')) { throwUnexpected(lookahead); } param = parseExpression(); // 12.14.1 if (strict && param.type === Syntax.Identifier && isRestrictedWord(param.name)) { throwErrorTolerant({}, Messages.StrictCatchVariable); } expect(')'); body = parseBlock(); return markerApply(marker, delegate.createCatchClause(param, body)); } function parseTryStatement() { var block, handlers = [], finalizer = null, marker = markerCreate(); expectKeyword('try'); block = parseBlock(); if (matchKeyword('catch')) { handlers.push(parseCatchClause()); } if (matchKeyword('finally')) { lex(); finalizer = parseBlock(); } if (handlers.length === 0 && !finalizer) { throwError({}, Messages.NoCatchOrFinally); } return markerApply(marker, delegate.createTryStatement(block, [], handlers, finalizer)); } // 12.15 The debugger statement function parseDebuggerStatement() { var marker = markerCreate(); expectKeyword('debugger'); consumeSemicolon(); return markerApply(marker, delegate.createDebuggerStatement()); } // 12 Statements function parseStatement() { var type = lookahead.type, marker, expr, labeledBody; if (type === Token.EOF) { throwUnexpected(lookahead); } if (type === Token.Punctuator) { switch (lookahead.value) { case ';': return parseEmptyStatement(); case '{': return parseBlock(); case '(': return parseExpressionStatement(); default: break; } } if (type === Token.Keyword) { switch (lookahead.value) { case 'break': return parseBreakStatement(); case 'continue': return parseContinueStatement(); case 'debugger': return parseDebuggerStatement(); case 'do': return parseDoWhileStatement(); case 'for': return parseForStatement(); case 'function': return parseFunctionDeclaration(); case 'class': return parseClassDeclaration(); case 'if': return parseIfStatement(); case 'return': return parseReturnStatement(); case 'switch': return parseSwitchStatement(); case 'throw': return parseThrowStatement(); case 'try': return parseTryStatement(); case 'var': return parseVariableStatement(); case 'while': return parseWhileStatement(); case 'with': return parseWithStatement(); default: break; } } if (matchAsyncFuncExprOrDecl()) { return parseFunctionDeclaration(); } marker = markerCreate(); expr = parseExpression(); // 12.12 Labelled Statements if ((expr.type === Syntax.Identifier) && match(':')) { lex(); if (state.labelSet.has(expr.name)) { throwError({}, Messages.Redeclaration, 'Label', expr.name); } state.labelSet.set(expr.name, true); labeledBody = parseStatement(); state.labelSet.delete(expr.name); return markerApply(marker, delegate.createLabeledStatement(expr, labeledBody)); } consumeSemicolon(); return markerApply(marker, delegate.createExpressionStatement(expr)); } // 13 Function Definition function parseConciseBody() { if (match('{')) { return parseFunctionSourceElements(); } return parseAssignmentExpression(); } function parseFunctionSourceElements() { var sourceElement, sourceElements = [], token, directive, firstRestricted, oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, oldParenthesizedCount, marker = markerCreate(); expect('{'); while (index < length) { if (lookahead.type !== Token.StringLiteral) { break; } token = lookahead; sourceElement = parseSourceElement(); sourceElements.push(sourceElement); if (sourceElement.expression.type !== Syntax.Literal) { // this is not directive break; } directive = source.slice(token.range[0] + 1, token.range[1] - 1); if (directive === 'use strict') { strict = true; if (firstRestricted) { throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral); } } else { if (!firstRestricted && token.octal) { firstRestricted = token; } } } oldLabelSet = state.labelSet; oldInIteration = state.inIteration; oldInSwitch = state.inSwitch; oldInFunctionBody = state.inFunctionBody; oldParenthesizedCount = state.parenthesizedCount; state.labelSet = new StringMap(); state.inIteration = false; state.inSwitch = false; state.inFunctionBody = true; state.parenthesizedCount = 0; while (index < length) { if (match('}')) { break; } sourceElement = parseSourceElement(); if (typeof sourceElement === 'undefined') { break; } sourceElements.push(sourceElement); } expect('}'); state.labelSet = oldLabelSet; state.inIteration = oldInIteration; state.inSwitch = oldInSwitch; state.inFunctionBody = oldInFunctionBody; state.parenthesizedCount = oldParenthesizedCount; return markerApply(marker, delegate.createBlockStatement(sourceElements)); } function validateParam(options, param, name) { if (strict) { if (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 (isRestrictedWord(name)) { options.firstRestricted = param; options.message = Messages.StrictParamName; } else if (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 marker, token, rest, param, def; token = lookahead; if (token.value === '...') { token = lex(); rest = true; } if (match('[')) { marker = markerCreate(); param = parseArrayInitialiser(); reinterpretAsDestructuredParameter(options, param); if (match(':')) { param.typeAnnotation = parseTypeAnnotation(); markerApply(marker, param); } } else if (match('{')) { marker = markerCreate(); if (rest) { throwError({}, Messages.ObjectPatternAsRestParameter); } param = parseObjectInitialiser(); reinterpretAsDestructuredParameter(options, param); if (match(':')) { param.typeAnnotation = parseTypeAnnotation(); markerApply(marker, param); } } else { param = rest ? parseTypeAnnotatableIdentifier( false, /* requireTypeAnnotation */ false /* canBeOptionalParam */ ) : parseTypeAnnotatableIdentifier( false, /* requireTypeAnnotation */ true /* canBeOptionalParam */ ); validateParam(options, token, token.value); } if (match('=')) { if (rest) { throwErrorTolerant(lookahead, Messages.DefaultRestParameter); } 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); return !match(')'); } function parseParams(firstRestricted) { var options, marker = markerCreate(); options = { params: [], defaultCount: 0, defaults: [], rest: null, firstRestricted: firstRestricted }; expect('('); if (!match(')')) { options.paramSet = new StringMap(); while (index < length) { if (!parseParam(options)) { break; } expect(','); if (!options.rest && match(')')) { break; } } } expect(')'); if (options.defaultCount === 0) { options.defaults = []; } if (match(':')) { options.returnType = parseTypeAnnotation(); } return markerApply(marker, options); } function parseFunctionDeclaration() { var id, body, token, tmp, firstRestricted, message, generator, isAsync, previousStrict, previousYieldAllowed, previousAwaitAllowed, marker = markerCreate(), typeParameters; isAsync = false; if (matchAsync()) { lex(); isAsync = true; } expectKeyword('function'); generator = false; if (match('*')) { lex(); generator = true; } token = lookahead; id = parseVariableIdentifier(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } if (strict) { if (isRestrictedWord(token.value)) { throwErrorTolerant(token, Messages.StrictFunctionName); } } else { if (isRestrictedWord(token.value)) { firstRestricted = token; message = Messages.StrictFunctionName; } else if (isStrictModeReservedWord(token.value)) { firstRestricted = token; message = Messages.StrictReservedWord; } } tmp = parseParams(firstRestricted); firstRestricted = tmp.firstRestricted; if (tmp.message) { message = tmp.message; } previousStrict = strict; previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = generator; previousAwaitAllowed = state.awaitAllowed; state.awaitAllowed = isAsync; body = parseFunctionSourceElements(); if (strict && firstRestricted) { throwError(firstRestricted, message); } if (strict && tmp.stricted) { throwErrorTolerant(tmp.stricted, message); } strict = previousStrict; state.yieldAllowed = previousYieldAllowed; state.awaitAllowed = previousAwaitAllowed; return markerApply( marker, delegate.createFunctionDeclaration( id, tmp.params, tmp.defaults, body, tmp.rest, generator, false, isAsync, tmp.returnType, typeParameters ) ); } function parseFunctionExpression() { var token, id = null, firstRestricted, message, tmp, body, generator, isAsync, previousStrict, previousYieldAllowed, previousAwaitAllowed, marker = markerCreate(), typeParameters; isAsync = false; if (matchAsync()) { lex(); isAsync = true; } expectKeyword('function'); generator = false; if (match('*')) { lex(); generator = true; } if (!match('(')) { if (!match('<')) { token = lookahead; id = parseVariableIdentifier(); if (strict) { if (isRestrictedWord(token.value)) { throwErrorTolerant(token, Messages.StrictFunctionName); } } else { if (isRestrictedWord(token.value)) { firstRestricted = token; message = Messages.StrictFunctionName; } else if (isStrictModeReservedWord(token.value)) { firstRestricted = token; message = Messages.StrictReservedWord; } } } if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } } tmp = parseParams(firstRestricted); firstRestricted = tmp.firstRestricted; if (tmp.message) { message = tmp.message; } previousStrict = strict; previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = generator; previousAwaitAllowed = state.awaitAllowed; state.awaitAllowed = isAsync; body = parseFunctionSourceElements(); if (strict && firstRestricted) { throwError(firstRestricted, message); } if (strict && tmp.stricted) { throwErrorTolerant(tmp.stricted, message); } strict = previousStrict; state.yieldAllowed = previousYieldAllowed; state.awaitAllowed = previousAwaitAllowed; return markerApply( marker, delegate.createFunctionExpression( id, tmp.params, tmp.defaults, body, tmp.rest, generator, false, isAsync, tmp.returnType, typeParameters ) ); } function parseYieldExpression() { var delegateFlag, expr, marker = markerCreate(); expectKeyword('yield', !strict); delegateFlag = false; if (match('*')) { lex(); delegateFlag = true; } expr = parseAssignmentExpression(); return markerApply(marker, delegate.createYieldExpression(expr, delegateFlag)); } function parseAwaitExpression() { var expr, marker = markerCreate(); expectContextualKeyword('await'); expr = parseAssignmentExpression(); return markerApply(marker, delegate.createAwaitExpression(expr)); } // 14 Functions and classes // 14.1 Functions is defined above (13 in ES5) // 14.2 Arrow Functions Definitions is defined in (7.3 assignments) // 14.3 Method Definitions // 14.3.7 function specialMethod(methodDefinition) { return methodDefinition.kind === 'get' || methodDefinition.kind === 'set' || methodDefinition.value.generator; } function parseMethodDefinition(key, isStatic, generator, computed) { var token, param, propType, isAsync, typeParameters, tokenValue, returnType; propType = isStatic ? ClassPropertyType.static : ClassPropertyType.prototype; if (generator) { return delegate.createMethodDefinition( propType, '', key, parsePropertyMethodFunction({ generator: true }), computed ); } tokenValue = key.type === 'Identifier' && key.name; if (tokenValue === 'get' && !match('(')) { key = parseObjectPropertyKey(); expect('('); expect(')'); if (match(':')) { returnType = parseTypeAnnotation(); } return delegate.createMethodDefinition( propType, 'get', key, parsePropertyFunction({ generator: false, returnType: returnType }), computed ); } if (tokenValue === 'set' && !match('(')) { key = parseObjectPropertyKey(); expect('('); token = lookahead; param = [ parseTypeAnnotatableIdentifier() ]; expect(')'); if (match(':')) { returnType = parseTypeAnnotation(); } return delegate.createMethodDefinition( propType, 'set', key, parsePropertyFunction({ params: param, generator: false, name: token, returnType: returnType }), computed ); } if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } isAsync = tokenValue === 'async' && !match('('); if (isAsync) { key = parseObjectPropertyKey(); } return delegate.createMethodDefinition( propType, '', key, parsePropertyMethodFunction({ generator: false, async: isAsync, typeParameters: typeParameters }), computed ); } function parseClassProperty(key, computed, isStatic) { var typeAnnotation; typeAnnotation = parseTypeAnnotation(); expect(';'); return delegate.createClassProperty( key, typeAnnotation, computed, isStatic ); } function parseClassElement() { var computed = false, generator = false, key, marker = markerCreate(), isStatic = false, possiblyOpenBracketToken; if (match(';')) { lex(); return undefined; } if (lookahead.value === 'static') { lex(); isStatic = true; } if (match('*')) { lex(); generator = true; } possiblyOpenBracketToken = lookahead; if (matchContextualKeyword('get') || matchContextualKeyword('set')) { possiblyOpenBracketToken = lookahead2(); } if (possiblyOpenBracketToken.type === Token.Punctuator && possiblyOpenBracketToken.value === '[') { computed = true; } key = parseObjectPropertyKey(); if (!generator && lookahead.value === ':') { return markerApply(marker, parseClassProperty(key, computed, isStatic)); } return markerApply(marker, parseMethodDefinition( key, isStatic, generator, computed )); } function parseClassBody() { var classElement, classElements = [], existingProps = {}, marker = markerCreate(), propName, propType; existingProps[ClassPropertyType.static] = new StringMap(); existingProps[ClassPropertyType.prototype] = new StringMap(); expect('{'); while (index < length) { if (match('}')) { break; } classElement = parseClassElement(existingProps); if (typeof classElement !== 'undefined') { classElements.push(classElement); propName = !classElement.computed && getFieldName(classElement.key); if (propName !== false) { propType = classElement.static ? ClassPropertyType.static : ClassPropertyType.prototype; if (classElement.type === Syntax.MethodDefinition) { if (propName === 'constructor' && !classElement.static) { if (specialMethod(classElement)) { throwError(classElement, Messages.IllegalClassConstructorProperty); } if (existingProps[ClassPropertyType.prototype].has('constructor')) { throwError(classElement.key, Messages.IllegalDuplicateClassProperty); } } existingProps[propType].set(propName, true); } } } } expect('}'); return markerApply(marker, delegate.createClassBody(classElements)); } function parseClassImplements() { var id, implemented = [], marker, typeParameters; if (strict) { expectKeyword('implements'); } else { expectContextualKeyword('implements'); } while (index < length) { marker = markerCreate(); id = parseVariableIdentifier(); if (match('<')) { typeParameters = parseTypeParameterInstantiation(); } else { typeParameters = null; } implemented.push(markerApply(marker, delegate.createClassImplements( id, typeParameters ))); if (!match(',')) { break; } expect(','); } return implemented; } function parseClassExpression() { var id, implemented, previousYieldAllowed, superClass = null, superTypeParameters, marker = markerCreate(), typeParameters, matchImplements; expectKeyword('class'); matchImplements = strict ? matchKeyword('implements') : matchContextualKeyword('implements'); if (!matchKeyword('extends') && !matchImplements && !match('{')) { id = parseVariableIdentifier(); } if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } if (matchKeyword('extends')) { expectKeyword('extends'); previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = false; superClass = parseLeftHandSideExpressionAllowCall(); if (match('<')) { superTypeParameters = parseTypeParameterInstantiation(); } state.yieldAllowed = previousYieldAllowed; } if (strict ? matchKeyword('implements') : matchContextualKeyword('implements')) { implemented = parseClassImplements(); } return markerApply(marker, delegate.createClassExpression( id, superClass, parseClassBody(), typeParameters, superTypeParameters, implemented )); } function parseClassDeclaration() { var id, implemented, previousYieldAllowed, superClass = null, superTypeParameters, marker = markerCreate(), typeParameters; expectKeyword('class'); id = parseVariableIdentifier(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } if (matchKeyword('extends')) { expectKeyword('extends'); previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = false; superClass = parseLeftHandSideExpressionAllowCall(); if (match('<')) { superTypeParameters = parseTypeParameterInstantiation(); } state.yieldAllowed = previousYieldAllowed; } if (strict ? matchKeyword('implements') : matchContextualKeyword('implements')) { implemented = parseClassImplements(); } return markerApply(marker, delegate.createClassDeclaration( id, superClass, parseClassBody(), typeParameters, superTypeParameters, implemented )); } // 15 Program function parseSourceElement() { var token; if (lookahead.type === Token.Keyword) { switch (lookahead.value) { case 'const': case 'let': return parseConstLetDeclaration(lookahead.value); case 'function': return parseFunctionDeclaration(); case 'export': throwErrorTolerant({}, Messages.IllegalExportDeclaration); return parseExportDeclaration(); case 'import': throwErrorTolerant({}, Messages.IllegalImportDeclaration); return parseImportDeclaration(); case 'interface': if (lookahead2().type === Token.Identifier) { return parseInterface(); } return parseStatement(); default: return parseStatement(); } } if (matchContextualKeyword('type') && lookahead2().type === Token.Identifier) { return parseTypeAlias(); } if (matchContextualKeyword('interface') && lookahead2().type === Token.Identifier) { return parseInterface(); } if (matchContextualKeyword('declare')) { token = lookahead2(); if (token.type === Token.Keyword) { switch (token.value) { case 'class': return parseDeclareClass(); case 'function': return parseDeclareFunction(); case 'var': return parseDeclareVariable(); } } else if (token.type === Token.Identifier && token.value === 'module') { return parseDeclareModule(); } } if (lookahead.type !== Token.EOF) { return parseStatement(); } } function parseProgramElement() { var isModule = extra.sourceType === 'module' || extra.sourceType === 'nonStrictModule'; if (isModule && lookahead.type === Token.Keyword) { switch (lookahead.value) { case 'export': return parseExportDeclaration(); case 'import': return parseImportDeclaration(); } } return parseSourceElement(); } function parseProgramElements() { var sourceElement, sourceElements = [], token, directive, firstRestricted; while (index < length) { token = lookahead; if (token.type !== Token.StringLiteral) { break; } sourceElement = parseProgramElement(); sourceElements.push(sourceElement); if (sourceElement.expression.type !== Syntax.Literal) { // this is not directive break; } directive = source.slice(token.range[0] + 1, token.range[1] - 1); if (directive === 'use strict') { strict = true; if (firstRestricted) { throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral); } } else { if (!firstRestricted && token.octal) { firstRestricted = token; } } } while (index < length) { sourceElement = parseProgramElement(); if (typeof sourceElement === 'undefined') { break; } sourceElements.push(sourceElement); } return sourceElements; } function parseProgram() { var body, marker = markerCreate(); strict = extra.sourceType === 'module'; peek(); body = parseProgramElements(); return markerApply(marker, delegate.createProgram(body)); } // 16 JSX XHTMLEntities = { quot: '\u0022', amp: '&', apos: '\u0027', lt: '<', gt: '>', nbsp: '\u00A0', iexcl: '\u00A1', cent: '\u00A2', pound: '\u00A3', curren: '\u00A4', yen: '\u00A5', brvbar: '\u00A6', sect: '\u00A7', uml: '\u00A8', copy: '\u00A9', ordf: '\u00AA', laquo: '\u00AB', not: '\u00AC', shy: '\u00AD', reg: '\u00AE', macr: '\u00AF', deg: '\u00B0', plusmn: '\u00B1', sup2: '\u00B2', sup3: '\u00B3', acute: '\u00B4', micro: '\u00B5', para: '\u00B6', middot: '\u00B7', cedil: '\u00B8', sup1: '\u00B9', ordm: '\u00BA', raquo: '\u00BB', frac14: '\u00BC', frac12: '\u00BD', frac34: '\u00BE', iquest: '\u00BF', Agrave: '\u00C0', Aacute: '\u00C1', Acirc: '\u00C2', Atilde: '\u00C3', Auml: '\u00C4', Aring: '\u00C5', AElig: '\u00C6', Ccedil: '\u00C7', Egrave: '\u00C8', Eacute: '\u00C9', Ecirc: '\u00CA', Euml: '\u00CB', Igrave: '\u00CC', Iacute: '\u00CD', Icirc: '\u00CE', Iuml: '\u00CF', ETH: '\u00D0', Ntilde: '\u00D1', Ograve: '\u00D2', Oacute: '\u00D3', Ocirc: '\u00D4', Otilde: '\u00D5', Ouml: '\u00D6', times: '\u00D7', Oslash: '\u00D8', Ugrave: '\u00D9', Uacute: '\u00DA', Ucirc: '\u00DB', Uuml: '\u00DC', Yacute: '\u00DD', THORN: '\u00DE', szlig: '\u00DF', agrave: '\u00E0', aacute: '\u00E1', acirc: '\u00E2', atilde: '\u00E3', auml: '\u00E4', aring: '\u00E5', aelig: '\u00E6', ccedil: '\u00E7', egrave: '\u00E8', eacute: '\u00E9', ecirc: '\u00EA', euml: '\u00EB', igrave: '\u00EC', iacute: '\u00ED', icirc: '\u00EE', iuml: '\u00EF', eth: '\u00F0', ntilde: '\u00F1', ograve: '\u00F2', oacute: '\u00F3', ocirc: '\u00F4', otilde: '\u00F5', ouml: '\u00F6', divide: '\u00F7', oslash: '\u00F8', ugrave: '\u00F9', uacute: '\u00FA', ucirc: '\u00FB', uuml: '\u00FC', yacute: '\u00FD', thorn: '\u00FE', yuml: '\u00FF', OElig: '\u0152', oelig: '\u0153', Scaron: '\u0160', scaron: '\u0161', Yuml: '\u0178', fnof: '\u0192', circ: '\u02C6', tilde: '\u02DC', Alpha: '\u0391', Beta: '\u0392', Gamma: '\u0393', Delta: '\u0394', Epsilon: '\u0395', Zeta: '\u0396', Eta: '\u0397', Theta: '\u0398', Iota: '\u0399', Kappa: '\u039A', Lambda: '\u039B', Mu: '\u039C', Nu: '\u039D', Xi: '\u039E', Omicron: '\u039F', Pi: '\u03A0', Rho: '\u03A1', Sigma: '\u03A3', Tau: '\u03A4', Upsilon: '\u03A5', Phi: '\u03A6', Chi: '\u03A7', Psi: '\u03A8', Omega: '\u03A9', alpha: '\u03B1', beta: '\u03B2', gamma: '\u03B3', delta: '\u03B4', epsilon: '\u03B5', zeta: '\u03B6', eta: '\u03B7', theta: '\u03B8', iota: '\u03B9', kappa: '\u03BA', lambda: '\u03BB', mu: '\u03BC', nu: '\u03BD', xi: '\u03BE', omicron: '\u03BF', pi: '\u03C0', rho: '\u03C1', sigmaf: '\u03C2', sigma: '\u03C3', tau: '\u03C4', upsilon: '\u03C5', phi: '\u03C6', chi: '\u03C7', psi: '\u03C8', omega: '\u03C9', thetasym: '\u03D1', upsih: '\u03D2', piv: '\u03D6', ensp: '\u2002', emsp: '\u2003', thinsp: '\u2009', zwnj: '\u200C', zwj: '\u200D', lrm: '\u200E', rlm: '\u200F', ndash: '\u2013', mdash: '\u2014', lsquo: '\u2018', rsquo: '\u2019', sbquo: '\u201A', ldquo: '\u201C', rdquo: '\u201D', bdquo: '\u201E', dagger: '\u2020', Dagger: '\u2021', bull: '\u2022', hellip: '\u2026', permil: '\u2030', prime: '\u2032', Prime: '\u2033', lsaquo: '\u2039', rsaquo: '\u203A', oline: '\u203E', frasl: '\u2044', euro: '\u20AC', image: '\u2111', weierp: '\u2118', real: '\u211C', trade: '\u2122', alefsym: '\u2135', larr: '\u2190', uarr: '\u2191', rarr: '\u2192', darr: '\u2193', harr: '\u2194', crarr: '\u21B5', lArr: '\u21D0', uArr: '\u21D1', rArr: '\u21D2', dArr: '\u21D3', hArr: '\u21D4', forall: '\u2200', part: '\u2202', exist: '\u2203', empty: '\u2205', nabla: '\u2207', isin: '\u2208', notin: '\u2209', ni: '\u220B', prod: '\u220F', sum: '\u2211', minus: '\u2212', lowast: '\u2217', radic: '\u221A', prop: '\u221D', infin: '\u221E', ang: '\u2220', and: '\u2227', or: '\u2228', cap: '\u2229', cup: '\u222A', 'int': '\u222B', there4: '\u2234', sim: '\u223C', cong: '\u2245', asymp: '\u2248', ne: '\u2260', equiv: '\u2261', le: '\u2264', ge: '\u2265', sub: '\u2282', sup: '\u2283', nsub: '\u2284', sube: '\u2286', supe: '\u2287', oplus: '\u2295', otimes: '\u2297', perp: '\u22A5', sdot: '\u22C5', lceil: '\u2308', rceil: '\u2309', lfloor: '\u230A', rfloor: '\u230B', lang: '\u2329', rang: '\u232A', loz: '\u25CA', spades: '\u2660', clubs: '\u2663', hearts: '\u2665', diams: '\u2666' }; function getQualifiedJSXName(object) { if (object.type === Syntax.JSXIdentifier) { return object.name; } if (object.type === Syntax.JSXNamespacedName) { return object.namespace.name + ':' + object.name.name; } /* istanbul ignore else */ if (object.type === Syntax.JSXMemberExpression) { return ( getQualifiedJSXName(object.object) + '.' + getQualifiedJSXName(object.property) ); } /* istanbul ignore next */ throwUnexpected(object); } function isJSXIdentifierStart(ch) { // exclude backslash (\) return (ch !== 92) && isIdentifierStart(ch); } function isJSXIdentifierPart(ch) { // exclude backslash (\) and add hyphen (-) return (ch !== 92) && (ch === 45 || isIdentifierPart(ch)); } function scanJSXIdentifier() { var ch, start, value = ''; start = index; while (index < length) { ch = source.charCodeAt(index); if (!isJSXIdentifierPart(ch)) { break; } value += source[index++]; } return { type: Token.JSXIdentifier, value: value, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanJSXEntity() { var ch, str = '', start = index, count = 0, code; ch = source[index]; assert(ch === '&', 'Entity must start with an ampersand'); index++; while (index < length && count++ < 10) { ch = source[index++]; if (ch === ';') { break; } str += ch; } // Well-formed entity (ending was found). if (ch === ';') { // Numeric entity. if (str[0] === '#') { if (str[1] === 'x') { code = +('0' + str.substr(1)); } else { // Removing leading zeros in order to avoid treating as octal in old browsers. code = +str.substr(1).replace(Regex.LeadingZeros, ''); } if (!isNaN(code)) { return String.fromCharCode(code); } /* istanbul ignore else */ } else if (XHTMLEntities[str]) { return XHTMLEntities[str]; } } // Treat non-entity sequences as regular text. index = start + 1; return '&'; } function scanJSXText(stopChars) { var ch, str = '', start; start = index; while (index < length) { ch = source[index]; if (stopChars.indexOf(ch) !== -1) { break; } if (ch === '&') { str += scanJSXEntity(); } else { index++; if (ch === '\r' && source[index] === '\n') { str += ch; ch = source[index]; index++; } if (isLineTerminator(ch.charCodeAt(0))) { ++lineNumber; lineStart = index; } str += ch; } } return { type: Token.JSXText, value: str, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanJSXStringLiteral() { var innerToken, quote, start; quote = source[index]; assert((quote === '\'' || quote === '"'), 'String literal must starts with a quote'); start = index; ++index; innerToken = scanJSXText([quote]); if (quote !== source[index]) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } ++index; innerToken.range = [start, index]; return innerToken; } /** * Between JSX opening and closing tags (e.g. HERE), anything that * is not another JSX tag and is not an expression wrapped by {} is text. */ function advanceJSXChild() { var ch = source.charCodeAt(index); // '<' 60, '>' 62, '{' 123, '}' 125 if (ch !== 60 && ch !== 62 && ch !== 123 && ch !== 125) { return scanJSXText(['<', '>', '{', '}']); } return scanPunctuator(); } function parseJSXIdentifier() { var token, marker = markerCreate(); if (lookahead.type !== Token.JSXIdentifier) { throwUnexpected(lookahead); } token = lex(); return markerApply(marker, delegate.createJSXIdentifier(token.value)); } function parseJSXNamespacedName() { var namespace, name, marker = markerCreate(); namespace = parseJSXIdentifier(); expect(':'); name = parseJSXIdentifier(); return markerApply(marker, delegate.createJSXNamespacedName(namespace, name)); } function parseJSXMemberExpression() { var marker = markerCreate(), expr = parseJSXIdentifier(); while (match('.')) { lex(); expr = markerApply(marker, delegate.createJSXMemberExpression(expr, parseJSXIdentifier())); } return expr; } function parseJSXElementName() { if (lookahead2().value === ':') { return parseJSXNamespacedName(); } if (lookahead2().value === '.') { return parseJSXMemberExpression(); } return parseJSXIdentifier(); } function parseJSXAttributeName() { if (lookahead2().value === ':') { return parseJSXNamespacedName(); } return parseJSXIdentifier(); } function parseJSXAttributeValue() { var value, marker; if (match('{')) { value = parseJSXExpressionContainer(); if (value.expression.type === Syntax.JSXEmptyExpression) { throwError( value, 'JSX attributes must only be assigned a non-empty ' + 'expression' ); } } else if (match('<')) { value = parseJSXElement(); } else if (lookahead.type === Token.JSXText) { marker = markerCreate(); value = markerApply(marker, delegate.createLiteral(lex())); } else { throwError({}, Messages.InvalidJSXAttributeValue); } return value; } function parseJSXEmptyExpression() { var ch, marker = markerCreatePreserveWhitespace(); while (index < length) { ch = source.charCodeAt(index); if (ch === 125) { break; } else if (isLineTerminator(ch)) { if (ch === 13 && source.charCodeAt(index + 1) === 10) { ++index; } ++lineNumber; lineStart = index; } ++index; } return markerApply(marker, delegate.createJSXEmptyExpression()); } function parseJSXExpressionContainer() { var expression, origInJSXChild, origInJSXTag, marker = markerCreate(); origInJSXChild = state.inJSXChild; origInJSXTag = state.inJSXTag; state.inJSXChild = false; state.inJSXTag = false; expect('{'); if (match('}')) { expression = parseJSXEmptyExpression(); } else { expression = parseExpression(); } state.inJSXChild = origInJSXChild; state.inJSXTag = origInJSXTag; expect('}'); return markerApply(marker, delegate.createJSXExpressionContainer(expression)); } function parseJSXSpreadAttribute() { var expression, origInJSXChild, origInJSXTag, marker = markerCreate(); origInJSXChild = state.inJSXChild; origInJSXTag = state.inJSXTag; state.inJSXChild = false; state.inJSXTag = false; expect('{'); expect('...'); expression = parseAssignmentExpression(); state.inJSXChild = origInJSXChild; state.inJSXTag = origInJSXTag; expect('}'); return markerApply(marker, delegate.createJSXSpreadAttribute(expression)); } function parseJSXAttribute() { var name, marker; if (match('{')) { return parseJSXSpreadAttribute(); } marker = markerCreate(); name = parseJSXAttributeName(); // HTML empty attribute if (match('=')) { lex(); return markerApply(marker, delegate.createJSXAttribute(name, parseJSXAttributeValue())); } return markerApply(marker, delegate.createJSXAttribute(name)); } function parseJSXChild() { var token, marker; if (match('{')) { token = parseJSXExpressionContainer(); } else if (lookahead.type === Token.JSXText) { marker = markerCreatePreserveWhitespace(); token = markerApply(marker, delegate.createLiteral(lex())); } else if (match('<')) { token = parseJSXElement(); } else { throwUnexpected(lookahead); } return token; } function parseJSXClosingElement() { var name, origInJSXChild, origInJSXTag, marker = markerCreate(); origInJSXChild = state.inJSXChild; origInJSXTag = state.inJSXTag; state.inJSXChild = false; state.inJSXTag = true; expect('<'); expect('/'); name = parseJSXElementName(); // Because advance() (called by lex() called by expect()) expects there // to be a valid token after >, it needs to know whether to look for a // standard JS token or an JSX text node state.inJSXChild = origInJSXChild; state.inJSXTag = origInJSXTag; expect('>'); return markerApply(marker, delegate.createJSXClosingElement(name)); } function parseJSXOpeningElement() { var name, attributes = [], selfClosing = false, origInJSXChild, origInJSXTag, marker = markerCreate(); origInJSXChild = state.inJSXChild; origInJSXTag = state.inJSXTag; state.inJSXChild = false; state.inJSXTag = true; expect('<'); name = parseJSXElementName(); while (index < length && lookahead.value !== '/' && lookahead.value !== '>') { attributes.push(parseJSXAttribute()); } state.inJSXTag = origInJSXTag; if (lookahead.value === '/') { expect('/'); // Because advance() (called by lex() called by expect()) expects // there to be a valid token after >, it needs to know whether to // look for a standard JS token or an JSX text node state.inJSXChild = origInJSXChild; expect('>'); selfClosing = true; } else { state.inJSXChild = true; expect('>'); } return markerApply(marker, delegate.createJSXOpeningElement(name, attributes, selfClosing)); } function parseJSXElement() { var openingElement, closingElement = null, children = [], origInJSXChild, origInJSXTag, marker = markerCreate(); origInJSXChild = state.inJSXChild; origInJSXTag = state.inJSXTag; openingElement = parseJSXOpeningElement(); if (!openingElement.selfClosing) { while (index < length) { state.inJSXChild = false; // Call lookahead2() with inJSXChild = false because one
two
; // // the default error message is a bit incomprehensible. Since it's // rarely (never?) useful to write a less-than sign after an JSX // element, we disallow it here in the parser in order to provide a // better error message. (In the rare case that the less-than operator // was intended, the left tag can be wrapped in parentheses.) if (!origInJSXChild && match('<')) { throwError(lookahead, Messages.AdjacentJSXElements); } return markerApply(marker, delegate.createJSXElement(openingElement, closingElement, children)); } function parseTypeAlias() { var id, marker = markerCreate(), typeParameters = null, right; expectContextualKeyword('type'); id = parseVariableIdentifier(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } expect('='); right = parseType(); consumeSemicolon(); return markerApply(marker, delegate.createTypeAlias(id, typeParameters, right)); } function parseInterfaceExtends() { var marker = markerCreate(), id, typeParameters = null; id = parseVariableIdentifier(); if (match('<')) { typeParameters = parseTypeParameterInstantiation(); } return markerApply(marker, delegate.createInterfaceExtends( id, typeParameters )); } function parseInterfaceish(marker, allowStatic) { var body, bodyMarker, extended = [], id, typeParameters = null; id = parseVariableIdentifier(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } if (matchKeyword('extends')) { expectKeyword('extends'); while (index < length) { extended.push(parseInterfaceExtends()); if (!match(',')) { break; } expect(','); } } bodyMarker = markerCreate(); body = markerApply(bodyMarker, parseObjectType(allowStatic)); return markerApply(marker, delegate.createInterface( id, typeParameters, body, extended )); } function parseInterface() { var marker = markerCreate(); if (strict) { expectKeyword('interface'); } else { expectContextualKeyword('interface'); } return parseInterfaceish(marker, /* allowStatic */false); } function parseDeclareClass() { var marker = markerCreate(), ret; expectContextualKeyword('declare'); expectKeyword('class'); ret = parseInterfaceish(marker, /* allowStatic */true); ret.type = Syntax.DeclareClass; return ret; } function parseDeclareFunction() { var id, idMarker, marker = markerCreate(), params, returnType, rest, tmp, typeParameters = null, value, valueMarker; expectContextualKeyword('declare'); expectKeyword('function'); idMarker = markerCreate(); id = parseVariableIdentifier(); valueMarker = markerCreate(); if (match('<')) { typeParameters = parseTypeParameterDeclaration(); } expect('('); tmp = parseFunctionTypeParams(); params = tmp.params; rest = tmp.rest; expect(')'); expect(':'); returnType = parseType(); value = markerApply(valueMarker, delegate.createFunctionTypeAnnotation( params, returnType, rest, typeParameters )); id.typeAnnotation = markerApply(valueMarker, delegate.createTypeAnnotation( value )); markerApply(idMarker, id); consumeSemicolon(); return markerApply(marker, delegate.createDeclareFunction( id )); } function parseDeclareVariable() { var id, marker = markerCreate(); expectContextualKeyword('declare'); expectKeyword('var'); id = parseTypeAnnotatableIdentifier(); consumeSemicolon(); return markerApply(marker, delegate.createDeclareVariable( id )); } function parseDeclareModule() { var body = [], bodyMarker, id, idMarker, marker = markerCreate(), token; expectContextualKeyword('declare'); expectContextualKeyword('module'); if (lookahead.type === Token.StringLiteral) { if (strict && lookahead.octal) { throwErrorTolerant(lookahead, Messages.StrictOctalLiteral); } idMarker = markerCreate(); id = markerApply(idMarker, delegate.createLiteral(lex())); } else { id = parseVariableIdentifier(); } bodyMarker = markerCreate(); expect('{'); while (index < length && !match('}')) { token = lookahead2(); switch (token.value) { case 'class': body.push(parseDeclareClass()); break; case 'function': body.push(parseDeclareFunction()); break; case 'var': body.push(parseDeclareVariable()); break; default: throwUnexpected(lookahead); } } expect('}'); return markerApply(marker, delegate.createDeclareModule( id, markerApply(bodyMarker, delegate.createBlockStatement(body)) )); } function collectToken() { var loc, token, range, value, entry; /* istanbul ignore else */ if (!state.inJSXChild) { skipComment(); } loc = { start: { line: lineNumber, column: index - lineStart } }; token = extra.advance(); loc.end = { line: lineNumber, column: index - lineStart }; if (token.type !== Token.EOF) { range = [token.range[0], token.range[1]]; value = source.slice(token.range[0], token.range[1]); entry = { type: TokenName[token.type], value: value, range: range, loc: loc }; if (token.regex) { entry.regex = { pattern: token.regex.pattern, flags: token.regex.flags }; } extra.tokens.push(entry); } return token; } function collectRegex() { var pos, loc, regex, token; skipComment(); pos = index; loc = { start: { line: lineNumber, column: index - lineStart } }; regex = extra.scanRegExp(); loc.end = { line: lineNumber, column: index - lineStart }; if (!extra.tokenize) { /* istanbul ignore next */ // Pop the previous token, which is likely '/' or '/=' if (extra.tokens.length > 0) { token = extra.tokens[extra.tokens.length - 1]; if (token.range[0] === pos && token.type === 'Punctuator') { if (token.value === '/' || token.value === '/=') { extra.tokens.pop(); } } } extra.tokens.push({ type: 'RegularExpression', value: regex.literal, regex: regex.regex, range: [pos, index], loc: loc }); } return regex; } function filterTokenLocation() { var i, entry, token, tokens = []; for (i = 0; i < extra.tokens.length; ++i) { entry = extra.tokens[i]; token = { type: entry.type, value: entry.value }; if (entry.regex) { token.regex = { pattern: entry.regex.pattern, flags: entry.regex.flags }; } if (extra.range) { token.range = entry.range; } if (extra.loc) { token.loc = entry.loc; } tokens.push(token); } extra.tokens = tokens; } function patch() { if (typeof extra.tokens !== 'undefined') { extra.advance = advance; extra.scanRegExp = scanRegExp; advance = collectToken; scanRegExp = collectRegex; } } function unpatch() { if (typeof extra.scanRegExp === 'function') { advance = extra.advance; scanRegExp = extra.scanRegExp; } } // This is used to modify the delegate. function extend(object, properties) { var entry, result = {}; for (entry in object) { /* istanbul ignore else */ if (object.hasOwnProperty(entry)) { result[entry] = object[entry]; } } for (entry in properties) { /* istanbul ignore else */ if (properties.hasOwnProperty(entry)) { result[entry] = properties[entry]; } } return result; } function tokenize(code, options) { var toString, token, tokens; toString = String; if (typeof code !== 'string' && !(code instanceof String)) { code = toString(code); } delegate = SyntaxTreeDelegate; source = code; index = 0; lineNumber = (source.length > 0) ? 1 : 0; lineStart = 0; length = source.length; lookahead = null; state = { allowKeyword: true, allowIn: true, labelSet: new StringMap(), inFunctionBody: false, inIteration: false, inSwitch: false, lastCommentStart: -1, curlyStack: [], curlyLastIndex: 0 }; extra = {}; // Options matching. options = options || {}; // Of course we collect tokens here. 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; extra.range = (typeof options.range === 'boolean') && options.range; extra.loc = (typeof options.loc === 'boolean') && options.loc; if (typeof options.comment === 'boolean' && options.comment) { extra.comments = []; } if (typeof options.tolerant === 'boolean' && options.tolerant) { extra.errors = []; } patch(); try { peek(); if (lookahead.type === Token.EOF) { return extra.tokens; } token = lex(); while (lookahead.type !== Token.EOF) { try { token = lex(); } catch (lexError) { token = lookahead; if (extra.errors) { extra.errors.push(lexError); // We have to break on the first error // to avoid infinite loops. break; } else { throw lexError; } } } filterTokenLocation(); tokens = extra.tokens; if (typeof extra.comments !== 'undefined') { tokens.comments = extra.comments; } if (typeof extra.errors !== 'undefined') { tokens.errors = extra.errors; } } catch (e) { throw e; } finally { unpatch(); extra = {}; } return tokens; } function parse(code, options) { var program, toString; toString = String; if (typeof code !== 'string' && !(code instanceof String)) { code = toString(code); } delegate = SyntaxTreeDelegate; source = code; index = 0; lineNumber = (source.length > 0) ? 1 : 0; lineStart = 0; length = source.length; lookahead = null; state = { allowKeyword: false, allowIn: true, labelSet: new StringMap(), parenthesizedCount: 0, inFunctionBody: false, inIteration: false, inSwitch: false, inJSXChild: false, inJSXTag: false, inType: false, lastCommentStart: -1, yieldAllowed: false, awaitAllowed: false, curlyPosition: 0, curlyStack: [], curlyLastIndex: 0 }; extra = {}; if (typeof options !== 'undefined') { extra.range = (typeof options.range === 'boolean') && options.range; extra.loc = (typeof options.loc === 'boolean') && options.loc; extra.attachComment = (typeof options.attachComment === 'boolean') && options.attachComment; if (extra.loc && options.source !== null && options.source !== undefined) { delegate = extend(delegate, { 'postProcess': function (node) { node.loc.source = toString(options.source); return node; } }); } extra.sourceType = options.sourceType; if (typeof options.tokens === 'boolean' && options.tokens) { extra.tokens = []; } if (typeof options.comment === 'boolean' && options.comment) { extra.comments = []; } if (typeof options.tolerant === 'boolean' && options.tolerant) { extra.errors = []; } if (extra.attachComment) { extra.range = true; extra.comments = []; extra.bottomRightStack = []; extra.trailingComments = []; extra.leadingComments = []; } } patch(); try { program = parseProgram(); if (typeof extra.comments !== 'undefined') { program.comments = extra.comments; } if (typeof extra.tokens !== 'undefined') { filterTokenLocation(); program.tokens = extra.tokens; } if (typeof extra.errors !== 'undefined') { program.errors = extra.errors; } } catch (e) { throw e; } finally { unpatch(); extra = {}; } return program; } // Sync with *.json manifests. exports.version = '14001.1.0-dev-harmony-fb'; exports.tokenize = tokenize; exports.parse = parse; // Deep copy. /* istanbul ignore next */ exports.Syntax = (function () { var name, types = {}; if (typeof Object.create === 'function') { types = Object.create(null); } for (name in Syntax) { if (Syntax.hasOwnProperty(name)) { types[name] = Syntax[name]; } } if (typeof Object.freeze === 'function') { Object.freeze(types); } return types; }()); })); /* vim: set sw=4 ts=4 et tw=80 : */ },{}],471:[function(require,module,exports){ (function (process){ var Stream = require('stream') // through // // a stream that does nothing but re-emit the input. // useful for aggregating a series of changing but not ending streams into one stream) exports = module.exports = through through.through = through //create a readable writable stream. function through (write, end, opts) { write = write || function (data) { this.queue(data) } end = end || function () { this.queue(null) } var ended = false, destroyed = false, buffer = [], _ended = false var stream = new Stream() stream.readable = stream.writable = true stream.paused = false // stream.autoPause = !(opts && opts.autoPause === false) stream.autoDestroy = !(opts && opts.autoDestroy === false) stream.write = function (data) { write.call(this, data) return !stream.paused } function drain() { while(buffer.length && !stream.paused) { var data = buffer.shift() if(null === data) return stream.emit('end') else stream.emit('data', data) } } stream.queue = stream.push = function (data) { // console.error(ended) if(_ended) return stream if(data === null) _ended = true buffer.push(data) drain() return stream } //this will be registered as the first 'end' listener //must call destroy next tick, to make sure we're after any //stream piped from here. //this is only a problem if end is not emitted synchronously. //a nicer way to do this is to make sure this is the last listener for 'end' stream.on('end', function () { stream.readable = false if(!stream.writable && stream.autoDestroy) process.nextTick(function () { stream.destroy() }) }) function _end () { stream.writable = false end.call(stream) if(!stream.readable && stream.autoDestroy) stream.destroy() } stream.end = function (data) { if(ended) return ended = true if(arguments.length) stream.write(data) _end() // will emit or queue return stream } stream.destroy = function () { if(destroyed) return destroyed = true ended = true buffer.length = 0 stream.writable = stream.readable = false stream.emit('close') return stream } stream.pause = function () { if(stream.paused) return stream.paused = true return stream } stream.resume = function () { if(stream.paused) { stream.paused = false stream.emit('resume') } drain() //may have become paused again, //as drain emits 'data'. if(!stream.paused) stream.emit('drain') return stream } return stream } }).call(this,require('_process')) },{"_process":200,"stream":212}],472:[function(require,module,exports){ (function (global){ /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * https://raw.github.com/facebook/regenerator/master/LICENSE file. An * additional grant of patent rights can be found in the PATENTS file in * the same directory. */ !(function(global) { "use strict"; var hasOwn = Object.prototype.hasOwnProperty; var undefined; // More compressible than void 0. var iteratorSymbol = typeof Symbol === "function" && Symbol.iterator || "@@iterator"; var inModule = typeof module === "object"; var runtime = global.regeneratorRuntime; if (runtime) { if (inModule) { // If regeneratorRuntime is defined globally and we're in a module, // make the exports object identical to regeneratorRuntime. module.exports = runtime; } // Don't bother evaluating the rest of this file if the runtime was // already defined globally. return; } // Define the runtime globally (as expected by generated code) as either // module.exports (if we're in a module) or a new, empty object. runtime = global.regeneratorRuntime = inModule ? module.exports : {}; function wrap(innerFn, outerFn, self, tryLocsList) { // If outerFn provided, then outerFn.prototype instanceof Generator. var generator = Object.create((outerFn || Generator).prototype); generator._invoke = makeInvokeMethod( innerFn, self || null, new Context(tryLocsList || []) ); return generator; } runtime.wrap = wrap; // Try/catch helper to minimize deoptimizations. Returns a completion // record like context.tryEntries[i].completion. This interface could // have been (and was previously) designed to take a closure to be // invoked without arguments, but in all the cases we care about we // already have an existing method we want to call, so there's no need // to create a new function object. We can even get away with assuming // the method takes exactly one argument, since that happens to be true // in every case, so we don't have to touch the arguments object. The // only additional allocation required is the completion record, which // has a stable shape and so hopefully should be cheap to allocate. function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } var GenStateSuspendedStart = "suspendedStart"; var GenStateSuspendedYield = "suspendedYield"; var GenStateExecuting = "executing"; var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as // breaking out of the dispatch switch statement. var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and // .constructor.prototype properties for functions that return Generator // objects. For full spec compliance, you may wish to configure your // minifier not to mangle the names of these two functions. function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype; GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; GeneratorFunctionPrototype.constructor = GeneratorFunction; GeneratorFunction.displayName = "GeneratorFunction"; runtime.isGeneratorFunction = function(genFun) { var ctor = typeof genFun === "function" && genFun.constructor; return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can // do is to check its .name property. (ctor.displayName || ctor.name) === "GeneratorFunction" : false; }; runtime.mark = function(genFun) { genFun.__proto__ = GeneratorFunctionPrototype; genFun.prototype = Object.create(Gp); return genFun; }; runtime.async = function(innerFn, outerFn, self, tryLocsList) { return new Promise(function(resolve, reject) { var generator = wrap(innerFn, outerFn, self, tryLocsList); var callNext = step.bind(generator, "next"); var callThrow = step.bind(generator, "throw"); function step(method, arg) { var record = tryCatch(generator[method], generator, arg); if (record.type === "throw") { reject(record.arg); return; } var info = record.arg; if (info.done) { resolve(info.value); } else { Promise.resolve(info.value).then(callNext, callThrow); } } callNext(); }); }; function makeInvokeMethod(innerFn, self, context) { var state = GenStateSuspendedStart; return function invoke(method, arg) { if (state === GenStateExecuting) { throw new Error("Generator is already running"); } if (state === GenStateCompleted) { // Be forgiving, per 25.3.3.3.3 of the spec: // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume return doneResult(); } while (true) { var delegate = context.delegate; if (delegate) { if (method === "return" || (method === "throw" && delegate.iterator[method] === undefined)) { // A return or throw (when the delegate iterator has no throw // method) always terminates the yield* loop. context.delegate = null; // If the delegate iterator has a return method, give it a // chance to clean up. var returnMethod = delegate.iterator["return"]; if (returnMethod) { var record = tryCatch(returnMethod, delegate.iterator, arg); if (record.type === "throw") { // If the return method threw an exception, let that // exception prevail over the original return or throw. method = "throw"; arg = record.arg; continue; } } if (method === "return") { // Continue with the outer return, now that the delegate // iterator has been terminated. continue; } } var record = tryCatch( delegate.iterator[method], delegate.iterator, arg ); if (record.type === "throw") { context.delegate = null; // Like returning generator.throw(uncaught), but without the // overhead of an extra function call. method = "throw"; arg = record.arg; continue; } // Delegate generator ran and handled its own exceptions so // regardless of what the method was, we continue as if it is // "next" with an undefined arg. method = "next"; arg = undefined; var info = record.arg; if (info.done) { context[delegate.resultName] = info.value; context.next = delegate.nextLoc; } else { state = GenStateSuspendedYield; return info; } context.delegate = null; } if (method === "next") { if (state === GenStateSuspendedYield) { context.sent = arg; } else { delete context.sent; } } else if (method === "throw") { if (state === GenStateSuspendedStart) { state = GenStateCompleted; throw arg; } if (context.dispatchException(arg)) { // If the dispatched exception was caught by a catch block, // then let that catch block handle the exception normally. method = "next"; arg = undefined; } } else if (method === "return") { context.abrupt("return", arg); } state = GenStateExecuting; var record = tryCatch(innerFn, self, context); if (record.type === "normal") { // If an exception is thrown from innerFn, we leave state === // GenStateExecuting and loop back for another invocation. state = context.done ? GenStateCompleted : GenStateSuspendedYield; var info = { value: record.arg, done: context.done }; if (record.arg === ContinueSentinel) { if (context.delegate && method === "next") { // Deliberately forget the last sent value so that we don't // accidentally pass it on to the delegate. arg = undefined; } } else { return info; } } else if (record.type === "throw") { state = GenStateCompleted; // Dispatch the exception by looping back around to the // context.dispatchException(arg) call above. method = "throw"; arg = record.arg; } } }; } function defineGeneratorMethod(method) { Gp[method] = function(arg) { return this._invoke(method, arg); }; } defineGeneratorMethod("next"); defineGeneratorMethod("throw"); defineGeneratorMethod("return"); Gp[iteratorSymbol] = function() { return this; }; Gp.toString = function() { return "[object Generator]"; }; function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; if (1 in locs) { entry.catchLoc = locs[1]; } if (2 in locs) { entry.finallyLoc = locs[2]; entry.afterLoc = locs[3]; } this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal"; delete record.arg; entry.completion = record; } function Context(tryLocsList) { // The root entry object (effectively a try statement without a catch // or a finally block) gives us a place to store values thrown from // locations where there is no enclosing try statement. this.tryEntries = [{ tryLoc: "root" }]; tryLocsList.forEach(pushTryEntry, this); this.reset(); } runtime.keys = function(object) { var keys = []; for (var key in object) { keys.push(key); } keys.reverse(); // Rather than returning an object with a next method, we keep // things simple and return the next function itself. return function next() { while (keys.length) { var key = keys.pop(); if (key in object) { next.value = key; next.done = false; return next; } } // To avoid creating an additional object, we just hang the .value // and .done properties off the next function object itself. This // also ensures that the minifier will not anonymize the function. next.done = true; return next; }; }; function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) { return iteratorMethod.call(iterable); } if (typeof iterable.next === "function") { return iterable; } if (!isNaN(iterable.length)) { var i = -1, next = function next() { while (++i < iterable.length) { if (hasOwn.call(iterable, i)) { next.value = iterable[i]; next.done = false; return next; } } next.value = undefined; next.done = true; return next; }; return next.next = next; } } // Return an iterator with no values. return { next: doneResult }; } runtime.values = values; function doneResult() { return { value: undefined, done: true }; } Context.prototype = { constructor: Context, reset: function() { this.prev = 0; this.next = 0; this.sent = undefined; this.done = false; this.delegate = null; this.tryEntries.forEach(resetTryEntry); // Pre-initialize at least 20 temporary variables to enable hidden // class optimizations for simple generators. for (var tempIndex = 0, tempName; hasOwn.call(this, tempName = "t" + tempIndex) || tempIndex < 20; ++tempIndex) { this[tempName] = null; } }, stop: function() { this.done = true; var rootEntry = this.tryEntries[0]; var rootRecord = rootEntry.completion; if (rootRecord.type === "throw") { throw rootRecord.arg; } return this.rval; }, dispatchException: function(exception) { if (this.done) { throw exception; } var context = this; function handle(loc, caught) { record.type = "throw"; record.arg = exception; context.next = loc; return !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; var record = entry.completion; if (entry.tryLoc === "root") { // Exception thrown outside of any try block that could handle // it, so set the completion value of the entire function to // throw the exception. return handle("end"); } if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"); var hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } else if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else if (hasCatch) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } } else if (hasFinally) { if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else { throw new Error("try statement without catch or finally"); } } } }, abrupt: function(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { // Ignore the finally entry if control is not jumping to a // location outside the try/catch block. finallyEntry = null; } var record = finallyEntry ? finallyEntry.completion : {}; record.type = type; record.arg = arg; if (finallyEntry) { this.next = finallyEntry.finallyLoc; } else { this.complete(record); } return ContinueSentinel; }, complete: function(record, afterLoc) { if (record.type === "throw") { throw record.arg; } if (record.type === "break" || record.type === "continue") { this.next = record.arg; } else if (record.type === "return") { this.rval = record.arg; this.next = "end"; } else if (record.type === "normal" && afterLoc) { this.next = afterLoc; } return ContinueSentinel; }, finish: function(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) { return this.complete(entry.completion, entry.afterLoc); } } }, "catch": function(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if (record.type === "throw") { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } // The context.catch method must only be called with a location // argument that corresponds to a known catch block. throw new Error("illegal catch attempt"); }, delegateYield: function(iterable, resultName, nextLoc) { this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }; return ContinueSentinel; } }; })( // Among the various tricks for obtaining a reference to the global // object, this seems to be the most reliable technique that does not // use indirect eval (which violates Content Security Policy). typeof global === "object" ? global : typeof window === "object" ? window : typeof self === "object" ? self : this ); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],473:[function(require,module,exports){ // Generated by `/scripts/character-class-escape-sets.js`. Do not edit. var regenerate = require('regenerate'); exports.REGULAR = { 'd': regenerate() .addRange(0x30, 0x39), 'D': regenerate() .addRange(0x0, 0x2F) .addRange(0x3A, 0xFFFF), 's': regenerate(0x20, 0xA0, 0x1680, 0x180E, 0x202F, 0x205F, 0x3000, 0xFEFF) .addRange(0x9, 0xD) .addRange(0x2000, 0x200A) .addRange(0x2028, 0x2029), 'S': regenerate() .addRange(0x0, 0x8) .addRange(0xE, 0x1F) .addRange(0x21, 0x9F) .addRange(0xA1, 0x167F) .addRange(0x1681, 0x180D) .addRange(0x180F, 0x1FFF) .addRange(0x200B, 0x2027) .addRange(0x202A, 0x202E) .addRange(0x2030, 0x205E) .addRange(0x2060, 0x2FFF) .addRange(0x3001, 0xFEFE) .addRange(0xFF00, 0xFFFF), 'w': regenerate(0x5F) .addRange(0x30, 0x39) .addRange(0x41, 0x5A) .addRange(0x61, 0x7A), 'W': regenerate(0x60) .addRange(0x0, 0x2F) .addRange(0x3A, 0x40) .addRange(0x5B, 0x5E) .addRange(0x7B, 0xFFFF) }; exports.UNICODE = { 'd': regenerate() .addRange(0x30, 0x39), 'D': regenerate() .addRange(0x0, 0x2F) .addRange(0x3A, 0x10FFFF), 's': regenerate(0x20, 0xA0, 0x1680, 0x180E, 0x202F, 0x205F, 0x3000, 0xFEFF) .addRange(0x9, 0xD) .addRange(0x2000, 0x200A) .addRange(0x2028, 0x2029), 'S': regenerate() .addRange(0x0, 0x8) .addRange(0xE, 0x1F) .addRange(0x21, 0x9F) .addRange(0xA1, 0x167F) .addRange(0x1681, 0x180D) .addRange(0x180F, 0x1FFF) .addRange(0x200B, 0x2027) .addRange(0x202A, 0x202E) .addRange(0x2030, 0x205E) .addRange(0x2060, 0x2FFF) .addRange(0x3001, 0xFEFE) .addRange(0xFF00, 0x10FFFF), 'w': regenerate(0x5F) .addRange(0x30, 0x39) .addRange(0x41, 0x5A) .addRange(0x61, 0x7A), 'W': regenerate(0x60) .addRange(0x0, 0x2F) .addRange(0x3A, 0x40) .addRange(0x5B, 0x5E) .addRange(0x7B, 0x10FFFF) }; exports.UNICODE_IGNORE_CASE = { 'd': regenerate() .addRange(0x30, 0x39), 'D': regenerate() .addRange(0x0, 0x2F) .addRange(0x3A, 0x10FFFF), 's': regenerate(0x20, 0xA0, 0x1680, 0x180E, 0x202F, 0x205F, 0x3000, 0xFEFF) .addRange(0x9, 0xD) .addRange(0x2000, 0x200A) .addRange(0x2028, 0x2029), 'S': regenerate() .addRange(0x0, 0x8) .addRange(0xE, 0x1F) .addRange(0x21, 0x9F) .addRange(0xA1, 0x167F) .addRange(0x1681, 0x180D) .addRange(0x180F, 0x1FFF) .addRange(0x200B, 0x2027) .addRange(0x202A, 0x202E) .addRange(0x2030, 0x205E) .addRange(0x2060, 0x2FFF) .addRange(0x3001, 0xFEFE) .addRange(0xFF00, 0x10FFFF), 'w': regenerate(0x5F, 0x17F, 0x212A) .addRange(0x30, 0x39) .addRange(0x41, 0x5A) .addRange(0x61, 0x7A), 'W': regenerate(0x4B, 0x53, 0x60) .addRange(0x0, 0x2F) .addRange(0x3A, 0x40) .addRange(0x5B, 0x5E) .addRange(0x7B, 0x10FFFF) }; },{"regenerate":475}],474:[function(require,module,exports){ module.exports={ "75": 8490, "83": 383, "107": 8490, "115": 383, "181": 924, "197": 8491, "383": 83, "452": 453, "453": 452, "455": 456, "456": 455, "458": 459, "459": 458, "497": 498, "498": 497, "837": 8126, "914": 976, "917": 1013, "920": 1012, "921": 8126, "922": 1008, "924": 181, "928": 982, "929": 1009, "931": 962, "934": 981, "937": 8486, "962": 931, "976": 914, "977": 1012, "981": 934, "982": 928, "1008": 922, "1009": 929, "1012": [ 920, 977 ], "1013": 917, "7776": 7835, "7835": 7776, "8126": [ 837, 921 ], "8486": 937, "8490": 75, "8491": 197, "66560": 66600, "66561": 66601, "66562": 66602, "66563": 66603, "66564": 66604, "66565": 66605, "66566": 66606, "66567": 66607, "66568": 66608, "66569": 66609, "66570": 66610, "66571": 66611, "66572": 66612, "66573": 66613, "66574": 66614, "66575": 66615, "66576": 66616, "66577": 66617, "66578": 66618, "66579": 66619, "66580": 66620, "66581": 66621, "66582": 66622, "66583": 66623, "66584": 66624, "66585": 66625, "66586": 66626, "66587": 66627, "66588": 66628, "66589": 66629, "66590": 66630, "66591": 66631, "66592": 66632, "66593": 66633, "66594": 66634, "66595": 66635, "66596": 66636, "66597": 66637, "66598": 66638, "66599": 66639, "66600": 66560, "66601": 66561, "66602": 66562, "66603": 66563, "66604": 66564, "66605": 66565, "66606": 66566, "66607": 66567, "66608": 66568, "66609": 66569, "66610": 66570, "66611": 66571, "66612": 66572, "66613": 66573, "66614": 66574, "66615": 66575, "66616": 66576, "66617": 66577, "66618": 66578, "66619": 66579, "66620": 66580, "66621": 66581, "66622": 66582, "66623": 66583, "66624": 66584, "66625": 66585, "66626": 66586, "66627": 66587, "66628": 66588, "66629": 66589, "66630": 66590, "66631": 66591, "66632": 66592, "66633": 66593, "66634": 66594, "66635": 66595, "66636": 66596, "66637": 66597, "66638": 66598, "66639": 66599, "71840": 71872, "71841": 71873, "71842": 71874, "71843": 71875, "71844": 71876, "71845": 71877, "71846": 71878, "71847": 71879, "71848": 71880, "71849": 71881, "71850": 71882, "71851": 71883, "71852": 71884, "71853": 71885, "71854": 71886, "71855": 71887, "71856": 71888, "71857": 71889, "71858": 71890, "71859": 71891, "71860": 71892, "71861": 71893, "71862": 71894, "71863": 71895, "71864": 71896, "71865": 71897, "71866": 71898, "71867": 71899, "71868": 71900, "71869": 71901, "71870": 71902, "71871": 71903, "71872": 71840, "71873": 71841, "71874": 71842, "71875": 71843, "71876": 71844, "71877": 71845, "71878": 71846, "71879": 71847, "71880": 71848, "71881": 71849, "71882": 71850, "71883": 71851, "71884": 71852, "71885": 71853, "71886": 71854, "71887": 71855, "71888": 71856, "71889": 71857, "71890": 71858, "71891": 71859, "71892": 71860, "71893": 71861, "71894": 71862, "71895": 71863, "71896": 71864, "71897": 71865, "71898": 71866, "71899": 71867, "71900": 71868, "71901": 71869, "71902": 71870, "71903": 71871 } },{}],475:[function(require,module,exports){ (function (global){ /*! https://mths.be/regenerate v1.2.0 by @mathias | MIT license */ ;(function(root) { // Detect free variables `exports`. var freeExports = typeof exports == 'object' && exports; // Detect free variable `module`. var freeModule = typeof module == 'object' && module && module.exports == freeExports && module; // Detect free variable `global`, from Node.js or Browserified code, // and use it as `root`. var freeGlobal = typeof global == 'object' && global; if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { root = freeGlobal; } /*--------------------------------------------------------------------------*/ var ERRORS = { 'rangeOrder': 'A range\u2019s `stop` value must be greater than or equal ' + 'to the `start` value.', 'codePointRange': 'Invalid code point value. Code points range from ' + 'U+000000 to U+10FFFF.' }; // https://mathiasbynens.be/notes/javascript-encoding#surrogate-pairs var HIGH_SURROGATE_MIN = 0xD800; var HIGH_SURROGATE_MAX = 0xDBFF; var LOW_SURROGATE_MIN = 0xDC00; var LOW_SURROGATE_MAX = 0xDFFF; // In Regenerate output, `\0` will never be preceded by `\` because we sort // by code point value, so let’s keep this regular expression simple. var regexNull = /\\x00([^0123456789]|$)/g; var object = {}; var hasOwnProperty = object.hasOwnProperty; var extend = function(destination, source) { var key; for (key in source) { if (hasOwnProperty.call(source, key)) { destination[key] = source[key]; } } return destination; }; var forEach = function(array, callback) { var index = -1; var length = array.length; while (++index < length) { callback(array[index], index); } }; var toString = object.toString; var isArray = function(value) { return toString.call(value) == '[object Array]'; }; var isNumber = function(value) { return typeof value == 'number' || toString.call(value) == '[object Number]'; }; // This assumes that `number` is a positive integer that `toString()`s nicely // (which is the case for all code point values). var zeroes = '0000'; var pad = function(number, totalCharacters) { var string = String(number); return string.length < totalCharacters ? (zeroes + string).slice(-totalCharacters) : string; }; var hex = function(number) { return Number(number).toString(16).toUpperCase(); }; var slice = [].slice; /*--------------------------------------------------------------------------*/ var dataFromCodePoints = function(codePoints) { var index = -1; var length = codePoints.length; var max = length - 1; var result = []; var isStart = true; var tmp; var previous = 0; while (++index < length) { tmp = codePoints[index]; if (isStart) { result.push(tmp); previous = tmp; isStart = false; } else { if (tmp == previous + 1) { if (index != max) { previous = tmp; continue; } else { isStart = true; result.push(tmp + 1); } } else { // End the previous range and start a new one. result.push(previous + 1, tmp); previous = tmp; } } } if (!isStart) { result.push(tmp + 1); } return result; }; var dataRemove = function(data, codePoint) { // Iterate over the data per `(start, end)` pair. var index = 0; var start; var end; var length = data.length; while (index < length) { start = data[index]; end = data[index + 1]; if (codePoint >= start && codePoint < end) { // Modify this pair. if (codePoint == start) { if (end == start + 1) { // Just remove `start` and `end`. data.splice(index, 2); return data; } else { // Just replace `start` with a new value. data[index] = codePoint + 1; return data; } } else if (codePoint == end - 1) { // Just replace `end` with a new value. data[index + 1] = codePoint; return data; } else { // Replace `[start, end]` with `[startA, endA, startB, endB]`. data.splice(index, 2, start, codePoint, codePoint + 1, end); return data; } } index += 2; } return data; }; var dataRemoveRange = function(data, rangeStart, rangeEnd) { if (rangeEnd < rangeStart) { throw Error(ERRORS.rangeOrder); } // Iterate over the data per `(start, end)` pair. var index = 0; var start; var end; while (index < data.length) { start = data[index]; end = data[index + 1] - 1; // Note: the `- 1` makes `end` inclusive. // Exit as soon as no more matching pairs can be found. if (start > rangeEnd) { return data; } // Check if this range pair is equal to, or forms a subset of, the range // to be removed. // E.g. we have `[0, 11, 40, 51]` and want to remove 0-10 → `[40, 51]`. // E.g. we have `[40, 51]` and want to remove 0-100 → `[]`. if (rangeStart <= start && rangeEnd >= end) { // Remove this pair. data.splice(index, 2); continue; } // Check if both `rangeStart` and `rangeEnd` are within the bounds of // this pair. // E.g. we have `[0, 11]` and want to remove 4-6 → `[0, 4, 7, 11]`. if (rangeStart >= start && rangeEnd < end) { if (rangeStart == start) { // Replace `[start, end]` with `[startB, endB]`. data[index] = rangeEnd + 1; data[index + 1] = end + 1; return data; } // Replace `[start, end]` with `[startA, endA, startB, endB]`. data.splice(index, 2, start, rangeStart, rangeEnd + 1, end + 1); return data; } // Check if only `rangeStart` is within the bounds of this pair. // E.g. we have `[0, 11]` and want to remove 4-20 → `[0, 4]`. if (rangeStart >= start && rangeStart <= end) { // Replace `end` with `rangeStart`. data[index + 1] = rangeStart; // Note: we cannot `return` just yet, in case any following pairs still // contain matching code points. // E.g. we have `[0, 11, 14, 31]` and want to remove 4-20 // → `[0, 4, 21, 31]`. } // Check if only `rangeEnd` is within the bounds of this pair. // E.g. we have `[14, 31]` and want to remove 4-20 → `[21, 31]`. else if (rangeEnd >= start && rangeEnd <= end) { // Just replace `start`. data[index] = rangeEnd + 1; return data; } index += 2; } return data; }; var dataAdd = function(data, codePoint) { // Iterate over the data per `(start, end)` pair. var index = 0; var start; var end; var lastIndex = null; var length = data.length; if (codePoint < 0x0 || codePoint > 0x10FFFF) { throw RangeError(ERRORS.codePointRange); } while (index < length) { start = data[index]; end = data[index + 1]; // Check if the code point is already in the set. if (codePoint >= start && codePoint < end) { return data; } if (codePoint == start - 1) { // Just replace `start` with a new value. data[index] = codePoint; return data; } // At this point, if `start` is `greater` than `codePoint`, insert a new // `[start, end]` pair before the current pair, or after the current pair // if there is a known `lastIndex`. if (start > codePoint) { data.splice( lastIndex != null ? lastIndex + 2 : 0, 0, codePoint, codePoint + 1 ); return data; } if (codePoint == end) { // Check if adding this code point causes two separate ranges to become // a single range, e.g. `dataAdd([0, 4, 5, 10], 4)` → `[0, 10]`. if (codePoint + 1 == data[index + 2]) { data.splice(index, 4, start, data[index + 3]); return data; } // Else, just replace `end` with a new value. data[index + 1] = codePoint + 1; return data; } lastIndex = index; index += 2; } // The loop has finished; add the new pair to the end of the data set. data.push(codePoint, codePoint + 1); return data; }; var dataAddData = function(dataA, dataB) { // Iterate over the data per `(start, end)` pair. var index = 0; var start; var end; var data = dataA.slice(); var length = dataB.length; while (index < length) { start = dataB[index]; end = dataB[index + 1] - 1; if (start == end) { data = dataAdd(data, start); } else { data = dataAddRange(data, start, end); } index += 2; } return data; }; var dataRemoveData = function(dataA, dataB) { // Iterate over the data per `(start, end)` pair. var index = 0; var start; var end; var data = dataA.slice(); var length = dataB.length; while (index < length) { start = dataB[index]; end = dataB[index + 1] - 1; if (start == end) { data = dataRemove(data, start); } else { data = dataRemoveRange(data, start, end); } index += 2; } return data; }; var dataAddRange = function(data, rangeStart, rangeEnd) { if (rangeEnd < rangeStart) { throw Error(ERRORS.rangeOrder); } if ( rangeStart < 0x0 || rangeStart > 0x10FFFF || rangeEnd < 0x0 || rangeEnd > 0x10FFFF ) { throw RangeError(ERRORS.codePointRange); } // Iterate over the data per `(start, end)` pair. var index = 0; var start; var end; var added = false; var length = data.length; while (index < length) { start = data[index]; end = data[index + 1]; if (added) { // The range has already been added to the set; at this point, we just // need to get rid of the following ranges in case they overlap. // Check if this range can be combined with the previous range. if (start == rangeEnd + 1) { data.splice(index - 1, 2); return data; } // Exit as soon as no more possibly overlapping pairs can be found. if (start > rangeEnd) { return data; } // E.g. `[0, 11, 12, 16]` and we’ve added 5-15, so we now have // `[0, 16, 12, 16]`. Remove the `12,16` part, as it lies within the // `0,16` range that was previously added. if (start >= rangeStart && start <= rangeEnd) { // `start` lies within the range that was previously added. if (end > rangeStart && end - 1 <= rangeEnd) { // `end` lies within the range that was previously added as well, // so remove this pair. data.splice(index, 2); index -= 2; // Note: we cannot `return` just yet, as there may still be other // overlapping pairs. } else { // `start` lies within the range that was previously added, but // `end` doesn’t. E.g. `[0, 11, 12, 31]` and we’ve added 5-15, so // now we have `[0, 16, 12, 31]`. This must be written as `[0, 31]`. // Remove the previously added `end` and the current `start`. data.splice(index - 1, 2); index -= 2; } // Note: we cannot return yet. } } else if (start == rangeEnd + 1) { data[index] = rangeStart; return data; } // Check if a new pair must be inserted *before* the current one. else if (start > rangeEnd) { data.splice(index, 0, rangeStart, rangeEnd + 1); return data; } else if (rangeStart >= start && rangeStart < end && rangeEnd + 1 <= end) { // The new range lies entirely within an existing range pair. No action // needed. return data; } else if ( // E.g. `[0, 11]` and you add 5-15 → `[0, 16]`. (rangeStart >= start && rangeStart < end) || // E.g. `[0, 3]` and you add 3-6 → `[0, 7]`. end == rangeStart ) { // Replace `end` with the new value. data[index + 1] = rangeEnd + 1; // Make sure the next range pair doesn’t overlap, e.g. `[0, 11, 12, 14]` // and you add 5-15 → `[0, 16]`, i.e. remove the `12,14` part. added = true; // Note: we cannot `return` just yet. } else if (rangeStart <= start && rangeEnd + 1 >= end) { // The new range is a superset of the old range. data[index] = rangeStart; data[index + 1] = rangeEnd + 1; added = true; } index += 2; } // The loop has finished without doing anything; add the new pair to the end // of the data set. if (!added) { data.push(rangeStart, rangeEnd + 1); } return data; }; var dataContains = function(data, codePoint) { var index = 0; var length = data.length; // Exit early if `codePoint` is not within `data`’s overall range. var start = data[index]; var end = data[length - 1]; if (length >= 2) { if (codePoint < start || codePoint > end) { return false; } } // Iterate over the data per `(start, end)` pair. while (index < length) { start = data[index]; end = data[index + 1]; if (codePoint >= start && codePoint < end) { return true; } index += 2; } return false; }; var dataIntersection = function(data, codePoints) { var index = 0; var length = codePoints.length; var codePoint; var result = []; while (index < length) { codePoint = codePoints[index]; if (dataContains(data, codePoint)) { result.push(codePoint); } ++index; } return dataFromCodePoints(result); }; var dataIsEmpty = function(data) { return !data.length; }; var dataIsSingleton = function(data) { // Check if the set only represents a single code point. return data.length == 2 && data[0] + 1 == data[1]; }; var dataToArray = function(data) { // Iterate over the data per `(start, end)` pair. var index = 0; var start; var end; var result = []; var length = data.length; while (index < length) { start = data[index]; end = data[index + 1]; while (start < end) { result.push(start); ++start; } index += 2; } return result; }; /*--------------------------------------------------------------------------*/ // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae var floor = Math.floor; var highSurrogate = function(codePoint) { return parseInt( floor((codePoint - 0x10000) / 0x400) + HIGH_SURROGATE_MIN, 10 ); }; var lowSurrogate = function(codePoint) { return parseInt( (codePoint - 0x10000) % 0x400 + LOW_SURROGATE_MIN, 10 ); }; var stringFromCharCode = String.fromCharCode; var codePointToString = function(codePoint) { var string; // https://mathiasbynens.be/notes/javascript-escapes#single // Note: the `\b` escape sequence for U+0008 BACKSPACE in strings has a // different meaning in regular expressions (word boundary), so it cannot // be used here. if (codePoint == 0x09) { string = '\\t'; } // Note: IE < 9 treats `'\v'` as `'v'`, so avoid using it. // else if (codePoint == 0x0B) { // string = '\\v'; // } else if (codePoint == 0x0A) { string = '\\n'; } else if (codePoint == 0x0C) { string = '\\f'; } else if (codePoint == 0x0D) { string = '\\r'; } else if (codePoint == 0x5C) { string = '\\\\'; } else if ( codePoint == 0x24 || (codePoint >= 0x28 && codePoint <= 0x2B) || codePoint == 0x2D || codePoint == 0x2E || codePoint == 0x3F || (codePoint >= 0x5B && codePoint <= 0x5E) || (codePoint >= 0x7B && codePoint <= 0x7D) ) { // The code point maps to an unsafe printable ASCII character; // backslash-escape it. Here’s the list of those symbols: // // $()*+-.?[\]^{|} // // See #7 for more info. string = '\\' + stringFromCharCode(codePoint); } else if (codePoint >= 0x20 && codePoint <= 0x7E) { // The code point maps to one of these printable ASCII symbols // (including the space character): // // !"#%&',/0123456789:;<=>@ABCDEFGHIJKLMNO // PQRSTUVWXYZ_`abcdefghijklmnopqrstuvwxyz~ // // These can safely be used directly. string = stringFromCharCode(codePoint); } else if (codePoint <= 0xFF) { // https://mathiasbynens.be/notes/javascript-escapes#hexadecimal string = '\\x' + pad(hex(codePoint), 2); } else { // `codePoint <= 0xFFFF` holds true. // https://mathiasbynens.be/notes/javascript-escapes#unicode string = '\\u' + pad(hex(codePoint), 4); } // There’s no need to account for astral symbols / surrogate pairs here, // since `codePointToString` is private and only used for BMP code points. // But if that’s what you need, just add an `else` block with this code: // // string = '\\u' + pad(hex(highSurrogate(codePoint)), 4) // + '\\u' + pad(hex(lowSurrogate(codePoint)), 4); return string; }; var symbolToCodePoint = function(symbol) { var length = symbol.length; var first = symbol.charCodeAt(0); var second; if ( first >= HIGH_SURROGATE_MIN && first <= HIGH_SURROGATE_MAX && length > 1 // There is a next code unit. ) { // `first` is a high surrogate, and there is a next character. Assume // it’s a low surrogate (else it’s invalid usage of Regenerate anyway). second = symbol.charCodeAt(1); // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae return (first - HIGH_SURROGATE_MIN) * 0x400 + second - LOW_SURROGATE_MIN + 0x10000; } return first; }; var createBMPCharacterClasses = function(data) { // Iterate over the data per `(start, end)` pair. var result = ''; var index = 0; var start; var end; var length = data.length; if (dataIsSingleton(data)) { return codePointToString(data[0]); } while (index < length) { start = data[index]; end = data[index + 1] - 1; // Note: the `- 1` makes `end` inclusive. if (start == end) { result += codePointToString(start); } else if (start + 1 == end) { result += codePointToString(start) + codePointToString(end); } else { result += codePointToString(start) + '-' + codePointToString(end); } index += 2; } return '[' + result + ']'; }; var splitAtBMP = function(data) { // Iterate over the data per `(start, end)` pair. var loneHighSurrogates = []; var loneLowSurrogates = []; var bmp = []; var astral = []; var index = 0; var start; var end; var length = data.length; while (index < length) { start = data[index]; end = data[index + 1] - 1; // Note: the `- 1` makes `end` inclusive. if (start < HIGH_SURROGATE_MIN) { // The range starts and ends before the high surrogate range. // E.g. (0, 0x10). if (end < HIGH_SURROGATE_MIN) { bmp.push(start, end + 1); } // The range starts before the high surrogate range and ends within it. // E.g. (0, 0xD855). if (end >= HIGH_SURROGATE_MIN && end <= HIGH_SURROGATE_MAX) { bmp.push(start, HIGH_SURROGATE_MIN); loneHighSurrogates.push(HIGH_SURROGATE_MIN, end + 1); } // The range starts before the high surrogate range and ends in the low // surrogate range. E.g. (0, 0xDCFF). if (end >= LOW_SURROGATE_MIN && end <= LOW_SURROGATE_MAX) { bmp.push(start, HIGH_SURROGATE_MIN); loneHighSurrogates.push(HIGH_SURROGATE_MIN, HIGH_SURROGATE_MAX + 1); loneLowSurrogates.push(LOW_SURROGATE_MIN, end + 1); } // The range starts before the high surrogate range and ends after the // low surrogate range. E.g. (0, 0x10FFFF). if (end > LOW_SURROGATE_MAX) { bmp.push(start, HIGH_SURROGATE_MIN); loneHighSurrogates.push(HIGH_SURROGATE_MIN, HIGH_SURROGATE_MAX + 1); loneLowSurrogates.push(LOW_SURROGATE_MIN, LOW_SURROGATE_MAX + 1); if (end <= 0xFFFF) { bmp.push(LOW_SURROGATE_MAX + 1, end + 1); } else { bmp.push(LOW_SURROGATE_MAX + 1, 0xFFFF + 1); astral.push(0xFFFF + 1, end + 1); } } } else if (start >= HIGH_SURROGATE_MIN && start <= HIGH_SURROGATE_MAX) { // The range starts and ends in the high surrogate range. // E.g. (0xD855, 0xD866). if (end >= HIGH_SURROGATE_MIN && end <= HIGH_SURROGATE_MAX) { loneHighSurrogates.push(start, end + 1); } // The range starts in the high surrogate range and ends in the low // surrogate range. E.g. (0xD855, 0xDCFF). if (end >= LOW_SURROGATE_MIN && end <= LOW_SURROGATE_MAX) { loneHighSurrogates.push(start, HIGH_SURROGATE_MAX + 1); loneLowSurrogates.push(LOW_SURROGATE_MIN, end + 1); } // The range starts in the high surrogate range and ends after the low // surrogate range. E.g. (0xD855, 0x10FFFF). if (end > LOW_SURROGATE_MAX) { loneHighSurrogates.push(start, HIGH_SURROGATE_MAX + 1); loneLowSurrogates.push(LOW_SURROGATE_MIN, LOW_SURROGATE_MAX + 1); if (end <= 0xFFFF) { bmp.push(LOW_SURROGATE_MAX + 1, end + 1); } else { bmp.push(LOW_SURROGATE_MAX + 1, 0xFFFF + 1); astral.push(0xFFFF + 1, end + 1); } } } else if (start >= LOW_SURROGATE_MIN && start <= LOW_SURROGATE_MAX) { // The range starts and ends in the low surrogate range. // E.g. (0xDCFF, 0xDDFF). if (end >= LOW_SURROGATE_MIN && end <= LOW_SURROGATE_MAX) { loneLowSurrogates.push(start, end + 1); } // The range starts in the low surrogate range and ends after the low // surrogate range. E.g. (0xDCFF, 0x10FFFF). if (end > LOW_SURROGATE_MAX) { loneLowSurrogates.push(start, LOW_SURROGATE_MAX + 1); if (end <= 0xFFFF) { bmp.push(LOW_SURROGATE_MAX + 1, end + 1); } else { bmp.push(LOW_SURROGATE_MAX + 1, 0xFFFF + 1); astral.push(0xFFFF + 1, end + 1); } } } else if (start > LOW_SURROGATE_MAX && start <= 0xFFFF) { // The range starts and ends after the low surrogate range. // E.g. (0xFFAA, 0x10FFFF). if (end <= 0xFFFF) { bmp.push(start, end + 1); } else { bmp.push(start, 0xFFFF + 1); astral.push(0xFFFF + 1, end + 1); } } else { // The range starts and ends in the astral range. astral.push(start, end + 1); } index += 2; } return { 'loneHighSurrogates': loneHighSurrogates, 'loneLowSurrogates': loneLowSurrogates, 'bmp': bmp, 'astral': astral }; }; var optimizeSurrogateMappings = function(surrogateMappings) { var result = []; var tmpLow = []; var addLow = false; var mapping; var nextMapping; var highSurrogates; var lowSurrogates; var nextHighSurrogates; var nextLowSurrogates; var index = -1; var length = surrogateMappings.length; while (++index < length) { mapping = surrogateMappings[index]; nextMapping = surrogateMappings[index + 1]; if (!nextMapping) { result.push(mapping); continue; } highSurrogates = mapping[0]; lowSurrogates = mapping[1]; nextHighSurrogates = nextMapping[0]; nextLowSurrogates = nextMapping[1]; // Check for identical high surrogate ranges. tmpLow = lowSurrogates; while ( nextHighSurrogates && highSurrogates[0] == nextHighSurrogates[0] && highSurrogates[1] == nextHighSurrogates[1] ) { // Merge with the next item. if (dataIsSingleton(nextLowSurrogates)) { tmpLow = dataAdd(tmpLow, nextLowSurrogates[0]); } else { tmpLow = dataAddRange( tmpLow, nextLowSurrogates[0], nextLowSurrogates[1] - 1 ); } ++index; mapping = surrogateMappings[index]; highSurrogates = mapping[0]; lowSurrogates = mapping[1]; nextMapping = surrogateMappings[index + 1]; nextHighSurrogates = nextMapping && nextMapping[0]; nextLowSurrogates = nextMapping && nextMapping[1]; addLow = true; } result.push([ highSurrogates, addLow ? tmpLow : lowSurrogates ]); addLow = false; } return optimizeByLowSurrogates(result); }; var optimizeByLowSurrogates = function(surrogateMappings) { if (surrogateMappings.length == 1) { return surrogateMappings; } var index = -1; var innerIndex = -1; while (++index < surrogateMappings.length) { var mapping = surrogateMappings[index]; var lowSurrogates = mapping[1]; var lowSurrogateStart = lowSurrogates[0]; var lowSurrogateEnd = lowSurrogates[1]; innerIndex = index; // Note: the loop starts at the next index. while (++innerIndex < surrogateMappings.length) { var otherMapping = surrogateMappings[innerIndex]; var otherLowSurrogates = otherMapping[1]; var otherLowSurrogateStart = otherLowSurrogates[0]; var otherLowSurrogateEnd = otherLowSurrogates[1]; if ( lowSurrogateStart == otherLowSurrogateStart && lowSurrogateEnd == otherLowSurrogateEnd ) { // Add the code points in the other item to this one. if (dataIsSingleton(otherMapping[0])) { mapping[0] = dataAdd(mapping[0], otherMapping[0][0]); } else { mapping[0] = dataAddRange( mapping[0], otherMapping[0][0], otherMapping[0][1] - 1 ); } // Remove the other, now redundant, item. surrogateMappings.splice(innerIndex, 1); --innerIndex; } } } return surrogateMappings; }; var surrogateSet = function(data) { // Exit early if `data` is an empty set. if (!data.length) { return []; } // Iterate over the data per `(start, end)` pair. var index = 0; var start; var end; var startHigh; var startLow; var prevStartHigh = 0; var prevEndHigh = 0; var tmpLow = []; var endHigh; var endLow; var surrogateMappings = []; var length = data.length; var dataHigh = []; while (index < length) { start = data[index]; end = data[index + 1] - 1; startHigh = highSurrogate(start); startLow = lowSurrogate(start); endHigh = highSurrogate(end); endLow = lowSurrogate(end); var startsWithLowestLowSurrogate = startLow == LOW_SURROGATE_MIN; var endsWithHighestLowSurrogate = endLow == LOW_SURROGATE_MAX; var complete = false; // Append the previous high-surrogate-to-low-surrogate mappings. // Step 1: `(startHigh, startLow)` to `(startHigh, LOW_SURROGATE_MAX)`. if ( startHigh == endHigh || startsWithLowestLowSurrogate && endsWithHighestLowSurrogate ) { surrogateMappings.push([ [startHigh, endHigh + 1], [startLow, endLow + 1] ]); complete = true; } else { surrogateMappings.push([ [startHigh, startHigh + 1], [startLow, LOW_SURROGATE_MAX + 1] ]); } // Step 2: `(startHigh + 1, LOW_SURROGATE_MIN)` to // `(endHigh - 1, LOW_SURROGATE_MAX)`. if (!complete && startHigh + 1 < endHigh) { if (endsWithHighestLowSurrogate) { // Combine step 2 and step 3. surrogateMappings.push([ [startHigh + 1, endHigh + 1], [LOW_SURROGATE_MIN, endLow + 1] ]); complete = true; } else { surrogateMappings.push([ [startHigh + 1, endHigh], [LOW_SURROGATE_MIN, LOW_SURROGATE_MAX + 1] ]); } } // Step 3. `(endHigh, LOW_SURROGATE_MIN)` to `(endHigh, endLow)`. if (!complete) { surrogateMappings.push([ [endHigh, endHigh + 1], [LOW_SURROGATE_MIN, endLow + 1] ]); } prevStartHigh = startHigh; prevEndHigh = endHigh; index += 2; } // The format of `surrogateMappings` is as follows: // // [ surrogateMapping1, surrogateMapping2 ] // // i.e.: // // [ // [ highSurrogates1, lowSurrogates1 ], // [ highSurrogates2, lowSurrogates2 ] // ] return optimizeSurrogateMappings(surrogateMappings); }; var createSurrogateCharacterClasses = function(surrogateMappings) { var result = []; forEach(surrogateMappings, function(surrogateMapping) { var highSurrogates = surrogateMapping[0]; var lowSurrogates = surrogateMapping[1]; result.push( createBMPCharacterClasses(highSurrogates) + createBMPCharacterClasses(lowSurrogates) ); }); return result.join('|'); }; var createCharacterClassesFromData = function(data, bmpOnly) { var result = []; var parts = splitAtBMP(data); var loneHighSurrogates = parts.loneHighSurrogates; var loneLowSurrogates = parts.loneLowSurrogates; var bmp = parts.bmp; var astral = parts.astral; var hasAstral = !dataIsEmpty(parts.astral); var hasLoneHighSurrogates = !dataIsEmpty(loneHighSurrogates); var hasLoneLowSurrogates = !dataIsEmpty(loneLowSurrogates); var surrogateMappings = surrogateSet(astral); if (bmpOnly) { bmp = dataAddData(bmp, loneHighSurrogates); hasLoneHighSurrogates = false; bmp = dataAddData(bmp, loneLowSurrogates); hasLoneLowSurrogates = false; } if (!dataIsEmpty(bmp)) { // The data set contains BMP code points that are not high surrogates // needed for astral code points in the set. result.push(createBMPCharacterClasses(bmp)); } if (surrogateMappings.length) { // The data set contains astral code points; append character classes // based on their surrogate pairs. result.push(createSurrogateCharacterClasses(surrogateMappings)); } // https://gist.github.com/mathiasbynens/bbe7f870208abcfec860 if (hasLoneHighSurrogates) { result.push( createBMPCharacterClasses(loneHighSurrogates) + // Make sure the high surrogates aren’t part of a surrogate pair. '(?![\\uDC00-\\uDFFF])' ); } if (hasLoneLowSurrogates) { result.push( // Make sure the low surrogates aren’t part of a surrogate pair. '(?:[^\\uD800-\\uDBFF]|^)' + createBMPCharacterClasses(loneLowSurrogates) ); } return result.join('|'); }; /*--------------------------------------------------------------------------*/ // `regenerate` can be used as a constructor (and new methods can be added to // its prototype) but also as a regular function, the latter of which is the // documented and most common usage. For that reason, it’s not capitalized. var regenerate = function(value) { if (arguments.length > 1) { value = slice.call(arguments); } if (this instanceof regenerate) { this.data = []; return value ? this.add(value) : this; } return (new regenerate).add(value); }; regenerate.version = '1.2.0'; var proto = regenerate.prototype; extend(proto, { 'add': function(value) { var $this = this; if (value == null) { return $this; } if (value instanceof regenerate) { // Allow passing other Regenerate instances. $this.data = dataAddData($this.data, value.data); return $this; } if (arguments.length > 1) { value = slice.call(arguments); } if (isArray(value)) { forEach(value, function(item) { $this.add(item); }); return $this; } $this.data = dataAdd( $this.data, isNumber(value) ? value : symbolToCodePoint(value) ); return $this; }, 'remove': function(value) { var $this = this; if (value == null) { return $this; } if (value instanceof regenerate) { // Allow passing other Regenerate instances. $this.data = dataRemoveData($this.data, value.data); return $this; } if (arguments.length > 1) { value = slice.call(arguments); } if (isArray(value)) { forEach(value, function(item) { $this.remove(item); }); return $this; } $this.data = dataRemove( $this.data, isNumber(value) ? value : symbolToCodePoint(value) ); return $this; }, 'addRange': function(start, end) { var $this = this; $this.data = dataAddRange($this.data, isNumber(start) ? start : symbolToCodePoint(start), isNumber(end) ? end : symbolToCodePoint(end) ); return $this; }, 'removeRange': function(start, end) { var $this = this; var startCodePoint = isNumber(start) ? start : symbolToCodePoint(start); var endCodePoint = isNumber(end) ? end : symbolToCodePoint(end); $this.data = dataRemoveRange( $this.data, startCodePoint, endCodePoint ); return $this; }, 'intersection': function(argument) { var $this = this; // Allow passing other Regenerate instances. // TODO: Optimize this by writing and using `dataIntersectionData()`. var array = argument instanceof regenerate ? dataToArray(argument.data) : argument; $this.data = dataIntersection($this.data, array); return $this; }, 'contains': function(codePoint) { return dataContains( this.data, isNumber(codePoint) ? codePoint : symbolToCodePoint(codePoint) ); }, 'clone': function() { var set = new regenerate; set.data = this.data.slice(0); return set; }, 'toString': function(options) { var result = createCharacterClassesFromData( this.data, options ? options.bmpOnly : false ); // Use `\0` instead of `\x00` where possible. return result.replace(regexNull, '\\0$1'); }, 'toRegExp': function(flags) { return RegExp(this.toString(), flags || ''); }, 'valueOf': function() { // Note: `valueOf` is aliased as `toArray`. return dataToArray(this.data); } }); proto.toArray = proto.valueOf; // Some AMD build optimizers, like r.js, check for specific condition patterns // like the following: if ( typeof define == 'function' && typeof define.amd == 'object' && define.amd ) { define(function() { return regenerate; }); } else if (freeExports && !freeExports.nodeType) { if (freeModule) { // in Node.js, io.js, or RingoJS v0.8.0+ freeModule.exports = regenerate; } else { // in Narwhal or RingoJS v0.7.0- freeExports.regenerate = regenerate; } } else { // in Rhino or a web browser root.regenerate = regenerate; } }(this)); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],476:[function(require,module,exports){ (function (global){ /*! * RegJSGen * Copyright 2014 Benjamin Tan * Available under MIT license */ ;(function() { 'use strict'; /** Used to determine if values are of the language type `Object` */ var objectTypes = { 'function': true, 'object': true }; /** Used as a reference to the global object */ var root = (objectTypes[typeof window] && window) || this; /** Backup possible global object */ var oldRoot = root; /** Detect free variable `exports` */ var freeExports = objectTypes[typeof exports] && exports; /** Detect free variable `module` */ var freeModule = objectTypes[typeof module] && module && !module.nodeType && module; /** Detect free variable `global` from Node.js or Browserified code and use it as `root` */ var freeGlobal = freeExports && freeModule && typeof global == 'object' && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal)) { root = freeGlobal; } /*--------------------------------------------------------------------------*/ /*! Based on https://mths.be/fromcodepoint v0.2.0 by @mathias */ var stringFromCharCode = String.fromCharCode; var floor = Math.floor; function fromCodePoint() { var MAX_SIZE = 0x4000; var codeUnits = []; var highSurrogate; var lowSurrogate; var index = -1; var length = arguments.length; if (!length) { return ''; } var result = ''; while (++index < length) { var codePoint = Number(arguments[index]); if ( !isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity` codePoint < 0 || // not a valid Unicode code point codePoint > 0x10FFFF || // not a valid Unicode code point floor(codePoint) != codePoint // not an integer ) { throw RangeError('Invalid code point: ' + codePoint); } if (codePoint <= 0xFFFF) { // BMP code point codeUnits.push(codePoint); } else { // Astral code point; split in surrogate halves // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae codePoint -= 0x10000; highSurrogate = (codePoint >> 10) + 0xD800; lowSurrogate = (codePoint % 0x400) + 0xDC00; codeUnits.push(highSurrogate, lowSurrogate); } if (index + 1 == length || codeUnits.length > MAX_SIZE) { result += stringFromCharCode.apply(null, codeUnits); codeUnits.length = 0; } } return result; } function assertType(type, expected) { if (expected.indexOf('|') == -1) { if (type == expected) { return; } throw Error('Invalid node type: ' + type); } expected = assertType.hasOwnProperty(expected) ? assertType[expected] : (assertType[expected] = RegExp('^(?:' + expected + ')$')); if (expected.test(type)) { return; } throw Error('Invalid node type: ' + type); } /*--------------------------------------------------------------------------*/ function generate(node) { var type = node.type; if (generate.hasOwnProperty(type) && typeof generate[type] == 'function') { return generate[type](node); } throw Error('Invalid node type: ' + type); } /*--------------------------------------------------------------------------*/ function generateAlternative(node) { assertType(node.type, 'alternative'); var terms = node.body, length = terms ? terms.length : 0; if (length == 1) { return generateTerm(terms[0]); } else { var i = -1, result = ''; while (++i < length) { result += generateTerm(terms[i]); } return result; } } function generateAnchor(node) { assertType(node.type, 'anchor'); switch (node.kind) { case 'start': return '^'; case 'end': return '$'; case 'boundary': return '\\b'; case 'not-boundary': return '\\B'; default: throw Error('Invalid assertion'); } } function generateAtom(node) { assertType(node.type, 'anchor|characterClass|characterClassEscape|dot|group|reference|value'); return generate(node); } function generateCharacterClass(node) { assertType(node.type, 'characterClass'); var classRanges = node.body, length = classRanges ? classRanges.length : 0; var i = -1, result = '['; if (node.negative) { result += '^'; } while (++i < length) { result += generateClassAtom(classRanges[i]); } result += ']'; return result; } function generateCharacterClassEscape(node) { assertType(node.type, 'characterClassEscape'); return '\\' + node.value; } function generateCharacterClassRange(node) { assertType(node.type, 'characterClassRange'); var min = node.min, max = node.max; if (min.type == 'characterClassRange' || max.type == 'characterClassRange') { throw Error('Invalid character class range'); } return generateClassAtom(min) + '-' + generateClassAtom(max); } function generateClassAtom(node) { assertType(node.type, 'anchor|characterClassEscape|characterClassRange|dot|value'); return generate(node); } function generateDisjunction(node) { assertType(node.type, 'disjunction'); var body = node.body, length = body ? body.length : 0; if (length == 0) { throw Error('No body'); } else if (length == 1) { return generate(body[0]); } else { var i = -1, result = ''; while (++i < length) { if (i != 0) { result += '|'; } result += generate(body[i]); } return result; } } function generateDot(node) { assertType(node.type, 'dot'); return '.'; } function generateGroup(node) { assertType(node.type, 'group'); var result = '('; switch (node.behavior) { case 'normal': break; case 'ignore': result += '?:'; break; case 'lookahead': result += '?='; break; case 'negativeLookahead': result += '?!'; break; default: throw Error('Invalid behaviour: ' + node.behaviour); } var body = node.body, length = body ? body.length : 0; if (length == 1) { result += generate(body[0]); } else { var i = -1; while (++i < length) { result += generate(body[i]); } } result += ')'; return result; } function generateQuantifier(node) { assertType(node.type, 'quantifier'); var quantifier = '', min = node.min, max = node.max; switch (max) { case undefined: case null: switch (min) { case 0: quantifier = '*' break; case 1: quantifier = '+'; break; default: quantifier = '{' + min + ',}'; break; } break; default: if (min == max) { quantifier = '{' + min + '}'; } else if (min == 0 && max == 1) { quantifier = '?'; } else { quantifier = '{' + min + ',' + max + '}'; } break; } if (!node.greedy) { quantifier += '?'; } return generateAtom(node.body[0]) + quantifier; } function generateReference(node) { assertType(node.type, 'reference'); return '\\' + node.matchIndex; } function generateTerm(node) { assertType(node.type, 'anchor|characterClass|characterClassEscape|empty|group|quantifier|reference|value'); return generate(node); } function generateValue(node) { assertType(node.type, 'value'); var kind = node.kind, codePoint = node.codePoint; switch (kind) { case 'controlLetter': return '\\c' + fromCodePoint(codePoint + 64); case 'hexadecimalEscape': return '\\x' + ('00' + codePoint.toString(16).toUpperCase()).slice(-2); case 'identifier': return '\\' + fromCodePoint(codePoint); case 'null': return '\\' + codePoint; case 'octal': return '\\' + codePoint.toString(8); case 'singleEscape': switch (codePoint) { case 0x0008: return '\\b'; case 0x009: return '\\t'; case 0x00A: return '\\n'; case 0x00B: return '\\v'; case 0x00C: return '\\f'; case 0x00D: return '\\r'; default: throw Error('Invalid codepoint: ' + codePoint); } case 'symbol': return fromCodePoint(codePoint); case 'unicodeEscape': return '\\u' + ('0000' + codePoint.toString(16).toUpperCase()).slice(-4); case 'unicodeCodePointEscape': return '\\u{' + codePoint.toString(16).toUpperCase() + '}'; default: throw Error('Unsupported node kind: ' + kind); } } /*--------------------------------------------------------------------------*/ generate.alternative = generateAlternative; generate.anchor = generateAnchor; generate.characterClass = generateCharacterClass; generate.characterClassEscape = generateCharacterClassEscape; generate.characterClassRange = generateCharacterClassRange; generate.disjunction = generateDisjunction; generate.dot = generateDot; generate.group = generateGroup; generate.quantifier = generateQuantifier; generate.reference = generateReference; generate.value = generateValue; /*--------------------------------------------------------------------------*/ // export regjsgen // some AMD build optimizers, like r.js, check for condition patterns like the following: if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { // define as an anonymous module so, through path mapping, it can be aliased define(function() { return { 'generate': generate }; }); } // check for `exports` after `define` in case a build optimizer adds an `exports` object else if (freeExports && freeModule) { // in Narwhal, Node.js, Rhino -require, or RingoJS freeExports.generate = generate; } // in a browser or Rhino else { root.regjsgen = { 'generate': generate }; } }.call(this)); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],477:[function(require,module,exports){ // regjsparser // // ================================================================== // // See ECMA-262 Standard: 15.10.1 // // NOTE: The ECMA-262 standard uses the term "Assertion" for /^/. Here the // term "Anchor" is used. // // Pattern :: // Disjunction // // Disjunction :: // Alternative // Alternative | Disjunction // // Alternative :: // [empty] // Alternative Term // // Term :: // Anchor // Atom // Atom Quantifier // // Anchor :: // ^ // $ // \ b // \ B // ( ? = Disjunction ) // ( ? ! Disjunction ) // // Quantifier :: // QuantifierPrefix // QuantifierPrefix ? // // QuantifierPrefix :: // * // + // ? // { DecimalDigits } // { DecimalDigits , } // { DecimalDigits , DecimalDigits } // // Atom :: // PatternCharacter // . // \ AtomEscape // CharacterClass // ( Disjunction ) // ( ? : Disjunction ) // // PatternCharacter :: // SourceCharacter but not any of: ^ $ \ . * + ? ( ) [ ] { } | // // AtomEscape :: // DecimalEscape // CharacterEscape // CharacterClassEscape // // CharacterEscape[U] :: // ControlEscape // c ControlLetter // HexEscapeSequence // RegExpUnicodeEscapeSequence[?U] (ES6) // IdentityEscape[?U] // // ControlEscape :: // one of f n r t v // ControlLetter :: // one of // a b c d e f g h i j k l m n o p q r s t u v w x y z // A B C D E F G H I J K L M N O P Q R S T U V W X Y Z // // IdentityEscape :: // SourceCharacter but not IdentifierPart // // // // DecimalEscape :: // DecimalIntegerLiteral [lookahead ∉ DecimalDigit] // // CharacterClassEscape :: // one of d D s S w W // // CharacterClass :: // [ [lookahead ∉ {^}] ClassRanges ] // [ ^ ClassRanges ] // // ClassRanges :: // [empty] // NonemptyClassRanges // // NonemptyClassRanges :: // ClassAtom // ClassAtom NonemptyClassRangesNoDash // ClassAtom - ClassAtom ClassRanges // // NonemptyClassRangesNoDash :: // ClassAtom // ClassAtomNoDash NonemptyClassRangesNoDash // ClassAtomNoDash - ClassAtom ClassRanges // // ClassAtom :: // - // ClassAtomNoDash // // ClassAtomNoDash :: // SourceCharacter but not one of \ or ] or - // \ ClassEscape // // ClassEscape :: // DecimalEscape // b // CharacterEscape // CharacterClassEscape (function() { function parse(str, flags) { function addRaw(node) { node.raw = str.substring(node.range[0], node.range[1]); return node; } function updateRawStart(node, start) { node.range[0] = start; return addRaw(node); } function createAnchor(kind, rawLength) { return addRaw({ type: 'anchor', kind: kind, range: [ pos - rawLength, pos ] }); } function createValue(kind, codePoint, from, to) { return addRaw({ type: 'value', kind: kind, codePoint: codePoint, range: [from, to] }); } function createEscaped(kind, codePoint, value, fromOffset) { fromOffset = fromOffset || 0; return createValue(kind, codePoint, pos - (value.length + fromOffset), pos); } function createCharacter(matches) { var _char = matches[0]; var first = _char.charCodeAt(0); if (hasUnicodeFlag) { var second; if (_char.length === 1 && first >= 0xD800 && first <= 0xDBFF) { second = lookahead().charCodeAt(0); if (second >= 0xDC00 && second <= 0xDFFF) { // Unicode surrogate pair pos++; return createValue( 'symbol', (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000, pos - 2, pos); } } } return createValue('symbol', first, pos - 1, pos); } function createDisjunction(alternatives, from, to) { return addRaw({ type: 'disjunction', body: alternatives, range: [ from, to ] }); } function createDot() { return addRaw({ type: 'dot', range: [ pos - 1, pos ] }); } function createCharacterClassEscape(value) { return addRaw({ type: 'characterClassEscape', value: value, range: [ pos - 2, pos ] }); } function createReference(matchIndex) { return addRaw({ type: 'reference', matchIndex: parseInt(matchIndex, 10), range: [ pos - 1 - matchIndex.length, pos ] }); } function createGroup(behavior, disjunction, from, to) { return addRaw({ type: 'group', behavior: behavior, body: disjunction, range: [ from, to ] }); } function createQuantifier(min, max, from, to) { if (to == null) { from = pos - 1; to = pos; } return addRaw({ type: 'quantifier', min: min, max: max, greedy: true, body: null, // set later on, range: [ from, to ] }); } function createAlternative(terms, from, to) { return addRaw({ type: 'alternative', body: terms, range: [ from, to ] }); } function createCharacterClass(classRanges, negative, from, to) { return addRaw({ type: 'characterClass', body: classRanges, negative: negative, range: [ from, to ] }); } function createClassRange(min, max, from, to) { // See 15.10.2.15: if (min.codePoint > max.codePoint) { throw SyntaxError('invalid range in character class'); } return addRaw({ type: 'characterClassRange', min: min, max: max, range: [ from, to ] }); } function flattenBody(body) { if (body.type === 'alternative') { return body.body; } else { return [body]; } } function isEmpty(obj) { return obj.type === 'empty'; } function incr(amount) { amount = (amount || 1); var res = str.substring(pos, pos + amount); pos += (amount || 1); return res; } function skip(value) { if (!match(value)) { throw SyntaxError('character: ' + value); } } function match(value) { if (str.indexOf(value, pos) === pos) { return incr(value.length); } } function lookahead() { return str[pos]; } function current(value) { return str.indexOf(value, pos) === pos; } function next(value) { return str[pos + 1] === value; } function matchReg(regExp) { var subStr = str.substring(pos); var res = subStr.match(regExp); if (res) { res.range = []; res.range[0] = pos; incr(res[0].length); res.range[1] = pos; } return res; } function parseDisjunction() { // Disjunction :: // Alternative // Alternative | Disjunction var res = [], from = pos; res.push(parseAlternative()); while (match('|')) { res.push(parseAlternative()); } if (res.length === 1) { return res[0]; } return createDisjunction(res, from, pos); } function parseAlternative() { var res = [], from = pos; var term; // Alternative :: // [empty] // Alternative Term while (term = parseTerm()) { res.push(term); } if (res.length === 1) { return res[0]; } return createAlternative(res, from, pos); } function parseTerm() { // Term :: // Anchor // Atom // Atom Quantifier if (pos >= str.length || current('|') || current(')')) { return null; /* Means: The term is empty */ } var anchor = parseAnchor(); if (anchor) { return anchor; } var atom = parseAtom(); if (!atom) { throw SyntaxError('Expected atom') } var quantifier = parseQuantifier() || false; if (quantifier) { quantifier.body = flattenBody(atom); // The quantifier contains the atom. Therefore, the beginning of the // quantifier range is given by the beginning of the atom. updateRawStart(quantifier, atom.range[0]); return quantifier; } return atom; } function parseGroup(matchA, typeA, matchB, typeB) { var type = null, from = pos; if (match(matchA)) { type = typeA; } else if (match(matchB)) { type = typeB; } else { return false; } var body = parseDisjunction(); if (!body) { throw SyntaxError('Expected disjunction'); } skip(')'); var group = createGroup(type, flattenBody(body), from, pos); if (type == 'normal') { // Keep track of the number of closed groups. This is required for // parseDecimalEscape(). In case the string is parsed a second time the // value already holds the total count and no incrementation is required. if (firstIteration) { closedCaptureCounter++; } } return group; } function parseAnchor() { // Anchor :: // ^ // $ // \ b // \ B // ( ? = Disjunction ) // ( ? ! Disjunction ) var res, from = pos; if (match('^')) { return createAnchor('start', 1 /* rawLength */); } else if (match('$')) { return createAnchor('end', 1 /* rawLength */); } else if (match('\\b')) { return createAnchor('boundary', 2 /* rawLength */); } else if (match('\\B')) { return createAnchor('not-boundary', 2 /* rawLength */); } else { return parseGroup('(?=', 'lookahead', '(?!', 'negativeLookahead'); } } function parseQuantifier() { // Quantifier :: // QuantifierPrefix // QuantifierPrefix ? // // QuantifierPrefix :: // * // + // ? // { DecimalDigits } // { DecimalDigits , } // { DecimalDigits , DecimalDigits } var res; var quantifier; var min, max; if (match('*')) { quantifier = createQuantifier(0); } else if (match('+')) { quantifier = createQuantifier(1); } else if (match('?')) { quantifier = createQuantifier(0, 1); } else if (res = matchReg(/^\{([0-9]+)\}/)) { min = parseInt(res[1], 10); quantifier = createQuantifier(min, min, res.range[0], res.range[1]); } else if (res = matchReg(/^\{([0-9]+),\}/)) { min = parseInt(res[1], 10); quantifier = createQuantifier(min, undefined, res.range[0], res.range[1]); } else if (res = matchReg(/^\{([0-9]+),([0-9]+)\}/)) { min = parseInt(res[1], 10); max = parseInt(res[2], 10); if (min > max) { throw SyntaxError('numbers out of order in {} quantifier'); } quantifier = createQuantifier(min, max, res.range[0], res.range[1]); } if (quantifier) { if (match('?')) { quantifier.greedy = false; quantifier.range[1] += 1; } } return quantifier; } function parseAtom() { // Atom :: // PatternCharacter // . // \ AtomEscape // CharacterClass // ( Disjunction ) // ( ? : Disjunction ) var res; // jviereck: allow ']', '}' here as well to be compatible with browser's // implementations: ']'.match(/]/); // if (res = matchReg(/^[^^$\\.*+?()[\]{}|]/)) { if (res = matchReg(/^[^^$\\.*+?(){[|]/)) { // PatternCharacter return createCharacter(res); } else if (match('.')) { // . return createDot(); } else if (match('\\')) { // \ AtomEscape res = parseAtomEscape(); if (!res) { throw SyntaxError('atomEscape'); } return res; } else if (res = parseCharacterClass()) { return res; } else { // ( Disjunction ) // ( ? : Disjunction ) return parseGroup('(?:', 'ignore', '(', 'normal'); } } function parseUnicodeSurrogatePairEscape(firstEscape) { if (hasUnicodeFlag) { var first, second; if (firstEscape.kind == 'unicodeEscape' && (first = firstEscape.codePoint) >= 0xD800 && first <= 0xDBFF && current('\\') && next('u') ) { var prevPos = pos; pos++; var secondEscape = parseClassEscape(); if (secondEscape.kind == 'unicodeEscape' && (second = secondEscape.codePoint) >= 0xDC00 && second <= 0xDFFF) { // Unicode surrogate pair firstEscape.range[1] = secondEscape.range[1]; firstEscape.codePoint = (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; firstEscape.type = 'value'; firstEscape.kind = 'unicodeCodePointEscape'; addRaw(firstEscape); } else { pos = prevPos; } } } return firstEscape; } function parseClassEscape() { return parseAtomEscape(true); } function parseAtomEscape(insideCharacterClass) { // AtomEscape :: // DecimalEscape // CharacterEscape // CharacterClassEscape var res; res = parseDecimalEscape(); if (res) { return res; } // For ClassEscape if (insideCharacterClass) { if (match('b')) { // 15.10.2.19 // The production ClassEscape :: b evaluates by returning the // CharSet containing the one character (Unicode value 0008). return createEscaped('singleEscape', 0x0008, '\\b'); } else if (match('B')) { throw SyntaxError('\\B not possible inside of CharacterClass'); } } res = parseCharacterEscape(); return res; } function parseDecimalEscape() { // DecimalEscape :: // DecimalIntegerLiteral [lookahead ∉ DecimalDigit] // CharacterClassEscape :: one of d D s S w W var res, match; if (res = matchReg(/^(?!0)\d+/)) { match = res[0]; var refIdx = parseInt(res[0], 10); if (refIdx <= closedCaptureCounter) { // If the number is smaller than the normal-groups found so // far, then it is a reference... return createReference(res[0]); } else { // ... otherwise it needs to be interpreted as a octal (if the // number is in an octal format). If it is NOT octal format, // then the slash is ignored and the number is matched later // as normal characters. // Recall the negative decision to decide if the input must be parsed // a second time with the total normal-groups. backrefDenied.push(refIdx); // Reset the position again, as maybe only parts of the previous // matched numbers are actual octal numbers. E.g. in '019' only // the '01' should be matched. incr(-res[0].length); if (res = matchReg(/^[0-7]{1,3}/)) { return createEscaped('octal', parseInt(res[0], 8), res[0], 1); } else { // If we end up here, we have a case like /\91/. Then the // first slash is to be ignored and the 9 & 1 to be treated // like ordinary characters. Create a character for the // first number only here - other number-characters // (if available) will be matched later. res = createCharacter(matchReg(/^[89]/)); return updateRawStart(res, res.range[0] - 1); } } } // Only allow octal numbers in the following. All matched numbers start // with a zero (if the do not, the previous if-branch is executed). // If the number is not octal format and starts with zero (e.g. `091`) // then only the zeros `0` is treated here and the `91` are ordinary // characters. // Example: // /\091/.exec('\091')[0].length === 3 else if (res = matchReg(/^[0-7]{1,3}/)) { match = res[0]; if (/^0{1,3}$/.test(match)) { // If they are all zeros, then only take the first one. return createEscaped('null', 0x0000, '0', match.length + 1); } else { return createEscaped('octal', parseInt(match, 8), match, 1); } } else if (res = matchReg(/^[dDsSwW]/)) { return createCharacterClassEscape(res[0]); } return false; } function parseCharacterEscape() { // CharacterEscape :: // ControlEscape // c ControlLetter // HexEscapeSequence // UnicodeEscapeSequence // IdentityEscape var res; if (res = matchReg(/^[fnrtv]/)) { // ControlEscape var codePoint = 0; switch (res[0]) { case 't': codePoint = 0x009; break; case 'n': codePoint = 0x00A; break; case 'v': codePoint = 0x00B; break; case 'f': codePoint = 0x00C; break; case 'r': codePoint = 0x00D; break; } return createEscaped('singleEscape', codePoint, '\\' + res[0]); } else if (res = matchReg(/^c([a-zA-Z])/)) { // c ControlLetter return createEscaped('controlLetter', res[1].charCodeAt(0) % 32, res[1], 2); } else if (res = matchReg(/^x([0-9a-fA-F]{2})/)) { // HexEscapeSequence return createEscaped('hexadecimalEscape', parseInt(res[1], 16), res[1], 2); } else if (res = matchReg(/^u([0-9a-fA-F]{4})/)) { // UnicodeEscapeSequence return parseUnicodeSurrogatePairEscape( createEscaped('unicodeEscape', parseInt(res[1], 16), res[1], 2) ); } else if (hasUnicodeFlag && (res = matchReg(/^u\{([0-9a-fA-F]+)\}/))) { // RegExpUnicodeEscapeSequence (ES6 Unicode code point escape) return createEscaped('unicodeCodePointEscape', parseInt(res[1], 16), res[1], 4); } else { // IdentityEscape return parseIdentityEscape(); } } // Taken from the Esprima parser. function isIdentifierPart(ch) { // Generated by `tools/generate-identifier-regex.js`. var NonAsciiIdentifierPart = new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]'); return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore) (ch >= 65 && ch <= 90) || // A..Z (ch >= 97 && ch <= 122) || // a..z (ch >= 48 && ch <= 57) || // 0..9 (ch === 92) || // \ (backslash) ((ch >= 0x80) && NonAsciiIdentifierPart.test(String.fromCharCode(ch))); } function parseIdentityEscape() { // IdentityEscape :: // SourceCharacter but not IdentifierPart // // var ZWJ = '\u200C'; var ZWNJ = '\u200D'; var res; var tmp; if (!isIdentifierPart(lookahead())) { tmp = incr(); return createEscaped('identifier', tmp.charCodeAt(0), tmp, 1); } if (match(ZWJ)) { // return createEscaped('identifier', 0x200C, ZWJ); } else if (match(ZWNJ)) { // return createEscaped('identifier', 0x200D, ZWNJ); } return null; } function parseCharacterClass() { // CharacterClass :: // [ [lookahead ∉ {^}] ClassRanges ] // [ ^ ClassRanges ] var res, from = pos; if (res = matchReg(/^\[\^/)) { res = parseClassRanges(); skip(']'); return createCharacterClass(res, true, from, pos); } else if (match('[')) { res = parseClassRanges(); skip(']'); return createCharacterClass(res, false, from, pos); } return null; } function parseClassRanges() { // ClassRanges :: // [empty] // NonemptyClassRanges var res; if (current(']')) { // Empty array means nothing insinde of the ClassRange. return []; } else { res = parseNonemptyClassRanges(); if (!res) { throw SyntaxError('nonEmptyClassRanges'); } return res; } } function parseHelperClassRanges(atom) { var from, to, res; if (current('-') && !next(']')) { // ClassAtom - ClassAtom ClassRanges skip('-'); res = parseClassAtom(); if (!res) { throw SyntaxError('classAtom'); } to = pos; var classRanges = parseClassRanges(); if (!classRanges) { throw SyntaxError('classRanges'); } from = atom.range[0]; if (classRanges.type === 'empty') { return [createClassRange(atom, res, from, to)]; } return [createClassRange(atom, res, from, to)].concat(classRanges); } res = parseNonemptyClassRangesNoDash(); if (!res) { throw SyntaxError('nonEmptyClassRangesNoDash'); } return [atom].concat(res); } function parseNonemptyClassRanges() { // NonemptyClassRanges :: // ClassAtom // ClassAtom NonemptyClassRangesNoDash // ClassAtom - ClassAtom ClassRanges var atom = parseClassAtom(); if (!atom) { throw SyntaxError('classAtom'); } if (current(']')) { // ClassAtom return [atom]; } // ClassAtom NonemptyClassRangesNoDash // ClassAtom - ClassAtom ClassRanges return parseHelperClassRanges(atom); } function parseNonemptyClassRangesNoDash() { // NonemptyClassRangesNoDash :: // ClassAtom // ClassAtomNoDash NonemptyClassRangesNoDash // ClassAtomNoDash - ClassAtom ClassRanges var res = parseClassAtom(); if (!res) { throw SyntaxError('classAtom'); } if (current(']')) { // ClassAtom return res; } // ClassAtomNoDash NonemptyClassRangesNoDash // ClassAtomNoDash - ClassAtom ClassRanges return parseHelperClassRanges(res); } function parseClassAtom() { // ClassAtom :: // - // ClassAtomNoDash if (match('-')) { return createCharacter('-'); } else { return parseClassAtomNoDash(); } } function parseClassAtomNoDash() { // ClassAtomNoDash :: // SourceCharacter but not one of \ or ] or - // \ ClassEscape var res; if (res = matchReg(/^[^\\\]-]/)) { return createCharacter(res[0]); } else if (match('\\')) { res = parseClassEscape(); if (!res) { throw SyntaxError('classEscape'); } return parseUnicodeSurrogatePairEscape(res); } } var backrefDenied = []; var closedCaptureCounter = 0; var firstIteration = true; var hasUnicodeFlag = (flags || "").indexOf("u") !== -1; var pos = 0; // Convert the input to a string and treat the empty string special. str = String(str); if (str === '') { str = '(?:)'; } var result = parseDisjunction(); if (result.range[1] !== str.length) { throw SyntaxError('Could not parse entire input - got stuck: ' + str); } // The spec requires to interpret the `\2` in `/\2()()/` as backreference. // As the parser collects the number of capture groups as the string is // parsed it is impossible to make these decisions at the point the `\2` is // handled. In case the local decision turns out to be wrongq after the // parsing has finished, the input string is parsed a second time with the // total count of capture groups set. // // SEE: https://github.com/jviereck/regjsparser/issues/70 for (var i = 0; i < backrefDenied.length; i++) { if (backrefDenied[i] <= closedCaptureCounter) { // Parse the input a second time. pos = 0; firstIteration = false; return parseDisjunction(); } } return result; }; var regjsparser = { parse: parse }; if (typeof module !== 'undefined' && module.exports) { module.exports = regjsparser; } else { window.regjsparser = regjsparser; } }()); },{}],478:[function(require,module,exports){ var generate = require('regjsgen').generate; var parse = require('regjsparser').parse; var regenerate = require('regenerate'); var iuMappings = require('./data/iu-mappings.json'); var ESCAPE_SETS = require('./data/character-class-escape-sets.js'); function getCharacterClassEscapeSet(character) { if (unicode) { if (ignoreCase) { return ESCAPE_SETS.UNICODE_IGNORE_CASE[character]; } return ESCAPE_SETS.UNICODE[character]; } return ESCAPE_SETS.REGULAR[character]; } var object = {}; var hasOwnProperty = object.hasOwnProperty; function has(object, property) { return hasOwnProperty.call(object, property); } // Prepare a Regenerate set containing all code points, used for negative // character classes (if any). var UNICODE_SET = regenerate().addRange(0x0, 0x10FFFF); // Without the `u` flag, the range stops at 0xFFFF. // https://mths.be/es6#sec-pattern-semantics var BMP_SET = regenerate().addRange(0x0, 0xFFFF); // Prepare a Regenerate set containing all code points that are supposed to be // matched by `/./u`. https://mths.be/es6#sec-atom var DOT_SET_UNICODE = UNICODE_SET.clone() // all Unicode code points .remove( // minus `LineTerminator`s (https://mths.be/es6#sec-line-terminators): 0x000A, // Line Feed 0x000D, // Carriage Return 0x2028, // Line Separator 0x2029 // Paragraph Separator ); // Prepare a Regenerate set containing all code points that are supposed to be // matched by `/./` (only BMP code points). var DOT_SET = DOT_SET_UNICODE.clone() .intersection(BMP_SET); // Add a range of code points + any case-folded code points in that range to a // set. regenerate.prototype.iuAddRange = function(min, max) { var $this = this; do { var folded = caseFold(min); if (folded) { $this.add(folded); } } while (++min <= max); return $this; }; function assign(target, source) { for (var key in source) { // Note: `hasOwnProperty` is not needed here. target[key] = source[key]; } } function update(item, pattern) { // TODO: Test if memoizing `pattern` here is worth the effort. if (!pattern) { return; } var tree = parse(pattern, ''); switch (tree.type) { case 'characterClass': case 'group': case 'value': // No wrapping needed. break; default: // Wrap the pattern in a non-capturing group. tree = wrap(tree, pattern); } assign(item, tree); } function wrap(tree, pattern) { // Wrap the pattern in a non-capturing group. return { 'type': 'group', 'behavior': 'ignore', 'body': [tree], 'raw': '(?:' + pattern + ')' }; } function caseFold(codePoint) { return has(iuMappings, codePoint) ? iuMappings[codePoint] : false; } var ignoreCase = false; var unicode = false; function processCharacterClass(characterClassItem) { var set = regenerate(); var body = characterClassItem.body.forEach(function(item) { switch (item.type) { case 'value': set.add(item.codePoint); if (ignoreCase && unicode) { var folded = caseFold(item.codePoint); if (folded) { set.add(folded); } } break; case 'characterClassRange': var min = item.min.codePoint; var max = item.max.codePoint; set.addRange(min, max); if (ignoreCase && unicode) { set.iuAddRange(min, max); } break; case 'characterClassEscape': set.add(getCharacterClassEscapeSet(item.value)); break; // The `default` clause is only here as a safeguard; it should never be // reached. Code coverage tools should ignore it. /* istanbul ignore next */ default: throw Error('Unknown term type: ' + item.type); } }); if (characterClassItem.negative) { set = (unicode ? UNICODE_SET : BMP_SET).clone().remove(set); } update(characterClassItem, set.toString()); return characterClassItem; } function processTerm(item) { switch (item.type) { case 'dot': update( item, (unicode ? DOT_SET_UNICODE : DOT_SET).toString() ); break; case 'characterClass': item = processCharacterClass(item); break; case 'characterClassEscape': update( item, getCharacterClassEscapeSet(item.value).toString() ); break; case 'alternative': case 'disjunction': case 'group': case 'quantifier': item.body = item.body.map(processTerm); break; case 'value': var codePoint = item.codePoint; var set = regenerate(codePoint); if (ignoreCase && unicode) { var folded = caseFold(codePoint); if (folded) { set.add(folded); } } update(item, set.toString()); break; case 'anchor': case 'empty': case 'group': case 'reference': // Nothing to do here. break; // The `default` clause is only here as a safeguard; it should never be // reached. Code coverage tools should ignore it. /* istanbul ignore next */ default: throw Error('Unknown term type: ' + item.type); } return item; }; module.exports = function(pattern, flags) { var tree = parse(pattern, flags); ignoreCase = flags ? flags.indexOf('i') > -1 : false; unicode = flags ? flags.indexOf('u') > -1 : false; assign(tree, processTerm(tree)); return generate(tree); }; },{"./data/character-class-escape-sets.js":473,"./data/iu-mappings.json":474,"regenerate":475,"regjsgen":476,"regjsparser":477}],479:[function(require,module,exports){ 'use strict'; var isFinite = require('is-finite'); module.exports = function (str, n) { if (typeof str !== 'string') { throw new TypeError('Expected a string as the first argument'); } if (n < 0 || !isFinite(n)) { throw new TypeError('Expected a finite positive number'); } var ret = ''; do { if (n & 1) { ret += str; } str += str; } while (n = n >> 1); return ret; }; },{"is-finite":480}],480:[function(require,module,exports){ arguments[4][318][0].apply(exports,arguments) },{"dup":318}],481:[function(require,module,exports){ 'use strict'; module.exports = /^#!.*/; },{}],482:[function(require,module,exports){ 'use strict'; module.exports = function (str) { var isExtendedLengthPath = /^\\\\\?\\/.test(str); var hasNonAscii = /[^\x00-\x80]+/.test(str); if (isExtendedLengthPath || hasNonAscii) { return str; } return str.replace(/\\/g, '/'); }; },{}],483:[function(require,module,exports){ /* * Copyright 2009-2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE.txt or: * http://opensource.org/licenses/BSD-3-Clause */ exports.SourceMapGenerator = require('./source-map/source-map-generator').SourceMapGenerator; exports.SourceMapConsumer = require('./source-map/source-map-consumer').SourceMapConsumer; exports.SourceNode = require('./source-map/source-node').SourceNode; },{"./source-map/source-map-consumer":489,"./source-map/source-map-generator":490,"./source-map/source-node":491}],484:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = require('amdefine')(module, require); } define(function (require, exports, module) { var util = require('./util'); /** * A data structure which is a combination of an array and a set. Adding a new * member is O(1), testing for membership is O(1), and finding the index of an * element is O(1). Removing elements from the set is not supported. Only * strings are supported for membership. */ function ArraySet() { this._array = []; this._set = {}; } /** * Static method for creating ArraySet instances from an existing array. */ ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { var set = new ArraySet(); for (var i = 0, len = aArray.length; i < len; i++) { set.add(aArray[i], aAllowDuplicates); } return set; }; /** * Add the given string to this set. * * @param String aStr */ ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { var isDuplicate = this.has(aStr); var idx = this._array.length; if (!isDuplicate || aAllowDuplicates) { this._array.push(aStr); } if (!isDuplicate) { this._set[util.toSetString(aStr)] = idx; } }; /** * Is the given string a member of this set? * * @param String aStr */ ArraySet.prototype.has = function ArraySet_has(aStr) { return Object.prototype.hasOwnProperty.call(this._set, util.toSetString(aStr)); }; /** * What is the index of the given string in the array? * * @param String aStr */ ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { if (this.has(aStr)) { return this._set[util.toSetString(aStr)]; } throw new Error('"' + aStr + '" is not in the set.'); }; /** * What is the element at the given index? * * @param Number aIdx */ ArraySet.prototype.at = function ArraySet_at(aIdx) { if (aIdx >= 0 && aIdx < this._array.length) { return this._array[aIdx]; } throw new Error('No element indexed by ' + aIdx); }; /** * Returns the array representation of this set (which has the proper indices * indicated by indexOf). Note that this is a copy of the internal array used * for storing the members so that no one can mess with internal state. */ ArraySet.prototype.toArray = function ArraySet_toArray() { return this._array.slice(); }; exports.ArraySet = ArraySet; }); },{"./util":492,"amdefine":493}],485:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause * * Based on the Base 64 VLQ implementation in Closure Compiler: * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java * * Copyright 2011 The Closure Compiler Authors. All rights reserved. * 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. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * 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 THE COPYRIGHT * OWNER OR CONTRIBUTORS 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. */ if (typeof define !== 'function') { var define = require('amdefine')(module, require); } define(function (require, exports, module) { var base64 = require('./base64'); // A single base 64 digit can contain 6 bits of data. For the base 64 variable // length quantities we use in the source map spec, the first bit is the sign, // the next four bits are the actual value, and the 6th bit is the // continuation bit. The continuation bit tells us whether there are more // digits in this value following this digit. // // Continuation // | Sign // | | // V V // 101011 var VLQ_BASE_SHIFT = 5; // binary: 100000 var VLQ_BASE = 1 << VLQ_BASE_SHIFT; // binary: 011111 var VLQ_BASE_MASK = VLQ_BASE - 1; // binary: 100000 var VLQ_CONTINUATION_BIT = VLQ_BASE; /** * Converts from a two-complement value to a value where the sign bit is * placed in the least significant bit. For example, as decimals: * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) */ function toVLQSigned(aValue) { return aValue < 0 ? ((-aValue) << 1) + 1 : (aValue << 1) + 0; } /** * Converts to a two-complement value from a value where the sign bit is * placed in the least significant bit. For example, as decimals: * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 */ function fromVLQSigned(aValue) { var isNegative = (aValue & 1) === 1; var shifted = aValue >> 1; return isNegative ? -shifted : shifted; } /** * Returns the base 64 VLQ encoded value. */ exports.encode = function base64VLQ_encode(aValue) { var encoded = ""; var digit; var vlq = toVLQSigned(aValue); do { digit = vlq & VLQ_BASE_MASK; vlq >>>= VLQ_BASE_SHIFT; if (vlq > 0) { // There are still more digits in this value, so we must make sure the // continuation bit is marked. digit |= VLQ_CONTINUATION_BIT; } encoded += base64.encode(digit); } while (vlq > 0); return encoded; }; /** * Decodes the next base 64 VLQ value from the given string and returns the * value and the rest of the string via the out parameter. */ exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { var strLen = aStr.length; var result = 0; var shift = 0; var continuation, digit; do { if (aIndex >= strLen) { throw new Error("Expected more digits in base 64 VLQ value."); } digit = base64.decode(aStr.charAt(aIndex++)); continuation = !!(digit & VLQ_CONTINUATION_BIT); digit &= VLQ_BASE_MASK; result = result + (digit << shift); shift += VLQ_BASE_SHIFT; } while (continuation); aOutParam.value = fromVLQSigned(result); aOutParam.rest = aIndex; }; }); },{"./base64":486,"amdefine":493}],486:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = require('amdefine')(module, require); } define(function (require, exports, module) { var charToIntMap = {}; var intToCharMap = {}; 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' .split('') .forEach(function (ch, index) { charToIntMap[ch] = index; intToCharMap[index] = ch; }); /** * Encode an integer in the range of 0 to 63 to a single base 64 digit. */ exports.encode = function base64_encode(aNumber) { if (aNumber in intToCharMap) { return intToCharMap[aNumber]; } throw new TypeError("Must be between 0 and 63: " + aNumber); }; /** * Decode a single base 64 digit to an integer. */ exports.decode = function base64_decode(aChar) { if (aChar in charToIntMap) { return charToIntMap[aChar]; } throw new TypeError("Not a valid base 64 digit: " + aChar); }; }); },{"amdefine":493}],487:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = require('amdefine')(module, require); } define(function (require, exports, module) { exports.GREATEST_LOWER_BOUND = 1; exports.LEAST_UPPER_BOUND = 2; /** * Recursive implementation of binary search. * * @param aLow Indices here and lower do not contain the needle. * @param aHigh Indices here and higher do not contain the needle. * @param aNeedle The element being searched for. * @param aHaystack The non-empty array being searched. * @param aCompare Function which takes two elements and returns -1, 0, or 1. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. */ function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { // This function terminates when one of the following is true: // // 1. We find the exact element we are looking for. // // 2. We did not find the exact element, but we can return the index of // the next-closest element. // // 3. We did not find the exact element, and there is no next-closest // element than the one we are searching for, so we return -1. var mid = Math.floor((aHigh - aLow) / 2) + aLow; var cmp = aCompare(aNeedle, aHaystack[mid], true); if (cmp === 0) { // Found the element we are looking for. return mid; } else if (cmp > 0) { // Our needle is greater than aHaystack[mid]. if (aHigh - mid > 1) { // The element is in the upper half. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); } // The exact needle element was not found in this haystack. Determine if // we are in termination case (3) or (2) and return the appropriate thing. if (aBias == exports.LEAST_UPPER_BOUND) { return aHigh < aHaystack.length ? aHigh : -1; } else { return mid; } } else { // Our needle is less than aHaystack[mid]. if (mid - aLow > 1) { // The element is in the lower half. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); } // we are in termination case (3) or (2) and return the appropriate thing. if (aBias == exports.LEAST_UPPER_BOUND) { return mid; } else { return aLow < 0 ? -1 : aLow; } } } /** * This is an implementation of binary search which will always try and return * the index of the closest element if there is no exact hit. This is because * mappings between original and generated line/col pairs are single points, * and there is an implicit region between each of them, so a miss just means * that you aren't on the very start of a region. * * @param aNeedle The element you are looking for. * @param aHaystack The array that is being searched. * @param aCompare A function which takes the needle and an element in the * array and returns -1, 0, or 1 depending on whether the needle is less * than, equal to, or greater than the element, respectively. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. */ exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { if (aHaystack.length === 0) { return -1; } var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare, aBias || exports.GREATEST_LOWER_BOUND); if (index < 0) { return -1; } // We have found either the exact element, or the next-closest element than // the one we are searching for. However, there may be more than one such // element. Make sure we always return the smallest of these. while (index - 1 >= 0) { if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { break; } --index; } return index; }; }); },{"amdefine":493}],488:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2014 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = require('amdefine')(module, require); } define(function (require, exports, module) { var util = require('./util'); /** * Determine whether mappingB is after mappingA with respect to generated * position. */ function generatedPositionAfter(mappingA, mappingB) { // Optimized for most common case var lineA = mappingA.generatedLine; var lineB = mappingB.generatedLine; var columnA = mappingA.generatedColumn; var columnB = mappingB.generatedColumn; return lineB > lineA || lineB == lineA && columnB >= columnA || util.compareByGeneratedPositions(mappingA, mappingB) <= 0; } /** * A data structure to provide a sorted view of accumulated mappings in a * performance conscious manner. It trades a neglibable overhead in general * case for a large speedup in case of mappings being added in order. */ function MappingList() { this._array = []; this._sorted = true; // Serves as infimum this._last = {generatedLine: -1, generatedColumn: 0}; } /** * Iterate through internal items. This method takes the same arguments that * `Array.prototype.forEach` takes. * * NOTE: The order of the mappings is NOT guaranteed. */ MappingList.prototype.unsortedForEach = function MappingList_forEach(aCallback, aThisArg) { this._array.forEach(aCallback, aThisArg); }; /** * Add the given source mapping. * * @param Object aMapping */ MappingList.prototype.add = function MappingList_add(aMapping) { var mapping; if (generatedPositionAfter(this._last, aMapping)) { this._last = aMapping; this._array.push(aMapping); } else { this._sorted = false; this._array.push(aMapping); } }; /** * Returns the flat, sorted array of mappings. The mappings are sorted by * generated position. * * WARNING: This method returns internal data without copying, for * performance. The return value must NOT be mutated, and should be treated as * an immutable borrow. If you want to take ownership, you must make your own * copy. */ MappingList.prototype.toArray = function MappingList_toArray() { if (!this._sorted) { this._array.sort(util.compareByGeneratedPositions); this._sorted = true; } return this._array; }; exports.MappingList = MappingList; }); },{"./util":492,"amdefine":493}],489:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = require('amdefine')(module, require); } define(function (require, exports, module) { var util = require('./util'); var binarySearch = require('./binary-search'); var ArraySet = require('./array-set').ArraySet; var base64VLQ = require('./base64-vlq'); function SourceMapConsumer(aSourceMap) { var sourceMap = aSourceMap; if (typeof aSourceMap === 'string') { sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); } return sourceMap.sections != null ? new IndexedSourceMapConsumer(sourceMap) : new BasicSourceMapConsumer(sourceMap); } SourceMapConsumer.fromSourceMap = function(aSourceMap) { return BasicSourceMapConsumer.fromSourceMap(aSourceMap); } /** * The version of the source mapping spec that we are consuming. */ SourceMapConsumer.prototype._version = 3; // `__generatedMappings` and `__originalMappings` are arrays that hold the // parsed mapping coordinates from the source map's "mappings" attribute. They // are lazily instantiated, accessed via the `_generatedMappings` and // `_originalMappings` getters respectively, and we only parse the mappings // and create these arrays once queried for a source location. We jump through // these hoops because there can be many thousands of mappings, and parsing // them is expensive, so we only want to do it if we must. // // Each object in the arrays is of the form: // // { // generatedLine: The line number in the generated code, // generatedColumn: The column number in the generated code, // source: The path to the original source file that generated this // chunk of code, // originalLine: The line number in the original source that // corresponds to this chunk of generated code, // originalColumn: The column number in the original source that // corresponds to this chunk of generated code, // name: The name of the original symbol which generated this chunk of // code. // } // // All properties except for `generatedLine` and `generatedColumn` can be // `null`. // // `_generatedMappings` is ordered by the generated positions. // // `_originalMappings` is ordered by the original positions. SourceMapConsumer.prototype.__generatedMappings = null; Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { get: function () { if (!this.__generatedMappings) { this.__generatedMappings = []; this.__originalMappings = []; this._parseMappings(this._mappings, this.sourceRoot); } return this.__generatedMappings; } }); SourceMapConsumer.prototype.__originalMappings = null; Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { get: function () { if (!this.__originalMappings) { this.__generatedMappings = []; this.__originalMappings = []; this._parseMappings(this._mappings, this.sourceRoot); } return this.__originalMappings; } }); SourceMapConsumer.prototype._nextCharIsMappingSeparator = function SourceMapConsumer_nextCharIsMappingSeparator(aStr, index) { var c = aStr.charAt(index); return c === ";" || c === ","; }; /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ SourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { throw new Error("Subclasses must implement _parseMappings"); }; SourceMapConsumer.GENERATED_ORDER = 1; SourceMapConsumer.ORIGINAL_ORDER = 2; SourceMapConsumer.GREATEST_LOWER_BOUND = 1; SourceMapConsumer.LEAST_UPPER_BOUND = 2; /** * Iterate over each mapping between an original source/line/column and a * generated line/column in this source map. * * @param Function aCallback * The function that is called with each mapping. * @param Object aContext * Optional. If specified, this object will be the value of `this` every * time that `aCallback` is called. * @param aOrder * Either `SourceMapConsumer.GENERATED_ORDER` or * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to * iterate over the mappings sorted by the generated file's line/column * order or the original's source/line/column order, respectively. Defaults to * `SourceMapConsumer.GENERATED_ORDER`. */ SourceMapConsumer.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { var context = aContext || null; var order = aOrder || SourceMapConsumer.GENERATED_ORDER; var mappings; switch (order) { case SourceMapConsumer.GENERATED_ORDER: mappings = this._generatedMappings; break; case SourceMapConsumer.ORIGINAL_ORDER: mappings = this._originalMappings; break; default: throw new Error("Unknown order of iteration."); } var sourceRoot = this.sourceRoot; mappings.map(function (mapping) { var source = mapping.source; if (source != null && sourceRoot != null) { source = util.join(sourceRoot, source); } return { source: source, generatedLine: mapping.generatedLine, generatedColumn: mapping.generatedColumn, originalLine: mapping.originalLine, originalColumn: mapping.originalColumn, name: mapping.name }; }).forEach(aCallback, context); }; /** * Returns all generated line and column information for the original source, * line, and column provided. If no column is provided, returns all mappings * corresponding to a single line. Otherwise, returns all mappings * corresponding to a single line and column. * * The only argument is an object with the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. * - column: Optional. the column number in the original source. * * and an array of objects is returned, each with the following properties: * * - line: The line number in the generated source, or null. * - column: The column number in the generated source, or null. */ SourceMapConsumer.prototype.allGeneratedPositionsFor = function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping // returns the index of the closest mapping less than the needle. By // setting needle.originalColumn to 0, we thus find the last mapping for // the given line, provided such a mapping exists. var needle = { source: util.getArg(aArgs, 'source'), originalLine: util.getArg(aArgs, 'line'), originalColumn: util.getArg(aArgs, 'column', 0) }; if (this.sourceRoot != null) { needle.source = util.relative(this.sourceRoot, needle.source); } var mappings = []; var index = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions, binarySearch.LEAST_UPPER_BOUND); if (index >= 0) { var mapping = this._originalMappings[index]; var originalLine = mapping.originalLine; var originalColumn = mapping.originalColumn; // Iterate until either we run out of mappings, or we run into // a mapping for a different line. Since mappings are sorted, this is // guaranteed to find all mappings for the line we are searching for. while (mapping && mapping.originalLine === originalLine && (aArgs.column === undefined || mapping.originalColumn === originalColumn)) { mappings.push({ line: util.getArg(mapping, 'generatedLine', null), column: util.getArg(mapping, 'generatedColumn', null), lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) }); mapping = this._originalMappings[++index]; } } return mappings; }; exports.SourceMapConsumer = SourceMapConsumer; /** * A BasicSourceMapConsumer instance represents a parsed source map which we can * query for information about the original file positions by giving it a file * position in the generated source. * * The only parameter is the raw source map (either as a JSON string, or * already parsed to an object). According to the spec, source maps have the * following attributes: * * - version: Which version of the source map spec this map is following. * - sources: An array of URLs to the original source files. * - names: An array of identifiers which can be referrenced by individual mappings. * - sourceRoot: Optional. The URL root from which all sources are relative. * - sourcesContent: Optional. An array of contents of the original source files. * - mappings: A string of base64 VLQs which contain the actual mappings. * - file: Optional. The generated file this source map is associated with. * * Here is an example source map, taken from the source map spec[0]: * * { * version : 3, * file: "out.js", * sourceRoot : "", * sources: ["foo.js", "bar.js"], * names: ["src", "maps", "are", "fun"], * mappings: "AA,AB;;ABCDE;" * } * * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# */ function BasicSourceMapConsumer(aSourceMap) { var sourceMap = aSourceMap; if (typeof aSourceMap === 'string') { sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); } var version = util.getArg(sourceMap, 'version'); var sources = util.getArg(sourceMap, 'sources'); // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which // requires the array) to play nice here. var names = util.getArg(sourceMap, 'names', []); var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); var mappings = util.getArg(sourceMap, 'mappings'); var file = util.getArg(sourceMap, 'file', null); // Once again, Sass deviates from the spec and supplies the version as a // string rather than a number, so we use loose equality checking here. if (version != this._version) { throw new Error('Unsupported version: ' + version); } // Some source maps produce relative source paths like "./foo.js" instead of // "foo.js". Normalize these first so that future comparisons will succeed. // See bugzil.la/1090768. sources = sources.map(util.normalize); // Pass `true` below to allow duplicate names and sources. While source maps // are intended to be compressed and deduplicated, the TypeScript compiler // sometimes generates source maps with duplicates in them. See Github issue // #72 and bugzil.la/889492. this._names = ArraySet.fromArray(names, true); this._sources = ArraySet.fromArray(sources, true); this.sourceRoot = sourceRoot; this.sourcesContent = sourcesContent; this._mappings = mappings; this.file = file; } BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; /** * Create a BasicSourceMapConsumer from a SourceMapGenerator. * * @param SourceMapGenerator aSourceMap * The source map that will be consumed. * @returns BasicSourceMapConsumer */ BasicSourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap(aSourceMap) { var smc = Object.create(BasicSourceMapConsumer.prototype); smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); smc.sourceRoot = aSourceMap._sourceRoot; smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), smc.sourceRoot); smc.file = aSourceMap._file; smc.__generatedMappings = aSourceMap._mappings.toArray().slice(); smc.__originalMappings = aSourceMap._mappings.toArray().slice() .sort(util.compareByOriginalPositions); return smc; }; /** * The version of the source mapping spec that we are consuming. */ BasicSourceMapConsumer.prototype._version = 3; /** * The list of original sources. */ Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { get: function () { return this._sources.toArray().map(function (s) { return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s; }, this); } }); /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ BasicSourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { var generatedLine = 1; var previousGeneratedColumn = 0; var previousOriginalLine = 0; var previousOriginalColumn = 0; var previousSource = 0; var previousName = 0; var length = aStr.length; var index = 0; var cachedValues = {}; var temp = {}; var mapping, str, values, end, value; while (index < length) { if (aStr.charAt(index) === ';') { generatedLine++; ++index; previousGeneratedColumn = 0; } else if (aStr.charAt(index) === ',') { ++index; } else { mapping = {}; mapping.generatedLine = generatedLine; // Because each offset is encoded relative to the previous one, // many segments often have the same encoding. We can exploit this // fact by caching the parsed variable length fields of each segment, // allowing us to avoid a second parse if we encounter the same // segment again. for (end = index; end < length; ++end) { if (this._nextCharIsMappingSeparator(aStr, end)) { break; } } str = aStr.slice(index, end); values = cachedValues[str]; if (values) { index += str.length; } else { values = []; while (index < end) { base64VLQ.decode(aStr, index, temp); value = temp.value; index = temp.rest; values.push(value); } cachedValues[str] = values; } // Generated column. mapping.generatedColumn = previousGeneratedColumn + values[0]; previousGeneratedColumn = mapping.generatedColumn; if (values.length > 1) { // Original source. mapping.source = this._sources.at(previousSource + values[1]); previousSource += values[1]; if (values.length === 2) { throw new Error('Found a source, but no line and column'); } // Original line. mapping.originalLine = previousOriginalLine + values[2]; previousOriginalLine = mapping.originalLine; // Lines are stored 0-based mapping.originalLine += 1; if (values.length === 3) { throw new Error('Found a source and line, but no column'); } // Original column. mapping.originalColumn = previousOriginalColumn + values[3]; previousOriginalColumn = mapping.originalColumn; if (values.length > 4) { // Original name. mapping.name = this._names.at(previousName + values[4]); previousName += values[4]; } } this.__generatedMappings.push(mapping); if (typeof mapping.originalLine === 'number') { this.__originalMappings.push(mapping); } } } this.__generatedMappings.sort(util.compareByGeneratedPositions); this.__originalMappings.sort(util.compareByOriginalPositions); }; /** * Find the mapping that best matches the hypothetical "needle" mapping that * we are searching for in the given "haystack" of mappings. */ BasicSourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator, aBias) { // To return the position we are searching for, we must first find the // mapping for the given position and then return the opposite position it // points to. Because the mappings are sorted, we can use binary search to // find the best mapping. if (aNeedle[aLineName] <= 0) { throw new TypeError('Line must be greater than or equal to 1, got ' + aNeedle[aLineName]); } if (aNeedle[aColumnName] < 0) { throw new TypeError('Column must be greater than or equal to 0, got ' + aNeedle[aColumnName]); } return binarySearch.search(aNeedle, aMappings, aComparator, aBias); }; /** * Compute the last column for each generated mapping. The last column is * inclusive. */ BasicSourceMapConsumer.prototype.computeColumnSpans = function SourceMapConsumer_computeColumnSpans() { for (var index = 0; index < this._generatedMappings.length; ++index) { var mapping = this._generatedMappings[index]; // Mappings do not contain a field for the last generated columnt. We // can come up with an optimistic estimate, however, by assuming that // mappings are contiguous (i.e. given two consecutive mappings, the // first mapping ends where the second one starts). if (index + 1 < this._generatedMappings.length) { var nextMapping = this._generatedMappings[index + 1]; if (mapping.generatedLine === nextMapping.generatedLine) { mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; continue; } } // The last mapping for each line spans the entire line. mapping.lastGeneratedColumn = Infinity; } }; /** * Returns the original source, line, and column information for the generated * source's line and column positions provided. The only argument is an object * with the following properties: * * - line: The line number in the generated source. * - column: The column number in the generated source. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. * * and an object is returned with the following properties: * * - source: The original source file, or null. * - line: The line number in the original source, or null. * - column: The column number in the original source, or null. * - name: The original identifier, or null. */ BasicSourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) { var needle = { generatedLine: util.getArg(aArgs, 'line'), generatedColumn: util.getArg(aArgs, 'column') }; var index = this._findMapping( needle, this._generatedMappings, "generatedLine", "generatedColumn", util.compareByGeneratedPositions, util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) ); if (index >= 0) { var mapping = this._generatedMappings[index]; if (mapping.generatedLine === needle.generatedLine) { var source = util.getArg(mapping, 'source', null); if (source != null && this.sourceRoot != null) { source = util.join(this.sourceRoot, source); } return { source: source, line: util.getArg(mapping, 'originalLine', null), column: util.getArg(mapping, 'originalColumn', null), name: util.getArg(mapping, 'name', null) }; } } return { source: null, line: null, column: null, name: null }; }; /** * Returns the original source content. The only argument is the url of the * original source file. Returns null if no original source content is * availible. */ BasicSourceMapConsumer.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { if (!this.sourcesContent) { return null; } if (this.sourceRoot != null) { aSource = util.relative(this.sourceRoot, aSource); } if (this._sources.has(aSource)) { return this.sourcesContent[this._sources.indexOf(aSource)]; } var url; if (this.sourceRoot != null && (url = util.urlParse(this.sourceRoot))) { // XXX: file:// URIs and absolute paths lead to unexpected behavior for // many users. We can help them out when they expect file:// URIs to // behave like it would if they were running a local HTTP server. See // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); if (url.scheme == "file" && this._sources.has(fileUriAbsPath)) { return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] } if ((!url.path || url.path == "/") && this._sources.has("/" + aSource)) { return this.sourcesContent[this._sources.indexOf("/" + aSource)]; } } // This function is used recursively from // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we // don't want to throw if we can't find the source - we just want to // return null, so we provide a flag to exit gracefully. if (nullOnMissing) { return null; } else { throw new Error('"' + aSource + '" is not in the SourceMap.'); } }; /** * Returns the generated line and column information for the original source, * line, and column positions provided. The only argument is an object with * the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. * - column: The column number in the original source. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. * * and an object is returned with the following properties: * * - line: The line number in the generated source, or null. * - column: The column number in the generated source, or null. */ BasicSourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) { var needle = { source: util.getArg(aArgs, 'source'), originalLine: util.getArg(aArgs, 'line'), originalColumn: util.getArg(aArgs, 'column') }; if (this.sourceRoot != null) { needle.source = util.relative(this.sourceRoot, needle.source); } var index = this._findMapping( needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions, util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) ); if (index >= 0) { var mapping = this._originalMappings[index]; if (mapping.source === needle.source) { return { line: util.getArg(mapping, 'generatedLine', null), column: util.getArg(mapping, 'generatedColumn', null), lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) }; } } return { line: null, column: null, lastColumn: null }; }; exports.BasicSourceMapConsumer = BasicSourceMapConsumer; /** * An IndexedSourceMapConsumer instance represents a parsed source map which * we can query for information. It differs from BasicSourceMapConsumer in * that it takes "indexed" source maps (i.e. ones with a "sections" field) as * input. * * The only parameter is a raw source map (either as a JSON string, or already * parsed to an object). According to the spec for indexed source maps, they * have the following attributes: * * - version: Which version of the source map spec this map is following. * - file: Optional. The generated file this source map is associated with. * - sections: A list of section definitions. * * Each value under the "sections" field has two fields: * - offset: The offset into the original specified at which this section * begins to apply, defined as an object with a "line" and "column" * field. * - map: A source map definition. This source map could also be indexed, * but doesn't have to be. * * Instead of the "map" field, it's also possible to have a "url" field * specifying a URL to retrieve a source map from, but that's currently * unsupported. * * Here's an example source map, taken from the source map spec[0], but * modified to omit a section which uses the "url" field. * * { * version : 3, * file: "app.js", * sections: [{ * offset: {line:100, column:10}, * map: { * version : 3, * file: "section.js", * sources: ["foo.js", "bar.js"], * names: ["src", "maps", "are", "fun"], * mappings: "AAAA,E;;ABCDE;" * } * }], * } * * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt */ function IndexedSourceMapConsumer(aSourceMap) { var sourceMap = aSourceMap; if (typeof aSourceMap === 'string') { sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); } var version = util.getArg(sourceMap, 'version'); var sections = util.getArg(sourceMap, 'sections'); if (version != this._version) { throw new Error('Unsupported version: ' + version); } var lastOffset = { line: -1, column: 0 }; this._sections = sections.map(function (s) { if (s.url) { // The url field will require support for asynchronicity. // See https://github.com/mozilla/source-map/issues/16 throw new Error('Support for url field in sections not implemented.'); } var offset = util.getArg(s, 'offset'); var offsetLine = util.getArg(offset, 'line'); var offsetColumn = util.getArg(offset, 'column'); if (offsetLine < lastOffset.line || (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { throw new Error('Section offsets must be ordered and non-overlapping.'); } lastOffset = offset; return { generatedOffset: { // The offset fields are 0-based, but we use 1-based indices when // encoding/decoding from VLQ. generatedLine: offsetLine + 1, generatedColumn: offsetColumn + 1 }, consumer: new SourceMapConsumer(util.getArg(s, 'map')) } }); } IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; /** * The version of the source mapping spec that we are consuming. */ IndexedSourceMapConsumer.prototype._version = 3; /** * The list of original sources. */ Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { get: function () { var sources = []; for (var i = 0; i < this._sections.length; i++) { for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { sources.push(this._sections[i].consumer.sources[j]); } }; return sources; } }); /** * Returns the original source, line, and column information for the generated * source's line and column positions provided. The only argument is an object * with the following properties: * * - line: The line number in the generated source. * - column: The column number in the generated source. * * and an object is returned with the following properties: * * - source: The original source file, or null. * - line: The line number in the original source, or null. * - column: The column number in the original source, or null. * - name: The original identifier, or null. */ IndexedSourceMapConsumer.prototype.originalPositionFor = function IndexedSourceMapConsumer_originalPositionFor(aArgs) { var needle = { generatedLine: util.getArg(aArgs, 'line'), generatedColumn: util.getArg(aArgs, 'column') }; // Find the section containing the generated position we're trying to map // to an original position. var sectionIndex = binarySearch.search(needle, this._sections, function(needle, section) { var cmp = needle.generatedLine - section.generatedOffset.generatedLine; if (cmp) { return cmp; } return (needle.generatedColumn - section.generatedOffset.generatedColumn); }); var section = this._sections[sectionIndex]; if (!section) { return { source: null, line: null, column: null, name: null }; } return section.consumer.originalPositionFor({ line: needle.generatedLine - (section.generatedOffset.generatedLine - 1), column: needle.generatedColumn - (section.generatedOffset.generatedLine === needle.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0), bias: aArgs.bias }); }; /** * Returns the original source content. The only argument is the url of the * original source file. Returns null if no original source content is * available. */ IndexedSourceMapConsumer.prototype.sourceContentFor = function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { for (var i = 0; i < this._sections.length; i++) { var section = this._sections[i]; var content = section.consumer.sourceContentFor(aSource, true); if (content) { return content; } } if (nullOnMissing) { return null; } else { throw new Error('"' + aSource + '" is not in the SourceMap.'); } }; /** * Returns the generated line and column information for the original source, * line, and column positions provided. The only argument is an object with * the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. * - column: The column number in the original source. * * and an object is returned with the following properties: * * - line: The line number in the generated source, or null. * - column: The column number in the generated source, or null. */ IndexedSourceMapConsumer.prototype.generatedPositionFor = function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { for (var i = 0; i < this._sections.length; i++) { var section = this._sections[i]; // Only consider this section if the requested source is in the list of // sources of the consumer. if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) { continue; } var generatedPosition = section.consumer.generatedPositionFor(aArgs); if (generatedPosition) { var ret = { line: generatedPosition.line + (section.generatedOffset.generatedLine - 1), column: generatedPosition.column + (section.generatedOffset.generatedLine === generatedPosition.line ? section.generatedOffset.generatedColumn - 1 : 0) }; return ret; } } return { line: null, column: null }; }; /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ IndexedSourceMapConsumer.prototype._parseMappings = function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { this.__generatedMappings = []; this.__originalMappings = []; for (var i = 0; i < this._sections.length; i++) { var section = this._sections[i]; var sectionMappings = section.consumer._generatedMappings; for (var j = 0; j < sectionMappings.length; j++) { var mapping = sectionMappings[i]; var source = mapping.source; var sourceRoot = section.consumer.sourceRoot; if (source != null && sourceRoot != null) { source = util.join(sourceRoot, source); } // The mappings coming from the consumer for the section have // generated positions relative to the start of the section, so we // need to offset them to be relative to the start of the concatenated // generated file. var adjustedMapping = { source: source, generatedLine: mapping.generatedLine + (section.generatedOffset.generatedLine - 1), generatedColumn: mapping.column + (section.generatedOffset.generatedLine === mapping.generatedLine) ? section.generatedOffset.generatedColumn - 1 : 0, originalLine: mapping.originalLine, originalColumn: mapping.originalColumn, name: mapping.name }; this.__generatedMappings.push(adjustedMapping); if (typeof adjustedMapping.originalLine === 'number') { this.__originalMappings.push(adjustedMapping); } }; }; this.__generatedMappings.sort(util.compareByGeneratedPositions); this.__originalMappings.sort(util.compareByOriginalPositions); }; exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; }); },{"./array-set":484,"./base64-vlq":485,"./binary-search":487,"./util":492,"amdefine":493}],490:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = require('amdefine')(module, require); } define(function (require, exports, module) { var base64VLQ = require('./base64-vlq'); var util = require('./util'); var ArraySet = require('./array-set').ArraySet; var MappingList = require('./mapping-list').MappingList; /** * An instance of the SourceMapGenerator represents a source map which is * being built incrementally. You may pass an object with the following * properties: * * - file: The filename of the generated source. * - sourceRoot: A root for all relative URLs in this source map. */ function SourceMapGenerator(aArgs) { if (!aArgs) { aArgs = {}; } this._file = util.getArg(aArgs, 'file', null); this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); this._skipValidation = util.getArg(aArgs, 'skipValidation', false); this._sources = new ArraySet(); this._names = new ArraySet(); this._mappings = new MappingList(); this._sourcesContents = null; } SourceMapGenerator.prototype._version = 3; /** * Creates a new SourceMapGenerator based on a SourceMapConsumer * * @param aSourceMapConsumer The SourceMap. */ SourceMapGenerator.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { var sourceRoot = aSourceMapConsumer.sourceRoot; var generator = new SourceMapGenerator({ file: aSourceMapConsumer.file, sourceRoot: sourceRoot }); aSourceMapConsumer.eachMapping(function (mapping) { var newMapping = { generated: { line: mapping.generatedLine, column: mapping.generatedColumn } }; if (mapping.source != null) { newMapping.source = mapping.source; if (sourceRoot != null) { newMapping.source = util.relative(sourceRoot, newMapping.source); } newMapping.original = { line: mapping.originalLine, column: mapping.originalColumn }; if (mapping.name != null) { newMapping.name = mapping.name; } } generator.addMapping(newMapping); }); aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content != null) { generator.setSourceContent(sourceFile, content); } }); return generator; }; /** * Add a single mapping from original source line and column to the generated * source's line and column for this source map being created. The mapping * object should have the following properties: * * - generated: An object with the generated line and column positions. * - original: An object with the original line and column positions. * - source: The original source file (relative to the sourceRoot). * - name: An optional original token name for this mapping. */ SourceMapGenerator.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) { var generated = util.getArg(aArgs, 'generated'); var original = util.getArg(aArgs, 'original', null); var source = util.getArg(aArgs, 'source', null); var name = util.getArg(aArgs, 'name', null); if (!this._skipValidation) { this._validateMapping(generated, original, source, name); } if (source != null && !this._sources.has(source)) { this._sources.add(source); } if (name != null && !this._names.has(name)) { this._names.add(name); } this._mappings.add({ generatedLine: generated.line, generatedColumn: generated.column, originalLine: original != null && original.line, originalColumn: original != null && original.column, source: source, name: name }); }; /** * Set the source content for a source file. */ SourceMapGenerator.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { var source = aSourceFile; if (this._sourceRoot != null) { source = util.relative(this._sourceRoot, source); } if (aSourceContent != null) { // Add the source content to the _sourcesContents map. // Create a new _sourcesContents map if the property is null. if (!this._sourcesContents) { this._sourcesContents = {}; } this._sourcesContents[util.toSetString(source)] = aSourceContent; } else if (this._sourcesContents) { // Remove the source file from the _sourcesContents map. // If the _sourcesContents map is empty, set the property to null. delete this._sourcesContents[util.toSetString(source)]; if (Object.keys(this._sourcesContents).length === 0) { this._sourcesContents = null; } } }; /** * Applies the mappings of a sub-source-map for a specific source file to the * source map being generated. Each mapping to the supplied source file is * rewritten using the supplied source map. Note: The resolution for the * resulting mappings is the minimium of this map and the supplied map. * * @param aSourceMapConsumer The source map to be applied. * @param aSourceFile Optional. The filename of the source file. * If omitted, SourceMapConsumer's file property will be used. * @param aSourceMapPath Optional. The dirname of the path to the source map * to be applied. If relative, it is relative to the SourceMapConsumer. * This parameter is needed when the two source maps aren't in the same * directory, and the source map to be applied contains relative source * paths. If so, those relative source paths need to be rewritten * relative to the SourceMapGenerator. */ SourceMapGenerator.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { var sourceFile = aSourceFile; // If aSourceFile is omitted, we will use the file property of the SourceMap if (aSourceFile == null) { if (aSourceMapConsumer.file == null) { throw new Error( 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + 'or the source map\'s "file" property. Both were omitted.' ); } sourceFile = aSourceMapConsumer.file; } var sourceRoot = this._sourceRoot; // Make "sourceFile" relative if an absolute Url is passed. if (sourceRoot != null) { sourceFile = util.relative(sourceRoot, sourceFile); } // Applying the SourceMap can add and remove items from the sources and // the names array. var newSources = new ArraySet(); var newNames = new ArraySet(); // Find mappings for the "sourceFile" this._mappings.unsortedForEach(function (mapping) { if (mapping.source === sourceFile && mapping.originalLine != null) { // Check if it can be mapped by the source map, then update the mapping. var original = aSourceMapConsumer.originalPositionFor({ line: mapping.originalLine, column: mapping.originalColumn }); if (original.source != null) { // Copy mapping mapping.source = original.source; if (aSourceMapPath != null) { mapping.source = util.join(aSourceMapPath, mapping.source) } if (sourceRoot != null) { mapping.source = util.relative(sourceRoot, mapping.source); } mapping.originalLine = original.line; mapping.originalColumn = original.column; if (original.name != null) { mapping.name = original.name; } } } var source = mapping.source; if (source != null && !newSources.has(source)) { newSources.add(source); } var name = mapping.name; if (name != null && !newNames.has(name)) { newNames.add(name); } }, this); this._sources = newSources; this._names = newNames; // Copy sourcesContents of applied map. aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content != null) { if (aSourceMapPath != null) { sourceFile = util.join(aSourceMapPath, sourceFile); } if (sourceRoot != null) { sourceFile = util.relative(sourceRoot, sourceFile); } this.setSourceContent(sourceFile, content); } }, this); }; /** * A mapping can have one of the three levels of data: * * 1. Just the generated position. * 2. The Generated position, original position, and original source. * 3. Generated and original position, original source, as well as a name * token. * * To maintain consistency, we validate that any new mapping being added falls * in to one of these categories. */ SourceMapGenerator.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) { if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) { // Case 1. return; } else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aOriginal && 'line' in aOriginal && 'column' in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) { // Cases 2 and 3. return; } else { throw new Error('Invalid mapping: ' + JSON.stringify({ generated: aGenerated, source: aSource, original: aOriginal, name: aName })); } }; /** * Serialize the accumulated mappings in to the stream of base 64 VLQs * specified by the source map format. */ SourceMapGenerator.prototype._serializeMappings = function SourceMapGenerator_serializeMappings() { var previousGeneratedColumn = 0; var previousGeneratedLine = 1; var previousOriginalColumn = 0; var previousOriginalLine = 0; var previousName = 0; var previousSource = 0; var result = ''; var mapping; var mappings = this._mappings.toArray(); for (var i = 0, len = mappings.length; i < len; i++) { mapping = mappings[i]; if (mapping.generatedLine !== previousGeneratedLine) { previousGeneratedColumn = 0; while (mapping.generatedLine !== previousGeneratedLine) { result += ';'; previousGeneratedLine++; } } else { if (i > 0) { if (!util.compareByGeneratedPositions(mapping, mappings[i - 1])) { continue; } result += ','; } } result += base64VLQ.encode(mapping.generatedColumn - previousGeneratedColumn); previousGeneratedColumn = mapping.generatedColumn; if (mapping.source != null) { result += base64VLQ.encode(this._sources.indexOf(mapping.source) - previousSource); previousSource = this._sources.indexOf(mapping.source); // lines are stored 0-based in SourceMap spec version 3 result += base64VLQ.encode(mapping.originalLine - 1 - previousOriginalLine); previousOriginalLine = mapping.originalLine - 1; result += base64VLQ.encode(mapping.originalColumn - previousOriginalColumn); previousOriginalColumn = mapping.originalColumn; if (mapping.name != null) { result += base64VLQ.encode(this._names.indexOf(mapping.name) - previousName); previousName = this._names.indexOf(mapping.name); } } } return result; }; SourceMapGenerator.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { return aSources.map(function (source) { if (!this._sourcesContents) { return null; } if (aSourceRoot != null) { source = util.relative(aSourceRoot, source); } var key = util.toSetString(source); return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null; }, this); }; /** * Externalize the source map. */ SourceMapGenerator.prototype.toJSON = function SourceMapGenerator_toJSON() { var map = { version: this._version, sources: this._sources.toArray(), names: this._names.toArray(), mappings: this._serializeMappings() }; if (this._file != null) { map.file = this._file; } if (this._sourceRoot != null) { map.sourceRoot = this._sourceRoot; } if (this._sourcesContents) { map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); } return map; }; /** * Render the source map being generated to a string. */ SourceMapGenerator.prototype.toString = function SourceMapGenerator_toString() { return JSON.stringify(this.toJSON()); }; exports.SourceMapGenerator = SourceMapGenerator; }); },{"./array-set":484,"./base64-vlq":485,"./mapping-list":488,"./util":492,"amdefine":493}],491:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = require('amdefine')(module, require); } define(function (require, exports, module) { var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; var util = require('./util'); // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other // operating systems these days (capturing the result). var REGEX_NEWLINE = /(\r?\n)/; // Newline character code for charCodeAt() comparisons var NEWLINE_CODE = 10; // Private symbol for identifying `SourceNode`s when multiple versions of // the source-map library are loaded. This MUST NOT CHANGE across // versions! var isSourceNode = "$$$isSourceNode$$$"; /** * SourceNodes provide a way to abstract over interpolating/concatenating * snippets of generated JavaScript source code while maintaining the line and * column information associated with the original source code. * * @param aLine The original line number. * @param aColumn The original column number. * @param aSource The original source's filename. * @param aChunks Optional. An array of strings which are snippets of * generated JS, or other SourceNodes. * @param aName The original identifier. */ function SourceNode(aLine, aColumn, aSource, aChunks, aName) { this.children = []; this.sourceContents = {}; this.line = aLine == null ? null : aLine; this.column = aColumn == null ? null : aColumn; this.source = aSource == null ? null : aSource; this.name = aName == null ? null : aName; this[isSourceNode] = true; if (aChunks != null) this.add(aChunks); } /** * Creates a SourceNode from generated code and a SourceMapConsumer. * * @param aGeneratedCode The generated code * @param aSourceMapConsumer The SourceMap for the generated code * @param aRelativePath Optional. The path that relative sources in the * SourceMapConsumer should be relative to. */ SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { // The SourceNode we want to fill with the generated code // and the SourceMap var node = new SourceNode(); // All even indices of this array are one line of the generated code, // while all odd indices are the newlines between two adjacent lines // (since `REGEX_NEWLINE` captures its match). // Processed fragments are removed from this array, by calling `shiftNextLine`. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); var shiftNextLine = function() { var lineContents = remainingLines.shift(); // The last line of a file might not have a newline. var newLine = remainingLines.shift() || ""; return lineContents + newLine; }; // We need to remember the position of "remainingLines" var lastGeneratedLine = 1, lastGeneratedColumn = 0; // The generate SourceNodes we need a code range. // To extract it current and last mapping is used. // Here we store the last mapping. var lastMapping = null; aSourceMapConsumer.eachMapping(function (mapping) { if (lastMapping !== null) { // We add the code from "lastMapping" to "mapping": // First check if there is a new line in between. if (lastGeneratedLine < mapping.generatedLine) { var code = ""; // Associate first line with "lastMapping" addMappingWithCode(lastMapping, shiftNextLine()); lastGeneratedLine++; lastGeneratedColumn = 0; // The remaining code is added without mapping } else { // There is no new line in between. // Associate the code between "lastGeneratedColumn" and // "mapping.generatedColumn" with "lastMapping" var nextLine = remainingLines[0]; var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn); remainingLines[0] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn); lastGeneratedColumn = mapping.generatedColumn; addMappingWithCode(lastMapping, code); // No more remaining code, continue lastMapping = mapping; return; } } // We add the generated code until the first mapping // to the SourceNode without any mapping. // Each line is added as separate string. while (lastGeneratedLine < mapping.generatedLine) { node.add(shiftNextLine()); lastGeneratedLine++; } if (lastGeneratedColumn < mapping.generatedColumn) { var nextLine = remainingLines[0]; node.add(nextLine.substr(0, mapping.generatedColumn)); remainingLines[0] = nextLine.substr(mapping.generatedColumn); lastGeneratedColumn = mapping.generatedColumn; } lastMapping = mapping; }, this); // We have processed all mappings. if (remainingLines.length > 0) { if (lastMapping) { // Associate the remaining code in the current line with "lastMapping" addMappingWithCode(lastMapping, shiftNextLine()); } // and add the remaining lines without any mapping node.add(remainingLines.join("")); } // Copy sourcesContent into SourceNode aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content != null) { if (aRelativePath != null) { sourceFile = util.join(aRelativePath, sourceFile); } node.setSourceContent(sourceFile, content); } }); return node; function addMappingWithCode(mapping, code) { if (mapping === null || mapping.source === undefined) { node.add(code); } else { var source = aRelativePath ? util.join(aRelativePath, mapping.source) : mapping.source; node.add(new SourceNode(mapping.originalLine, mapping.originalColumn, source, code, mapping.name)); } } }; /** * Add a chunk of generated JS to this source node. * * @param aChunk A string snippet of generated JS code, another instance of * SourceNode, or an array where each member is one of those things. */ SourceNode.prototype.add = function SourceNode_add(aChunk) { if (Array.isArray(aChunk)) { aChunk.forEach(function (chunk) { this.add(chunk); }, this); } else if (aChunk[isSourceNode] || typeof aChunk === "string") { if (aChunk) { this.children.push(aChunk); } } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; /** * Add a chunk of generated JS to the beginning of this source node. * * @param aChunk A string snippet of generated JS code, another instance of * SourceNode, or an array where each member is one of those things. */ SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { if (Array.isArray(aChunk)) { for (var i = aChunk.length-1; i >= 0; i--) { this.prepend(aChunk[i]); } } else if (aChunk[isSourceNode] || typeof aChunk === "string") { this.children.unshift(aChunk); } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; /** * Walk over the tree of JS snippets in this node and its children. The * walking function is called once for each snippet of JS and is passed that * snippet and the its original associated source's line/column location. * * @param aFn The traversal function. */ SourceNode.prototype.walk = function SourceNode_walk(aFn) { var chunk; for (var i = 0, len = this.children.length; i < len; i++) { chunk = this.children[i]; if (chunk[isSourceNode]) { chunk.walk(aFn); } else { if (chunk !== '') { aFn(chunk, { source: this.source, line: this.line, column: this.column, name: this.name }); } } } }; /** * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between * each of `this.children`. * * @param aSep The separator. */ SourceNode.prototype.join = function SourceNode_join(aSep) { var newChildren; var i; var len = this.children.length; if (len > 0) { newChildren = []; for (i = 0; i < len-1; i++) { newChildren.push(this.children[i]); newChildren.push(aSep); } newChildren.push(this.children[i]); this.children = newChildren; } return this; }; /** * Call String.prototype.replace on the very right-most source snippet. Useful * for trimming whitespace from the end of a source node, etc. * * @param aPattern The pattern to replace. * @param aReplacement The thing to replace the pattern with. */ SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { var lastChild = this.children[this.children.length - 1]; if (lastChild[isSourceNode]) { lastChild.replaceRight(aPattern, aReplacement); } else if (typeof lastChild === 'string') { this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); } else { this.children.push(''.replace(aPattern, aReplacement)); } return this; }; /** * Set the source content for a source file. This will be added to the SourceMapGenerator * in the sourcesContent field. * * @param aSourceFile The filename of the source file * @param aSourceContent The content of the source file */ SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) { this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; }; /** * Walk over the tree of SourceNodes. The walking function is called for each * source file content and is passed the filename and source content. * * @param aFn The traversal function. */ SourceNode.prototype.walkSourceContents = function SourceNode_walkSourceContents(aFn) { for (var i = 0, len = this.children.length; i < len; i++) { if (this.children[i][isSourceNode]) { this.children[i].walkSourceContents(aFn); } } var sources = Object.keys(this.sourceContents); for (var i = 0, len = sources.length; i < len; i++) { aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); } }; /** * Return the string representation of this source node. Walks over the tree * and concatenates all the various snippets together to one string. */ SourceNode.prototype.toString = function SourceNode_toString() { var str = ""; this.walk(function (chunk) { str += chunk; }); return str; }; /** * Returns the string representation of this source node along with a source * map. */ SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { var generated = { code: "", line: 1, column: 0 }; var map = new SourceMapGenerator(aArgs); var sourceMappingActive = false; var lastOriginalSource = null; var lastOriginalLine = null; var lastOriginalColumn = null; var lastOriginalName = null; this.walk(function (chunk, original) { generated.code += chunk; if (original.source !== null && original.line !== null && original.column !== null) { if(lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) { map.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name }); } lastOriginalSource = original.source; lastOriginalLine = original.line; lastOriginalColumn = original.column; lastOriginalName = original.name; sourceMappingActive = true; } else if (sourceMappingActive) { map.addMapping({ generated: { line: generated.line, column: generated.column } }); lastOriginalSource = null; sourceMappingActive = false; } for (var idx = 0, length = chunk.length; idx < length; idx++) { if (chunk.charCodeAt(idx) === NEWLINE_CODE) { generated.line++; generated.column = 0; // Mappings end at eol if (idx + 1 === length) { lastOriginalSource = null; sourceMappingActive = false; } else if (sourceMappingActive) { map.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name }); } } else { generated.column++; } } }); this.walkSourceContents(function (sourceFile, sourceContent) { map.setSourceContent(sourceFile, sourceContent); }); return { code: generated.code, map: map }; }; exports.SourceNode = SourceNode; }); },{"./source-map-generator":490,"./util":492,"amdefine":493}],492:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = require('amdefine')(module, require); } define(function (require, exports, module) { /** * This is a helper function for getting values from parameter/options * objects. * * @param args The object we are extracting values from * @param name The name of the property we are getting. * @param defaultValue An optional value to return if the property is missing * from the object. If this is not specified and the property is missing, an * error will be thrown. */ function getArg(aArgs, aName, aDefaultValue) { if (aName in aArgs) { return aArgs[aName]; } else if (arguments.length === 3) { return aDefaultValue; } else { throw new Error('"' + aName + '" is a required argument.'); } } exports.getArg = getArg; var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/; var dataUrlRegexp = /^data:.+\,.+$/; function urlParse(aUrl) { var match = aUrl.match(urlRegexp); if (!match) { return null; } return { scheme: match[1], auth: match[2], host: match[3], port: match[4], path: match[5] }; } exports.urlParse = urlParse; function urlGenerate(aParsedUrl) { var url = ''; if (aParsedUrl.scheme) { url += aParsedUrl.scheme + ':'; } url += '//'; if (aParsedUrl.auth) { url += aParsedUrl.auth + '@'; } if (aParsedUrl.host) { url += aParsedUrl.host; } if (aParsedUrl.port) { url += ":" + aParsedUrl.port } if (aParsedUrl.path) { url += aParsedUrl.path; } return url; } exports.urlGenerate = urlGenerate; /** * Normalizes a path, or the path portion of a URL: * * - Replaces consequtive slashes with one slash. * - Removes unnecessary '.' parts. * - Removes unnecessary '/..' parts. * * Based on code in the Node.js 'path' core module. * * @param aPath The path or url to normalize. */ function normalize(aPath) { var path = aPath; var url = urlParse(aPath); if (url) { if (!url.path) { return aPath; } path = url.path; } var isAbsolute = (path.charAt(0) === '/'); var parts = path.split(/\/+/); for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { part = parts[i]; if (part === '.') { parts.splice(i, 1); } else if (part === '..') { up++; } else if (up > 0) { if (part === '') { // The first part is blank if the path is absolute. Trying to go // above the root is a no-op. Therefore we can remove all '..' parts // directly after the root. parts.splice(i + 1, up); up = 0; } else { parts.splice(i, 2); up--; } } } path = parts.join('/'); if (path === '') { path = isAbsolute ? '/' : '.'; } if (url) { url.path = path; return urlGenerate(url); } return path; } exports.normalize = normalize; /** * Joins two paths/URLs. * * @param aRoot The root path or URL. * @param aPath The path or URL to be joined with the root. * * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a * scheme-relative URL: Then the scheme of aRoot, if any, is prepended * first. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion * is updated with the result and aRoot is returned. Otherwise the result * is returned. * - If aPath is absolute, the result is aPath. * - Otherwise the two paths are joined with a slash. * - Joining for example 'http://' and 'www.example.com' is also supported. */ function join(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } if (aPath === "") { aPath = "."; } var aPathUrl = urlParse(aPath); var aRootUrl = urlParse(aRoot); if (aRootUrl) { aRoot = aRootUrl.path || '/'; } // `join(foo, '//www.example.org')` if (aPathUrl && !aPathUrl.scheme) { if (aRootUrl) { aPathUrl.scheme = aRootUrl.scheme; } return urlGenerate(aPathUrl); } if (aPathUrl || aPath.match(dataUrlRegexp)) { return aPath; } // `join('http://', 'www.example.com')` if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { aRootUrl.host = aPath; return urlGenerate(aRootUrl); } var joined = aPath.charAt(0) === '/' ? aPath : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); if (aRootUrl) { aRootUrl.path = joined; return urlGenerate(aRootUrl); } return joined; } exports.join = join; /** * Make a path relative to a URL or another path. * * @param aRoot The root path or URL. * @param aPath The path or URL to be made relative to aRoot. */ function relative(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } aRoot = aRoot.replace(/\/$/, ''); // XXX: It is possible to remove this block, and the tests still pass! var url = urlParse(aRoot); if (aPath.charAt(0) == "/" && url && url.path == "/") { return aPath.slice(1); } return aPath.indexOf(aRoot + '/') === 0 ? aPath.substr(aRoot.length + 1) : aPath; } exports.relative = relative; /** * Because behavior goes wacky when you set `__proto__` on objects, we * have to prefix all the strings in our set with an arbitrary character. * * See https://github.com/mozilla/source-map/pull/31 and * https://github.com/mozilla/source-map/issues/30 * * @param String aStr */ function toSetString(aStr) { return '$' + aStr; } exports.toSetString = toSetString; function fromSetString(aStr) { return aStr.substr(1); } exports.fromSetString = fromSetString; function strcmp(aStr1, aStr2) { var s1 = aStr1 || ""; var s2 = aStr2 || ""; return (s1 > s2) - (s1 < s2); } /** * Comparator between two mappings where the original positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same original source/line/column, but different generated * line and column the same. Useful when searching for a mapping with a * stubbed out mapping. */ function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { var cmp; cmp = strcmp(mappingA.source, mappingB.source); if (cmp) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp || onlyCompareOriginal) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp) { return cmp; } cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp) { return cmp; } return strcmp(mappingA.name, mappingB.name); }; exports.compareByOriginalPositions = compareByOriginalPositions; /** * Comparator between two mappings where the generated positions are * compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same generated line and column, but different * source/name/original line and column the same. Useful when searching for a * mapping with a stubbed out mapping. */ function compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) { var cmp; cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp || onlyCompareGenerated) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp) { return cmp; } return strcmp(mappingA.name, mappingB.name); }; exports.compareByGeneratedPositions = compareByGeneratedPositions; }); },{"amdefine":493}],493:[function(require,module,exports){ (function (process,__filename){ /** vim: et:ts=4:sw=4:sts=4 * @license amdefine 0.1.0 Copyright (c) 2011, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/jrburke/amdefine for details */ /*jslint node: true */ /*global module, process */ 'use strict'; /** * Creates a define for node. * @param {Object} module the "module" object that is defined by Node for the * current module. * @param {Function} [requireFn]. Node's require function for the current module. * It only needs to be passed in Node versions before 0.5, when module.require * did not exist. * @returns {Function} a define function that is usable for the current node * module. */ function amdefine(module, requireFn) { 'use strict'; var defineCache = {}, loaderCache = {}, alreadyCalled = false, path = require('path'), makeRequire, stringRequire; /** * Trims the . and .. from an array of path segments. * It will keep a leading path segment if a .. will become * the first path segment, to help with module name lookups, * which act like paths, but can be remapped. But the end result, * all paths that use this function should look normalized. * NOTE: this method MODIFIES the input array. * @param {Array} ary the array of path segments. */ function trimDots(ary) { var i, part; for (i = 0; ary[i]; i+= 1) { part = ary[i]; if (part === '.') { ary.splice(i, 1); i -= 1; } else if (part === '..') { if (i === 1 && (ary[2] === '..' || ary[0] === '..')) { //End of the line. Keep at least one non-dot //path segment at the front so it can be mapped //correctly to disk. Otherwise, there is likely //no path mapping for a path starting with '..'. //This can still fail, but catches the most reasonable //uses of .. break; } else if (i > 0) { ary.splice(i - 1, 2); i -= 2; } } } } function normalize(name, baseName) { var baseParts; //Adjust any relative paths. if (name && name.charAt(0) === '.') { //If have a base name, try to normalize against it, //otherwise, assume it is a top-level require that will //be relative to baseUrl in the end. if (baseName) { baseParts = baseName.split('/'); baseParts = baseParts.slice(0, baseParts.length - 1); baseParts = baseParts.concat(name.split('/')); trimDots(baseParts); name = baseParts.join('/'); } } return name; } /** * Create the normalize() function passed to a loader plugin's * normalize method. */ function makeNormalize(relName) { return function (name) { return normalize(name, relName); }; } function makeLoad(id) { function load(value) { loaderCache[id] = value; } load.fromText = function (id, text) { //This one is difficult because the text can/probably uses //define, and any relative paths and requires should be relative //to that id was it would be found on disk. But this would require //bootstrapping a module/require fairly deeply from node core. //Not sure how best to go about that yet. throw new Error('amdefine does not implement load.fromText'); }; return load; } makeRequire = function (systemRequire, exports, module, relId) { function amdRequire(deps, callback) { if (typeof deps === 'string') { //Synchronous, single module require('') return stringRequire(systemRequire, exports, module, deps, relId); } else { //Array of dependencies with a callback. //Convert the dependencies to modules. deps = deps.map(function (depName) { return stringRequire(systemRequire, exports, module, depName, relId); }); //Wait for next tick to call back the require call. process.nextTick(function () { callback.apply(null, deps); }); } } amdRequire.toUrl = function (filePath) { if (filePath.indexOf('.') === 0) { return normalize(filePath, path.dirname(module.filename)); } else { return filePath; } }; return amdRequire; }; //Favor explicit value, passed in if the module wants to support Node 0.4. requireFn = requireFn || function req() { return module.require.apply(module, arguments); }; function runFactory(id, deps, factory) { var r, e, m, result; if (id) { e = loaderCache[id] = {}; m = { id: id, uri: __filename, exports: e }; r = makeRequire(requireFn, e, m, id); } else { //Only support one define call per file if (alreadyCalled) { throw new Error('amdefine with no module ID cannot be called more than once per file.'); } alreadyCalled = true; //Use the real variables from node //Use module.exports for exports, since //the exports in here is amdefine exports. e = module.exports; m = module; r = makeRequire(requireFn, e, m, module.id); } //If there are dependencies, they are strings, so need //to convert them to dependency values. if (deps) { deps = deps.map(function (depName) { return r(depName); }); } //Call the factory with the right dependencies. if (typeof factory === 'function') { result = factory.apply(m.exports, deps); } else { result = factory; } if (result !== undefined) { m.exports = result; if (id) { loaderCache[id] = m.exports; } } } stringRequire = function (systemRequire, exports, module, id, relId) { //Split the ID by a ! so that var index = id.indexOf('!'), originalId = id, prefix, plugin; if (index === -1) { id = normalize(id, relId); //Straight module lookup. If it is one of the special dependencies, //deal with it, otherwise, delegate to node. if (id === 'require') { return makeRequire(systemRequire, exports, module, relId); } else if (id === 'exports') { return exports; } else if (id === 'module') { return module; } else if (loaderCache.hasOwnProperty(id)) { return loaderCache[id]; } else if (defineCache[id]) { runFactory.apply(null, defineCache[id]); return loaderCache[id]; } else { if(systemRequire) { return systemRequire(originalId); } else { throw new Error('No module with ID: ' + id); } } } else { //There is a plugin in play. prefix = id.substring(0, index); id = id.substring(index + 1, id.length); plugin = stringRequire(systemRequire, exports, module, prefix, relId); if (plugin.normalize) { id = plugin.normalize(id, makeNormalize(relId)); } else { //Normalize the ID normally. id = normalize(id, relId); } if (loaderCache[id]) { return loaderCache[id]; } else { plugin.load(id, makeRequire(systemRequire, exports, module, relId), makeLoad(id), {}); return loaderCache[id]; } } }; //Create a define function specific to the module asking for amdefine. function define(id, deps, factory) { if (Array.isArray(id)) { factory = deps; deps = id; id = undefined; } else if (typeof id !== 'string') { factory = id; id = deps = undefined; } if (deps && !Array.isArray(deps)) { factory = deps; deps = undefined; } if (!deps) { deps = ['require', 'exports', 'module']; } //Set up properties for this module. If an ID, then use //internal cache. If no ID, then use the external variables //for this node module. if (id) { //Put the module in deep freeze until there is a //require call for it. defineCache[id] = [id, deps, factory]; } else { runFactory(id, deps, factory); } } //define.require, which has access to all the values in the //cache. Useful for AMD modules that all have IDs in the file, //but need to finally export a value to node based on one of those //IDs. define.require = function (id) { if (loaderCache[id]) { return loaderCache[id]; } if (defineCache[id]) { runFactory.apply(null, defineCache[id]); return loaderCache[id]; } }; define.amd = {}; return define; } module.exports = amdefine; }).call(this,require('_process'),"/node_modules/source-map/node_modules/amdefine/amdefine.js") },{"_process":200,"path":199}],494:[function(require,module,exports){ /*! strip-json-comments Strip comments from JSON. Lets you use comments in your JSON files! https://github.com/sindresorhus/strip-json-comments by Sindre Sorhus MIT License */ (function () { 'use strict'; function stripJsonComments(str) { var currentChar; var nextChar; var insideString = false; var insideComment = false; var ret = ''; for (var i = 0; i < str.length; i++) { currentChar = str[i]; nextChar = str[i + 1]; if (!insideComment && str[i - 1] !== '\\' && currentChar === '"') { insideString = !insideString; } if (insideString) { ret += currentChar; continue; } if (!insideComment && currentChar + nextChar === '//') { insideComment = 'single'; i++; } else if (insideComment === 'single' && currentChar + nextChar === '\r\n') { insideComment = false; i++; ret += currentChar; ret += nextChar; continue; } else if (insideComment === 'single' && currentChar === '\n') { insideComment = false; } else if (!insideComment && currentChar + nextChar === '/*') { insideComment = 'multi'; i++; continue; } else if (insideComment === 'multi' && currentChar + nextChar === '*/') { insideComment = false; i++; continue; } if (insideComment) { continue; } ret += currentChar; } return ret; } if (typeof module !== 'undefined' && module.exports) { module.exports = stripJsonComments; } else { window.stripJsonComments = stripJsonComments; } })(); },{}],495:[function(require,module,exports){ 'use strict'; module.exports = function toFastProperties(obj) { /*jshint -W027*/ function f() {} f.prototype = obj; new f(); return; eval(obj); }; },{}],496:[function(require,module,exports){ 'use strict'; module.exports = function (str) { return str.replace(/[\s\uFEFF\xA0]+$/g, ''); }; },{}],497:[function(require,module,exports){ module.exports={ "name": "babel-core", "description": "Turn ES6 code into readable vanilla ES5 with source maps", "version": "5.4.3", "author": "Sebastian McKenzie ", "homepage": "https://babeljs.io/", "license": "MIT", "repository": "babel/babel", "main": "lib/babel/api/node.js", "browser": { "./lib/babel/api/register/node.js": "./lib/babel/api/register/browser.js" }, "keywords": [ "harmony", "classes", "modules", "let", "const", "var", "es6", "transpile", "transpiler", "6to5", "babel" ], "scripts": { "bench": "make bench", "test": "make test" }, "dependencies": { "acorn-jsx": "^1.0.0", "ast-types": "~0.7.0", "bluebird": "^2.9.25", "chalk": "^1.0.0", "convert-source-map": "^1.1.0", "core-js": "^0.9.0", "debug": "^2.1.1", "detect-indent": "^3.0.0", "esquery": "^0.4.0", "estraverse": "^4.0.0", "esutils": "^2.0.0", "fs-readdir-recursive": "^0.1.0", "globals": "^6.4.0", "is-integer": "^1.0.4", "js-tokens": "1.0.0", "leven": "^1.0.1", "line-numbers": "0.2.0", "lodash": "^3.6.0", "minimatch": "^2.0.3", "output-file-sync": "^1.1.0", "path-is-absolute": "^1.0.0", "private": "^0.1.6", "regenerator": "^0.8.20", "regexpu": "^1.1.2", "repeating": "^1.1.2", "resolve": "^1.1.6", "shebang-regex": "^1.0.0", "slash": "^1.0.0", "source-map": "^0.4.0", "source-map-support": "^0.2.10", "strip-json-comments": "^1.0.2", "to-fast-properties": "^1.0.0", "trim-right": "^1.0.0", "user-home": "^1.1.1" }, "devDependencies": { "babel": "5.3.1", "browserify": "^9.0.8", "chai": "^2.2.0", "eslint": "^0.18.0", "babel-eslint": "^2.0.0", "esvalid": "^1.1.0", "istanbul": "^0.3.5", "matcha": "^0.6.0", "mocha": "2.2.0", "rimraf": "^2.3.2", "uglify-js": "^2.4.16" } } },{}],498:[function(require,module,exports){ module.exports={"abstract-expression-call":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"PROPERTY","type":"Identifier","end":null},"property":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Symbol","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"referenceGet","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"OBJECT","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"property":{"start":null,"loc":null,"range":null,"name":"call","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"OBJECT","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"abstract-expression-delete":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"PROPERTY","type":"Identifier","end":null},"property":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Symbol","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"referenceDelete","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"OBJECT","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"abstract-expression-get":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"PROPERTY","type":"Identifier","end":null},"property":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Symbol","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"referenceGet","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"OBJECT","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"abstract-expression-set":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"PROPERTY","type":"Identifier","end":null},"property":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Symbol","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"referenceSet","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"OBJECT","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"VALUE","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"array-comprehension-container":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"KEY","type":"Identifier","end":null},"init":{"start":null,"loc":null,"range":null,"elements":[],"type":"ArrayExpression","end":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"name":"KEY","type":"Identifier","end":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"arguments":[],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"array-from":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Array","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"from","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"VALUE","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"array-push":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"KEY","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"push","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"STATEMENT","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"call":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"OBJECT","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"call","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"CONTEXT","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"class-decorator":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"start":null,"loc":null,"range":null,"name":"CLASS_REF","type":"Identifier","end":null},"right":{"loc":null,"start":null,"range":null,"left":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"DECORATOR","type":"Identifier","end":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"CLASS_REF","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"operator":"||","right":{"start":null,"loc":null,"range":null,"name":"CLASS_REF","type":"Identifier","end":null},"type":"LogicalExpression","end":null,"_paths":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"class-super-constructor-call-loose":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"SUPER_NAME","type":"Identifier","end":null},"operator":"!=","right":{"start":null,"loc":null,"range":null,"value":null,"raw":null,"type":"Literal","end":null},"type":"BinaryExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"SUPER_NAME","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"apply","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"type":"ThisExpression","end":null},{"start":null,"loc":null,"range":null,"name":"arguments","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null}],"type":"Program","end":null},"class-super-constructor-call":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"SUPER_NAME","type":"Identifier","end":null},"operator":"!=","right":{"start":null,"loc":null,"range":null,"value":null,"raw":null,"type":"Literal","end":null},"type":"BinaryExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"SUPER_NAME","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"apply","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"type":"ThisExpression","end":null},{"start":null,"loc":null,"range":null,"name":"arguments","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null}],"type":"Program","end":null},"class-super-native-constructor-call":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"SUPER_NAME","type":"Identifier","end":null},"operator":"!=","right":{"start":null,"loc":null,"range":null,"value":null,"raw":null,"type":"Literal","end":null},"type":"BinaryExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"NATIVE_REF","type":"Identifier","end":null},"init":{"start":null,"loc":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"SUPER_NAME","type":"Identifier","end":null},"arguments":[{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"name":"arguments","type":"Identifier","end":null},"type":"SpreadElement","end":null,"_paths":null}],"type":"NewExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"NATIVE_REF","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"__proto__","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"CLASS_NAME","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"prototype","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"name":"NATIVE_REF","type":"Identifier","end":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null}],"type":"Program","end":null},"default-parameter":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"VARIABLE_NAME","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"ARGUMENTS","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"ARGUMENT_KEY","type":"Identifier","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"operator":"===","right":{"start":null,"loc":null,"range":null,"name":"undefined","type":"Identifier","end":null},"type":"BinaryExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"name":"DEFAULT_VALUE","type":"Identifier","end":null},"alternate":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"ARGUMENTS","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"ARGUMENT_KEY","type":"Identifier","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"type":"ConditionalExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"let","type":"VariableDeclaration","end":null}],"type":"Program","end":null},"exports-assign":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"exports","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"KEY","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"right":{"start":null,"loc":null,"range":null,"name":"VALUE","type":"Identifier","end":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"exports-default-assign":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"module","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"exports","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"right":{"start":null,"loc":null,"range":null,"name":"VALUE","type":"Identifier","end":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"exports-from-assign":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Object","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"defineProperty","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"exports","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"ID","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"properties":[{"start":null,"loc":null,"range":null,"method":false,"shorthand":false,"computed":false,"key":{"start":null,"loc":null,"range":null,"name":"enumerable","type":"Identifier","end":null},"value":{"start":null,"loc":null,"range":null,"value":true,"raw":null,"type":"Literal","end":null},"kind":"init","type":"Property","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"method":false,"shorthand":false,"computed":false,"key":{"start":null,"loc":null,"range":null,"name":"get","type":"Identifier","end":null},"value":{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"get","type":"Identifier","end":null},"generator":false,"expression":false,"params":[],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"name":"INIT","type":"Identifier","end":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"_paths":null},"kind":"init","type":"Property","end":null,"_paths":null}],"type":"ObjectExpression","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"exports-module-declaration-loose":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"exports","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"__esModule","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"right":{"start":null,"loc":null,"range":null,"value":true,"raw":null,"type":"Literal","end":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"exports-module-declaration":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Object","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"defineProperty","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"exports","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"value":"__esModule","raw":null,"type":"Literal","end":null},{"start":null,"loc":null,"range":null,"properties":[{"start":null,"loc":null,"range":null,"method":false,"shorthand":false,"computed":false,"key":{"start":null,"loc":null,"range":null,"name":"value","type":"Identifier","end":null},"value":{"start":null,"loc":null,"range":null,"value":true,"raw":null,"type":"Literal","end":null},"kind":"init","type":"Property","end":null,"_paths":null}],"type":"ObjectExpression","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"for-of-array":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"init":{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"KEY","type":"Identifier","end":null},"init":{"start":null,"loc":null,"range":null,"value":0,"raw":null,"type":"Literal","end":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"KEY","type":"Identifier","end":null},"operator":"<","right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"ARR","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"length","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"BinaryExpression","end":null,"_paths":null},"update":{"loc":null,"start":null,"range":null,"operator":"++","prefix":false,"argument":{"start":null,"loc":null,"range":null,"name":"KEY","type":"Identifier","end":null},"type":"UpdateExpression","end":null,"_paths":null},"body":{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"name":"BODY","type":"Identifier","end":null},"type":"ExpressionStatement","end":null,"_paths":null},"type":"ForStatement","end":null,"_paths":null}],"type":"Program","end":null},"for-of-loose":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"init":{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"LOOP_OBJECT","type":"Identifier","end":null},"init":{"start":null,"loc":null,"range":null,"name":"OBJECT","type":"Identifier","end":null},"type":"VariableDeclarator","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"IS_ARRAY","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Array","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"isArray","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"LOOP_OBJECT","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"INDEX","type":"Identifier","end":null},"init":{"start":null,"loc":null,"range":null,"value":0,"raw":null,"type":"Literal","end":null},"type":"VariableDeclarator","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"LOOP_OBJECT","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"test":{"start":null,"loc":null,"range":null,"name":"IS_ARRAY","type":"Identifier","end":null},"consequent":{"start":null,"loc":null,"range":null,"name":"LOOP_OBJECT","type":"Identifier","end":null},"alternate":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"LOOP_OBJECT","type":"Identifier","end":null},"property":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Symbol","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"iterator","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"arguments":[],"type":"CallExpression","end":null,"_paths":null},"type":"ConditionalExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},"test":null,"update":null,"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"ID","type":"Identifier","end":null},"init":null,"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"test":{"start":null,"loc":null,"range":null,"name":"IS_ARRAY","type":"Identifier","end":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"INDEX","type":"Identifier","end":null},"operator":">=","right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"LOOP_OBJECT","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"length","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"BinaryExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"label":null,"type":"BreakStatement","end":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"start":null,"loc":null,"range":null,"name":"ID","type":"Identifier","end":null},"right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"LOOP_OBJECT","type":"Identifier","end":null},"property":{"loc":null,"start":null,"range":null,"operator":"++","prefix":false,"argument":{"start":null,"loc":null,"range":null,"name":"INDEX","type":"Identifier","end":null},"type":"UpdateExpression","end":null,"_paths":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"start":null,"loc":null,"range":null,"name":"INDEX","type":"Identifier","end":null},"right":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"LOOP_OBJECT","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"next","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[],"type":"CallExpression","end":null,"_paths":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"INDEX","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"done","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"label":null,"type":"BreakStatement","end":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"start":null,"loc":null,"range":null,"name":"ID","type":"Identifier","end":null},"right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"INDEX","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"value","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"IfStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"ForStatement","end":null,"_paths":null}],"type":"Program","end":null},"for-of":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"ITERATOR_COMPLETION","type":"Identifier","end":null},"init":{"start":null,"loc":null,"range":null,"value":true,"raw":null,"type":"Literal","end":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"ITERATOR_HAD_ERROR_KEY","type":"Identifier","end":null},"init":{"start":null,"loc":null,"range":null,"value":false,"raw":null,"type":"Literal","end":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"ITERATOR_ERROR_KEY","type":"Identifier","end":null},"init":{"start":null,"loc":null,"range":null,"name":"undefined","type":"Identifier","end":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"block":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"init":{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"ITERATOR_KEY","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"OBJECT","type":"Identifier","end":null},"property":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Symbol","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"iterator","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"arguments":[],"type":"CallExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"STEP_KEY","type":"Identifier","end":null},"init":null,"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},"test":{"start":null,"loc":null,"range":null,"operator":"!","prefix":true,"argument":{"loc":null,"start":null,"range":null,"operator":"=","left":{"start":null,"loc":null,"range":null,"name":"ITERATOR_COMPLETION","type":"Identifier","end":null},"right":{"loc":null,"start":null,"range":null,"object":{"loc":null,"start":null,"range":null,"operator":"=","left":{"start":null,"loc":null,"range":null,"name":"STEP_KEY","type":"Identifier","end":null},"right":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"ITERATOR_KEY","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"next","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[],"type":"CallExpression","end":null,"_paths":null},"type":"AssignmentExpression","end":null,"parenthesizedExpression":true,"_paths":null},"property":{"start":null,"loc":null,"range":null,"name":"done","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"AssignmentExpression","end":null,"parenthesizedExpression":true,"_paths":null},"type":"UnaryExpression","end":null,"_paths":null},"update":{"loc":null,"start":null,"range":null,"operator":"=","left":{"start":null,"loc":null,"range":null,"name":"ITERATOR_COMPLETION","type":"Identifier","end":null},"right":{"start":null,"loc":null,"range":null,"value":true,"raw":null,"type":"Literal","end":null},"type":"AssignmentExpression","end":null,"_paths":null},"body":{"start":null,"loc":null,"range":null,"body":[],"type":"BlockStatement","end":null},"type":"ForStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"handler":{"start":null,"loc":null,"range":null,"param":{"start":null,"loc":null,"range":null,"name":"err","type":"Identifier","end":null},"guard":null,"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"start":null,"loc":null,"range":null,"name":"ITERATOR_HAD_ERROR_KEY","type":"Identifier","end":null},"right":{"start":null,"loc":null,"range":null,"value":true,"raw":null,"type":"Literal","end":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"start":null,"loc":null,"range":null,"name":"ITERATOR_ERROR_KEY","type":"Identifier","end":null},"right":{"start":null,"loc":null,"range":null,"name":"err","type":"Identifier","end":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"CatchClause","end":null,"_paths":null},"guardedHandlers":[],"finalizer":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"block":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"operator":"!","prefix":true,"argument":{"start":null,"loc":null,"range":null,"name":"ITERATOR_COMPLETION","type":"Identifier","end":null},"type":"UnaryExpression","end":null,"_paths":null},"operator":"&&","right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"ITERATOR_KEY","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"value":"return","raw":null,"type":"Literal","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"type":"LogicalExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"ITERATOR_KEY","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"value":"return","raw":null,"type":"Literal","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"arguments":[],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"handler":null,"guardedHandlers":[],"finalizer":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"test":{"start":null,"loc":null,"range":null,"name":"ITERATOR_HAD_ERROR_KEY","type":"Identifier","end":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"name":"ITERATOR_ERROR_KEY","type":"Identifier","end":null},"type":"ThrowStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"TryStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"TryStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-async-to-generator":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"fn","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"gen","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"fn","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"apply","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"type":"ThisExpression","end":null},{"start":null,"loc":null,"range":null,"name":"arguments","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"Promise","type":"Identifier","end":null},"arguments":[{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"resolve","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"reject","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"callNext","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"step","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"bind","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"value":null,"raw":null,"type":"Literal","end":null},{"start":null,"loc":null,"range":null,"value":"next","raw":null,"type":"Literal","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"callThrow","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"step","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"bind","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"value":null,"raw":null,"type":"Literal","end":null},{"start":null,"loc":null,"range":null,"value":"throw","raw":null,"type":"Literal","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"step","type":"Identifier","end":null},"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"arg","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"block":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"info","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"gen","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"arg","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"value","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"info","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"value","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null}],"type":"BlockStatement","end":null},"handler":{"start":null,"loc":null,"range":null,"param":{"start":null,"loc":null,"range":null,"name":"error","type":"Identifier","end":null},"guard":null,"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"reject","type":"Identifier","end":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"error","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"argument":null,"type":"ReturnStatement","end":null}],"type":"BlockStatement","end":null},"type":"CatchClause","end":null,"_paths":null},"guardedHandlers":[],"finalizer":null,"type":"TryStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"info","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"done","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"resolve","type":"Identifier","end":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"value","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Promise","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"resolve","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"value","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"property":{"start":null,"loc":null,"range":null,"name":"then","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"callNext","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"callThrow","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"IfStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionDeclaration","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"callNext","type":"Identifier","end":null},"arguments":[],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"_paths":null}],"type":"NewExpression","end":null,"_paths":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"_paths":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-bind":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"object":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Function","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"prototype","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"property":{"start":null,"loc":null,"range":null,"name":"bind","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-class-call-check":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"instance","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"Constructor","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"test":{"start":null,"loc":null,"range":null,"operator":"!","prefix":true,"argument":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"instance","type":"Identifier","end":null},"operator":"instanceof","right":{"start":null,"loc":null,"range":null,"name":"Constructor","type":"Identifier","end":null},"type":"BinaryExpression","end":null,"parenthesizedExpression":true,"_paths":null},"type":"UnaryExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"TypeError","type":"Identifier","end":null},"arguments":[{"start":null,"loc":null,"range":null,"value":"Cannot call a class as a function","raw":null,"type":"Literal","end":null}],"type":"NewExpression","end":null,"_paths":null},"type":"ThrowStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-create-class":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"defineProperties","type":"Identifier","end":null},"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"target","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"props","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"init":{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"init":{"start":null,"loc":null,"range":null,"value":0,"raw":null,"type":"Literal","end":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"operator":"<","right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"props","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"length","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"BinaryExpression","end":null,"_paths":null},"update":{"loc":null,"start":null,"range":null,"operator":"++","prefix":false,"argument":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"type":"UpdateExpression","end":null,"_paths":null},"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"props","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"enumerable","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"right":{"loc":null,"start":null,"range":null,"left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"enumerable","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"operator":"||","right":{"start":null,"loc":null,"range":null,"value":false,"raw":null,"type":"Literal","end":null},"type":"LogicalExpression","end":null,"_paths":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"configurable","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"right":{"start":null,"loc":null,"range":null,"value":true,"raw":null,"type":"Literal","end":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"value":"value","raw":null,"type":"Literal","end":null},"operator":"in","right":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"type":"BinaryExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"writable","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"right":{"start":null,"loc":null,"range":null,"value":true,"raw":null,"type":"Literal","end":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Object","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"defineProperty","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"target","type":"Identifier","end":null},{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"ForStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionDeclaration","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"Constructor","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"protoProps","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"staticProps","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"test":{"start":null,"loc":null,"range":null,"name":"protoProps","type":"Identifier","end":null},"consequent":{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"defineProperties","type":"Identifier","end":null},"arguments":[{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Constructor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"prototype","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"name":"protoProps","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"test":{"start":null,"loc":null,"range":null,"name":"staticProps","type":"Identifier","end":null},"consequent":{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"defineProperties","type":"Identifier","end":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"Constructor","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"staticProps","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"name":"Constructor","type":"Identifier","end":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"_paths":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"arguments":[],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-create-decorated-class":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"defineProperties","type":"Identifier","end":null},"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"target","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"descriptors","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"initializers","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"init":{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"init":{"start":null,"loc":null,"range":null,"value":0,"raw":null,"type":"Literal","end":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"operator":"<","right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptors","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"length","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"BinaryExpression","end":null,"_paths":null},"update":{"loc":null,"start":null,"range":null,"operator":"++","prefix":false,"argument":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"type":"UpdateExpression","end":null,"_paths":null},"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptors","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"decorators","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"decorators","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"operator":"delete","prefix":true,"argument":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"UnaryExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"leadingComments":null,"_paths":null},{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"operator":"delete","prefix":true,"argument":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"decorators","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"UnaryExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"enumerable","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"right":{"loc":null,"start":null,"range":null,"left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"enumerable","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"operator":"||","right":{"start":null,"loc":null,"range":null,"value":false,"raw":null,"type":"Literal","end":null},"type":"LogicalExpression","end":null,"_paths":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"configurable","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"right":{"start":null,"loc":null,"range":null,"value":true,"raw":null,"type":"Literal","end":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"value":"value","raw":null,"type":"Literal","end":null},"operator":"in","right":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"type":"BinaryExpression","end":null,"_paths":null},"operator":"||","right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"initializer","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"LogicalExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"writable","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"right":{"start":null,"loc":null,"range":null,"value":true,"raw":null,"type":"Literal","end":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"test":{"start":null,"loc":null,"range":null,"name":"decorators","type":"Identifier","end":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"init":{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"f","type":"Identifier","end":null},"init":{"start":null,"loc":null,"range":null,"value":0,"raw":null,"type":"Literal","end":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"f","type":"Identifier","end":null},"operator":"<","right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"decorators","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"length","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"BinaryExpression","end":null,"_paths":null},"update":{"loc":null,"start":null,"range":null,"operator":"++","prefix":false,"argument":{"start":null,"loc":null,"range":null,"name":"f","type":"Identifier","end":null},"type":"UpdateExpression","end":null,"_paths":null},"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"decorator","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"decorators","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"f","type":"Identifier","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"operator":"typeof","prefix":true,"argument":{"start":null,"loc":null,"range":null,"name":"decorator","type":"Identifier","end":null},"type":"UnaryExpression","end":null,"_paths":null},"operator":"===","right":{"start":null,"loc":null,"range":null,"value":"function","raw":null,"type":"Literal","end":null},"type":"BinaryExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"right":{"loc":null,"start":null,"range":null,"left":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"decorator","type":"Identifier","end":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"target","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"operator":"||","right":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"type":"LogicalExpression","end":null,"_paths":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"TypeError","type":"Identifier","end":null},"arguments":[{"loc":null,"start":null,"range":null,"left":{"loc":null,"start":null,"range":null,"left":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"value":"The decorator for method ","raw":null,"type":"Literal","end":null},"operator":"+","right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"BinaryExpression","end":null,"_paths":null},"operator":"+","right":{"start":null,"loc":null,"range":null,"value":" is of the invalid type ","raw":null,"type":"Literal","end":null},"type":"BinaryExpression","end":null,"_paths":null},"operator":"+","right":{"start":null,"loc":null,"range":null,"operator":"typeof","prefix":true,"argument":{"start":null,"loc":null,"range":null,"name":"decorator","type":"Identifier","end":null},"type":"UnaryExpression","end":null,"_paths":null},"type":"BinaryExpression","end":null,"_paths":null}],"type":"NewExpression","end":null,"_paths":null},"type":"ThrowStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"IfStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"ForStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"initializer","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"operator":"!==","right":{"start":null,"loc":null,"range":null,"name":"undefined","type":"Identifier","end":null},"type":"BinaryExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"initializers","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"right":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"label":null,"type":"ContinueStatement","end":null}],"type":"BlockStatement","end":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Object","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"defineProperty","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"target","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"ForStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionDeclaration","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"Constructor","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"protoProps","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"staticProps","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"protoInitializers","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"staticInitializers","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"test":{"start":null,"loc":null,"range":null,"name":"protoProps","type":"Identifier","end":null},"consequent":{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"defineProperties","type":"Identifier","end":null},"arguments":[{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Constructor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"prototype","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"name":"protoProps","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"protoInitializers","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"test":{"start":null,"loc":null,"range":null,"name":"staticProps","type":"Identifier","end":null},"consequent":{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"defineProperties","type":"Identifier","end":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"Constructor","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"staticProps","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"staticInitializers","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"name":"Constructor","type":"Identifier","end":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"_paths":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"arguments":[],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-create-decorated-object":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"descriptors","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"target","type":"Identifier","end":null},"init":{"start":null,"loc":null,"range":null,"properties":[],"type":"ObjectExpression","end":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"init":{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"init":{"start":null,"loc":null,"range":null,"value":0,"raw":null,"type":"Literal","end":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"operator":"<","right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptors","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"length","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"BinaryExpression","end":null,"_paths":null},"update":{"loc":null,"start":null,"range":null,"operator":"++","prefix":false,"argument":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"type":"UpdateExpression","end":null,"_paths":null},"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptors","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"decorators","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"decorators","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"operator":"delete","prefix":true,"argument":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"UnaryExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"leadingComments":null,"_paths":null},{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"operator":"delete","prefix":true,"argument":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"decorators","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"UnaryExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"enumerable","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"right":{"start":null,"loc":null,"range":null,"value":true,"raw":null,"type":"Literal","end":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"configurable","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"right":{"start":null,"loc":null,"range":null,"value":true,"raw":null,"type":"Literal","end":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"writable","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"right":{"start":null,"loc":null,"range":null,"value":true,"raw":null,"type":"Literal","end":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"test":{"start":null,"loc":null,"range":null,"name":"decorators","type":"Identifier","end":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"init":{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"f","type":"Identifier","end":null},"init":{"start":null,"loc":null,"range":null,"value":0,"raw":null,"type":"Literal","end":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"f","type":"Identifier","end":null},"operator":"<","right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"decorators","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"length","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"BinaryExpression","end":null,"_paths":null},"update":{"loc":null,"start":null,"range":null,"operator":"++","prefix":false,"argument":{"start":null,"loc":null,"range":null,"name":"f","type":"Identifier","end":null},"type":"UpdateExpression","end":null,"_paths":null},"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"decorator","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"decorators","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"f","type":"Identifier","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"operator":"typeof","prefix":true,"argument":{"start":null,"loc":null,"range":null,"name":"decorator","type":"Identifier","end":null},"type":"UnaryExpression","end":null,"_paths":null},"operator":"===","right":{"start":null,"loc":null,"range":null,"value":"function","raw":null,"type":"Literal","end":null},"type":"BinaryExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"right":{"loc":null,"start":null,"range":null,"left":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"decorator","type":"Identifier","end":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"target","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"operator":"||","right":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"type":"LogicalExpression","end":null,"_paths":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"TypeError","type":"Identifier","end":null},"arguments":[{"loc":null,"start":null,"range":null,"left":{"loc":null,"start":null,"range":null,"left":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"value":"The decorator for method ","raw":null,"type":"Literal","end":null},"operator":"+","right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"BinaryExpression","end":null,"_paths":null},"operator":"+","right":{"start":null,"loc":null,"range":null,"value":" is of the invalid type ","raw":null,"type":"Literal","end":null},"type":"BinaryExpression","end":null,"_paths":null},"operator":"+","right":{"start":null,"loc":null,"range":null,"operator":"typeof","prefix":true,"argument":{"start":null,"loc":null,"range":null,"name":"decorator","type":"Identifier","end":null},"type":"UnaryExpression","end":null,"_paths":null},"type":"BinaryExpression","end":null,"_paths":null}],"type":"NewExpression","end":null,"_paths":null},"type":"ThrowStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"IfStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"ForStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"initializer","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"value","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"right":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"initializer","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"property":{"start":null,"loc":null,"range":null,"name":"call","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"target","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Object","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"defineProperty","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"target","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"ForStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"name":"target","type":"Identifier","end":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-default-props":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"defaultProps","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"props","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"test":{"start":null,"loc":null,"range":null,"name":"defaultProps","type":"Identifier","end":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"left":{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"propName","type":"Identifier","end":null},"init":null,"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},"right":{"start":null,"loc":null,"range":null,"name":"defaultProps","type":"Identifier","end":null},"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"operator":"typeof","prefix":true,"argument":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"props","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"propName","type":"Identifier","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"type":"UnaryExpression","end":null,"_paths":null},"operator":"===","right":{"start":null,"loc":null,"range":null,"value":"undefined","raw":null,"type":"Literal","end":null},"type":"BinaryExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"props","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"propName","type":"Identifier","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"defaultProps","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"propName","type":"Identifier","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"ForInStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"name":"props","type":"Identifier","end":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-defaults":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"defaults","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"keys","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Object","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"getOwnPropertyNames","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"defaults","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"init":{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"init":{"start":null,"loc":null,"range":null,"value":0,"raw":null,"type":"Literal","end":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"operator":"<","right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"keys","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"length","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"BinaryExpression","end":null,"_paths":null},"update":{"loc":null,"start":null,"range":null,"operator":"++","prefix":false,"argument":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"type":"UpdateExpression","end":null,"_paths":null},"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"keys","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"value","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Object","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"getOwnPropertyDescriptor","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"defaults","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"value","type":"Identifier","end":null},"operator":"&&","right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"value","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"configurable","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"LogicalExpression","end":null,"_paths":null},"operator":"&&","right":{"loc":null,"start":null,"range":null,"left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"operator":"===","right":{"start":null,"loc":null,"range":null,"name":"undefined","type":"Identifier","end":null},"type":"BinaryExpression","end":null,"_paths":null},"type":"LogicalExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Object","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"defineProperty","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"value","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"ForStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-define-decorated-property-descriptor":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"target","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"descriptors","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"_descriptor","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptors","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"test":{"start":null,"loc":null,"range":null,"operator":"!","prefix":true,"argument":{"start":null,"loc":null,"range":null,"name":"_descriptor","type":"Identifier","end":null},"type":"UnaryExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"argument":null,"type":"ReturnStatement","end":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"init":{"start":null,"loc":null,"range":null,"properties":[],"type":"ObjectExpression","end":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null,"leadingComments":null},{"start":null,"loc":null,"range":null,"left":{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"_key","type":"Identifier","end":null},"init":null,"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},"right":{"start":null,"loc":null,"range":null,"name":"_descriptor","type":"Identifier","end":null},"body":{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"_key","type":"Identifier","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"_descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"_key","type":"Identifier","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},"type":"ForInStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"value","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"right":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"initializer","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"property":{"start":null,"loc":null,"range":null,"name":"call","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"target","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"leadingComments":null,"_paths":null},{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Object","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"defineProperty","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"target","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"descriptor","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-define-property":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"value","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Object","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"defineProperty","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"properties":[{"start":null,"loc":null,"range":null,"method":false,"shorthand":false,"computed":false,"key":{"start":null,"loc":null,"range":null,"name":"value","type":"Identifier","end":null},"value":{"start":null,"loc":null,"range":null,"name":"value","type":"Identifier","end":null},"kind":"init","type":"Property","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"method":false,"shorthand":false,"computed":false,"key":{"start":null,"loc":null,"range":null,"name":"enumerable","type":"Identifier","end":null},"value":{"start":null,"loc":null,"range":null,"value":true,"raw":null,"type":"Literal","end":null},"kind":"init","type":"Property","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"method":false,"shorthand":false,"computed":false,"key":{"start":null,"loc":null,"range":null,"name":"configurable","type":"Identifier","end":null},"value":{"start":null,"loc":null,"range":null,"value":true,"raw":null,"type":"Literal","end":null},"kind":"init","type":"Property","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"method":false,"shorthand":false,"computed":false,"key":{"start":null,"loc":null,"range":null,"name":"writable","type":"Identifier","end":null},"value":{"start":null,"loc":null,"range":null,"value":true,"raw":null,"type":"Literal","end":null},"kind":"init","type":"Property","end":null,"_paths":null}],"type":"ObjectExpression","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-extends":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Object","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"assign","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"operator":"||","right":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"target","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"init":{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"init":{"start":null,"loc":null,"range":null,"value":1,"raw":null,"type":"Literal","end":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"operator":"<","right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"arguments","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"length","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"BinaryExpression","end":null,"_paths":null},"update":{"loc":null,"start":null,"range":null,"operator":"++","prefix":false,"argument":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"type":"UpdateExpression","end":null,"_paths":null},"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"source","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"arguments","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"left":{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null},"init":null,"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},"right":{"start":null,"loc":null,"range":null,"name":"source","type":"Identifier","end":null},"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"loc":null,"start":null,"range":null,"object":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Object","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"prototype","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"property":{"start":null,"loc":null,"range":null,"name":"hasOwnProperty","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"property":{"start":null,"loc":null,"range":null,"name":"call","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"source","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"target","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"source","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"ForInStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"ForStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"name":"target","type":"Identifier","end":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"_paths":null},"type":"LogicalExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-get":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"get","type":"Identifier","end":null},"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"object","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"property","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"receiver","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"desc","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Object","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"getOwnPropertyDescriptor","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"object","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"property","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"desc","type":"Identifier","end":null},"operator":"===","right":{"start":null,"loc":null,"range":null,"name":"undefined","type":"Identifier","end":null},"type":"BinaryExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"parent","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Object","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"getPrototypeOf","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"object","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"parent","type":"Identifier","end":null},"operator":"===","right":{"start":null,"loc":null,"range":null,"value":null,"raw":null,"type":"Literal","end":null},"type":"BinaryExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"name":"undefined","type":"Identifier","end":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"get","type":"Identifier","end":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"parent","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"property","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"receiver","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"IfStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"value":"value","raw":null,"type":"Literal","end":null},"operator":"in","right":{"start":null,"loc":null,"range":null,"name":"desc","type":"Identifier","end":null},"type":"BinaryExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"desc","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"value","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"getter","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"desc","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"get","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"getter","type":"Identifier","end":null},"operator":"===","right":{"start":null,"loc":null,"range":null,"name":"undefined","type":"Identifier","end":null},"type":"BinaryExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"name":"undefined","type":"Identifier","end":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"argument":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"getter","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"call","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"receiver","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"IfStatement","end":null,"_paths":null},"type":"IfStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-has-own":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"object":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Object","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"prototype","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"property":{"start":null,"loc":null,"range":null,"name":"hasOwnProperty","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-inherits":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"subClass","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"superClass","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"operator":"typeof","prefix":true,"argument":{"start":null,"loc":null,"range":null,"name":"superClass","type":"Identifier","end":null},"type":"UnaryExpression","end":null,"_paths":null},"operator":"!==","right":{"start":null,"loc":null,"range":null,"value":"function","raw":null,"type":"Literal","end":null},"type":"BinaryExpression","end":null,"_paths":null},"operator":"&&","right":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"superClass","type":"Identifier","end":null},"operator":"!==","right":{"start":null,"loc":null,"range":null,"value":null,"raw":null,"type":"Literal","end":null},"type":"BinaryExpression","end":null,"_paths":null},"type":"LogicalExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"TypeError","type":"Identifier","end":null},"arguments":[{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"value":"Super expression must either be null or a function, not ","raw":null,"type":"Literal","end":null},"operator":"+","right":{"start":null,"loc":null,"range":null,"operator":"typeof","prefix":true,"argument":{"start":null,"loc":null,"range":null,"name":"superClass","type":"Identifier","end":null},"type":"UnaryExpression","end":null,"_paths":null},"type":"BinaryExpression","end":null,"_paths":null}],"type":"NewExpression","end":null,"_paths":null},"type":"ThrowStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"subClass","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"prototype","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"right":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Object","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"create","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"superClass","type":"Identifier","end":null},"operator":"&&","right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"superClass","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"prototype","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"LogicalExpression","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"properties":[{"start":null,"loc":null,"range":null,"method":false,"shorthand":false,"computed":false,"key":{"start":null,"loc":null,"range":null,"name":"constructor","type":"Identifier","end":null},"value":{"start":null,"loc":null,"range":null,"properties":[{"start":null,"loc":null,"range":null,"method":false,"shorthand":false,"computed":false,"key":{"start":null,"loc":null,"range":null,"name":"value","type":"Identifier","end":null},"value":{"start":null,"loc":null,"range":null,"name":"subClass","type":"Identifier","end":null},"kind":"init","type":"Property","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"method":false,"shorthand":false,"computed":false,"key":{"start":null,"loc":null,"range":null,"name":"enumerable","type":"Identifier","end":null},"value":{"start":null,"loc":null,"range":null,"value":false,"raw":null,"type":"Literal","end":null},"kind":"init","type":"Property","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"method":false,"shorthand":false,"computed":false,"key":{"start":null,"loc":null,"range":null,"name":"writable","type":"Identifier","end":null},"value":{"start":null,"loc":null,"range":null,"value":true,"raw":null,"type":"Literal","end":null},"kind":"init","type":"Property","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"method":false,"shorthand":false,"computed":false,"key":{"start":null,"loc":null,"range":null,"name":"configurable","type":"Identifier","end":null},"value":{"start":null,"loc":null,"range":null,"value":true,"raw":null,"type":"Literal","end":null},"kind":"init","type":"Property","end":null,"_paths":null}],"type":"ObjectExpression","end":null},"kind":"init","type":"Property","end":null,"_paths":null}],"type":"ObjectExpression","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"test":{"start":null,"loc":null,"range":null,"name":"superClass","type":"Identifier","end":null},"consequent":{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"subClass","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"__proto__","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"right":{"start":null,"loc":null,"range":null,"name":"superClass","type":"Identifier","end":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-instanceof":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"left","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"right","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"right","type":"Identifier","end":null},"operator":"!=","right":{"start":null,"loc":null,"range":null,"value":null,"raw":null,"type":"Literal","end":null},"type":"BinaryExpression","end":null,"_paths":null},"operator":"&&","right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"right","type":"Identifier","end":null},"property":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Symbol","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"hasInstance","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"type":"LogicalExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"right","type":"Identifier","end":null},"property":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Symbol","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"hasInstance","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"left","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"left","type":"Identifier","end":null},"operator":"instanceof","right":{"start":null,"loc":null,"range":null,"name":"right","type":"Identifier","end":null},"type":"BinaryExpression","end":null,"_paths":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"IfStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-interop-require-default":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"loc":null,"start":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null},"operator":"&&","right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"__esModule","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"LogicalExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null},"alternate":{"start":null,"loc":null,"range":null,"properties":[{"start":null,"loc":null,"range":null,"method":false,"shorthand":false,"computed":false,"key":{"start":null,"loc":null,"range":null,"value":"default","raw":null,"type":"Literal","end":null},"value":{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null},"kind":"init","type":"Property","end":null,"_paths":null}],"type":"ObjectExpression","end":null},"type":"ConditionalExpression","end":null,"_paths":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-interop-require-wildcard":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null},"operator":"&&","right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"__esModule","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"LogicalExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"newObj","type":"Identifier","end":null},"init":{"start":null,"loc":null,"range":null,"properties":[],"type":"ObjectExpression","end":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null},"operator":"!=","right":{"start":null,"loc":null,"range":null,"value":null,"raw":null,"type":"Literal","end":null},"type":"BinaryExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"left":{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null},"init":null,"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},"right":{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null},"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"loc":null,"start":null,"range":null,"object":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Object","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"prototype","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"property":{"start":null,"loc":null,"range":null,"name":"hasOwnProperty","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"property":{"start":null,"loc":null,"range":null,"name":"call","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"newObj","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"key","type":"Identifier","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"ForInStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"newObj","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"value":"default","raw":null,"type":"Literal","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"right":{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"name":"newObj","type":"Identifier","end":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"IfStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-interop-require":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"loc":null,"start":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null},"operator":"&&","right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"__esModule","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"LogicalExpression","end":null,"_paths":null},"consequent":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"value":"default","raw":null,"type":"Literal","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"alternate":{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null},"type":"ConditionalExpression","end":null,"_paths":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-object-destructuring-empty":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null},"operator":"==","right":{"start":null,"loc":null,"range":null,"value":null,"raw":null,"type":"Literal","end":null},"type":"BinaryExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"TypeError","type":"Identifier","end":null},"arguments":[{"start":null,"loc":null,"range":null,"value":"Cannot destructure undefined","raw":null,"type":"Literal","end":null}],"type":"NewExpression","end":null,"_paths":null},"type":"ThrowStatement","end":null,"_paths":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-object-without-properties":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"keys","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"target","type":"Identifier","end":null},"init":{"start":null,"loc":null,"range":null,"properties":[],"type":"ObjectExpression","end":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"left":{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"init":null,"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},"right":{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null},"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"keys","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"indexOf","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"operator":">=","right":{"start":null,"loc":null,"range":null,"value":0,"raw":null,"type":"Literal","end":null},"type":"BinaryExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"label":null,"type":"ContinueStatement","end":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"test":{"start":null,"loc":null,"range":null,"operator":"!","prefix":true,"argument":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"loc":null,"start":null,"range":null,"object":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Object","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"prototype","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"property":{"start":null,"loc":null,"range":null,"name":"hasOwnProperty","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"property":{"start":null,"loc":null,"range":null,"name":"call","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"UnaryExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"label":null,"type":"ContinueStatement","end":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"target","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"ForInStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"name":"target","type":"Identifier","end":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-self-global":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"operator":"typeof","prefix":true,"argument":{"start":null,"loc":null,"range":null,"name":"global","type":"Identifier","end":null},"type":"UnaryExpression","end":null,"_paths":null},"operator":"===","right":{"start":null,"loc":null,"range":null,"value":"undefined","raw":null,"type":"Literal","end":null},"type":"BinaryExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"name":"self","type":"Identifier","end":null},"alternate":{"start":null,"loc":null,"range":null,"name":"global","type":"Identifier","end":null},"type":"ConditionalExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-set":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"set","type":"Identifier","end":null},"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"object","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"property","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"value","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"receiver","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"desc","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Object","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"getOwnPropertyDescriptor","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"object","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"property","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"desc","type":"Identifier","end":null},"operator":"===","right":{"start":null,"loc":null,"range":null,"name":"undefined","type":"Identifier","end":null},"type":"BinaryExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"parent","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Object","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"getPrototypeOf","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"object","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"parent","type":"Identifier","end":null},"operator":"!==","right":{"start":null,"loc":null,"range":null,"value":null,"raw":null,"type":"Literal","end":null},"type":"BinaryExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"set","type":"Identifier","end":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"parent","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"property","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"value","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"receiver","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"value":"value","raw":null,"type":"Literal","end":null},"operator":"in","right":{"start":null,"loc":null,"range":null,"name":"desc","type":"Identifier","end":null},"type":"BinaryExpression","end":null,"_paths":null},"operator":"&&","right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"desc","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"writable","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"LogicalExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"desc","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"value","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"right":{"start":null,"loc":null,"range":null,"name":"value","type":"Identifier","end":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"setter","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"desc","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"set","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"setter","type":"Identifier","end":null},"operator":"!==","right":{"start":null,"loc":null,"range":null,"name":"undefined","type":"Identifier","end":null},"type":"BinaryExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"setter","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"call","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"receiver","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"value","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"IfStatement","end":null,"_paths":null},"type":"IfStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"name":"value","type":"Identifier","end":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-slice":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"object":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Array","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"prototype","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"property":{"start":null,"loc":null,"range":null,"name":"slice","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-sliced-to-array-loose":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"arr","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Array","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"isArray","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"arr","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"name":"arr","type":"Identifier","end":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Symbol","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"iterator","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"operator":"in","right":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"Object","type":"Identifier","end":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"arr","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"BinaryExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"_arr","type":"Identifier","end":null},"init":{"start":null,"loc":null,"range":null,"elements":[],"type":"ArrayExpression","end":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"init":{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"_iterator","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"arr","type":"Identifier","end":null},"property":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Symbol","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"iterator","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"arguments":[],"type":"CallExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"_step","type":"Identifier","end":null},"init":null,"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},"test":{"start":null,"loc":null,"range":null,"operator":"!","prefix":true,"argument":{"loc":null,"start":null,"range":null,"object":{"loc":null,"start":null,"range":null,"operator":"=","left":{"start":null,"loc":null,"range":null,"name":"_step","type":"Identifier","end":null},"right":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"_iterator","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"next","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[],"type":"CallExpression","end":null,"_paths":null},"type":"AssignmentExpression","end":null,"parenthesizedExpression":true,"_paths":null},"property":{"start":null,"loc":null,"range":null,"name":"done","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"UnaryExpression","end":null,"_paths":null},"update":null,"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"_arr","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"push","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"_step","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"value","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"operator":"&&","right":{"loc":null,"start":null,"range":null,"left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"_arr","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"length","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"operator":"===","right":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"type":"BinaryExpression","end":null,"_paths":null},"type":"LogicalExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"label":null,"type":"BreakStatement","end":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"ForStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"name":"_arr","type":"Identifier","end":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"TypeError","type":"Identifier","end":null},"arguments":[{"start":null,"loc":null,"range":null,"value":"Invalid attempt to destructure non-iterable instance","raw":null,"type":"Literal","end":null}],"type":"NewExpression","end":null,"_paths":null},"type":"ThrowStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"IfStatement","end":null,"_paths":null},"type":"IfStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-sliced-to-array":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"arr","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Array","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"isArray","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"arr","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"name":"arr","type":"Identifier","end":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Symbol","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"iterator","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"operator":"in","right":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"Object","type":"Identifier","end":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"arr","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"BinaryExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"_arr","type":"Identifier","end":null},"init":{"start":null,"loc":null,"range":null,"elements":[],"type":"ArrayExpression","end":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null,"leadingComments":null},{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"_n","type":"Identifier","end":null},"init":{"start":null,"loc":null,"range":null,"value":true,"raw":null,"type":"Literal","end":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"_d","type":"Identifier","end":null},"init":{"start":null,"loc":null,"range":null,"value":false,"raw":null,"type":"Literal","end":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"_e","type":"Identifier","end":null},"init":{"start":null,"loc":null,"range":null,"name":"undefined","type":"Identifier","end":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"block":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"init":{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"_i","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"arr","type":"Identifier","end":null},"property":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Symbol","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"iterator","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"arguments":[],"type":"CallExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"_s","type":"Identifier","end":null},"init":null,"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},"test":{"start":null,"loc":null,"range":null,"operator":"!","prefix":true,"argument":{"loc":null,"start":null,"range":null,"operator":"=","left":{"start":null,"loc":null,"range":null,"name":"_n","type":"Identifier","end":null},"right":{"loc":null,"start":null,"range":null,"object":{"loc":null,"start":null,"range":null,"operator":"=","left":{"start":null,"loc":null,"range":null,"name":"_s","type":"Identifier","end":null},"right":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"_i","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"next","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[],"type":"CallExpression","end":null,"_paths":null},"type":"AssignmentExpression","end":null,"parenthesizedExpression":true,"_paths":null},"property":{"start":null,"loc":null,"range":null,"name":"done","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"AssignmentExpression","end":null,"parenthesizedExpression":true,"_paths":null},"type":"UnaryExpression","end":null,"_paths":null},"update":{"loc":null,"start":null,"range":null,"operator":"=","left":{"start":null,"loc":null,"range":null,"name":"_n","type":"Identifier","end":null},"right":{"start":null,"loc":null,"range":null,"value":true,"raw":null,"type":"Literal","end":null},"type":"AssignmentExpression","end":null,"_paths":null},"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"_arr","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"push","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"_s","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"value","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"operator":"&&","right":{"loc":null,"start":null,"range":null,"left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"_arr","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"length","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"operator":"===","right":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"type":"BinaryExpression","end":null,"_paths":null},"type":"LogicalExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"label":null,"type":"BreakStatement","end":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"ForStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"handler":{"start":null,"loc":null,"range":null,"param":{"start":null,"loc":null,"range":null,"name":"err","type":"Identifier","end":null},"guard":null,"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"start":null,"loc":null,"range":null,"name":"_d","type":"Identifier","end":null},"right":{"start":null,"loc":null,"range":null,"value":true,"raw":null,"type":"Literal","end":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"start":null,"loc":null,"range":null,"name":"_e","type":"Identifier","end":null},"right":{"start":null,"loc":null,"range":null,"name":"err","type":"Identifier","end":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"CatchClause","end":null,"_paths":null},"guardedHandlers":[],"finalizer":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"block":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"operator":"!","prefix":true,"argument":{"start":null,"loc":null,"range":null,"name":"_n","type":"Identifier","end":null},"type":"UnaryExpression","end":null,"_paths":null},"operator":"&&","right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"_i","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"value":"return","raw":null,"type":"Literal","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"type":"LogicalExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"_i","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"value":"return","raw":null,"type":"Literal","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"arguments":[],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"handler":null,"guardedHandlers":[],"finalizer":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"test":{"start":null,"loc":null,"range":null,"name":"_d","type":"Identifier","end":null},"consequent":{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"name":"_e","type":"Identifier","end":null},"type":"ThrowStatement","end":null,"_paths":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"TryStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"TryStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"name":"_arr","type":"Identifier","end":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"TypeError","type":"Identifier","end":null},"arguments":[{"start":null,"loc":null,"range":null,"value":"Invalid attempt to destructure non-iterable instance","raw":null,"type":"Literal","end":null}],"type":"NewExpression","end":null,"_paths":null},"type":"ThrowStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"IfStatement","end":null,"_paths":null},"type":"IfStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-tagged-template-literal-loose":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"strings","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"raw","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"strings","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"raw","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"right":{"start":null,"loc":null,"range":null,"name":"raw","type":"Identifier","end":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"name":"strings","type":"Identifier","end":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-tagged-template-literal":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"strings","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"raw","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Object","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"freeze","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Object","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"defineProperties","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"strings","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"properties":[{"start":null,"loc":null,"range":null,"method":false,"shorthand":false,"computed":false,"key":{"start":null,"loc":null,"range":null,"name":"raw","type":"Identifier","end":null},"value":{"start":null,"loc":null,"range":null,"properties":[{"start":null,"loc":null,"range":null,"method":false,"shorthand":false,"computed":false,"key":{"start":null,"loc":null,"range":null,"name":"value","type":"Identifier","end":null},"value":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Object","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"freeze","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"raw","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"kind":"init","type":"Property","end":null,"_paths":null}],"type":"ObjectExpression","end":null},"kind":"init","type":"Property","end":null,"_paths":null}],"type":"ObjectExpression","end":null}],"type":"CallExpression","end":null,"_paths":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-temporal-assert-defined":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"val","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"name","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"undef","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"val","type":"Identifier","end":null},"operator":"===","right":{"start":null,"loc":null,"range":null,"name":"undef","type":"Identifier","end":null},"type":"BinaryExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"ReferenceError","type":"Identifier","end":null},"arguments":[{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"name","type":"Identifier","end":null},"operator":"+","right":{"start":null,"loc":null,"range":null,"value":" is not defined - temporal dead zone","raw":null,"type":"Literal","end":null},"type":"BinaryExpression","end":null,"_paths":null}],"type":"NewExpression","end":null,"_paths":null},"type":"ThrowStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"value":true,"raw":null,"type":"Literal","end":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-temporal-undefined":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"properties":[],"type":"ObjectExpression","end":null,"parenthesizedExpression":true},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-to-array":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"arr","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"loc":null,"start":null,"range":null,"test":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Array","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"isArray","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"arr","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"name":"arr","type":"Identifier","end":null},"alternate":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Array","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"from","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"arr","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ConditionalExpression","end":null,"_paths":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-to-consumable-array":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"arr","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Array","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"isArray","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"arr","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"init":{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"init":{"start":null,"loc":null,"range":null,"value":0,"raw":null,"type":"Literal","end":null},"type":"VariableDeclarator","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"arr2","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"Array","type":"Identifier","end":null},"arguments":[{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"arr","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"length","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null}],"type":"CallExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"operator":"<","right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"arr","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"length","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"BinaryExpression","end":null,"_paths":null},"update":{"loc":null,"start":null,"range":null,"operator":"++","prefix":false,"argument":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"type":"UpdateExpression","end":null,"_paths":null},"body":{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"arr2","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"arr","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"i","type":"Identifier","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},"type":"ForStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"name":"arr2","type":"Identifier","end":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"Array","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"from","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"arr","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"IfStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"helper-typeof":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"loc":null,"start":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null},"operator":"&&","right":{"loc":null,"start":null,"range":null,"left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"constructor","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"operator":"===","right":{"start":null,"loc":null,"range":null,"name":"Symbol","type":"Identifier","end":null},"type":"BinaryExpression","end":null,"_paths":null},"type":"LogicalExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"value":"symbol","raw":null,"type":"Literal","end":null},"alternate":{"start":null,"loc":null,"range":null,"operator":"typeof","prefix":true,"argument":{"start":null,"loc":null,"range":null,"name":"obj","type":"Identifier","end":null},"type":"UnaryExpression","end":null,"_paths":null},"type":"ConditionalExpression","end":null,"_paths":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"let-scoping-return":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"operator":"typeof","prefix":true,"argument":{"start":null,"loc":null,"range":null,"name":"RETURN","type":"Identifier","end":null},"type":"UnaryExpression","end":null,"_paths":null},"operator":"===","right":{"start":null,"loc":null,"range":null,"value":"object","raw":null,"type":"Literal","end":null},"type":"BinaryExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"argument":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"RETURN","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"v","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"ReturnStatement","end":null,"_paths":null},"alternate":null,"type":"IfStatement","end":null,"_paths":null}],"type":"Program","end":null},"named-function":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"GET_OUTER_ID","type":"Identifier","end":null},"generator":false,"expression":false,"params":[],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"name":"FUNCTION_ID","type":"Identifier","end":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionDeclaration","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"name":"FUNCTION","type":"Identifier","end":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"arguments":[],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"property-method-assignment-wrapper-generator":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"FUNCTION_KEY","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"FUNCTION_ID","type":"Identifier","end":null},"generator":true,"expression":false,"params":[],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"delegate":true,"argument":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"FUNCTION_KEY","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"apply","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"type":"ThisExpression","end":null},{"start":null,"loc":null,"range":null,"name":"arguments","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"YieldExpression","end":null,"_paths":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionDeclaration","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"FUNCTION_ID","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"toString","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"right":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"FUNCTION_KEY","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"toString","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[],"type":"CallExpression","end":null,"_paths":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"_paths":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"name":"FUNCTION_ID","type":"Identifier","end":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"FUNCTION","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"property-method-assignment-wrapper":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"FUNCTION_KEY","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"FUNCTION_ID","type":"Identifier","end":null},"generator":false,"expression":false,"params":[],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"FUNCTION_KEY","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"apply","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"type":"ThisExpression","end":null},{"start":null,"loc":null,"range":null,"name":"arguments","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionDeclaration","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"FUNCTION_ID","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"toString","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"right":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"FUNCTION_KEY","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"toString","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[],"type":"CallExpression","end":null,"_paths":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"_paths":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"name":"FUNCTION_ID","type":"Identifier","end":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"FUNCTION","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"prototype-identifier":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"CLASS_NAME","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"prototype","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"require-assign-key":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"VARIABLE_NAME","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"object":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"require","type":"Identifier","end":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"MODULE_NAME","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"property":{"start":null,"loc":null,"range":null,"name":"KEY","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null}],"type":"Program","end":null},"require":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"require","type":"Identifier","end":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"MODULE_NAME","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"rest":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"init":{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"LEN","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"ARGUMENTS","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"length","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"ARRAY","type":"Identifier","end":null},"init":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"Array","type":"Identifier","end":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"ARRAY_LEN","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"VariableDeclarator","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"KEY","type":"Identifier","end":null},"init":{"start":null,"loc":null,"range":null,"name":"START","type":"Identifier","end":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"name":"KEY","type":"Identifier","end":null},"operator":"<","right":{"start":null,"loc":null,"range":null,"name":"LEN","type":"Identifier","end":null},"type":"BinaryExpression","end":null,"_paths":null},"update":{"loc":null,"start":null,"range":null,"operator":"++","prefix":false,"argument":{"start":null,"loc":null,"range":null,"name":"KEY","type":"Identifier","end":null},"type":"UpdateExpression","end":null,"_paths":null},"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"ARRAY","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"ARRAY_KEY","type":"Identifier","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"ARGUMENTS","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"KEY","type":"Identifier","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"ForStatement","end":null,"_paths":null}],"type":"Program","end":null},"self-contained-helpers-head":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"exports","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"value":"default","raw":null,"type":"Literal","end":null},"computed":true,"type":"MemberExpression","end":null,"_paths":null},"right":{"start":null,"loc":null,"range":null,"name":"HELPER","type":"Identifier","end":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"exports","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"__esModule","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"right":{"start":null,"loc":null,"range":null,"value":true,"raw":null,"type":"Literal","end":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"system":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"System","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"register","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"MODULE_NAME","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"MODULE_DEPENDENCIES","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"EXPORT_IDENTIFIER","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"argument":{"start":null,"loc":null,"range":null,"properties":[{"start":null,"loc":null,"range":null,"method":false,"shorthand":false,"computed":false,"key":{"start":null,"loc":null,"range":null,"name":"setters","type":"Identifier","end":null},"value":{"start":null,"loc":null,"range":null,"name":"SETTERS","type":"Identifier","end":null},"kind":"init","type":"Property","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"method":false,"shorthand":false,"computed":false,"key":{"start":null,"loc":null,"range":null,"name":"execute","type":"Identifier","end":null},"value":{"start":null,"loc":null,"range":null,"name":"EXECUTE","type":"Identifier","end":null},"kind":"init","type":"Property","end":null,"_paths":null}],"type":"ObjectExpression","end":null},"type":"ReturnStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"_paths":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"tail-call-body":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"AGAIN_ID","type":"Identifier","end":null},"init":{"start":null,"loc":null,"range":null,"value":true,"raw":null,"type":"Literal","end":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"body":{"start":null,"loc":null,"range":null,"test":{"start":null,"loc":null,"range":null,"name":"AGAIN_ID","type":"Identifier","end":null},"body":{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"name":"BLOCK","type":"Identifier","end":null},"type":"ExpressionStatement","end":null,"_paths":null},"type":"WhileStatement","end":null,"_paths":null},"label":{"start":null,"loc":null,"range":null,"name":"FUNCTION_ID","type":"Identifier","end":null},"type":"LabeledStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null}],"type":"Program","end":null},"test-exports":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"operator":"typeof","prefix":true,"argument":{"start":null,"loc":null,"range":null,"name":"exports","type":"Identifier","end":null},"type":"UnaryExpression","end":null,"_paths":null},"operator":"!==","right":{"start":null,"loc":null,"range":null,"value":"undefined","raw":null,"type":"Literal","end":null},"type":"BinaryExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"test-module":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"operator":"typeof","prefix":true,"argument":{"start":null,"loc":null,"range":null,"name":"module","type":"Identifier","end":null},"type":"UnaryExpression","end":null,"_paths":null},"operator":"!==","right":{"start":null,"loc":null,"range":null,"value":"undefined","raw":null,"type":"Literal","end":null},"type":"BinaryExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"umd-commonjs-strict":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"root","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"factory","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"operator":"typeof","prefix":true,"argument":{"start":null,"loc":null,"range":null,"name":"define","type":"Identifier","end":null},"type":"UnaryExpression","end":null,"_paths":null},"operator":"===","right":{"start":null,"loc":null,"range":null,"value":"function","raw":null,"type":"Literal","end":null},"type":"BinaryExpression","end":null,"_paths":null},"operator":"&&","right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"define","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"amd","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"LogicalExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"define","type":"Identifier","end":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"AMD_ARGUMENTS","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"factory","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"operator":"typeof","prefix":true,"argument":{"start":null,"loc":null,"range":null,"name":"exports","type":"Identifier","end":null},"type":"UnaryExpression","end":null,"_paths":null},"operator":"===","right":{"start":null,"loc":null,"range":null,"value":"object","raw":null,"type":"Literal","end":null},"type":"BinaryExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"factory","type":"Identifier","end":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"COMMON_ARGUMENTS","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"factory","type":"Identifier","end":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"BROWSER_ARGUMENTS","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"IfStatement","end":null,"_paths":null},"type":"IfStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"UMD_ROOT","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"FACTORY_PARAMETERS","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"name":"FACTORY_BODY","type":"Identifier","end":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"_paths":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null},"umd-runner-body":{"loc":null,"start":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"start":null,"loc":null,"range":null,"id":null,"generator":false,"expression":false,"params":[{"start":null,"loc":null,"range":null,"name":"global","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"factory","type":"Identifier","end":null}],"body":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"test":{"loc":null,"start":null,"range":null,"left":{"loc":null,"start":null,"range":null,"left":{"start":null,"loc":null,"range":null,"operator":"typeof","prefix":true,"argument":{"start":null,"loc":null,"range":null,"name":"define","type":"Identifier","end":null},"type":"UnaryExpression","end":null,"_paths":null},"operator":"===","right":{"start":null,"loc":null,"range":null,"value":"function","raw":null,"type":"Literal","end":null},"type":"BinaryExpression","end":null,"_paths":null},"operator":"&&","right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"define","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"amd","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"LogicalExpression","end":null,"_paths":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"define","type":"Identifier","end":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"AMD_ARGUMENTS","type":"Identifier","end":null},{"start":null,"loc":null,"range":null,"name":"factory","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":{"start":null,"loc":null,"range":null,"test":{"start":null,"loc":null,"range":null,"name":"COMMON_TEST","type":"Identifier","end":null},"consequent":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"factory","type":"Identifier","end":null},"arguments":[{"start":null,"loc":null,"range":null,"name":"COMMON_ARGUMENTS","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"alternate":{"start":null,"loc":null,"range":null,"body":[{"start":null,"loc":null,"range":null,"declarations":[{"start":null,"loc":null,"range":null,"id":{"start":null,"loc":null,"range":null,"name":"mod","type":"Identifier","end":null},"init":{"start":null,"loc":null,"range":null,"properties":[{"start":null,"loc":null,"range":null,"method":false,"shorthand":false,"computed":false,"key":{"start":null,"loc":null,"range":null,"name":"exports","type":"Identifier","end":null},"value":{"start":null,"loc":null,"range":null,"properties":[],"type":"ObjectExpression","end":null},"kind":"init","type":"Property","end":null,"_paths":null}],"type":"ObjectExpression","end":null},"type":"VariableDeclarator","end":null,"_paths":null}],"kind":"var","type":"VariableDeclaration","end":null},{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"callee":{"start":null,"loc":null,"range":null,"name":"factory","type":"Identifier","end":null},"arguments":[{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"mod","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"exports","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"name":"BROWSER_ARGUMENTS","type":"Identifier","end":null}],"type":"CallExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null},{"start":null,"loc":null,"range":null,"expression":{"loc":null,"start":null,"range":null,"operator":"=","left":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"global","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"GLOBAL_ARG","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"right":{"loc":null,"start":null,"range":null,"object":{"start":null,"loc":null,"range":null,"name":"mod","type":"Identifier","end":null},"property":{"start":null,"loc":null,"range":null,"name":"exports","type":"Identifier","end":null},"computed":false,"type":"MemberExpression","end":null,"_paths":null},"type":"AssignmentExpression","end":null,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"IfStatement","end":null,"_paths":null},"type":"IfStatement","end":null,"_paths":null}],"type":"BlockStatement","end":null},"type":"FunctionExpression","end":null,"parenthesizedExpression":true,"_paths":null},"type":"ExpressionStatement","end":null,"_paths":null}],"type":"Program","end":null}} },{}]},{},[19])(19) });