acorn.js 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642
  1. // Acorn is a tiny, fast JavaScript parser written in JavaScript.
  2. //
  3. // Acorn was written by Marijn Haverbeke and various contributors and
  4. // released under an MIT license. The Unicode regexps (for identifiers
  5. // and whitespace) were taken from [Esprima](http://esprima.org) by
  6. // Ariya Hidayat.
  7. //
  8. // Git repositories for Acorn are available at
  9. //
  10. // http://marijnhaverbeke.nl/git/acorn
  11. // https://github.com/marijnh/acorn.git
  12. //
  13. // Please use the [github bug tracker][ghbt] to report issues.
  14. //
  15. // [ghbt]: https://github.com/marijnh/acorn/issues
  16. //
  17. // This file defines the main parser interface. The library also comes
  18. // with a [error-tolerant parser][dammit] and an
  19. // [abstract syntax tree walker][walk], defined in other files.
  20. //
  21. // [dammit]: acorn_loose.js
  22. // [walk]: util/walk.js
  23. (function(root, mod) {
  24. if (typeof exports == "object" && typeof module == "object") return mod(exports); // CommonJS
  25. if (typeof define == "function" && define.amd) return define(["exports"], mod); // AMD
  26. mod(root.acorn || (root.acorn = {})); // Plain browser env
  27. })(this, function(exports) {
  28. "use strict";
  29. exports.version = "0.9.1";
  30. // The main exported interface (under `self.acorn` when in the
  31. // browser) is a `parse` function that takes a code string and
  32. // returns an abstract syntax tree as specified by [Mozilla parser
  33. // API][api], with the caveat that inline XML is not recognized.
  34. //
  35. // [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
  36. var options, input, inputLen, sourceFile;
  37. exports.parse = function(inpt, opts) {
  38. input = String(inpt); inputLen = input.length;
  39. setOptions(opts);
  40. initTokenState();
  41. var startPos = options.locations ? [tokPos, new Position] : tokPos;
  42. initParserState();
  43. return parseTopLevel(options.program || startNodeAt(startPos));
  44. };
  45. // A second optional argument can be given to further configure
  46. // the parser process. These options are recognized:
  47. var defaultOptions = exports.defaultOptions = {
  48. // `ecmaVersion` indicates the ECMAScript version to parse. Must
  49. // be either 3, or 5, or 6. This influences support for strict
  50. // mode, the set of reserved words, support for getters and
  51. // setters and other features.
  52. ecmaVersion: 5,
  53. // Turn on `strictSemicolons` to prevent the parser from doing
  54. // automatic semicolon insertion.
  55. strictSemicolons: false,
  56. // When `allowTrailingCommas` is false, the parser will not allow
  57. // trailing commas in array and object literals.
  58. allowTrailingCommas: true,
  59. // By default, reserved words are not enforced. Enable
  60. // `forbidReserved` to enforce them. When this option has the
  61. // value "everywhere", reserved words and keywords can also not be
  62. // used as property names.
  63. forbidReserved: false,
  64. // When enabled, a return at the top level is not considered an
  65. // error.
  66. allowReturnOutsideFunction: false,
  67. // When `locations` is on, `loc` properties holding objects with
  68. // `start` and `end` properties in `{line, column}` form (with
  69. // line being 1-based and column 0-based) will be attached to the
  70. // nodes.
  71. locations: false,
  72. // A function can be passed as `onToken` option, which will
  73. // cause Acorn to call that function with object in the same
  74. // format as tokenize() returns. Note that you are not
  75. // allowed to call the parser from the callback—that will
  76. // corrupt its internal state.
  77. onToken: null,
  78. // A function can be passed as `onComment` option, which will
  79. // cause Acorn to call that function with `(block, text, start,
  80. // end)` parameters whenever a comment is skipped. `block` is a
  81. // boolean indicating whether this is a block (`/* */`) comment,
  82. // `text` is the content of the comment, and `start` and `end` are
  83. // character offsets that denote the start and end of the comment.
  84. // When the `locations` option is on, two more parameters are
  85. // passed, the full `{line, column}` locations of the start and
  86. // end of the comments. Note that you are not allowed to call the
  87. // parser from the callback—that will corrupt its internal state.
  88. onComment: null,
  89. // Nodes have their start and end characters offsets recorded in
  90. // `start` and `end` properties (directly on the node, rather than
  91. // the `loc` object, which holds line/column data. To also add a
  92. // [semi-standardized][range] `range` property holding a `[start,
  93. // end]` array with the same numbers, set the `ranges` option to
  94. // `true`.
  95. //
  96. // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
  97. ranges: false,
  98. // It is possible to parse multiple files into a single AST by
  99. // passing the tree produced by parsing the first file as
  100. // `program` option in subsequent parses. This will add the
  101. // toplevel forms of the parsed file to the `Program` (top) node
  102. // of an existing parse tree.
  103. program: null,
  104. // When `locations` is on, you can pass this to record the source
  105. // file in every node's `loc` object.
  106. sourceFile: null,
  107. // This value, if given, is stored in every node, whether
  108. // `locations` is on or off.
  109. directSourceFile: null,
  110. // When enabled, parenthesized expressions are represented by
  111. // (non-standard) ParenthesizedExpression nodes
  112. preserveParens: false
  113. };
  114. // This function tries to parse a single expression at a given
  115. // offset in a string. Useful for parsing mixed-language formats
  116. // that embed JavaScript expressions.
  117. exports.parseExpressionAt = function(inpt, pos, opts) {
  118. input = String(inpt); inputLen = input.length;
  119. setOptions(opts);
  120. initTokenState(pos);
  121. initParserState();
  122. return parseExpression();
  123. };
  124. var isArray = function (obj) {
  125. return Object.prototype.toString.call(obj) === "[object Array]";
  126. };
  127. function setOptions(opts) {
  128. options = {};
  129. for (var opt in defaultOptions)
  130. options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt];
  131. sourceFile = options.sourceFile || null;
  132. if (isArray(options.onToken)) {
  133. var tokens = options.onToken;
  134. options.onToken = function (token) {
  135. tokens.push(token);
  136. };
  137. }
  138. if (isArray(options.onComment)) {
  139. var comments = options.onComment;
  140. options.onComment = function (block, text, start, end, startLoc, endLoc) {
  141. var comment = {
  142. type: block ? 'Block' : 'Line',
  143. value: text,
  144. start: start,
  145. end: end
  146. };
  147. if (options.locations) {
  148. comment.loc = new SourceLocation();
  149. comment.loc.start = startLoc;
  150. comment.loc.end = endLoc;
  151. }
  152. if (options.ranges)
  153. comment.range = [start, end];
  154. comments.push(comment);
  155. };
  156. }
  157. isKeyword = options.ecmaVersion >= 6 ? isEcma6Keyword : isEcma5AndLessKeyword;
  158. }
  159. // The `getLineInfo` function is mostly useful when the
  160. // `locations` option is off (for performance reasons) and you
  161. // want to find the line/column position for a given character
  162. // offset. `input` should be the code string that the offset refers
  163. // into.
  164. var getLineInfo = exports.getLineInfo = function(input, offset) {
  165. for (var line = 1, cur = 0;;) {
  166. lineBreak.lastIndex = cur;
  167. var match = lineBreak.exec(input);
  168. if (match && match.index < offset) {
  169. ++line;
  170. cur = match.index + match[0].length;
  171. } else break;
  172. }
  173. return {line: line, column: offset - cur};
  174. };
  175. function Token() {
  176. this.type = tokType;
  177. this.value = tokVal;
  178. this.start = tokStart;
  179. this.end = tokEnd;
  180. if (options.locations) {
  181. this.loc = new SourceLocation();
  182. this.loc.end = tokEndLoc;
  183. // TODO: remove in next major release
  184. this.startLoc = tokStartLoc;
  185. this.endLoc = tokEndLoc;
  186. }
  187. if (options.ranges)
  188. this.range = [tokStart, tokEnd];
  189. }
  190. exports.Token = Token;
  191. // Acorn is organized as a tokenizer and a recursive-descent parser.
  192. // The `tokenize` export provides an interface to the tokenizer.
  193. // Because the tokenizer is optimized for being efficiently used by
  194. // the Acorn parser itself, this interface is somewhat crude and not
  195. // very modular. Performing another parse or call to `tokenize` will
  196. // reset the internal state, and invalidate existing tokenizers.
  197. exports.tokenize = function(inpt, opts) {
  198. input = String(inpt); inputLen = input.length;
  199. setOptions(opts);
  200. initTokenState();
  201. skipSpace();
  202. function getToken(forceRegexp) {
  203. lastEnd = tokEnd;
  204. readToken(forceRegexp);
  205. return new Token();
  206. }
  207. getToken.jumpTo = function(pos, reAllowed) {
  208. tokPos = pos;
  209. if (options.locations) {
  210. tokCurLine = 1;
  211. tokLineStart = lineBreak.lastIndex = 0;
  212. var match;
  213. while ((match = lineBreak.exec(input)) && match.index < pos) {
  214. ++tokCurLine;
  215. tokLineStart = match.index + match[0].length;
  216. }
  217. }
  218. tokRegexpAllowed = reAllowed;
  219. skipSpace();
  220. };
  221. getToken.noRegexp = function() {
  222. tokRegexpAllowed = false;
  223. };
  224. getToken.options = options;
  225. return getToken;
  226. };
  227. // State is kept in (closure-)global variables. We already saw the
  228. // `options`, `input`, and `inputLen` variables above.
  229. // The current position of the tokenizer in the input.
  230. var tokPos;
  231. // The start and end offsets of the current token.
  232. var tokStart, tokEnd;
  233. // When `options.locations` is true, these hold objects
  234. // containing the tokens start and end line/column pairs.
  235. var tokStartLoc, tokEndLoc;
  236. // The type and value of the current token. Token types are objects,
  237. // named by variables against which they can be compared, and
  238. // holding properties that describe them (indicating, for example,
  239. // the precedence of an infix operator, and the original name of a
  240. // keyword token). The kind of value that's held in `tokVal` depends
  241. // on the type of the token. For literals, it is the literal value,
  242. // for operators, the operator name, and so on.
  243. var tokType, tokVal;
  244. // Internal state for the tokenizer. To distinguish between division
  245. // operators and regular expressions, it remembers whether the last
  246. // token was one that is allowed to be followed by an expression.
  247. // (If it is, a slash is probably a regexp, if it isn't it's a
  248. // division operator. See the `parseStatement` function for a
  249. // caveat.)
  250. var tokRegexpAllowed;
  251. // When `options.locations` is true, these are used to keep
  252. // track of the current line, and know when a new line has been
  253. // entered.
  254. var tokCurLine, tokLineStart;
  255. // These store the position of the previous token, which is useful
  256. // when finishing a node and assigning its `end` position.
  257. var lastStart, lastEnd, lastEndLoc;
  258. // This is the parser's state. `inFunction` is used to reject
  259. // `return` statements outside of functions, `inGenerator` to
  260. // reject `yield`s outside of generators, `labels` to verify
  261. // that `break` and `continue` have somewhere to jump to, and
  262. // `strict` indicates whether strict mode is on.
  263. var inFunction, inGenerator, labels, strict;
  264. // This counter is used for checking that arrow expressions did
  265. // not contain nested parentheses in argument list.
  266. var metParenL;
  267. // This is used by parser for detecting if it's inside ES6
  268. // Template String. If it is, it should treat '$' as prefix before
  269. // '{expression}' and everything else as string literals.
  270. var inTemplate;
  271. function initParserState() {
  272. lastStart = lastEnd = tokPos;
  273. if (options.locations) lastEndLoc = new Position;
  274. inFunction = inGenerator = strict = false;
  275. labels = [];
  276. skipSpace();
  277. readToken();
  278. }
  279. // This function is used to raise exceptions on parse errors. It
  280. // takes an offset integer (into the current `input`) to indicate
  281. // the location of the error, attaches the position to the end
  282. // of the error message, and then raises a `SyntaxError` with that
  283. // message.
  284. function raise(pos, message) {
  285. var loc = getLineInfo(input, pos);
  286. message += " (" + loc.line + ":" + loc.column + ")";
  287. var err = new SyntaxError(message);
  288. err.pos = pos; err.loc = loc; err.raisedAt = tokPos;
  289. throw err;
  290. }
  291. // Reused empty array added for node fields that are always empty.
  292. var empty = [];
  293. // ## Token types
  294. // The assignment of fine-grained, information-carrying type objects
  295. // allows the tokenizer to store the information it has about a
  296. // token in a way that is very cheap for the parser to look up.
  297. // All token type variables start with an underscore, to make them
  298. // easy to recognize.
  299. // These are the general types. The `type` property is only used to
  300. // make them recognizeable when debugging.
  301. var _num = {type: "num"}, _regexp = {type: "regexp"}, _string = {type: "string"};
  302. var _name = {type: "name"}, _eof = {type: "eof"};
  303. // Keyword tokens. The `keyword` property (also used in keyword-like
  304. // operators) indicates that the token originated from an
  305. // identifier-like word, which is used when parsing property names.
  306. //
  307. // The `beforeExpr` property is used to disambiguate between regular
  308. // expressions and divisions. It is set on all token types that can
  309. // be followed by an expression (thus, a slash after them would be a
  310. // regular expression).
  311. //
  312. // `isLoop` marks a keyword as starting a loop, which is important
  313. // to know when parsing a label, in order to allow or disallow
  314. // continue jumps to that label.
  315. var _break = {keyword: "break"}, _case = {keyword: "case", beforeExpr: true}, _catch = {keyword: "catch"};
  316. var _continue = {keyword: "continue"}, _debugger = {keyword: "debugger"}, _default = {keyword: "default"};
  317. var _do = {keyword: "do", isLoop: true}, _else = {keyword: "else", beforeExpr: true};
  318. var _finally = {keyword: "finally"}, _for = {keyword: "for", isLoop: true}, _function = {keyword: "function"};
  319. var _if = {keyword: "if"}, _return = {keyword: "return", beforeExpr: true}, _switch = {keyword: "switch"};
  320. var _throw = {keyword: "throw", beforeExpr: true}, _try = {keyword: "try"}, _var = {keyword: "var"};
  321. var _let = {keyword: "let"}, _const = {keyword: "const"};
  322. var _while = {keyword: "while", isLoop: true}, _with = {keyword: "with"}, _new = {keyword: "new", beforeExpr: true};
  323. var _this = {keyword: "this"};
  324. var _class = {keyword: "class"}, _extends = {keyword: "extends", beforeExpr: true};
  325. var _export = {keyword: "export"}, _import = {keyword: "import"};
  326. var _yield = {keyword: "yield", beforeExpr: true};
  327. // The keywords that denote values.
  328. var _null = {keyword: "null", atomValue: null}, _true = {keyword: "true", atomValue: true};
  329. var _false = {keyword: "false", atomValue: false};
  330. // Some keywords are treated as regular operators. `in` sometimes
  331. // (when parsing `for`) needs to be tested against specifically, so
  332. // we assign a variable name to it for quick comparing.
  333. var _in = {keyword: "in", binop: 7, beforeExpr: true};
  334. // Map keyword names to token types.
  335. var keywordTypes = {"break": _break, "case": _case, "catch": _catch,
  336. "continue": _continue, "debugger": _debugger, "default": _default,
  337. "do": _do, "else": _else, "finally": _finally, "for": _for,
  338. "function": _function, "if": _if, "return": _return, "switch": _switch,
  339. "throw": _throw, "try": _try, "var": _var, "let": _let, "const": _const,
  340. "while": _while, "with": _with,
  341. "null": _null, "true": _true, "false": _false, "new": _new, "in": _in,
  342. "instanceof": {keyword: "instanceof", binop: 7, beforeExpr: true}, "this": _this,
  343. "typeof": {keyword: "typeof", prefix: true, beforeExpr: true},
  344. "void": {keyword: "void", prefix: true, beforeExpr: true},
  345. "delete": {keyword: "delete", prefix: true, beforeExpr: true},
  346. "class": _class, "extends": _extends,
  347. "export": _export, "import": _import, "yield": _yield};
  348. // Punctuation token types. Again, the `type` property is purely for debugging.
  349. var _bracketL = {type: "[", beforeExpr: true}, _bracketR = {type: "]"}, _braceL = {type: "{", beforeExpr: true};
  350. var _braceR = {type: "}"}, _parenL = {type: "(", beforeExpr: true}, _parenR = {type: ")"};
  351. var _comma = {type: ",", beforeExpr: true}, _semi = {type: ";", beforeExpr: true};
  352. var _colon = {type: ":", beforeExpr: true}, _dot = {type: "."}, _question = {type: "?", beforeExpr: true};
  353. var _arrow = {type: "=>", beforeExpr: true}, _bquote = {type: "`"}, _dollarBraceL = {type: "${", beforeExpr: true};
  354. var _ellipsis = {type: "...", prefix: true, beforeExpr: true};
  355. // Operators. These carry several kinds of properties to help the
  356. // parser use them properly (the presence of these properties is
  357. // what categorizes them as operators).
  358. //
  359. // `binop`, when present, specifies that this operator is a binary
  360. // operator, and will refer to its precedence.
  361. //
  362. // `prefix` and `postfix` mark the operator as a prefix or postfix
  363. // unary operator. `isUpdate` specifies that the node produced by
  364. // the operator should be of type UpdateExpression rather than
  365. // simply UnaryExpression (`++` and `--`).
  366. //
  367. // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
  368. // binary operators with a very low precedence, that should result
  369. // in AssignmentExpression nodes.
  370. var _slash = {binop: 10, beforeExpr: true}, _eq = {isAssign: true, beforeExpr: true};
  371. var _assign = {isAssign: true, beforeExpr: true};
  372. var _incDec = {postfix: true, prefix: true, isUpdate: true}, _prefix = {prefix: true, beforeExpr: true};
  373. var _logicalOR = {binop: 1, beforeExpr: true};
  374. var _logicalAND = {binop: 2, beforeExpr: true};
  375. var _bitwiseOR = {binop: 3, beforeExpr: true};
  376. var _bitwiseXOR = {binop: 4, beforeExpr: true};
  377. var _bitwiseAND = {binop: 5, beforeExpr: true};
  378. var _equality = {binop: 6, beforeExpr: true};
  379. var _relational = {binop: 7, beforeExpr: true};
  380. var _bitShift = {binop: 8, beforeExpr: true};
  381. var _plusMin = {binop: 9, prefix: true, beforeExpr: true};
  382. var _modulo = {binop: 10, beforeExpr: true};
  383. // '*' may be multiply or have special meaning in ES6
  384. var _star = {binop: 10, beforeExpr: true};
  385. // Provide access to the token types for external users of the
  386. // tokenizer.
  387. exports.tokTypes = {bracketL: _bracketL, bracketR: _bracketR, braceL: _braceL, braceR: _braceR,
  388. parenL: _parenL, parenR: _parenR, comma: _comma, semi: _semi, colon: _colon,
  389. dot: _dot, ellipsis: _ellipsis, question: _question, slash: _slash, eq: _eq,
  390. name: _name, eof: _eof, num: _num, regexp: _regexp, string: _string,
  391. arrow: _arrow, bquote: _bquote, dollarBraceL: _dollarBraceL, star: _star,
  392. assign: _assign};
  393. for (var kw in keywordTypes) exports.tokTypes["_" + kw] = keywordTypes[kw];
  394. // This is a trick taken from Esprima. It turns out that, on
  395. // non-Chrome browsers, to check whether a string is in a set, a
  396. // predicate containing a big ugly `switch` statement is faster than
  397. // a regular expression, and on Chrome the two are about on par.
  398. // This function uses `eval` (non-lexical) to produce such a
  399. // predicate from a space-separated string of words.
  400. //
  401. // It starts by sorting the words by length.
  402. function makePredicate(words) {
  403. words = words.split(" ");
  404. var f = "", cats = [];
  405. out: for (var i = 0; i < words.length; ++i) {
  406. for (var j = 0; j < cats.length; ++j)
  407. if (cats[j][0].length == words[i].length) {
  408. cats[j].push(words[i]);
  409. continue out;
  410. }
  411. cats.push([words[i]]);
  412. }
  413. function compareTo(arr) {
  414. if (arr.length == 1) return f += "return str === " + JSON.stringify(arr[0]) + ";";
  415. f += "switch(str){";
  416. for (var i = 0; i < arr.length; ++i) f += "case " + JSON.stringify(arr[i]) + ":";
  417. f += "return true}return false;";
  418. }
  419. // When there are more than three length categories, an outer
  420. // switch first dispatches on the lengths, to save on comparisons.
  421. if (cats.length > 3) {
  422. cats.sort(function(a, b) {return b.length - a.length;});
  423. f += "switch(str.length){";
  424. for (var i = 0; i < cats.length; ++i) {
  425. var cat = cats[i];
  426. f += "case " + cat[0].length + ":";
  427. compareTo(cat);
  428. }
  429. f += "}";
  430. // Otherwise, simply generate a flat `switch` statement.
  431. } else {
  432. compareTo(words);
  433. }
  434. return new Function("str", f);
  435. }
  436. // The ECMAScript 3 reserved word list.
  437. var isReservedWord3 = 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");
  438. // ECMAScript 5 reserved words.
  439. var isReservedWord5 = makePredicate("class enum extends super const export import");
  440. // The additional reserved words in strict mode.
  441. var isStrictReservedWord = makePredicate("implements interface let package private protected public static yield");
  442. // The forbidden variable names in strict mode.
  443. var isStrictBadIdWord = makePredicate("eval arguments");
  444. // And the keywords.
  445. 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";
  446. var isEcma5AndLessKeyword = makePredicate(ecma5AndLessKeywords);
  447. var isEcma6Keyword = makePredicate(ecma5AndLessKeywords + " let const class extends export import yield");
  448. var isKeyword = isEcma5AndLessKeyword;
  449. // ## Character categories
  450. // Big ugly regular expressions that match characters in the
  451. // whitespace, identifier, and identifier-start categories. These
  452. // are only applied when a character is found to actually have a
  453. // code point above 128.
  454. // Generated by `tools/generate-identifier-regex.js`.
  455. var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  456. var nonASCIIidentifierStartChars = "\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\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-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\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-\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-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\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-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\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";
  457. var nonASCIIidentifierChars = "\u0300-\u036F\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08E4-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19B0-\u19C0\u19C8\u19C9\u19D0-\u19D9\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFC-\u1DFF\u200C\u200D\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA620-\uA629\uA66F\uA674-\uA67D\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F1\uA900-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F";
  458. var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  459. var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  460. // Whether a single character denotes a newline.
  461. var newline = /[\n\r\u2028\u2029]/;
  462. // Matches a whole line break (where CRLF is considered a single
  463. // line break). Used to count lines.
  464. var lineBreak = /\r\n|[\n\r\u2028\u2029]/g;
  465. // Test whether a given character code starts an identifier.
  466. var isIdentifierStart = exports.isIdentifierStart = function(code) {
  467. if (code < 65) return code === 36;
  468. if (code < 91) return true;
  469. if (code < 97) return code === 95;
  470. if (code < 123)return true;
  471. return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
  472. };
  473. // Test whether a given character is part of an identifier.
  474. var isIdentifierChar = exports.isIdentifierChar = function(code) {
  475. if (code < 48) return code === 36;
  476. if (code < 58) return true;
  477. if (code < 65) return false;
  478. if (code < 91) return true;
  479. if (code < 97) return code === 95;
  480. if (code < 123)return true;
  481. return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
  482. };
  483. // ## Tokenizer
  484. // These are used when `options.locations` is on, for the
  485. // `tokStartLoc` and `tokEndLoc` properties.
  486. function Position() {
  487. this.line = tokCurLine;
  488. this.column = tokPos - tokLineStart;
  489. }
  490. // Reset the token state. Used at the start of a parse.
  491. function initTokenState(pos) {
  492. if (pos) {
  493. tokPos = pos;
  494. tokLineStart = Math.max(0, input.lastIndexOf("\n", pos));
  495. tokCurLine = input.slice(0, tokLineStart).split(newline).length;
  496. } else {
  497. tokCurLine = 1;
  498. tokPos = tokLineStart = 0;
  499. }
  500. tokRegexpAllowed = true;
  501. metParenL = 0;
  502. inTemplate = false;
  503. }
  504. // Called at the end of every token. Sets `tokEnd`, `tokVal`, and
  505. // `tokRegexpAllowed`, and skips the space after the token, so that
  506. // the next one's `tokStart` will point at the right position.
  507. function finishToken(type, val, shouldSkipSpace) {
  508. tokEnd = tokPos;
  509. if (options.locations) tokEndLoc = new Position;
  510. tokType = type;
  511. if (shouldSkipSpace !== false) skipSpace();
  512. tokVal = val;
  513. tokRegexpAllowed = type.beforeExpr;
  514. if (options.onToken) {
  515. options.onToken(new Token());
  516. }
  517. }
  518. function skipBlockComment() {
  519. var startLoc = options.onComment && options.locations && new Position;
  520. var start = tokPos, end = input.indexOf("*/", tokPos += 2);
  521. if (end === -1) raise(tokPos - 2, "Unterminated comment");
  522. tokPos = end + 2;
  523. if (options.locations) {
  524. lineBreak.lastIndex = start;
  525. var match;
  526. while ((match = lineBreak.exec(input)) && match.index < tokPos) {
  527. ++tokCurLine;
  528. tokLineStart = match.index + match[0].length;
  529. }
  530. }
  531. if (options.onComment)
  532. options.onComment(true, input.slice(start + 2, end), start, tokPos,
  533. startLoc, options.locations && new Position);
  534. }
  535. function skipLineComment(startSkip) {
  536. var start = tokPos;
  537. var startLoc = options.onComment && options.locations && new Position;
  538. var ch = input.charCodeAt(tokPos+=startSkip);
  539. while (tokPos < inputLen && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) {
  540. ++tokPos;
  541. ch = input.charCodeAt(tokPos);
  542. }
  543. if (options.onComment)
  544. options.onComment(false, input.slice(start + startSkip, tokPos), start, tokPos,
  545. startLoc, options.locations && new Position);
  546. }
  547. // Called at the start of the parse and after every token. Skips
  548. // whitespace and comments, and.
  549. function skipSpace() {
  550. while (tokPos < inputLen) {
  551. var ch = input.charCodeAt(tokPos);
  552. if (ch === 32) { // ' '
  553. ++tokPos;
  554. } else if (ch === 13) {
  555. ++tokPos;
  556. var next = input.charCodeAt(tokPos);
  557. if (next === 10) {
  558. ++tokPos;
  559. }
  560. if (options.locations) {
  561. ++tokCurLine;
  562. tokLineStart = tokPos;
  563. }
  564. } else if (ch === 10 || ch === 8232 || ch === 8233) {
  565. ++tokPos;
  566. if (options.locations) {
  567. ++tokCurLine;
  568. tokLineStart = tokPos;
  569. }
  570. } else if (ch > 8 && ch < 14) {
  571. ++tokPos;
  572. } else if (ch === 47) { // '/'
  573. var next = input.charCodeAt(tokPos + 1);
  574. if (next === 42) { // '*'
  575. skipBlockComment();
  576. } else if (next === 47) { // '/'
  577. skipLineComment(2);
  578. } else break;
  579. } else if (ch === 160) { // '\xa0'
  580. ++tokPos;
  581. } else if (ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
  582. ++tokPos;
  583. } else {
  584. break;
  585. }
  586. }
  587. }
  588. // ### Token reading
  589. // This is the function that is called to fetch the next token. It
  590. // is somewhat obscure, because it works in character codes rather
  591. // than characters, and because operator parsing has been inlined
  592. // into it.
  593. //
  594. // All in the name of speed.
  595. //
  596. // The `forceRegexp` parameter is used in the one case where the
  597. // `tokRegexpAllowed` trick does not work. See `parseStatement`.
  598. function readToken_dot() {
  599. var next = input.charCodeAt(tokPos + 1);
  600. if (next >= 48 && next <= 57) return readNumber(true);
  601. var next2 = input.charCodeAt(tokPos + 2);
  602. if (options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
  603. tokPos += 3;
  604. return finishToken(_ellipsis);
  605. } else {
  606. ++tokPos;
  607. return finishToken(_dot);
  608. }
  609. }
  610. function readToken_slash() { // '/'
  611. var next = input.charCodeAt(tokPos + 1);
  612. if (tokRegexpAllowed) {++tokPos; return readRegexp();}
  613. if (next === 61) return finishOp(_assign, 2);
  614. return finishOp(_slash, 1);
  615. }
  616. function readToken_mult_modulo(code) { // '%*'
  617. var next = input.charCodeAt(tokPos + 1);
  618. if (next === 61) return finishOp(_assign, 2);
  619. return finishOp(code === 42 ? _star : _modulo, 1);
  620. }
  621. function readToken_pipe_amp(code) { // '|&'
  622. var next = input.charCodeAt(tokPos + 1);
  623. if (next === code) return finishOp(code === 124 ? _logicalOR : _logicalAND, 2);
  624. if (next === 61) return finishOp(_assign, 2);
  625. return finishOp(code === 124 ? _bitwiseOR : _bitwiseAND, 1);
  626. }
  627. function readToken_caret() { // '^'
  628. var next = input.charCodeAt(tokPos + 1);
  629. if (next === 61) return finishOp(_assign, 2);
  630. return finishOp(_bitwiseXOR, 1);
  631. }
  632. function readToken_plus_min(code) { // '+-'
  633. var next = input.charCodeAt(tokPos + 1);
  634. if (next === code) {
  635. if (next == 45 && input.charCodeAt(tokPos + 2) == 62 &&
  636. newline.test(input.slice(lastEnd, tokPos))) {
  637. // A `-->` line comment
  638. skipLineComment(3);
  639. skipSpace();
  640. return readToken();
  641. }
  642. return finishOp(_incDec, 2);
  643. }
  644. if (next === 61) return finishOp(_assign, 2);
  645. return finishOp(_plusMin, 1);
  646. }
  647. function readToken_lt_gt(code) { // '<>'
  648. var next = input.charCodeAt(tokPos + 1);
  649. var size = 1;
  650. if (next === code) {
  651. size = code === 62 && input.charCodeAt(tokPos + 2) === 62 ? 3 : 2;
  652. if (input.charCodeAt(tokPos + size) === 61) return finishOp(_assign, size + 1);
  653. return finishOp(_bitShift, size);
  654. }
  655. if (next == 33 && code == 60 && input.charCodeAt(tokPos + 2) == 45 &&
  656. input.charCodeAt(tokPos + 3) == 45) {
  657. // `<!--`, an XML-style comment that should be interpreted as a line comment
  658. skipLineComment(4);
  659. skipSpace();
  660. return readToken();
  661. }
  662. if (next === 61)
  663. size = input.charCodeAt(tokPos + 2) === 61 ? 3 : 2;
  664. return finishOp(_relational, size);
  665. }
  666. function readToken_eq_excl(code) { // '=!', '=>'
  667. var next = input.charCodeAt(tokPos + 1);
  668. if (next === 61) return finishOp(_equality, input.charCodeAt(tokPos + 2) === 61 ? 3 : 2);
  669. if (code === 61 && next === 62 && options.ecmaVersion >= 6) { // '=>'
  670. tokPos += 2;
  671. return finishToken(_arrow);
  672. }
  673. return finishOp(code === 61 ? _eq : _prefix, 1);
  674. }
  675. // Get token inside ES6 template (special rules work there).
  676. function getTemplateToken(code) {
  677. // '`' and '${' have special meanings, but they should follow
  678. // string (can be empty)
  679. if (tokType === _string) {
  680. if (code === 96) { // '`'
  681. ++tokPos;
  682. return finishToken(_bquote);
  683. } else
  684. if (code === 36 && input.charCodeAt(tokPos + 1) === 123) { // '${'
  685. tokPos += 2;
  686. return finishToken(_dollarBraceL);
  687. }
  688. }
  689. if (code === 125) { // '}'
  690. ++tokPos;
  691. return finishToken(_braceR, undefined, false);
  692. }
  693. // anything else is considered string literal
  694. return readTmplString();
  695. }
  696. function getTokenFromCode(code) {
  697. switch (code) {
  698. // The interpretation of a dot depends on whether it is followed
  699. // by a digit or another two dots.
  700. case 46: // '.'
  701. return readToken_dot();
  702. // Punctuation tokens.
  703. case 40: ++tokPos; return finishToken(_parenL);
  704. case 41: ++tokPos; return finishToken(_parenR);
  705. case 59: ++tokPos; return finishToken(_semi);
  706. case 44: ++tokPos; return finishToken(_comma);
  707. case 91: ++tokPos; return finishToken(_bracketL);
  708. case 93: ++tokPos; return finishToken(_bracketR);
  709. case 123: ++tokPos; return finishToken(_braceL);
  710. case 125: ++tokPos; return finishToken(_braceR);
  711. case 58: ++tokPos; return finishToken(_colon);
  712. case 63: ++tokPos; return finishToken(_question);
  713. case 96: // '`'
  714. if (options.ecmaVersion >= 6) {
  715. ++tokPos;
  716. return finishToken(_bquote, undefined, false);
  717. }
  718. case 48: // '0'
  719. var next = input.charCodeAt(tokPos + 1);
  720. if (next === 120 || next === 88) return readRadixNumber(16); // '0x', '0X' - hex number
  721. if (options.ecmaVersion >= 6) {
  722. if (next === 111 || next === 79) return readRadixNumber(8); // '0o', '0O' - octal number
  723. if (next === 98 || next === 66) return readRadixNumber(2); // '0b', '0B' - binary number
  724. }
  725. // Anything else beginning with a digit is an integer, octal
  726. // number, or float.
  727. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
  728. return readNumber(false);
  729. // Quotes produce strings.
  730. case 34: case 39: // '"', "'"
  731. return readString(code);
  732. // Operators are parsed inline in tiny state machines. '=' (61) is
  733. // often referred to. `finishOp` simply skips the amount of
  734. // characters it is given as second argument, and returns a token
  735. // of the type given by its first argument.
  736. case 47: // '/'
  737. return readToken_slash();
  738. case 37: case 42: // '%*'
  739. return readToken_mult_modulo(code);
  740. case 124: case 38: // '|&'
  741. return readToken_pipe_amp(code);
  742. case 94: // '^'
  743. return readToken_caret();
  744. case 43: case 45: // '+-'
  745. return readToken_plus_min(code);
  746. case 60: case 62: // '<>'
  747. return readToken_lt_gt(code);
  748. case 61: case 33: // '=!'
  749. return readToken_eq_excl(code);
  750. case 126: // '~'
  751. return finishOp(_prefix, 1);
  752. }
  753. return false;
  754. }
  755. function readToken(forceRegexp) {
  756. if (!forceRegexp) tokStart = tokPos;
  757. else tokPos = tokStart + 1;
  758. if (options.locations) tokStartLoc = new Position;
  759. if (forceRegexp) return readRegexp();
  760. if (tokPos >= inputLen) return finishToken(_eof);
  761. var code = input.charCodeAt(tokPos);
  762. if (inTemplate) return getTemplateToken(code);
  763. // Identifier or keyword. '\uXXXX' sequences are allowed in
  764. // identifiers, so '\' also dispatches to that.
  765. if (isIdentifierStart(code) || code === 92 /* '\' */) return readWord();
  766. var tok = getTokenFromCode(code);
  767. if (tok === false) {
  768. // If we are here, we either found a non-ASCII identifier
  769. // character, or something that's entirely disallowed.
  770. var ch = String.fromCharCode(code);
  771. if (ch === "\\" || nonASCIIidentifierStart.test(ch)) return readWord();
  772. raise(tokPos, "Unexpected character '" + ch + "'");
  773. }
  774. return tok;
  775. }
  776. function finishOp(type, size) {
  777. var str = input.slice(tokPos, tokPos + size);
  778. tokPos += size;
  779. finishToken(type, str);
  780. }
  781. var regexpUnicodeSupport = false;
  782. try { new RegExp("\uffff", "u"); regexpUnicodeSupport = true; }
  783. catch(e) {}
  784. // Parse a regular expression. Some context-awareness is necessary,
  785. // since a '/' inside a '[]' set does not end the expression.
  786. function readRegexp() {
  787. var content = "", escaped, inClass, start = tokPos;
  788. for (;;) {
  789. if (tokPos >= inputLen) raise(start, "Unterminated regular expression");
  790. var ch = input.charAt(tokPos);
  791. if (newline.test(ch)) raise(start, "Unterminated regular expression");
  792. if (!escaped) {
  793. if (ch === "[") inClass = true;
  794. else if (ch === "]" && inClass) inClass = false;
  795. else if (ch === "/" && !inClass) break;
  796. escaped = ch === "\\";
  797. } else escaped = false;
  798. ++tokPos;
  799. }
  800. var content = input.slice(start, tokPos);
  801. ++tokPos;
  802. // Need to use `readWord1` because '\uXXXX' sequences are allowed
  803. // here (don't ask).
  804. var mods = readWord1();
  805. var tmp = content;
  806. if (mods) {
  807. var validFlags = /^[gmsiy]*$/;
  808. if (options.ecmaVersion >= 6) validFlags = /^[gmsiyu]*$/;
  809. if (!validFlags.test(mods)) raise(start, "Invalid regular expression flag");
  810. if (mods.indexOf('u') >= 0 && !regexpUnicodeSupport) {
  811. // Replace each astral symbol and every Unicode code point
  812. // escape sequence that represents such a symbol with a single
  813. // ASCII symbol to avoid throwing on regular expressions that
  814. // are only valid in combination with the `/u` flag.
  815. tmp = tmp
  816. .replace(/\\u\{([0-9a-fA-F]{5,6})\}/g, "x")
  817. .replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, "x");
  818. }
  819. }
  820. // Detect invalid regular expressions.
  821. try {
  822. new RegExp(tmp);
  823. } catch (e) {
  824. if (e instanceof SyntaxError) raise(start, "Error parsing regular expression: " + e.message);
  825. raise(e);
  826. }
  827. // Get a regular expression object for this pattern-flag pair, or `null` in
  828. // case the current environment doesn't support the flags it uses.
  829. try {
  830. var value = new RegExp(content, mods);
  831. } catch (err) {
  832. value = null;
  833. }
  834. return finishToken(_regexp, {pattern: content, flags: mods, value: value});
  835. }
  836. // Read an integer in the given radix. Return null if zero digits
  837. // were read, the integer value otherwise. When `len` is given, this
  838. // will return `null` unless the integer has exactly `len` digits.
  839. function readInt(radix, len) {
  840. var start = tokPos, total = 0;
  841. for (var i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  842. var code = input.charCodeAt(tokPos), val;
  843. if (code >= 97) val = code - 97 + 10; // a
  844. else if (code >= 65) val = code - 65 + 10; // A
  845. else if (code >= 48 && code <= 57) val = code - 48; // 0-9
  846. else val = Infinity;
  847. if (val >= radix) break;
  848. ++tokPos;
  849. total = total * radix + val;
  850. }
  851. if (tokPos === start || len != null && tokPos - start !== len) return null;
  852. return total;
  853. }
  854. function readRadixNumber(radix) {
  855. tokPos += 2; // 0x
  856. var val = readInt(radix);
  857. if (val == null) raise(tokStart + 2, "Expected number in radix " + radix);
  858. if (isIdentifierStart(input.charCodeAt(tokPos))) raise(tokPos, "Identifier directly after number");
  859. return finishToken(_num, val);
  860. }
  861. // Read an integer, octal integer, or floating-point number.
  862. function readNumber(startsWithDot) {
  863. var start = tokPos, isFloat = false, octal = input.charCodeAt(tokPos) === 48;
  864. if (!startsWithDot && readInt(10) === null) raise(start, "Invalid number");
  865. if (input.charCodeAt(tokPos) === 46) {
  866. ++tokPos;
  867. readInt(10);
  868. isFloat = true;
  869. }
  870. var next = input.charCodeAt(tokPos);
  871. if (next === 69 || next === 101) { // 'eE'
  872. next = input.charCodeAt(++tokPos);
  873. if (next === 43 || next === 45) ++tokPos; // '+-'
  874. if (readInt(10) === null) raise(start, "Invalid number");
  875. isFloat = true;
  876. }
  877. if (isIdentifierStart(input.charCodeAt(tokPos))) raise(tokPos, "Identifier directly after number");
  878. var str = input.slice(start, tokPos), val;
  879. if (isFloat) val = parseFloat(str);
  880. else if (!octal || str.length === 1) val = parseInt(str, 10);
  881. else if (/[89]/.test(str) || strict) raise(start, "Invalid number");
  882. else val = parseInt(str, 8);
  883. return finishToken(_num, val);
  884. }
  885. // Read a string value, interpreting backslash-escapes.
  886. function readCodePoint() {
  887. var ch = input.charCodeAt(tokPos), code;
  888. if (ch === 123) {
  889. if (options.ecmaVersion < 6) unexpected();
  890. ++tokPos;
  891. code = readHexChar(input.indexOf('}', tokPos) - tokPos);
  892. ++tokPos;
  893. if (code > 0x10FFFF) unexpected();
  894. } else {
  895. code = readHexChar(4);
  896. }
  897. // UTF-16 Encoding
  898. if (code <= 0xFFFF) {
  899. return String.fromCharCode(code);
  900. }
  901. var cu1 = ((code - 0x10000) >> 10) + 0xD800;
  902. var cu2 = ((code - 0x10000) & 1023) + 0xDC00;
  903. return String.fromCharCode(cu1, cu2);
  904. }
  905. function readString(quote) {
  906. ++tokPos;
  907. var out = "";
  908. for (;;) {
  909. if (tokPos >= inputLen) raise(tokStart, "Unterminated string constant");
  910. var ch = input.charCodeAt(tokPos);
  911. if (ch === quote) {
  912. ++tokPos;
  913. return finishToken(_string, out);
  914. }
  915. if (ch === 92) { // '\'
  916. out += readEscapedChar();
  917. } else {
  918. ++tokPos;
  919. if (newline.test(String.fromCharCode(ch))) {
  920. raise(tokStart, "Unterminated string constant");
  921. }
  922. out += String.fromCharCode(ch); // '\'
  923. }
  924. }
  925. }
  926. function readTmplString() {
  927. var out = "";
  928. for (;;) {
  929. if (tokPos >= inputLen) raise(tokStart, "Unterminated string constant");
  930. var ch = input.charCodeAt(tokPos);
  931. if (ch === 96 || ch === 36 && input.charCodeAt(tokPos + 1) === 123) // '`', '${'
  932. return finishToken(_string, out);
  933. if (ch === 92) { // '\'
  934. out += readEscapedChar();
  935. } else {
  936. ++tokPos;
  937. if (newline.test(String.fromCharCode(ch))) {
  938. if (ch === 13 && input.charCodeAt(tokPos) === 10) {
  939. ++tokPos;
  940. ch = 10;
  941. }
  942. if (options.locations) {
  943. ++tokCurLine;
  944. tokLineStart = tokPos;
  945. }
  946. }
  947. out += String.fromCharCode(ch); // '\'
  948. }
  949. }
  950. }
  951. // Used to read escaped characters
  952. function readEscapedChar() {
  953. var ch = input.charCodeAt(++tokPos);
  954. var octal = /^[0-7]+/.exec(input.slice(tokPos, tokPos + 3));
  955. if (octal) octal = octal[0];
  956. while (octal && parseInt(octal, 8) > 255) octal = octal.slice(0, -1);
  957. if (octal === "0") octal = null;
  958. ++tokPos;
  959. if (octal) {
  960. if (strict) raise(tokPos - 2, "Octal literal in strict mode");
  961. tokPos += octal.length - 1;
  962. return String.fromCharCode(parseInt(octal, 8));
  963. } else {
  964. switch (ch) {
  965. case 110: return "\n"; // 'n' -> '\n'
  966. case 114: return "\r"; // 'r' -> '\r'
  967. case 120: return String.fromCharCode(readHexChar(2)); // 'x'
  968. case 117: return readCodePoint(); // 'u'
  969. case 116: return "\t"; // 't' -> '\t'
  970. case 98: return "\b"; // 'b' -> '\b'
  971. case 118: return "\u000b"; // 'v' -> '\u000b'
  972. case 102: return "\f"; // 'f' -> '\f'
  973. case 48: return "\0"; // 0 -> '\0'
  974. case 13: if (input.charCodeAt(tokPos) === 10) ++tokPos; // '\r\n'
  975. case 10: // ' \n'
  976. if (options.locations) { tokLineStart = tokPos; ++tokCurLine; }
  977. return "";
  978. default: return String.fromCharCode(ch);
  979. }
  980. }
  981. }
  982. // Used to read character escape sequences ('\x', '\u', '\U').
  983. function readHexChar(len) {
  984. var n = readInt(16, len);
  985. if (n === null) raise(tokStart, "Bad character escape sequence");
  986. return n;
  987. }
  988. // Used to signal to callers of `readWord1` whether the word
  989. // contained any escape sequences. This is needed because words with
  990. // escape sequences must not be interpreted as keywords.
  991. var containsEsc;
  992. // Read an identifier, and return it as a string. Sets `containsEsc`
  993. // to whether the word contained a '\u' escape.
  994. //
  995. // Only builds up the word character-by-character when it actually
  996. // containeds an escape, as a micro-optimization.
  997. function readWord1() {
  998. containsEsc = false;
  999. var word, first = true, start = tokPos;
  1000. for (;;) {
  1001. var ch = input.charCodeAt(tokPos);
  1002. if (isIdentifierChar(ch)) {
  1003. if (containsEsc) word += input.charAt(tokPos);
  1004. ++tokPos;
  1005. } else if (ch === 92) { // "\"
  1006. if (!containsEsc) word = input.slice(start, tokPos);
  1007. containsEsc = true;
  1008. if (input.charCodeAt(++tokPos) != 117) // "u"
  1009. raise(tokPos, "Expecting Unicode escape sequence \\uXXXX");
  1010. ++tokPos;
  1011. var esc = readHexChar(4);
  1012. var escStr = String.fromCharCode(esc);
  1013. if (!escStr) raise(tokPos - 1, "Invalid Unicode escape");
  1014. if (!(first ? isIdentifierStart(esc) : isIdentifierChar(esc)))
  1015. raise(tokPos - 4, "Invalid Unicode escape");
  1016. word += escStr;
  1017. } else {
  1018. break;
  1019. }
  1020. first = false;
  1021. }
  1022. return containsEsc ? word : input.slice(start, tokPos);
  1023. }
  1024. // Read an identifier or keyword token. Will check for reserved
  1025. // words when necessary.
  1026. function readWord() {
  1027. var word = readWord1();
  1028. var type = _name;
  1029. if (!containsEsc && isKeyword(word))
  1030. type = keywordTypes[word];
  1031. return finishToken(type, word);
  1032. }
  1033. // ## Parser
  1034. // A recursive descent parser operates by defining functions for all
  1035. // syntactic elements, and recursively calling those, each function
  1036. // advancing the input stream and returning an AST node. Precedence
  1037. // of constructs (for example, the fact that `!x[1]` means `!(x[1])`
  1038. // instead of `(!x)[1]` is handled by the fact that the parser
  1039. // function that parses unary prefix operators is called first, and
  1040. // in turn calls the function that parses `[]` subscripts — that
  1041. // way, it'll receive the node for `x[1]` already parsed, and wraps
  1042. // *that* in the unary operator node.
  1043. //
  1044. // Acorn uses an [operator precedence parser][opp] to handle binary
  1045. // operator precedence, because it is much more compact than using
  1046. // the technique outlined above, which uses different, nesting
  1047. // functions to specify precedence, for all of the ten binary
  1048. // precedence levels that JavaScript defines.
  1049. //
  1050. // [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser
  1051. // ### Parser utilities
  1052. // Continue to the next token.
  1053. function next() {
  1054. lastStart = tokStart;
  1055. lastEnd = tokEnd;
  1056. lastEndLoc = tokEndLoc;
  1057. readToken();
  1058. }
  1059. // Enter strict mode. Re-reads the next token to please pedantic
  1060. // tests ("use strict"; 010; -- should fail).
  1061. function setStrict(strct) {
  1062. strict = strct;
  1063. tokPos = tokStart;
  1064. if (options.locations) {
  1065. while (tokPos < tokLineStart) {
  1066. tokLineStart = input.lastIndexOf("\n", tokLineStart - 2) + 1;
  1067. --tokCurLine;
  1068. }
  1069. }
  1070. skipSpace();
  1071. readToken();
  1072. }
  1073. // Start an AST node, attaching a start offset.
  1074. function Node() {
  1075. this.type = null;
  1076. this.start = tokStart;
  1077. this.end = null;
  1078. }
  1079. exports.Node = Node;
  1080. function SourceLocation() {
  1081. this.start = tokStartLoc;
  1082. this.end = null;
  1083. if (sourceFile !== null) this.source = sourceFile;
  1084. }
  1085. function startNode() {
  1086. var node = new Node();
  1087. if (options.locations)
  1088. node.loc = new SourceLocation();
  1089. if (options.directSourceFile)
  1090. node.sourceFile = options.directSourceFile;
  1091. if (options.ranges)
  1092. node.range = [tokStart, 0];
  1093. return node;
  1094. }
  1095. // Sometimes, a node is only started *after* the token stream passed
  1096. // its start position. The functions below help storing a position
  1097. // and creating a node from a previous position.
  1098. function storeCurrentPos() {
  1099. return options.locations ? [tokStart, tokStartLoc] : tokStart;
  1100. }
  1101. function startNodeAt(pos) {
  1102. var node = new Node(), start = pos;
  1103. if (options.locations) {
  1104. node.loc = new SourceLocation();
  1105. node.loc.start = start[1];
  1106. start = pos[0];
  1107. }
  1108. node.start = start;
  1109. if (options.directSourceFile)
  1110. node.sourceFile = options.directSourceFile;
  1111. if (options.ranges)
  1112. node.range = [start, 0];
  1113. return node;
  1114. }
  1115. // Finish an AST node, adding `type` and `end` properties.
  1116. function finishNode(node, type) {
  1117. node.type = type;
  1118. node.end = lastEnd;
  1119. if (options.locations)
  1120. node.loc.end = lastEndLoc;
  1121. if (options.ranges)
  1122. node.range[1] = lastEnd;
  1123. return node;
  1124. }
  1125. // Test whether a statement node is the string literal `"use strict"`.
  1126. function isUseStrict(stmt) {
  1127. return options.ecmaVersion >= 5 && stmt.type === "ExpressionStatement" &&
  1128. stmt.expression.type === "Literal" && stmt.expression.value === "use strict";
  1129. }
  1130. // Predicate that tests whether the next token is of the given
  1131. // type, and if yes, consumes it as a side effect.
  1132. function eat(type) {
  1133. if (tokType === type) {
  1134. next();
  1135. return true;
  1136. } else {
  1137. return false;
  1138. }
  1139. }
  1140. // Test whether a semicolon can be inserted at the current position.
  1141. function canInsertSemicolon() {
  1142. return !options.strictSemicolons &&
  1143. (tokType === _eof || tokType === _braceR || newline.test(input.slice(lastEnd, tokStart)));
  1144. }
  1145. // Consume a semicolon, or, failing that, see if we are allowed to
  1146. // pretend that there is a semicolon at this position.
  1147. function semicolon() {
  1148. if (!eat(_semi) && !canInsertSemicolon()) unexpected();
  1149. }
  1150. // Expect a token of a given type. If found, consume it, otherwise,
  1151. // raise an unexpected token error.
  1152. function expect(type) {
  1153. eat(type) || unexpected();
  1154. }
  1155. // Raise an unexpected token error.
  1156. function unexpected(pos) {
  1157. raise(pos != null ? pos : tokStart, "Unexpected token");
  1158. }
  1159. // Checks if hash object has a property.
  1160. function has(obj, propName) {
  1161. return Object.prototype.hasOwnProperty.call(obj, propName);
  1162. }
  1163. // Convert existing expression atom to assignable pattern
  1164. // if possible.
  1165. function toAssignable(node, allowSpread, checkType) {
  1166. if (options.ecmaVersion >= 6 && node) {
  1167. switch (node.type) {
  1168. case "Identifier":
  1169. case "MemberExpression":
  1170. break;
  1171. case "ObjectExpression":
  1172. node.type = "ObjectPattern";
  1173. for (var i = 0; i < node.properties.length; i++) {
  1174. var prop = node.properties[i];
  1175. if (prop.kind !== "init") unexpected(prop.key.start);
  1176. toAssignable(prop.value, false, checkType);
  1177. }
  1178. break;
  1179. case "ArrayExpression":
  1180. node.type = "ArrayPattern";
  1181. for (var i = 0, lastI = node.elements.length - 1; i <= lastI; i++) {
  1182. toAssignable(node.elements[i], i === lastI, checkType);
  1183. }
  1184. break;
  1185. case "SpreadElement":
  1186. if (allowSpread) {
  1187. toAssignable(node.argument, false, checkType);
  1188. checkSpreadAssign(node.argument);
  1189. } else {
  1190. unexpected(node.start);
  1191. }
  1192. break;
  1193. default:
  1194. if (checkType) unexpected(node.start);
  1195. }
  1196. }
  1197. return node;
  1198. }
  1199. // Checks if node can be assignable spread argument.
  1200. function checkSpreadAssign(node) {
  1201. if (node.type !== "Identifier" && node.type !== "ArrayPattern")
  1202. unexpected(node.start);
  1203. }
  1204. // Verify that argument names are not repeated, and it does not
  1205. // try to bind the words `eval` or `arguments`.
  1206. function checkFunctionParam(param, nameHash) {
  1207. switch (param.type) {
  1208. case "Identifier":
  1209. if (isStrictReservedWord(param.name) || isStrictBadIdWord(param.name))
  1210. raise(param.start, "Defining '" + param.name + "' in strict mode");
  1211. if (has(nameHash, param.name))
  1212. raise(param.start, "Argument name clash in strict mode");
  1213. nameHash[param.name] = true;
  1214. break;
  1215. case "ObjectPattern":
  1216. for (var i = 0; i < param.properties.length; i++)
  1217. checkFunctionParam(param.properties[i].value, nameHash);
  1218. break;
  1219. case "ArrayPattern":
  1220. for (var i = 0; i < param.elements.length; i++) {
  1221. var elem = param.elements[i];
  1222. if (elem) checkFunctionParam(elem, nameHash);
  1223. }
  1224. break;
  1225. }
  1226. }
  1227. // Check if property name clashes with already added.
  1228. // Object/class getters and setters are not allowed to clash —
  1229. // either with each other or with an init property — and in
  1230. // strict mode, init properties are also not allowed to be repeated.
  1231. function checkPropClash(prop, propHash) {
  1232. if (options.ecmaVersion >= 6) return;
  1233. var key = prop.key, name;
  1234. switch (key.type) {
  1235. case "Identifier": name = key.name; break;
  1236. case "Literal": name = String(key.value); break;
  1237. default: return;
  1238. }
  1239. var kind = prop.kind || "init", other;
  1240. if (has(propHash, name)) {
  1241. other = propHash[name];
  1242. var isGetSet = kind !== "init";
  1243. if ((strict || isGetSet) && other[kind] || !(isGetSet ^ other.init))
  1244. raise(key.start, "Redefinition of property");
  1245. } else {
  1246. other = propHash[name] = {
  1247. init: false,
  1248. get: false,
  1249. set: false
  1250. };
  1251. }
  1252. other[kind] = true;
  1253. }
  1254. // Verify that a node is an lval — something that can be assigned
  1255. // to.
  1256. function checkLVal(expr, isBinding) {
  1257. switch (expr.type) {
  1258. case "Identifier":
  1259. if (strict && (isStrictBadIdWord(expr.name) || isStrictReservedWord(expr.name)))
  1260. raise(expr.start, isBinding
  1261. ? "Binding " + expr.name + " in strict mode"
  1262. : "Assigning to " + expr.name + " in strict mode"
  1263. );
  1264. break;
  1265. case "MemberExpression":
  1266. if (!isBinding) break;
  1267. case "ObjectPattern":
  1268. for (var i = 0; i < expr.properties.length; i++)
  1269. checkLVal(expr.properties[i].value, isBinding);
  1270. break;
  1271. case "ArrayPattern":
  1272. for (var i = 0; i < expr.elements.length; i++) {
  1273. var elem = expr.elements[i];
  1274. if (elem) checkLVal(elem, isBinding);
  1275. }
  1276. break;
  1277. case "SpreadElement":
  1278. break;
  1279. default:
  1280. raise(expr.start, "Assigning to rvalue");
  1281. }
  1282. }
  1283. // ### Statement parsing
  1284. // Parse a program. Initializes the parser, reads any number of
  1285. // statements, and wraps them in a Program node. Optionally takes a
  1286. // `program` argument. If present, the statements will be appended
  1287. // to its body instead of creating a new node.
  1288. function parseTopLevel(node) {
  1289. var first = true;
  1290. if (!node.body) node.body = [];
  1291. while (tokType !== _eof) {
  1292. var stmt = parseStatement();
  1293. node.body.push(stmt);
  1294. if (first && isUseStrict(stmt)) setStrict(true);
  1295. first = false;
  1296. }
  1297. lastStart = tokStart;
  1298. lastEnd = tokEnd;
  1299. lastEndLoc = tokEndLoc;
  1300. return finishNode(node, "Program");
  1301. }
  1302. var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
  1303. // Parse a single statement.
  1304. //
  1305. // If expecting a statement and finding a slash operator, parse a
  1306. // regular expression literal. This is to handle cases like
  1307. // `if (foo) /blah/.exec(foo);`, where looking at the previous token
  1308. // does not help.
  1309. function parseStatement() {
  1310. if (tokType === _slash || tokType === _assign && tokVal == "/=")
  1311. readToken(true);
  1312. var starttype = tokType, node = startNode();
  1313. // Most types of statements are recognized by the keyword they
  1314. // start with. Many are trivial to parse, some require a bit of
  1315. // complexity.
  1316. switch (starttype) {
  1317. case _break: case _continue: return parseBreakContinueStatement(node, starttype.keyword);
  1318. case _debugger: return parseDebuggerStatement(node);
  1319. case _do: return parseDoStatement(node);
  1320. case _for: return parseForStatement(node);
  1321. case _function: return parseFunctionStatement(node);
  1322. case _class: return parseClass(node, true);
  1323. case _if: return parseIfStatement(node);
  1324. case _return: return parseReturnStatement(node);
  1325. case _switch: return parseSwitchStatement(node);
  1326. case _throw: return parseThrowStatement(node);
  1327. case _try: return parseTryStatement(node);
  1328. case _var: case _let: case _const: return parseVarStatement(node, starttype.keyword);
  1329. case _while: return parseWhileStatement(node);
  1330. case _with: return parseWithStatement(node);
  1331. case _braceL: return parseBlock(); // no point creating a function for this
  1332. case _semi: return parseEmptyStatement(node);
  1333. case _export: return parseExport(node);
  1334. case _import: return parseImport(node);
  1335. // If the statement does not start with a statement keyword or a
  1336. // brace, it's an ExpressionStatement or LabeledStatement. We
  1337. // simply start parsing an expression, and afterwards, if the
  1338. // next token is a colon and the expression was a simple
  1339. // Identifier node, we switch to interpreting it as a label.
  1340. default:
  1341. var maybeName = tokVal, expr = parseExpression();
  1342. if (starttype === _name && expr.type === "Identifier" && eat(_colon))
  1343. return parseLabeledStatement(node, maybeName, expr);
  1344. else return parseExpressionStatement(node, expr);
  1345. }
  1346. }
  1347. function parseBreakContinueStatement(node, keyword) {
  1348. var isBreak = keyword == "break";
  1349. next();
  1350. if (eat(_semi) || canInsertSemicolon()) node.label = null;
  1351. else if (tokType !== _name) unexpected();
  1352. else {
  1353. node.label = parseIdent();
  1354. semicolon();
  1355. }
  1356. // Verify that there is an actual destination to break or
  1357. // continue to.
  1358. for (var i = 0; i < labels.length; ++i) {
  1359. var lab = labels[i];
  1360. if (node.label == null || lab.name === node.label.name) {
  1361. if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
  1362. if (node.label && isBreak) break;
  1363. }
  1364. }
  1365. if (i === labels.length) raise(node.start, "Unsyntactic " + keyword);
  1366. return finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
  1367. }
  1368. function parseDebuggerStatement(node) {
  1369. next();
  1370. semicolon();
  1371. return finishNode(node, "DebuggerStatement");
  1372. }
  1373. function parseDoStatement(node) {
  1374. next();
  1375. labels.push(loopLabel);
  1376. node.body = parseStatement();
  1377. labels.pop();
  1378. expect(_while);
  1379. node.test = parseParenExpression();
  1380. semicolon();
  1381. return finishNode(node, "DoWhileStatement");
  1382. }
  1383. // Disambiguating between a `for` and a `for`/`in` or `for`/`of`
  1384. // loop is non-trivial. Basically, we have to parse the init `var`
  1385. // statement or expression, disallowing the `in` operator (see
  1386. // the second parameter to `parseExpression`), and then check
  1387. // whether the next token is `in` or `of`. When there is no init
  1388. // part (semicolon immediately after the opening parenthesis), it
  1389. // is a regular `for` loop.
  1390. function parseForStatement(node) {
  1391. next();
  1392. labels.push(loopLabel);
  1393. expect(_parenL);
  1394. if (tokType === _semi) return parseFor(node, null);
  1395. if (tokType === _var || tokType === _let) {
  1396. var init = startNode(), varKind = tokType.keyword, isLet = tokType === _let;
  1397. next();
  1398. parseVar(init, true, varKind);
  1399. finishNode(init, "VariableDeclaration");
  1400. if ((tokType === _in || (options.ecmaVersion >= 6 && tokType === _name && tokVal === "of")) && init.declarations.length === 1 &&
  1401. !(isLet && init.declarations[0].init))
  1402. return parseForIn(node, init);
  1403. return parseFor(node, init);
  1404. }
  1405. var init = parseExpression(false, true);
  1406. if (tokType === _in || (options.ecmaVersion >= 6 && tokType === _name && tokVal === "of")) {
  1407. checkLVal(init);
  1408. return parseForIn(node, init);
  1409. }
  1410. return parseFor(node, init);
  1411. }
  1412. function parseFunctionStatement(node) {
  1413. next();
  1414. return parseFunction(node, true);
  1415. }
  1416. function parseIfStatement(node) {
  1417. next();
  1418. node.test = parseParenExpression();
  1419. node.consequent = parseStatement();
  1420. node.alternate = eat(_else) ? parseStatement() : null;
  1421. return finishNode(node, "IfStatement");
  1422. }
  1423. function parseReturnStatement(node) {
  1424. if (!inFunction && !options.allowReturnOutsideFunction)
  1425. raise(tokStart, "'return' outside of function");
  1426. next();
  1427. // In `return` (and `break`/`continue`), the keywords with
  1428. // optional arguments, we eagerly look for a semicolon or the
  1429. // possibility to insert one.
  1430. if (eat(_semi) || canInsertSemicolon()) node.argument = null;
  1431. else { node.argument = parseExpression(); semicolon(); }
  1432. return finishNode(node, "ReturnStatement");
  1433. }
  1434. function parseSwitchStatement(node) {
  1435. next();
  1436. node.discriminant = parseParenExpression();
  1437. node.cases = [];
  1438. expect(_braceL);
  1439. labels.push(switchLabel);
  1440. // Statements under must be grouped (by label) in SwitchCase
  1441. // nodes. `cur` is used to keep the node that we are currently
  1442. // adding statements to.
  1443. for (var cur, sawDefault; tokType != _braceR;) {
  1444. if (tokType === _case || tokType === _default) {
  1445. var isCase = tokType === _case;
  1446. if (cur) finishNode(cur, "SwitchCase");
  1447. node.cases.push(cur = startNode());
  1448. cur.consequent = [];
  1449. next();
  1450. if (isCase) cur.test = parseExpression();
  1451. else {
  1452. if (sawDefault) raise(lastStart, "Multiple default clauses"); sawDefault = true;
  1453. cur.test = null;
  1454. }
  1455. expect(_colon);
  1456. } else {
  1457. if (!cur) unexpected();
  1458. cur.consequent.push(parseStatement());
  1459. }
  1460. }
  1461. if (cur) finishNode(cur, "SwitchCase");
  1462. next(); // Closing brace
  1463. labels.pop();
  1464. return finishNode(node, "SwitchStatement");
  1465. }
  1466. function parseThrowStatement(node) {
  1467. next();
  1468. if (newline.test(input.slice(lastEnd, tokStart)))
  1469. raise(lastEnd, "Illegal newline after throw");
  1470. node.argument = parseExpression();
  1471. semicolon();
  1472. return finishNode(node, "ThrowStatement");
  1473. }
  1474. function parseTryStatement(node) {
  1475. next();
  1476. node.block = parseBlock();
  1477. node.handler = null;
  1478. if (tokType === _catch) {
  1479. var clause = startNode();
  1480. next();
  1481. expect(_parenL);
  1482. clause.param = parseIdent();
  1483. if (strict && isStrictBadIdWord(clause.param.name))
  1484. raise(clause.param.start, "Binding " + clause.param.name + " in strict mode");
  1485. expect(_parenR);
  1486. clause.guard = null;
  1487. clause.body = parseBlock();
  1488. node.handler = finishNode(clause, "CatchClause");
  1489. }
  1490. node.guardedHandlers = empty;
  1491. node.finalizer = eat(_finally) ? parseBlock() : null;
  1492. if (!node.handler && !node.finalizer)
  1493. raise(node.start, "Missing catch or finally clause");
  1494. return finishNode(node, "TryStatement");
  1495. }
  1496. function parseVarStatement(node, kind) {
  1497. next();
  1498. parseVar(node, false, kind);
  1499. semicolon();
  1500. return finishNode(node, "VariableDeclaration");
  1501. }
  1502. function parseWhileStatement(node) {
  1503. next();
  1504. node.test = parseParenExpression();
  1505. labels.push(loopLabel);
  1506. node.body = parseStatement();
  1507. labels.pop();
  1508. return finishNode(node, "WhileStatement");
  1509. }
  1510. function parseWithStatement(node) {
  1511. if (strict) raise(tokStart, "'with' in strict mode");
  1512. next();
  1513. node.object = parseParenExpression();
  1514. node.body = parseStatement();
  1515. return finishNode(node, "WithStatement");
  1516. }
  1517. function parseEmptyStatement(node) {
  1518. next();
  1519. return finishNode(node, "EmptyStatement");
  1520. }
  1521. function parseLabeledStatement(node, maybeName, expr) {
  1522. for (var i = 0; i < labels.length; ++i)
  1523. if (labels[i].name === maybeName) raise(expr.start, "Label '" + maybeName + "' is already declared");
  1524. var kind = tokType.isLoop ? "loop" : tokType === _switch ? "switch" : null;
  1525. labels.push({name: maybeName, kind: kind});
  1526. node.body = parseStatement();
  1527. labels.pop();
  1528. node.label = expr;
  1529. return finishNode(node, "LabeledStatement");
  1530. }
  1531. function parseExpressionStatement(node, expr) {
  1532. node.expression = expr;
  1533. semicolon();
  1534. return finishNode(node, "ExpressionStatement");
  1535. }
  1536. // Used for constructs like `switch` and `if` that insist on
  1537. // parentheses around their expression.
  1538. function parseParenExpression() {
  1539. expect(_parenL);
  1540. var val = parseExpression();
  1541. expect(_parenR);
  1542. return val;
  1543. }
  1544. // Parse a semicolon-enclosed block of statements, handling `"use
  1545. // strict"` declarations when `allowStrict` is true (used for
  1546. // function bodies).
  1547. function parseBlock(allowStrict) {
  1548. var node = startNode(), first = true, oldStrict;
  1549. node.body = [];
  1550. expect(_braceL);
  1551. while (!eat(_braceR)) {
  1552. var stmt = parseStatement();
  1553. node.body.push(stmt);
  1554. if (first && allowStrict && isUseStrict(stmt)) {
  1555. oldStrict = strict;
  1556. setStrict(strict = true);
  1557. }
  1558. first = false;
  1559. }
  1560. if (oldStrict === false) setStrict(false);
  1561. return finishNode(node, "BlockStatement");
  1562. }
  1563. // Parse a regular `for` loop. The disambiguation code in
  1564. // `parseStatement` will already have parsed the init statement or
  1565. // expression.
  1566. function parseFor(node, init) {
  1567. node.init = init;
  1568. expect(_semi);
  1569. node.test = tokType === _semi ? null : parseExpression();
  1570. expect(_semi);
  1571. node.update = tokType === _parenR ? null : parseExpression();
  1572. expect(_parenR);
  1573. node.body = parseStatement();
  1574. labels.pop();
  1575. return finishNode(node, "ForStatement");
  1576. }
  1577. // Parse a `for`/`in` and `for`/`of` loop, which are almost
  1578. // same from parser's perspective.
  1579. function parseForIn(node, init) {
  1580. var type = tokType === _in ? "ForInStatement" : "ForOfStatement";
  1581. next();
  1582. node.left = init;
  1583. node.right = parseExpression();
  1584. expect(_parenR);
  1585. node.body = parseStatement();
  1586. labels.pop();
  1587. return finishNode(node, type);
  1588. }
  1589. // Parse a list of variable declarations.
  1590. function parseVar(node, noIn, kind) {
  1591. node.declarations = [];
  1592. node.kind = kind;
  1593. for (;;) {
  1594. var decl = startNode();
  1595. decl.id = options.ecmaVersion >= 6 ? toAssignable(parseExprAtom()) : parseIdent();
  1596. checkLVal(decl.id, true);
  1597. decl.init = eat(_eq) ? parseExpression(true, noIn) : (kind === _const.keyword ? unexpected() : null);
  1598. node.declarations.push(finishNode(decl, "VariableDeclarator"));
  1599. if (!eat(_comma)) break;
  1600. }
  1601. return node;
  1602. }
  1603. // ### Expression parsing
  1604. // These nest, from the most general expression type at the top to
  1605. // 'atomic', nondivisible expression types at the bottom. Most of
  1606. // the functions will simply let the function(s) below them parse,
  1607. // and, *if* the syntactic construct they handle is present, wrap
  1608. // the AST node that the inner parser gave them in another node.
  1609. // Parse a full expression. The arguments are used to forbid comma
  1610. // sequences (in argument lists, array literals, or object literals)
  1611. // or the `in` operator (in for loops initalization expressions).
  1612. function parseExpression(noComma, noIn) {
  1613. var start = storeCurrentPos();
  1614. var expr = parseMaybeAssign(noIn);
  1615. if (!noComma && tokType === _comma) {
  1616. var node = startNodeAt(start);
  1617. node.expressions = [expr];
  1618. while (eat(_comma)) node.expressions.push(parseMaybeAssign(noIn));
  1619. return finishNode(node, "SequenceExpression");
  1620. }
  1621. return expr;
  1622. }
  1623. // Parse an assignment expression. This includes applications of
  1624. // operators like `+=`.
  1625. function parseMaybeAssign(noIn) {
  1626. var start = storeCurrentPos();
  1627. var left = parseMaybeConditional(noIn);
  1628. if (tokType.isAssign) {
  1629. var node = startNodeAt(start);
  1630. node.operator = tokVal;
  1631. node.left = tokType === _eq ? toAssignable(left) : left;
  1632. checkLVal(left);
  1633. next();
  1634. node.right = parseMaybeAssign(noIn);
  1635. return finishNode(node, "AssignmentExpression");
  1636. }
  1637. return left;
  1638. }
  1639. // Parse a ternary conditional (`?:`) operator.
  1640. function parseMaybeConditional(noIn) {
  1641. var start = storeCurrentPos();
  1642. var expr = parseExprOps(noIn);
  1643. if (eat(_question)) {
  1644. var node = startNodeAt(start);
  1645. node.test = expr;
  1646. node.consequent = parseExpression(true);
  1647. expect(_colon);
  1648. node.alternate = parseExpression(true, noIn);
  1649. return finishNode(node, "ConditionalExpression");
  1650. }
  1651. return expr;
  1652. }
  1653. // Start the precedence parser.
  1654. function parseExprOps(noIn) {
  1655. var start = storeCurrentPos();
  1656. return parseExprOp(parseMaybeUnary(), start, -1, noIn);
  1657. }
  1658. // Parse binary operators with the operator precedence parsing
  1659. // algorithm. `left` is the left-hand side of the operator.
  1660. // `minPrec` provides context that allows the function to stop and
  1661. // defer further parser to one of its callers when it encounters an
  1662. // operator that has a lower precedence than the set it is parsing.
  1663. function parseExprOp(left, leftStart, minPrec, noIn) {
  1664. var prec = tokType.binop;
  1665. if (prec != null && (!noIn || tokType !== _in)) {
  1666. if (prec > minPrec) {
  1667. var node = startNodeAt(leftStart);
  1668. node.left = left;
  1669. node.operator = tokVal;
  1670. var op = tokType;
  1671. next();
  1672. var start = storeCurrentPos();
  1673. node.right = parseExprOp(parseMaybeUnary(), start, prec, noIn);
  1674. finishNode(node, (op === _logicalOR || op === _logicalAND) ? "LogicalExpression" : "BinaryExpression");
  1675. return parseExprOp(node, leftStart, minPrec, noIn);
  1676. }
  1677. }
  1678. return left;
  1679. }
  1680. // Parse unary operators, both prefix and postfix.
  1681. function parseMaybeUnary() {
  1682. if (tokType.prefix) {
  1683. var node = startNode(), update = tokType.isUpdate, nodeType;
  1684. if (tokType === _ellipsis) {
  1685. nodeType = "SpreadElement";
  1686. } else {
  1687. nodeType = update ? "UpdateExpression" : "UnaryExpression";
  1688. node.operator = tokVal;
  1689. node.prefix = true;
  1690. }
  1691. tokRegexpAllowed = true;
  1692. next();
  1693. node.argument = parseMaybeUnary();
  1694. if (update) checkLVal(node.argument);
  1695. else if (strict && node.operator === "delete" &&
  1696. node.argument.type === "Identifier")
  1697. raise(node.start, "Deleting local variable in strict mode");
  1698. return finishNode(node, nodeType);
  1699. }
  1700. var start = storeCurrentPos();
  1701. var expr = parseExprSubscripts();
  1702. while (tokType.postfix && !canInsertSemicolon()) {
  1703. var node = startNodeAt(start);
  1704. node.operator = tokVal;
  1705. node.prefix = false;
  1706. node.argument = expr;
  1707. checkLVal(expr);
  1708. next();
  1709. expr = finishNode(node, "UpdateExpression");
  1710. }
  1711. return expr;
  1712. }
  1713. // Parse call, dot, and `[]`-subscript expressions.
  1714. function parseExprSubscripts() {
  1715. var start = storeCurrentPos();
  1716. return parseSubscripts(parseExprAtom(), start);
  1717. }
  1718. function parseSubscripts(base, start, noCalls) {
  1719. if (eat(_dot)) {
  1720. var node = startNodeAt(start);
  1721. node.object = base;
  1722. node.property = parseIdent(true);
  1723. node.computed = false;
  1724. return parseSubscripts(finishNode(node, "MemberExpression"), start, noCalls);
  1725. } else if (eat(_bracketL)) {
  1726. var node = startNodeAt(start);
  1727. node.object = base;
  1728. node.property = parseExpression();
  1729. node.computed = true;
  1730. expect(_bracketR);
  1731. return parseSubscripts(finishNode(node, "MemberExpression"), start, noCalls);
  1732. } else if (!noCalls && eat(_parenL)) {
  1733. var node = startNodeAt(start);
  1734. node.callee = base;
  1735. node.arguments = parseExprList(_parenR, false);
  1736. return parseSubscripts(finishNode(node, "CallExpression"), start, noCalls);
  1737. } else if (tokType === _bquote) {
  1738. var node = startNodeAt(start);
  1739. node.tag = base;
  1740. node.quasi = parseTemplate();
  1741. return parseSubscripts(finishNode(node, "TaggedTemplateExpression"), start, noCalls);
  1742. } return base;
  1743. }
  1744. // Parse an atomic expression — either a single token that is an
  1745. // expression, an expression started by a keyword like `function` or
  1746. // `new`, or an expression wrapped in punctuation like `()`, `[]`,
  1747. // or `{}`.
  1748. function parseExprAtom() {
  1749. switch (tokType) {
  1750. case _this:
  1751. var node = startNode();
  1752. next();
  1753. return finishNode(node, "ThisExpression");
  1754. case _yield:
  1755. if (inGenerator) return parseYield();
  1756. case _name:
  1757. var start = storeCurrentPos();
  1758. var id = parseIdent(tokType !== _name);
  1759. if (eat(_arrow)) {
  1760. return parseArrowExpression(startNodeAt(start), [id]);
  1761. }
  1762. return id;
  1763. case _regexp:
  1764. var node = startNode();
  1765. node.regex = {pattern: tokVal.pattern, flags: tokVal.flags};
  1766. node.value = tokVal.value;
  1767. node.raw = input.slice(tokStart, tokEnd);
  1768. next();
  1769. return finishNode(node, "Literal");
  1770. case _num: case _string:
  1771. var node = startNode();
  1772. node.value = tokVal;
  1773. node.raw = input.slice(tokStart, tokEnd);
  1774. next();
  1775. return finishNode(node, "Literal");
  1776. case _null: case _true: case _false:
  1777. var node = startNode();
  1778. node.value = tokType.atomValue;
  1779. node.raw = tokType.keyword;
  1780. next();
  1781. return finishNode(node, "Literal");
  1782. case _parenL:
  1783. var start = storeCurrentPos();
  1784. var val, exprList;
  1785. next();
  1786. // check whether this is generator comprehension or regular expression
  1787. if (options.ecmaVersion >= 7 && tokType === _for) {
  1788. val = parseComprehension(startNodeAt(start), true);
  1789. } else {
  1790. var oldParenL = ++metParenL;
  1791. if (tokType !== _parenR) {
  1792. val = parseExpression();
  1793. exprList = val.type === "SequenceExpression" ? val.expressions : [val];
  1794. } else {
  1795. exprList = [];
  1796. }
  1797. expect(_parenR);
  1798. // if '=>' follows '(...)', convert contents to arguments
  1799. if (metParenL === oldParenL && eat(_arrow)) {
  1800. val = parseArrowExpression(startNodeAt(start), exprList);
  1801. } else {
  1802. // forbid '()' before everything but '=>'
  1803. if (!val) unexpected(lastStart);
  1804. // forbid '...' in sequence expressions
  1805. if (options.ecmaVersion >= 6) {
  1806. for (var i = 0; i < exprList.length; i++) {
  1807. if (exprList[i].type === "SpreadElement") unexpected();
  1808. }
  1809. }
  1810. if (options.preserveParens) {
  1811. var par = startNodeAt(start);
  1812. par.expression = val;
  1813. val = finishNode(par, "ParenthesizedExpression");
  1814. }
  1815. }
  1816. }
  1817. return val;
  1818. case _bracketL:
  1819. var node = startNode();
  1820. next();
  1821. // check whether this is array comprehension or regular array
  1822. if (options.ecmaVersion >= 7 && tokType === _for) {
  1823. return parseComprehension(node, false);
  1824. }
  1825. node.elements = parseExprList(_bracketR, true, true);
  1826. return finishNode(node, "ArrayExpression");
  1827. case _braceL:
  1828. return parseObj();
  1829. case _function:
  1830. var node = startNode();
  1831. next();
  1832. return parseFunction(node, false);
  1833. case _class:
  1834. return parseClass(startNode(), false);
  1835. case _new:
  1836. return parseNew();
  1837. case _bquote:
  1838. return parseTemplate();
  1839. default:
  1840. unexpected();
  1841. }
  1842. }
  1843. // New's precedence is slightly tricky. It must allow its argument
  1844. // to be a `[]` or dot subscript expression, but not a call — at
  1845. // least, not without wrapping it in parentheses. Thus, it uses the
  1846. function parseNew() {
  1847. var node = startNode();
  1848. next();
  1849. var start = storeCurrentPos();
  1850. node.callee = parseSubscripts(parseExprAtom(), start, true);
  1851. if (eat(_parenL)) node.arguments = parseExprList(_parenR, false);
  1852. else node.arguments = empty;
  1853. return finishNode(node, "NewExpression");
  1854. }
  1855. // Parse template expression.
  1856. function parseTemplate() {
  1857. var node = startNode();
  1858. node.expressions = [];
  1859. node.quasis = [];
  1860. inTemplate = true;
  1861. next();
  1862. for (;;) {
  1863. var elem = startNode();
  1864. elem.value = {cooked: tokVal, raw: input.slice(tokStart, tokEnd)};
  1865. elem.tail = false;
  1866. next();
  1867. node.quasis.push(finishNode(elem, "TemplateElement"));
  1868. if (tokType === _bquote) { // '`', end of template
  1869. elem.tail = true;
  1870. break;
  1871. }
  1872. inTemplate = false;
  1873. expect(_dollarBraceL);
  1874. node.expressions.push(parseExpression());
  1875. inTemplate = true;
  1876. // hack to include previously skipped space
  1877. tokPos = tokEnd;
  1878. expect(_braceR);
  1879. }
  1880. inTemplate = false;
  1881. next();
  1882. return finishNode(node, "TemplateLiteral");
  1883. }
  1884. // Parse an object literal.
  1885. function parseObj() {
  1886. var node = startNode(), first = true, propHash = {};
  1887. node.properties = [];
  1888. next();
  1889. while (!eat(_braceR)) {
  1890. if (!first) {
  1891. expect(_comma);
  1892. if (options.allowTrailingCommas && eat(_braceR)) break;
  1893. } else first = false;
  1894. var prop = startNode(), isGenerator;
  1895. if (options.ecmaVersion >= 6) {
  1896. prop.method = false;
  1897. prop.shorthand = false;
  1898. isGenerator = eat(_star);
  1899. }
  1900. parsePropertyName(prop);
  1901. if (eat(_colon)) {
  1902. prop.value = parseExpression(true);
  1903. prop.kind = "init";
  1904. } else if (options.ecmaVersion >= 6 && tokType === _parenL) {
  1905. prop.kind = "init";
  1906. prop.method = true;
  1907. prop.value = parseMethod(isGenerator);
  1908. } else if (options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
  1909. (prop.key.name === "get" || prop.key.name === "set")) {
  1910. if (isGenerator) unexpected();
  1911. prop.kind = prop.key.name;
  1912. parsePropertyName(prop);
  1913. prop.value = parseMethod(false);
  1914. } else if (options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
  1915. prop.kind = "init";
  1916. prop.value = prop.key;
  1917. prop.shorthand = true;
  1918. } else unexpected();
  1919. checkPropClash(prop, propHash);
  1920. node.properties.push(finishNode(prop, "Property"));
  1921. }
  1922. return finishNode(node, "ObjectExpression");
  1923. }
  1924. function parsePropertyName(prop) {
  1925. if (options.ecmaVersion >= 6) {
  1926. if (eat(_bracketL)) {
  1927. prop.computed = true;
  1928. prop.key = parseExpression();
  1929. expect(_bracketR);
  1930. return;
  1931. } else {
  1932. prop.computed = false;
  1933. }
  1934. }
  1935. prop.key = (tokType === _num || tokType === _string) ? parseExprAtom() : parseIdent(true);
  1936. }
  1937. // Initialize empty function node.
  1938. function initFunction(node) {
  1939. node.id = null;
  1940. node.params = [];
  1941. if (options.ecmaVersion >= 6) {
  1942. node.defaults = [];
  1943. node.rest = null;
  1944. node.generator = false;
  1945. }
  1946. }
  1947. // Parse a function declaration or literal (depending on the
  1948. // `isStatement` parameter).
  1949. function parseFunction(node, isStatement, allowExpressionBody) {
  1950. initFunction(node);
  1951. if (options.ecmaVersion >= 6) {
  1952. node.generator = eat(_star);
  1953. }
  1954. if (isStatement || tokType === _name) {
  1955. node.id = parseIdent();
  1956. }
  1957. parseFunctionParams(node);
  1958. parseFunctionBody(node, allowExpressionBody);
  1959. return finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
  1960. }
  1961. // Parse object or class method.
  1962. function parseMethod(isGenerator) {
  1963. var node = startNode();
  1964. initFunction(node);
  1965. parseFunctionParams(node);
  1966. var allowExpressionBody;
  1967. if (options.ecmaVersion >= 6) {
  1968. node.generator = isGenerator;
  1969. allowExpressionBody = true;
  1970. } else {
  1971. allowExpressionBody = false;
  1972. }
  1973. parseFunctionBody(node, allowExpressionBody);
  1974. return finishNode(node, "FunctionExpression");
  1975. }
  1976. // Parse arrow function expression with given parameters.
  1977. function parseArrowExpression(node, params) {
  1978. initFunction(node);
  1979. var defaults = node.defaults, hasDefaults = false;
  1980. for (var i = 0, lastI = params.length - 1; i <= lastI; i++) {
  1981. var param = params[i];
  1982. if (param.type === "AssignmentExpression" && param.operator === "=") {
  1983. hasDefaults = true;
  1984. params[i] = param.left;
  1985. defaults.push(param.right);
  1986. } else {
  1987. toAssignable(param, i === lastI, true);
  1988. defaults.push(null);
  1989. if (param.type === "SpreadElement") {
  1990. params.length--;
  1991. node.rest = param.argument;
  1992. break;
  1993. }
  1994. }
  1995. }
  1996. node.params = params;
  1997. if (!hasDefaults) node.defaults = [];
  1998. parseFunctionBody(node, true);
  1999. return finishNode(node, "ArrowFunctionExpression");
  2000. }
  2001. // Parse function parameters.
  2002. function parseFunctionParams(node) {
  2003. var defaults = [], hasDefaults = false;
  2004. expect(_parenL);
  2005. for (;;) {
  2006. if (eat(_parenR)) {
  2007. break;
  2008. } else if (options.ecmaVersion >= 6 && eat(_ellipsis)) {
  2009. node.rest = toAssignable(parseExprAtom(), false, true);
  2010. checkSpreadAssign(node.rest);
  2011. expect(_parenR);
  2012. defaults.push(null);
  2013. break;
  2014. } else {
  2015. node.params.push(options.ecmaVersion >= 6 ? toAssignable(parseExprAtom(), false, true) : parseIdent());
  2016. if (options.ecmaVersion >= 6) {
  2017. if (eat(_eq)) {
  2018. hasDefaults = true;
  2019. defaults.push(parseExpression(true));
  2020. } else {
  2021. defaults.push(null);
  2022. }
  2023. }
  2024. if (!eat(_comma)) {
  2025. expect(_parenR);
  2026. break;
  2027. }
  2028. }
  2029. }
  2030. if (hasDefaults) node.defaults = defaults;
  2031. }
  2032. // Parse function body and check parameters.
  2033. function parseFunctionBody(node, allowExpression) {
  2034. var isExpression = allowExpression && tokType !== _braceL;
  2035. if (isExpression) {
  2036. node.body = parseExpression(true);
  2037. node.expression = true;
  2038. } else {
  2039. // Start a new scope with regard to labels and the `inFunction`
  2040. // flag (restore them to their old value afterwards).
  2041. var oldInFunc = inFunction, oldInGen = inGenerator, oldLabels = labels;
  2042. inFunction = true; inGenerator = node.generator; labels = [];
  2043. node.body = parseBlock(true);
  2044. node.expression = false;
  2045. inFunction = oldInFunc; inGenerator = oldInGen; labels = oldLabels;
  2046. }
  2047. // If this is a strict mode function, verify that argument names
  2048. // are not repeated, and it does not try to bind the words `eval`
  2049. // or `arguments`.
  2050. if (strict || !isExpression && node.body.body.length && isUseStrict(node.body.body[0])) {
  2051. var nameHash = {};
  2052. if (node.id)
  2053. checkFunctionParam(node.id, {});
  2054. for (var i = 0; i < node.params.length; i++)
  2055. checkFunctionParam(node.params[i], nameHash);
  2056. if (node.rest)
  2057. checkFunctionParam(node.rest, nameHash);
  2058. }
  2059. }
  2060. // Parse a class declaration or literal (depending on the
  2061. // `isStatement` parameter).
  2062. function parseClass(node, isStatement) {
  2063. next();
  2064. node.id = tokType === _name ? parseIdent() : isStatement ? unexpected() : null;
  2065. node.superClass = eat(_extends) ? parseExpression() : null;
  2066. var classBody = startNode();
  2067. classBody.body = [];
  2068. expect(_braceL);
  2069. while (!eat(_braceR)) {
  2070. var method = startNode();
  2071. if (tokType === _name && tokVal === "static") {
  2072. next();
  2073. method['static'] = true;
  2074. } else {
  2075. method['static'] = false;
  2076. }
  2077. var isGenerator = eat(_star);
  2078. parsePropertyName(method);
  2079. if (tokType !== _parenL && !method.computed && method.key.type === "Identifier" &&
  2080. (method.key.name === "get" || method.key.name === "set")) {
  2081. if (isGenerator) unexpected();
  2082. method.kind = method.key.name;
  2083. parsePropertyName(method);
  2084. } else {
  2085. method.kind = "";
  2086. }
  2087. method.value = parseMethod(isGenerator);
  2088. classBody.body.push(finishNode(method, "MethodDefinition"));
  2089. eat(_semi);
  2090. }
  2091. node.body = finishNode(classBody, "ClassBody");
  2092. return finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
  2093. }
  2094. // Parses a comma-separated list of expressions, and returns them as
  2095. // an array. `close` is the token type that ends the list, and
  2096. // `allowEmpty` can be turned on to allow subsequent commas with
  2097. // nothing in between them to be parsed as `null` (which is needed
  2098. // for array literals).
  2099. function parseExprList(close, allowTrailingComma, allowEmpty) {
  2100. var elts = [], first = true;
  2101. while (!eat(close)) {
  2102. if (!first) {
  2103. expect(_comma);
  2104. if (allowTrailingComma && options.allowTrailingCommas && eat(close)) break;
  2105. } else first = false;
  2106. if (allowEmpty && tokType === _comma) elts.push(null);
  2107. else elts.push(parseExpression(true));
  2108. }
  2109. return elts;
  2110. }
  2111. // Parse the next token as an identifier. If `liberal` is true (used
  2112. // when parsing properties), it will also convert keywords into
  2113. // identifiers.
  2114. function parseIdent(liberal) {
  2115. var node = startNode();
  2116. if (liberal && options.forbidReserved == "everywhere") liberal = false;
  2117. if (tokType === _name) {
  2118. if (!liberal &&
  2119. (options.forbidReserved &&
  2120. (options.ecmaVersion === 3 ? isReservedWord3 : isReservedWord5)(tokVal) ||
  2121. strict && isStrictReservedWord(tokVal)) &&
  2122. input.slice(tokStart, tokEnd).indexOf("\\") == -1)
  2123. raise(tokStart, "The keyword '" + tokVal + "' is reserved");
  2124. node.name = tokVal;
  2125. } else if (liberal && tokType.keyword) {
  2126. node.name = tokType.keyword;
  2127. } else {
  2128. unexpected();
  2129. }
  2130. tokRegexpAllowed = false;
  2131. next();
  2132. return finishNode(node, "Identifier");
  2133. }
  2134. // Parses module export declaration.
  2135. function parseExport(node) {
  2136. next();
  2137. // export var|const|let|function|class ...;
  2138. if (tokType === _var || tokType === _const || tokType === _let || tokType === _function || tokType === _class) {
  2139. node.declaration = parseStatement();
  2140. node['default'] = false;
  2141. node.specifiers = null;
  2142. node.source = null;
  2143. } else
  2144. // export default ...;
  2145. if (eat(_default)) {
  2146. node.declaration = parseExpression(true);
  2147. node['default'] = true;
  2148. node.specifiers = null;
  2149. node.source = null;
  2150. semicolon();
  2151. } else {
  2152. // export * from '...';
  2153. // export { x, y as z } [from '...'];
  2154. var isBatch = tokType === _star;
  2155. node.declaration = null;
  2156. node['default'] = false;
  2157. node.specifiers = parseExportSpecifiers();
  2158. if (tokType === _name && tokVal === "from") {
  2159. next();
  2160. node.source = tokType === _string ? parseExprAtom() : unexpected();
  2161. } else {
  2162. if (isBatch) unexpected();
  2163. node.source = null;
  2164. }
  2165. semicolon();
  2166. }
  2167. return finishNode(node, "ExportDeclaration");
  2168. }
  2169. // Parses a comma-separated list of module exports.
  2170. function parseExportSpecifiers() {
  2171. var nodes = [], first = true;
  2172. if (tokType === _star) {
  2173. // export * from '...'
  2174. var node = startNode();
  2175. next();
  2176. nodes.push(finishNode(node, "ExportBatchSpecifier"));
  2177. } else {
  2178. // export { x, y as z } [from '...']
  2179. expect(_braceL);
  2180. while (!eat(_braceR)) {
  2181. if (!first) {
  2182. expect(_comma);
  2183. if (options.allowTrailingCommas && eat(_braceR)) break;
  2184. } else first = false;
  2185. var node = startNode();
  2186. node.id = parseIdent(tokType === _default);
  2187. if (tokType === _name && tokVal === "as") {
  2188. next();
  2189. node.name = parseIdent(true);
  2190. } else {
  2191. node.name = null;
  2192. }
  2193. nodes.push(finishNode(node, "ExportSpecifier"));
  2194. }
  2195. }
  2196. return nodes;
  2197. }
  2198. // Parses import declaration.
  2199. function parseImport(node) {
  2200. next();
  2201. // import '...';
  2202. if (tokType === _string) {
  2203. node.specifiers = [];
  2204. node.source = parseExprAtom();
  2205. node.kind = "";
  2206. } else {
  2207. node.specifiers = parseImportSpecifiers();
  2208. if (tokType !== _name || tokVal !== "from") unexpected();
  2209. next();
  2210. node.source = tokType === _string ? parseExprAtom() : unexpected();
  2211. }
  2212. semicolon();
  2213. return finishNode(node, "ImportDeclaration");
  2214. }
  2215. // Parses a comma-separated list of module imports.
  2216. function parseImportSpecifiers() {
  2217. var nodes = [], first = true;
  2218. if (tokType === _name) {
  2219. // import defaultObj, { x, y as z } from '...'
  2220. var node = startNode();
  2221. node.id = parseIdent();
  2222. checkLVal(node.id, true);
  2223. node.name = null;
  2224. node['default'] = true;
  2225. nodes.push(finishNode(node, "ImportSpecifier"));
  2226. if (!eat(_comma)) return nodes;
  2227. }
  2228. if (tokType === _star) {
  2229. var node = startNode();
  2230. next();
  2231. if (tokType !== _name || tokVal !== "as") unexpected();
  2232. next();
  2233. node.name = parseIdent();
  2234. checkLVal(node.name, true);
  2235. nodes.push(finishNode(node, "ImportBatchSpecifier"));
  2236. return nodes;
  2237. }
  2238. expect(_braceL);
  2239. while (!eat(_braceR)) {
  2240. if (!first) {
  2241. expect(_comma);
  2242. if (options.allowTrailingCommas && eat(_braceR)) break;
  2243. } else first = false;
  2244. var node = startNode();
  2245. node.id = parseIdent(true);
  2246. if (tokType === _name && tokVal === "as") {
  2247. next();
  2248. node.name = parseIdent();
  2249. } else {
  2250. node.name = null;
  2251. }
  2252. checkLVal(node.name || node.id, true);
  2253. node['default'] = false;
  2254. nodes.push(finishNode(node, "ImportSpecifier"));
  2255. }
  2256. return nodes;
  2257. }
  2258. // Parses yield expression inside generator.
  2259. function parseYield() {
  2260. var node = startNode();
  2261. next();
  2262. if (eat(_semi) || canInsertSemicolon()) {
  2263. node.delegate = false;
  2264. node.argument = null;
  2265. } else {
  2266. node.delegate = eat(_star);
  2267. node.argument = parseExpression(true);
  2268. }
  2269. return finishNode(node, "YieldExpression");
  2270. }
  2271. // Parses array and generator comprehensions.
  2272. function parseComprehension(node, isGenerator) {
  2273. node.blocks = [];
  2274. while (tokType === _for) {
  2275. var block = startNode();
  2276. next();
  2277. expect(_parenL);
  2278. block.left = toAssignable(parseExprAtom());
  2279. checkLVal(block.left, true);
  2280. if (tokType !== _name || tokVal !== "of") unexpected();
  2281. next();
  2282. // `of` property is here for compatibility with Esprima's AST
  2283. // which also supports deprecated [for (... in ...) expr]
  2284. block.of = true;
  2285. block.right = parseExpression();
  2286. expect(_parenR);
  2287. node.blocks.push(finishNode(block, "ComprehensionBlock"));
  2288. }
  2289. node.filter = eat(_if) ? parseParenExpression() : null;
  2290. node.body = parseExpression();
  2291. expect(isGenerator ? _parenR : _bracketR);
  2292. node.generator = isGenerator;
  2293. return finishNode(node, "ComprehensionExpression");
  2294. }
  2295. });