parse.js 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567
  1. /***********************************************************************
  2. A JavaScript tokenizer / parser / beautifier / compressor.
  3. https://github.com/mishoo/UglifyJS
  4. -------------------------------- (C) ---------------------------------
  5. Author: Mihai Bazon
  6. <mihai.bazon@gmail.com>
  7. http://mihai.bazon.net/blog
  8. Distributed under the BSD license:
  9. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  10. Parser based on parse-js (http://marijn.haverbeke.nl/parse-js/).
  11. Redistribution and use in source and binary forms, with or without
  12. modification, are permitted provided that the following conditions
  13. are met:
  14. * Redistributions of source code must retain the above
  15. copyright notice, this list of conditions and the following
  16. disclaimer.
  17. * Redistributions in binary form must reproduce the above
  18. copyright notice, this list of conditions and the following
  19. disclaimer in the documentation and/or other materials
  20. provided with the distribution.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  22. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  23. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  24. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  25. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  26. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  27. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  28. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  30. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  31. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  32. SUCH DAMAGE.
  33. ***********************************************************************/
  34. "use strict";
  35. var KEYWORDS = "break case catch class const continue debugger default delete do else extends finally for function if in instanceof new return switch throw try typeof var void while with";
  36. var KEYWORDS_ATOM = "false null true";
  37. var RESERVED_WORDS = [
  38. "abstract async await boolean byte char double enum export final float goto implements import int interface let long native package private protected public short static super synchronized this throws transient volatile yield",
  39. KEYWORDS_ATOM,
  40. KEYWORDS,
  41. ].join(" ");
  42. var KEYWORDS_BEFORE_EXPRESSION = "return new delete throw else case";
  43. KEYWORDS = makePredicate(KEYWORDS);
  44. RESERVED_WORDS = makePredicate(RESERVED_WORDS);
  45. KEYWORDS_BEFORE_EXPRESSION = makePredicate(KEYWORDS_BEFORE_EXPRESSION);
  46. KEYWORDS_ATOM = makePredicate(KEYWORDS_ATOM);
  47. var RE_BIN_NUMBER = /^0b([01]+)$/i;
  48. var RE_HEX_NUMBER = /^0x([0-9a-f]+)$/i;
  49. var RE_OCT_NUMBER = /^0o?([0-7]+)$/i;
  50. var OPERATORS = makePredicate([
  51. "in",
  52. "instanceof",
  53. "typeof",
  54. "new",
  55. "void",
  56. "delete",
  57. "++",
  58. "--",
  59. "+",
  60. "-",
  61. "!",
  62. "~",
  63. "&",
  64. "|",
  65. "^",
  66. "*",
  67. "/",
  68. "%",
  69. "**",
  70. ">>",
  71. "<<",
  72. ">>>",
  73. "<",
  74. ">",
  75. "<=",
  76. ">=",
  77. "==",
  78. "===",
  79. "!=",
  80. "!==",
  81. "?",
  82. "=",
  83. "+=",
  84. "-=",
  85. "/=",
  86. "*=",
  87. "%=",
  88. "**=",
  89. ">>=",
  90. "<<=",
  91. ">>>=",
  92. "&=",
  93. "|=",
  94. "^=",
  95. "&&",
  96. "||",
  97. "??",
  98. "&&=",
  99. "||=",
  100. "??=",
  101. ]);
  102. var NEWLINE_CHARS = "\n\r\u2028\u2029";
  103. var OPERATOR_CHARS = "+-*&%=<>!?|~^";
  104. var PUNC_OPENERS = "[{(";
  105. var PUNC_SEPARATORS = ",;:";
  106. var PUNC_CLOSERS = ")}]";
  107. var PUNC_AFTER_EXPRESSION = PUNC_SEPARATORS + PUNC_CLOSERS;
  108. var PUNC_BEFORE_EXPRESSION = PUNC_OPENERS + PUNC_SEPARATORS;
  109. var PUNC_CHARS = PUNC_BEFORE_EXPRESSION + "`" + PUNC_CLOSERS;
  110. var WHITESPACE_CHARS = NEWLINE_CHARS + " \u00a0\t\f\u000b\u200b\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\uFEFF";
  111. var NON_IDENTIFIER_CHARS = makePredicate(characters("./'\"#" + OPERATOR_CHARS + PUNC_CHARS + WHITESPACE_CHARS));
  112. NEWLINE_CHARS = makePredicate(characters(NEWLINE_CHARS));
  113. OPERATOR_CHARS = makePredicate(characters(OPERATOR_CHARS));
  114. PUNC_AFTER_EXPRESSION = makePredicate(characters(PUNC_AFTER_EXPRESSION));
  115. PUNC_BEFORE_EXPRESSION = makePredicate(characters(PUNC_BEFORE_EXPRESSION));
  116. PUNC_CHARS = makePredicate(characters(PUNC_CHARS));
  117. WHITESPACE_CHARS = makePredicate(characters(WHITESPACE_CHARS));
  118. /* -----[ Tokenizer ]----- */
  119. function is_surrogate_pair_head(code) {
  120. return code >= 0xd800 && code <= 0xdbff;
  121. }
  122. function is_surrogate_pair_tail(code) {
  123. return code >= 0xdc00 && code <= 0xdfff;
  124. }
  125. function is_digit(code) {
  126. return code >= 48 && code <= 57;
  127. }
  128. function is_identifier_char(ch) {
  129. return !NON_IDENTIFIER_CHARS[ch];
  130. }
  131. function is_identifier_string(str) {
  132. return /^[a-z_$][a-z0-9_$]*$/i.test(str);
  133. }
  134. function decode_escape_sequence(seq) {
  135. switch (seq[0]) {
  136. case "b": return "\b";
  137. case "f": return "\f";
  138. case "n": return "\n";
  139. case "r": return "\r";
  140. case "t": return "\t";
  141. case "u":
  142. var code;
  143. if (seq[1] == "{" && seq.slice(-1) == "}") {
  144. code = seq.slice(2, -1);
  145. } else if (seq.length == 5) {
  146. code = seq.slice(1);
  147. } else {
  148. return;
  149. }
  150. var num = parseInt(code, 16);
  151. if (num < 0 || isNaN(num)) return;
  152. if (num < 0x10000) return String.fromCharCode(num);
  153. if (num > 0x10ffff) return;
  154. return String.fromCharCode((num >> 10) + 0xd7c0) + String.fromCharCode((num & 0x03ff) + 0xdc00);
  155. case "v": return "\u000b";
  156. case "x":
  157. if (seq.length != 3) return;
  158. var num = parseInt(seq.slice(1), 16);
  159. if (num < 0 || isNaN(num)) return;
  160. return String.fromCharCode(num);
  161. case "\r":
  162. case "\n":
  163. return "";
  164. default:
  165. if (seq == "0") return "\0";
  166. if (seq[0] >= "0" && seq[0] <= "9") return;
  167. return seq;
  168. }
  169. }
  170. function parse_js_number(num) {
  171. var match;
  172. if (match = RE_BIN_NUMBER.exec(num)) return parseInt(match[1], 2);
  173. if (match = RE_HEX_NUMBER.exec(num)) return parseInt(match[1], 16);
  174. if (match = RE_OCT_NUMBER.exec(num)) return parseInt(match[1], 8);
  175. var val = parseFloat(num);
  176. if (val == num) return val;
  177. }
  178. function JS_Parse_Error(message, filename, line, col, pos) {
  179. this.message = message;
  180. this.filename = filename;
  181. this.line = line;
  182. this.col = col;
  183. this.pos = pos;
  184. }
  185. JS_Parse_Error.prototype = Object.create(Error.prototype);
  186. JS_Parse_Error.prototype.constructor = JS_Parse_Error;
  187. JS_Parse_Error.prototype.name = "SyntaxError";
  188. configure_error_stack(JS_Parse_Error);
  189. function js_error(message, filename, line, col, pos) {
  190. throw new JS_Parse_Error(message, filename, line, col, pos);
  191. }
  192. function is_token(token, type, val) {
  193. return token.type == type && (val == null || token.value == val);
  194. }
  195. var EX_EOF = {};
  196. function tokenizer($TEXT, filename, html5_comments, shebang) {
  197. var S = {
  198. text : $TEXT,
  199. filename : filename,
  200. pos : 0,
  201. tokpos : 0,
  202. line : 1,
  203. tokline : 0,
  204. col : 0,
  205. tokcol : 0,
  206. newline_before : false,
  207. regex_allowed : false,
  208. comments_before : [],
  209. directives : {},
  210. directive_stack : [],
  211. read_template : with_eof_error("Unterminated template literal", function(strings) {
  212. var s = "";
  213. for (;;) {
  214. var ch = read();
  215. switch (ch) {
  216. case "\\":
  217. ch += read();
  218. break;
  219. case "`":
  220. strings.push(s);
  221. return;
  222. case "$":
  223. if (peek() == "{") {
  224. next();
  225. strings.push(s);
  226. S.regex_allowed = true;
  227. return true;
  228. }
  229. }
  230. s += ch;
  231. }
  232. function read() {
  233. var ch = next(true, true);
  234. return ch == "\r" ? "\n" : ch;
  235. }
  236. }),
  237. };
  238. var prev_was_dot = false;
  239. function peek() {
  240. return S.text.charAt(S.pos);
  241. }
  242. function next(signal_eof, in_string) {
  243. var ch = S.text.charAt(S.pos++);
  244. if (signal_eof && !ch)
  245. throw EX_EOF;
  246. if (NEWLINE_CHARS[ch]) {
  247. S.col = 0;
  248. S.line++;
  249. if (!in_string) S.newline_before = true;
  250. if (ch == "\r" && peek() == "\n") {
  251. // treat `\r\n` as `\n`
  252. S.pos++;
  253. ch = "\n";
  254. }
  255. } else {
  256. S.col++;
  257. }
  258. return ch;
  259. }
  260. function forward(i) {
  261. while (i-- > 0) next();
  262. }
  263. function looking_at(str) {
  264. return S.text.substr(S.pos, str.length) == str;
  265. }
  266. function find_eol() {
  267. var text = S.text;
  268. for (var i = S.pos; i < S.text.length; ++i) {
  269. if (NEWLINE_CHARS[text[i]]) return i;
  270. }
  271. return -1;
  272. }
  273. function find(what, signal_eof) {
  274. var pos = S.text.indexOf(what, S.pos);
  275. if (signal_eof && pos == -1) throw EX_EOF;
  276. return pos;
  277. }
  278. function start_token() {
  279. S.tokline = S.line;
  280. S.tokcol = S.col;
  281. S.tokpos = S.pos;
  282. }
  283. function token(type, value, is_comment) {
  284. S.regex_allowed = type == "operator" && !UNARY_POSTFIX[value]
  285. || type == "keyword" && KEYWORDS_BEFORE_EXPRESSION[value]
  286. || type == "punc" && PUNC_BEFORE_EXPRESSION[value];
  287. if (type == "punc" && value == ".") prev_was_dot = true;
  288. else if (!is_comment) prev_was_dot = false;
  289. var ret = {
  290. type : type,
  291. value : value,
  292. line : S.tokline,
  293. col : S.tokcol,
  294. pos : S.tokpos,
  295. endline : S.line,
  296. endcol : S.col,
  297. endpos : S.pos,
  298. nlb : S.newline_before,
  299. file : filename
  300. };
  301. if (/^(?:num|string|regexp)$/i.test(type)) {
  302. ret.raw = $TEXT.substring(ret.pos, ret.endpos);
  303. }
  304. if (!is_comment) {
  305. ret.comments_before = S.comments_before;
  306. ret.comments_after = S.comments_before = [];
  307. }
  308. S.newline_before = false;
  309. return new AST_Token(ret);
  310. }
  311. function skip_whitespace() {
  312. while (WHITESPACE_CHARS[peek()])
  313. next();
  314. }
  315. function read_while(pred) {
  316. var ret = "", ch;
  317. while ((ch = peek()) && pred(ch, ret)) ret += next();
  318. return ret;
  319. }
  320. function parse_error(err) {
  321. js_error(err, filename, S.tokline, S.tokcol, S.tokpos);
  322. }
  323. function is_octal(num) {
  324. return /^0[0-7_]+$/.test(num);
  325. }
  326. function read_num(prefix) {
  327. var has_e = false, after_e = false, has_x = false, has_dot = prefix == ".";
  328. var num = read_while(function(ch, str) {
  329. switch (ch) {
  330. case "x": case "X":
  331. return has_x ? false : (has_x = true);
  332. case "e": case "E":
  333. return has_x ? true : has_e ? false : (has_e = after_e = true);
  334. case "+": case "-":
  335. return after_e;
  336. case (after_e = false, "."):
  337. return has_dot || has_e || has_x || is_octal(str) ? false : (has_dot = true);
  338. }
  339. return /[_0-9a-dfo]/i.test(ch);
  340. });
  341. if (prefix) num = prefix + num;
  342. if (is_octal(num)) {
  343. if (next_token.has_directive("use strict")) parse_error("Legacy octal literals are not allowed in strict mode");
  344. } else {
  345. num = num.replace(has_x ? /([1-9a-f]|.0)_(?=[0-9a-f])/gi : /([1-9]|.0)_(?=[0-9])/gi, "$1");
  346. }
  347. var valid = parse_js_number(num);
  348. if (isNaN(valid)) parse_error("Invalid syntax: " + num);
  349. if (has_dot || has_e || peek() != "n") return token("num", valid);
  350. return token("bigint", num.toLowerCase() + next());
  351. }
  352. function read_escaped_char(in_string) {
  353. var seq = next(true, in_string);
  354. if (seq >= "0" && seq <= "7") return read_octal_escape_sequence(seq);
  355. if (seq == "u") {
  356. var ch = next(true, in_string);
  357. seq += ch;
  358. if (ch != "{") {
  359. seq += next(true, in_string) + next(true, in_string) + next(true, in_string);
  360. } else do {
  361. ch = next(true, in_string);
  362. seq += ch;
  363. } while (ch != "}");
  364. } else if (seq == "x") {
  365. seq += next(true, in_string) + next(true, in_string);
  366. }
  367. var str = decode_escape_sequence(seq);
  368. if (typeof str != "string") parse_error("Invalid escape sequence: \\" + seq);
  369. return str;
  370. }
  371. function read_octal_escape_sequence(ch) {
  372. // Read
  373. var p = peek();
  374. if (p >= "0" && p <= "7") {
  375. ch += next(true);
  376. if (ch[0] <= "3" && (p = peek()) >= "0" && p <= "7")
  377. ch += next(true);
  378. }
  379. // Parse
  380. if (ch === "0") return "\0";
  381. if (ch.length > 0 && next_token.has_directive("use strict"))
  382. parse_error("Legacy octal escape sequences are not allowed in strict mode");
  383. return String.fromCharCode(parseInt(ch, 8));
  384. }
  385. var read_string = with_eof_error("Unterminated string constant", function(quote_char) {
  386. var quote = next(), ret = "";
  387. for (;;) {
  388. var ch = next(true, true);
  389. if (ch == "\\") ch = read_escaped_char(true);
  390. else if (NEWLINE_CHARS[ch]) parse_error("Unterminated string constant");
  391. else if (ch == quote) break;
  392. ret += ch;
  393. }
  394. var tok = token("string", ret);
  395. tok.quote = quote_char;
  396. return tok;
  397. });
  398. function skip_line_comment(type) {
  399. var regex_allowed = S.regex_allowed;
  400. var i = find_eol(), ret;
  401. if (i == -1) {
  402. ret = S.text.substr(S.pos);
  403. S.pos = S.text.length;
  404. } else {
  405. ret = S.text.substring(S.pos, i);
  406. S.pos = i;
  407. }
  408. S.col = S.tokcol + (S.pos - S.tokpos);
  409. S.comments_before.push(token(type, ret, true));
  410. S.regex_allowed = regex_allowed;
  411. return next_token;
  412. }
  413. var skip_multiline_comment = with_eof_error("Unterminated multiline comment", function() {
  414. var regex_allowed = S.regex_allowed;
  415. var i = find("*/", true);
  416. var text = S.text.substring(S.pos, i).replace(/\r\n|\r|\u2028|\u2029/g, "\n");
  417. // update stream position
  418. forward(text.length /* doesn't count \r\n as 2 char while S.pos - i does */ + 2);
  419. S.comments_before.push(token("comment2", text, true));
  420. S.regex_allowed = regex_allowed;
  421. return next_token;
  422. });
  423. function read_name() {
  424. var backslash = false, ch, escaped = false, name = peek() == "#" ? next() : "";
  425. while (ch = peek()) {
  426. if (!backslash) {
  427. if (ch == "\\") escaped = backslash = true, next();
  428. else if (is_identifier_char(ch)) name += next();
  429. else break;
  430. } else {
  431. if (ch != "u") parse_error("Expecting UnicodeEscapeSequence -- uXXXX");
  432. ch = read_escaped_char();
  433. if (!is_identifier_char(ch)) parse_error("Unicode char: " + ch.charCodeAt(0) + " is not valid in identifier");
  434. name += ch;
  435. backslash = false;
  436. }
  437. }
  438. if (KEYWORDS[name] && escaped) {
  439. var hex = name.charCodeAt(0).toString(16).toUpperCase();
  440. name = "\\u" + "0000".substr(hex.length) + hex + name.slice(1);
  441. }
  442. return name;
  443. }
  444. var read_regexp = with_eof_error("Unterminated regular expression", function(source) {
  445. var prev_backslash = false, ch, in_class = false;
  446. while ((ch = next(true))) if (NEWLINE_CHARS[ch]) {
  447. parse_error("Unexpected line terminator");
  448. } else if (prev_backslash) {
  449. source += "\\" + ch;
  450. prev_backslash = false;
  451. } else if (ch == "[") {
  452. in_class = true;
  453. source += ch;
  454. } else if (ch == "]" && in_class) {
  455. in_class = false;
  456. source += ch;
  457. } else if (ch == "/" && !in_class) {
  458. break;
  459. } else if (ch == "\\") {
  460. prev_backslash = true;
  461. } else {
  462. source += ch;
  463. }
  464. var mods = read_name();
  465. try {
  466. var regexp = new RegExp(source, mods);
  467. regexp.raw_source = source;
  468. return token("regexp", regexp);
  469. } catch (e) {
  470. parse_error(e.message);
  471. }
  472. });
  473. function read_operator(prefix) {
  474. function grow(op) {
  475. if (!peek()) return op;
  476. var bigger = op + peek();
  477. if (OPERATORS[bigger]) {
  478. next();
  479. return grow(bigger);
  480. } else {
  481. return op;
  482. }
  483. }
  484. return token("operator", grow(prefix || next()));
  485. }
  486. function handle_slash() {
  487. next();
  488. switch (peek()) {
  489. case "/":
  490. next();
  491. return skip_line_comment("comment1");
  492. case "*":
  493. next();
  494. return skip_multiline_comment();
  495. }
  496. return S.regex_allowed ? read_regexp("") : read_operator("/");
  497. }
  498. function handle_dot() {
  499. next();
  500. var ch = peek();
  501. if (ch == ".") {
  502. var op = ".";
  503. do {
  504. op += ".";
  505. next();
  506. } while (peek() == ".");
  507. return token("operator", op);
  508. }
  509. return is_digit(ch.charCodeAt(0)) ? read_num(".") : token("punc", ".");
  510. }
  511. function read_word() {
  512. var word = read_name();
  513. if (prev_was_dot) return token("name", word);
  514. return KEYWORDS_ATOM[word] ? token("atom", word)
  515. : !KEYWORDS[word] ? token("name", word)
  516. : OPERATORS[word] ? token("operator", word)
  517. : token("keyword", word);
  518. }
  519. function with_eof_error(eof_error, cont) {
  520. return function(x) {
  521. try {
  522. return cont(x);
  523. } catch (ex) {
  524. if (ex === EX_EOF) parse_error(eof_error);
  525. else throw ex;
  526. }
  527. };
  528. }
  529. function next_token(force_regexp) {
  530. if (force_regexp != null)
  531. return read_regexp(force_regexp);
  532. if (shebang && S.pos == 0 && looking_at("#!")) {
  533. start_token();
  534. forward(2);
  535. skip_line_comment("comment5");
  536. }
  537. for (;;) {
  538. skip_whitespace();
  539. start_token();
  540. if (html5_comments) {
  541. if (looking_at("<!--")) {
  542. forward(4);
  543. skip_line_comment("comment3");
  544. continue;
  545. }
  546. if (looking_at("-->") && S.newline_before) {
  547. forward(3);
  548. skip_line_comment("comment4");
  549. continue;
  550. }
  551. }
  552. var ch = peek();
  553. if (!ch) return token("eof");
  554. var code = ch.charCodeAt(0);
  555. switch (code) {
  556. case 34: case 39: return read_string(ch);
  557. case 46: return handle_dot();
  558. case 47:
  559. var tok = handle_slash();
  560. if (tok === next_token) continue;
  561. return tok;
  562. }
  563. if (is_digit(code)) return read_num();
  564. if (PUNC_CHARS[ch]) return token("punc", next());
  565. if (looking_at("=>")) return token("punc", next() + next());
  566. if (OPERATOR_CHARS[ch]) return read_operator();
  567. if (code == 35 || code == 92 || !NON_IDENTIFIER_CHARS[ch]) return read_word();
  568. break;
  569. }
  570. parse_error("Unexpected character '" + ch + "'");
  571. }
  572. next_token.context = function(nc) {
  573. if (nc) S = nc;
  574. return S;
  575. };
  576. next_token.add_directive = function(directive) {
  577. S.directive_stack[S.directive_stack.length - 1].push(directive);
  578. if (S.directives[directive]) S.directives[directive]++;
  579. else S.directives[directive] = 1;
  580. }
  581. next_token.push_directives_stack = function() {
  582. S.directive_stack.push([]);
  583. }
  584. next_token.pop_directives_stack = function() {
  585. var directives = S.directive_stack.pop();
  586. for (var i = directives.length; --i >= 0;) {
  587. S.directives[directives[i]]--;
  588. }
  589. }
  590. next_token.has_directive = function(directive) {
  591. return S.directives[directive] > 0;
  592. }
  593. return next_token;
  594. }
  595. /* -----[ Parser (constants) ]----- */
  596. var UNARY_PREFIX = makePredicate("typeof void delete -- ++ ! ~ - +");
  597. var UNARY_POSTFIX = makePredicate("-- ++");
  598. var ASSIGNMENT = makePredicate("= += -= /= *= %= **= >>= <<= >>>= &= |= ^= &&= ||= ??=");
  599. var PRECEDENCE = function(a, ret) {
  600. for (var i = 0; i < a.length;) {
  601. var b = a[i++];
  602. for (var j = 0; j < b.length; j++) {
  603. ret[b[j]] = i;
  604. }
  605. }
  606. return ret;
  607. }([
  608. ["??"],
  609. ["||"],
  610. ["&&"],
  611. ["|"],
  612. ["^"],
  613. ["&"],
  614. ["==", "===", "!=", "!=="],
  615. ["<", ">", "<=", ">=", "in", "instanceof"],
  616. [">>", "<<", ">>>"],
  617. ["+", "-"],
  618. ["*", "/", "%"],
  619. ["**"],
  620. ], {});
  621. var ATOMIC_START_TOKEN = makePredicate("atom bigint num regexp string");
  622. /* -----[ Parser ]----- */
  623. function parse($TEXT, options) {
  624. options = defaults(options, {
  625. bare_returns : false,
  626. expression : false,
  627. filename : null,
  628. html5_comments : true,
  629. shebang : true,
  630. strict : false,
  631. toplevel : null,
  632. }, true);
  633. var S = {
  634. input : typeof $TEXT == "string"
  635. ? tokenizer($TEXT, options.filename, options.html5_comments, options.shebang)
  636. : $TEXT,
  637. in_async : false,
  638. in_directives : true,
  639. in_funarg : -1,
  640. in_function : 0,
  641. in_generator : false,
  642. in_loop : 0,
  643. labels : [],
  644. peeked : null,
  645. prev : null,
  646. token : null,
  647. };
  648. S.token = next();
  649. function is(type, value) {
  650. return is_token(S.token, type, value);
  651. }
  652. function peek() {
  653. return S.peeked || (S.peeked = S.input());
  654. }
  655. function next() {
  656. S.prev = S.token;
  657. if (S.peeked) {
  658. S.token = S.peeked;
  659. S.peeked = null;
  660. } else {
  661. S.token = S.input();
  662. }
  663. S.in_directives = S.in_directives && (
  664. S.token.type == "string" || is("punc", ";")
  665. );
  666. return S.token;
  667. }
  668. function prev() {
  669. return S.prev;
  670. }
  671. function croak(msg, line, col, pos) {
  672. var ctx = S.input.context();
  673. js_error(msg,
  674. ctx.filename,
  675. line != null ? line : ctx.tokline,
  676. col != null ? col : ctx.tokcol,
  677. pos != null ? pos : ctx.tokpos);
  678. }
  679. function token_error(token, msg) {
  680. croak(msg, token.line, token.col);
  681. }
  682. function token_to_string(type, value) {
  683. return type + (value === undefined ? "" : " «" + value + "»");
  684. }
  685. function unexpected(token) {
  686. if (token == null) token = S.token;
  687. token_error(token, "Unexpected token: " + token_to_string(token.type, token.value));
  688. }
  689. function expect_token(type, val) {
  690. if (is(type, val)) return next();
  691. token_error(S.token, "Unexpected token: " + token_to_string(S.token.type, S.token.value) + ", expected: " + token_to_string(type, val));
  692. }
  693. function expect(punc) {
  694. return expect_token("punc", punc);
  695. }
  696. function has_newline_before(token) {
  697. return token.nlb || !all(token.comments_before, function(comment) {
  698. return !comment.nlb;
  699. });
  700. }
  701. function can_insert_semicolon() {
  702. return !options.strict
  703. && (is("eof") || is("punc", "}") || has_newline_before(S.token));
  704. }
  705. function semicolon(optional) {
  706. if (is("punc", ";")) next();
  707. else if (!optional && !can_insert_semicolon()) expect(";");
  708. }
  709. function parenthesised() {
  710. expect("(");
  711. var exp = expression();
  712. expect(")");
  713. return exp;
  714. }
  715. function embed_tokens(parser) {
  716. return function() {
  717. var start = S.token;
  718. var expr = parser.apply(null, arguments);
  719. var end = prev();
  720. expr.start = start;
  721. expr.end = end;
  722. return expr;
  723. };
  724. }
  725. function handle_regexp() {
  726. if (is("operator", "/") || is("operator", "/=")) {
  727. S.peeked = null;
  728. S.token = S.input(S.token.value.substr(1)); // force regexp
  729. }
  730. }
  731. var statement = embed_tokens(function() {
  732. handle_regexp();
  733. switch (S.token.type) {
  734. case "string":
  735. var dir = S.in_directives;
  736. var body = expression();
  737. if (dir) {
  738. if (body instanceof AST_String) {
  739. var value = body.start.raw.slice(1, -1);
  740. S.input.add_directive(value);
  741. body.value = value;
  742. } else {
  743. S.in_directives = dir = false;
  744. }
  745. }
  746. semicolon();
  747. return dir ? new AST_Directive(body) : new AST_SimpleStatement({ body: body });
  748. case "num":
  749. case "bigint":
  750. case "regexp":
  751. case "operator":
  752. case "atom":
  753. return simple_statement();
  754. case "name":
  755. switch (S.token.value) {
  756. case "async":
  757. if (is_token(peek(), "keyword", "function")) {
  758. next();
  759. next();
  760. if (!is("operator", "*")) return function_(AST_AsyncDefun);
  761. next();
  762. return function_(AST_AsyncGeneratorDefun);
  763. }
  764. break;
  765. case "await":
  766. if (S.in_async) return simple_statement();
  767. break;
  768. case "export":
  769. next();
  770. return export_();
  771. case "import":
  772. var token = peek();
  773. if (!(token.type == "punc" && /^[(.]$/.test(token.value))) {
  774. next();
  775. return import_();
  776. }
  777. break;
  778. case "let":
  779. if (is_vardefs()) {
  780. next();
  781. var node = let_();
  782. semicolon();
  783. return node;
  784. }
  785. break;
  786. case "yield":
  787. if (S.in_generator) return simple_statement();
  788. break;
  789. }
  790. return is_token(peek(), "punc", ":")
  791. ? labeled_statement()
  792. : simple_statement();
  793. case "punc":
  794. switch (S.token.value) {
  795. case "{":
  796. return new AST_BlockStatement({
  797. start : S.token,
  798. body : block_(),
  799. end : prev()
  800. });
  801. case "[":
  802. case "(":
  803. case "`":
  804. return simple_statement();
  805. case ";":
  806. S.in_directives = false;
  807. next();
  808. return new AST_EmptyStatement();
  809. default:
  810. unexpected();
  811. }
  812. case "keyword":
  813. switch (S.token.value) {
  814. case "break":
  815. next();
  816. return break_cont(AST_Break);
  817. case "class":
  818. next();
  819. return class_(AST_DefClass);
  820. case "const":
  821. next();
  822. var node = const_();
  823. semicolon();
  824. return node;
  825. case "continue":
  826. next();
  827. return break_cont(AST_Continue);
  828. case "debugger":
  829. next();
  830. semicolon();
  831. return new AST_Debugger();
  832. case "do":
  833. next();
  834. var body = in_loop(statement);
  835. expect_token("keyword", "while");
  836. var condition = parenthesised();
  837. semicolon(true);
  838. return new AST_Do({
  839. body : body,
  840. condition : condition
  841. });
  842. case "while":
  843. next();
  844. return new AST_While({
  845. condition : parenthesised(),
  846. body : in_loop(statement)
  847. });
  848. case "for":
  849. next();
  850. return for_();
  851. case "function":
  852. next();
  853. if (!is("operator", "*")) return function_(AST_Defun);
  854. next();
  855. return function_(AST_GeneratorDefun);
  856. case "if":
  857. next();
  858. return if_();
  859. case "return":
  860. if (S.in_function == 0 && !options.bare_returns)
  861. croak("'return' outside of function");
  862. next();
  863. var value = null;
  864. if (is("punc", ";")) {
  865. next();
  866. } else if (!can_insert_semicolon()) {
  867. value = expression();
  868. semicolon();
  869. }
  870. return new AST_Return({
  871. value: value
  872. });
  873. case "switch":
  874. next();
  875. return new AST_Switch({
  876. expression : parenthesised(),
  877. body : in_loop(switch_body_)
  878. });
  879. case "throw":
  880. next();
  881. if (has_newline_before(S.token))
  882. croak("Illegal newline after 'throw'");
  883. var value = expression();
  884. semicolon();
  885. return new AST_Throw({
  886. value: value
  887. });
  888. case "try":
  889. next();
  890. return try_();
  891. case "var":
  892. next();
  893. var node = var_();
  894. semicolon();
  895. return node;
  896. case "with":
  897. if (S.input.has_directive("use strict")) {
  898. croak("Strict mode may not include a with statement");
  899. }
  900. next();
  901. return new AST_With({
  902. expression : parenthesised(),
  903. body : statement()
  904. });
  905. }
  906. }
  907. unexpected();
  908. });
  909. function labeled_statement() {
  910. var label = as_symbol(AST_Label);
  911. if (!all(S.labels, function(l) {
  912. return l.name != label.name;
  913. })) {
  914. // ECMA-262, 12.12: An ECMAScript program is considered
  915. // syntactically incorrect if it contains a
  916. // LabelledStatement that is enclosed by a
  917. // LabelledStatement with the same Identifier as label.
  918. croak("Label " + label.name + " defined twice");
  919. }
  920. expect(":");
  921. S.labels.push(label);
  922. var stat = statement();
  923. S.labels.pop();
  924. if (!(stat instanceof AST_IterationStatement)) {
  925. // check for `continue` that refers to this label.
  926. // those should be reported as syntax errors.
  927. // https://github.com/mishoo/UglifyJS/issues/287
  928. label.references.forEach(function(ref) {
  929. if (ref instanceof AST_Continue) {
  930. token_error(ref.label.start, "Continue label `" + label.name + "` must refer to IterationStatement");
  931. }
  932. });
  933. }
  934. return new AST_LabeledStatement({ body: stat, label: label });
  935. }
  936. function simple_statement() {
  937. var body = expression();
  938. semicolon();
  939. return new AST_SimpleStatement({ body: body });
  940. }
  941. function break_cont(type) {
  942. var label = null, ldef;
  943. if (!can_insert_semicolon()) {
  944. label = as_symbol(AST_LabelRef, true);
  945. }
  946. if (label != null) {
  947. ldef = find_if(function(l) {
  948. return l.name == label.name;
  949. }, S.labels);
  950. if (!ldef) token_error(label.start, "Undefined label " + label.name);
  951. label.thedef = ldef;
  952. } else if (S.in_loop == 0) croak(type.TYPE + " not inside a loop or switch");
  953. semicolon();
  954. var stat = new type({ label: label });
  955. if (ldef) ldef.references.push(stat);
  956. return stat;
  957. }
  958. function has_modifier(name) {
  959. if (!is("name", name)) return;
  960. var token = peek();
  961. if (!token) return;
  962. if (is_token(token, "operator", "=")) return;
  963. if (token.type == "punc" && /^[(;}]$/.test(token.value)) return;
  964. if (has_newline_before(token)) return;
  965. return next();
  966. }
  967. function class_(ctor) {
  968. var was_async = S.in_async;
  969. var was_gen = S.in_generator;
  970. S.input.push_directives_stack();
  971. S.input.add_directive("use strict");
  972. var name;
  973. if (ctor === AST_DefClass) {
  974. name = as_symbol(AST_SymbolDefClass);
  975. } else {
  976. name = as_symbol(AST_SymbolClass, true);
  977. }
  978. var parent = null;
  979. if (is("keyword", "extends")) {
  980. next();
  981. handle_regexp();
  982. parent = expr_atom(true);
  983. }
  984. expect("{");
  985. var props = [];
  986. while (!is("punc", "}")) {
  987. if (is("punc", ";")) {
  988. next();
  989. continue;
  990. }
  991. var start = S.token;
  992. var fixed = !!has_modifier("static");
  993. var async = has_modifier("async");
  994. if (is("operator", "*")) {
  995. next();
  996. var internal = is("name") && /^#/.test(S.token.value);
  997. var key = as_property_key();
  998. var gen_start = S.token;
  999. var gen = function_(async ? AST_AsyncGeneratorFunction : AST_GeneratorFunction);
  1000. gen.start = gen_start;
  1001. gen.end = prev();
  1002. props.push(new AST_ClassMethod({
  1003. start: start,
  1004. static: fixed,
  1005. private: internal,
  1006. key: key,
  1007. value: gen,
  1008. end: prev(),
  1009. }));
  1010. continue;
  1011. }
  1012. var internal = is("name") && /^#/.test(S.token.value);
  1013. var key = as_property_key();
  1014. if (is("punc", "(")) {
  1015. var func_start = S.token;
  1016. var func = function_(async ? AST_AsyncFunction : AST_Function);
  1017. func.start = func_start;
  1018. func.end = prev();
  1019. props.push(new AST_ClassMethod({
  1020. start: start,
  1021. static: fixed,
  1022. private: internal,
  1023. key: key,
  1024. value: func,
  1025. end: prev(),
  1026. }));
  1027. continue;
  1028. }
  1029. if (async) unexpected(async);
  1030. var value = null;
  1031. if (is("operator", "=")) {
  1032. next();
  1033. S.in_async = false;
  1034. S.in_generator = false;
  1035. value = maybe_assign();
  1036. S.in_generator = was_gen;
  1037. S.in_async = was_async;
  1038. } else if (!(is("punc", ";") || is("punc", "}"))) {
  1039. var type = null;
  1040. switch (key) {
  1041. case "get":
  1042. type = AST_ClassGetter;
  1043. break;
  1044. case "set":
  1045. type = AST_ClassSetter;
  1046. break;
  1047. }
  1048. if (type) {
  1049. props.push(new type({
  1050. start: start,
  1051. static: fixed,
  1052. private: is("name") && /^#/.test(S.token.value),
  1053. key: as_property_key(),
  1054. value: create_accessor(),
  1055. end: prev(),
  1056. }));
  1057. continue;
  1058. }
  1059. }
  1060. semicolon();
  1061. props.push(new AST_ClassField({
  1062. start: start,
  1063. static: fixed,
  1064. private: internal,
  1065. key: key,
  1066. value: value,
  1067. end: prev(),
  1068. }));
  1069. }
  1070. next();
  1071. S.input.pop_directives_stack();
  1072. S.in_generator = was_gen;
  1073. S.in_async = was_async;
  1074. return new ctor({
  1075. extends: parent,
  1076. name: name,
  1077. properties: props,
  1078. });
  1079. }
  1080. function for_() {
  1081. var await_token = is("name", "await") && next();
  1082. expect("(");
  1083. var init = null;
  1084. if (await_token || !is("punc", ";")) {
  1085. init = is("keyword", "const")
  1086. ? (next(), const_(true))
  1087. : is("name", "let") && is_vardefs()
  1088. ? (next(), let_(true))
  1089. : is("keyword", "var")
  1090. ? (next(), var_(true))
  1091. : expression(true);
  1092. var ctor;
  1093. if (await_token) {
  1094. expect_token("name", "of");
  1095. ctor = AST_ForAwaitOf;
  1096. } else if (is("operator", "in")) {
  1097. next();
  1098. ctor = AST_ForIn;
  1099. } else if (is("name", "of")) {
  1100. next();
  1101. ctor = AST_ForOf;
  1102. }
  1103. if (ctor) {
  1104. if (init instanceof AST_Definitions) {
  1105. if (init.definitions.length > 1) {
  1106. token_error(init.start, "Only one variable declaration allowed in for..in/of loop");
  1107. }
  1108. if (ctor !== AST_ForIn && init.definitions[0].value) {
  1109. token_error(init.definitions[0].value.start, "No initializers allowed in for..of loop");
  1110. }
  1111. } else if (!(is_assignable(init) || (init = to_destructured(init)) instanceof AST_Destructured)) {
  1112. token_error(init.start, "Invalid left-hand side in for..in/of loop");
  1113. }
  1114. return for_enum(ctor, init);
  1115. }
  1116. }
  1117. return regular_for(init);
  1118. }
  1119. function regular_for(init) {
  1120. expect(";");
  1121. var test = is("punc", ";") ? null : expression();
  1122. expect(";");
  1123. var step = is("punc", ")") ? null : expression();
  1124. expect(")");
  1125. return new AST_For({
  1126. init : init,
  1127. condition : test,
  1128. step : step,
  1129. body : in_loop(statement)
  1130. });
  1131. }
  1132. function for_enum(ctor, init) {
  1133. handle_regexp();
  1134. var obj = expression();
  1135. expect(")");
  1136. return new ctor({
  1137. init : init,
  1138. object : obj,
  1139. body : in_loop(statement)
  1140. });
  1141. }
  1142. function to_funarg(node) {
  1143. if (node instanceof AST_Array) {
  1144. var rest = null;
  1145. if (node.elements[node.elements.length - 1] instanceof AST_Spread) {
  1146. rest = to_funarg(node.elements.pop().expression);
  1147. }
  1148. return new AST_DestructuredArray({
  1149. start: node.start,
  1150. elements: node.elements.map(to_funarg),
  1151. rest: rest,
  1152. end: node.end,
  1153. });
  1154. }
  1155. if (node instanceof AST_Assign) return new AST_DefaultValue({
  1156. start: node.start,
  1157. name: to_funarg(node.left),
  1158. value: node.right,
  1159. end: node.end,
  1160. });
  1161. if (node instanceof AST_DefaultValue) {
  1162. node.name = to_funarg(node.name);
  1163. return node;
  1164. }
  1165. if (node instanceof AST_DestructuredArray) {
  1166. node.elements = node.elements.map(to_funarg);
  1167. if (node.rest) node.rest = to_funarg(node.rest);
  1168. return node;
  1169. }
  1170. if (node instanceof AST_DestructuredObject) {
  1171. node.properties.forEach(function(prop) {
  1172. prop.value = to_funarg(prop.value);
  1173. });
  1174. if (node.rest) node.rest = to_funarg(node.rest);
  1175. return node;
  1176. }
  1177. if (node instanceof AST_Hole) return node;
  1178. if (node instanceof AST_Object) {
  1179. var rest = null;
  1180. if (node.properties[node.properties.length - 1] instanceof AST_Spread) {
  1181. rest = to_funarg(node.properties.pop().expression);
  1182. }
  1183. return new AST_DestructuredObject({
  1184. start: node.start,
  1185. properties: node.properties.map(function(prop) {
  1186. if (!(prop instanceof AST_ObjectKeyVal)) token_error(prop.start, "Invalid destructuring assignment");
  1187. return new AST_DestructuredKeyVal({
  1188. start: prop.start,
  1189. key: prop.key,
  1190. value: to_funarg(prop.value),
  1191. end: prop.end,
  1192. });
  1193. }),
  1194. rest: rest,
  1195. end: node.end,
  1196. });
  1197. }
  1198. if (node instanceof AST_SymbolFunarg) return node;
  1199. if (node instanceof AST_SymbolRef) return new AST_SymbolFunarg(node);
  1200. if (node instanceof AST_Yield) return new AST_SymbolFunarg({
  1201. start: node.start,
  1202. name: "yield",
  1203. end: node.end,
  1204. });
  1205. token_error(node.start, "Invalid arrow parameter");
  1206. }
  1207. function arrow(exprs, start, async) {
  1208. var was_async = S.in_async;
  1209. var was_gen = S.in_generator;
  1210. S.in_async = async;
  1211. S.in_generator = false;
  1212. var was_funarg = S.in_funarg;
  1213. S.in_funarg = S.in_function;
  1214. var argnames = exprs.map(to_funarg);
  1215. var rest = exprs.rest || null;
  1216. if (rest) rest = to_funarg(rest);
  1217. S.in_funarg = was_funarg;
  1218. expect("=>");
  1219. var body, value;
  1220. var loop = S.in_loop;
  1221. var labels = S.labels;
  1222. ++S.in_function;
  1223. S.in_directives = true;
  1224. S.input.push_directives_stack();
  1225. S.in_loop = 0;
  1226. S.labels = [];
  1227. if (is("punc", "{")) {
  1228. body = block_();
  1229. value = null;
  1230. } else {
  1231. body = [];
  1232. handle_regexp();
  1233. value = maybe_assign();
  1234. }
  1235. var is_strict = S.input.has_directive("use strict");
  1236. S.input.pop_directives_stack();
  1237. --S.in_function;
  1238. S.in_loop = loop;
  1239. S.labels = labels;
  1240. S.in_generator = was_gen;
  1241. S.in_async = was_async;
  1242. var node = new (async ? AST_AsyncArrow : AST_Arrow)({
  1243. start: start,
  1244. argnames: argnames,
  1245. rest: rest,
  1246. body: body,
  1247. value: value,
  1248. end: prev(),
  1249. });
  1250. if (is_strict) node.each_argname(strict_verify_symbol);
  1251. return node;
  1252. }
  1253. var function_ = function(ctor) {
  1254. var was_async = S.in_async;
  1255. var was_gen = S.in_generator;
  1256. var name;
  1257. if (/Defun$/.test(ctor.TYPE)) {
  1258. name = as_symbol(AST_SymbolDefun);
  1259. S.in_async = /^Async/.test(ctor.TYPE);
  1260. S.in_generator = /Generator/.test(ctor.TYPE);
  1261. } else {
  1262. S.in_async = /^Async/.test(ctor.TYPE);
  1263. S.in_generator = /Generator/.test(ctor.TYPE);
  1264. name = as_symbol(AST_SymbolLambda, true);
  1265. }
  1266. if (name && ctor !== AST_Accessor && !(name instanceof AST_SymbolDeclaration))
  1267. unexpected(prev());
  1268. expect("(");
  1269. var was_funarg = S.in_funarg;
  1270. S.in_funarg = S.in_function;
  1271. var argnames = expr_list(")", !options.strict, false, function() {
  1272. return maybe_default(AST_SymbolFunarg);
  1273. });
  1274. S.in_funarg = was_funarg;
  1275. var loop = S.in_loop;
  1276. var labels = S.labels;
  1277. ++S.in_function;
  1278. S.in_directives = true;
  1279. S.input.push_directives_stack();
  1280. S.in_loop = 0;
  1281. S.labels = [];
  1282. var body = block_();
  1283. var is_strict = S.input.has_directive("use strict");
  1284. S.input.pop_directives_stack();
  1285. --S.in_function;
  1286. S.in_loop = loop;
  1287. S.labels = labels;
  1288. S.in_generator = was_gen;
  1289. S.in_async = was_async;
  1290. var node = new ctor({
  1291. name: name,
  1292. argnames: argnames,
  1293. rest: argnames.rest || null,
  1294. body: body
  1295. });
  1296. if (is_strict) {
  1297. if (name) strict_verify_symbol(name);
  1298. node.each_argname(strict_verify_symbol);
  1299. }
  1300. return node;
  1301. };
  1302. function if_() {
  1303. var cond = parenthesised(), body = statement(), belse = null;
  1304. if (is("keyword", "else")) {
  1305. next();
  1306. belse = statement();
  1307. }
  1308. return new AST_If({
  1309. condition : cond,
  1310. body : body,
  1311. alternative : belse
  1312. });
  1313. }
  1314. function is_alias() {
  1315. return is("name") || is_identifier_string(S.token.value);
  1316. }
  1317. function export_() {
  1318. if (is("operator", "*")) {
  1319. next();
  1320. var alias = "*";
  1321. if (is("name", "as")) {
  1322. next();
  1323. if (!is_alias()) expect_token("name");
  1324. alias = S.token.value;
  1325. next();
  1326. }
  1327. expect_token("name", "from");
  1328. var path = S.token;
  1329. expect_token("string");
  1330. semicolon();
  1331. return new AST_ExportForeign({
  1332. aliases: [ alias ],
  1333. keys: [ "*" ],
  1334. path: path.value,
  1335. quote: path.quote,
  1336. });
  1337. }
  1338. if (is("punc", "{")) {
  1339. next();
  1340. var aliases = [];
  1341. var keys = [];
  1342. while (is_alias()) {
  1343. var key = S.token;
  1344. next();
  1345. keys.push(key);
  1346. if (is("name", "as")) {
  1347. next();
  1348. if (!is_alias()) expect_token("name");
  1349. aliases.push(S.token.value);
  1350. next();
  1351. } else {
  1352. aliases.push(key.value);
  1353. }
  1354. if (!is("punc", "}")) expect(",");
  1355. }
  1356. expect("}");
  1357. if (is("name", "from")) {
  1358. next();
  1359. var path = S.token;
  1360. expect_token("string");
  1361. semicolon();
  1362. return new AST_ExportForeign({
  1363. aliases: aliases,
  1364. keys: keys.map(function(token) {
  1365. return token.value;
  1366. }),
  1367. path: path.value,
  1368. quote: path.quote,
  1369. });
  1370. }
  1371. semicolon();
  1372. return new AST_ExportReferences({
  1373. properties: keys.map(function(token, index) {
  1374. if (!is_token(token, "name")) token_error(token, "Name expected");
  1375. var sym = _make_symbol(AST_SymbolExport, token);
  1376. sym.alias = aliases[index];
  1377. return sym;
  1378. }),
  1379. });
  1380. }
  1381. if (is("keyword", "default")) {
  1382. next();
  1383. var start = S.token;
  1384. var body = export_default_decl();
  1385. if (body) {
  1386. body.start = start;
  1387. body.end = prev();
  1388. } else {
  1389. handle_regexp();
  1390. body = expression();
  1391. semicolon();
  1392. }
  1393. return new AST_ExportDefault({ body: body });
  1394. }
  1395. return new AST_ExportDeclaration({ body: export_decl() });
  1396. }
  1397. function maybe_named(def, expr) {
  1398. if (expr.name) {
  1399. expr = new def(expr);
  1400. expr.name = new (def === AST_DefClass ? AST_SymbolDefClass : AST_SymbolDefun)(expr.name);
  1401. }
  1402. return expr;
  1403. }
  1404. function export_default_decl() {
  1405. if (is("name", "async")) {
  1406. if (!is_token(peek(), "keyword", "function")) return;
  1407. next();
  1408. next();
  1409. if (!is("operator", "*")) return maybe_named(AST_AsyncDefun, function_(AST_AsyncFunction));
  1410. next();
  1411. return maybe_named(AST_AsyncGeneratorDefun, function_(AST_AsyncGeneratorFunction));
  1412. } else if (is("keyword")) switch (S.token.value) {
  1413. case "class":
  1414. next();
  1415. return maybe_named(AST_DefClass, class_(AST_ClassExpression));
  1416. case "function":
  1417. next();
  1418. if (!is("operator", "*")) return maybe_named(AST_Defun, function_(AST_Function));
  1419. next();
  1420. return maybe_named(AST_GeneratorDefun, function_(AST_GeneratorFunction));
  1421. }
  1422. }
  1423. var export_decl = embed_tokens(function() {
  1424. if (is("name")) switch (S.token.value) {
  1425. case "async":
  1426. next();
  1427. expect_token("keyword", "function");
  1428. if (!is("operator", "*")) return function_(AST_AsyncDefun);
  1429. next();
  1430. return function_(AST_AsyncGeneratorDefun);
  1431. case "let":
  1432. next();
  1433. var node = let_();
  1434. semicolon();
  1435. return node;
  1436. } else if (is("keyword")) switch (S.token.value) {
  1437. case "class":
  1438. next();
  1439. return class_(AST_DefClass);
  1440. case "const":
  1441. next();
  1442. var node = const_();
  1443. semicolon();
  1444. return node;
  1445. case "function":
  1446. next();
  1447. if (!is("operator", "*")) return function_(AST_Defun);
  1448. next();
  1449. return function_(AST_GeneratorDefun);
  1450. case "var":
  1451. next();
  1452. var node = var_();
  1453. semicolon();
  1454. return node;
  1455. }
  1456. unexpected();
  1457. });
  1458. function import_() {
  1459. var all = null;
  1460. var def = as_symbol(AST_SymbolImport, true);
  1461. var props = null;
  1462. if (def ? (def.key = "", is("punc", ",") && next()) : !is("string")) {
  1463. if (is("operator", "*")) {
  1464. next();
  1465. expect_token("name", "as");
  1466. all = as_symbol(AST_SymbolImport);
  1467. all.key = "*";
  1468. } else {
  1469. expect("{");
  1470. props = [];
  1471. while (is_alias()) {
  1472. var alias;
  1473. if (is_token(peek(), "name", "as")) {
  1474. var key = S.token.value;
  1475. next();
  1476. next();
  1477. alias = as_symbol(AST_SymbolImport);
  1478. alias.key = key;
  1479. } else {
  1480. alias = as_symbol(AST_SymbolImport);
  1481. alias.key = alias.name;
  1482. }
  1483. props.push(alias);
  1484. if (!is("punc", "}")) expect(",");
  1485. }
  1486. expect("}");
  1487. }
  1488. }
  1489. if (all || def || props) expect_token("name", "from");
  1490. var path = S.token;
  1491. expect_token("string");
  1492. semicolon();
  1493. return new AST_Import({
  1494. all: all,
  1495. default: def,
  1496. path: path.value,
  1497. properties: props,
  1498. quote: path.quote,
  1499. });
  1500. }
  1501. function block_() {
  1502. expect("{");
  1503. var a = [];
  1504. while (!is("punc", "}")) {
  1505. if (is("eof")) expect("}");
  1506. a.push(statement());
  1507. }
  1508. next();
  1509. return a;
  1510. }
  1511. function switch_body_() {
  1512. expect("{");
  1513. var a = [], branch, cur, default_branch, tmp;
  1514. while (!is("punc", "}")) {
  1515. if (is("eof")) expect("}");
  1516. if (is("keyword", "case")) {
  1517. if (branch) branch.end = prev();
  1518. cur = [];
  1519. branch = new AST_Case({
  1520. start : (tmp = S.token, next(), tmp),
  1521. expression : expression(),
  1522. body : cur
  1523. });
  1524. a.push(branch);
  1525. expect(":");
  1526. } else if (is("keyword", "default")) {
  1527. if (branch) branch.end = prev();
  1528. if (default_branch) croak("More than one default clause in switch statement");
  1529. cur = [];
  1530. branch = new AST_Default({
  1531. start : (tmp = S.token, next(), expect(":"), tmp),
  1532. body : cur
  1533. });
  1534. a.push(branch);
  1535. default_branch = branch;
  1536. } else {
  1537. if (!cur) unexpected();
  1538. cur.push(statement());
  1539. }
  1540. }
  1541. if (branch) branch.end = prev();
  1542. next();
  1543. return a;
  1544. }
  1545. function try_() {
  1546. var body = block_(), bcatch = null, bfinally = null;
  1547. if (is("keyword", "catch")) {
  1548. var start = S.token;
  1549. next();
  1550. var name = null;
  1551. if (is("punc", "(")) {
  1552. next();
  1553. name = maybe_destructured(AST_SymbolCatch);
  1554. expect(")");
  1555. }
  1556. bcatch = new AST_Catch({
  1557. start : start,
  1558. argname : name,
  1559. body : block_(),
  1560. end : prev()
  1561. });
  1562. }
  1563. if (is("keyword", "finally")) {
  1564. var start = S.token;
  1565. next();
  1566. bfinally = new AST_Finally({
  1567. start : start,
  1568. body : block_(),
  1569. end : prev()
  1570. });
  1571. }
  1572. if (!bcatch && !bfinally)
  1573. croak("Missing catch/finally blocks");
  1574. return new AST_Try({
  1575. body : body,
  1576. bcatch : bcatch,
  1577. bfinally : bfinally
  1578. });
  1579. }
  1580. function vardefs(type, no_in) {
  1581. var a = [];
  1582. for (;;) {
  1583. var start = S.token;
  1584. var name = maybe_destructured(type);
  1585. var value = null;
  1586. if (is("operator", "=")) {
  1587. next();
  1588. value = maybe_assign(no_in);
  1589. } else if (!no_in && (type === AST_SymbolConst || name instanceof AST_Destructured)) {
  1590. croak("Missing initializer in declaration");
  1591. }
  1592. a.push(new AST_VarDef({
  1593. start : start,
  1594. name : name,
  1595. value : value,
  1596. end : prev()
  1597. }));
  1598. if (!is("punc", ","))
  1599. break;
  1600. next();
  1601. }
  1602. return a;
  1603. }
  1604. function is_vardefs() {
  1605. var token = peek();
  1606. return is_token(token, "name") || is_token(token, "punc", "[") || is_token(token, "punc", "{");
  1607. }
  1608. var const_ = function(no_in) {
  1609. return new AST_Const({
  1610. start : prev(),
  1611. definitions : vardefs(AST_SymbolConst, no_in),
  1612. end : prev()
  1613. });
  1614. };
  1615. var let_ = function(no_in) {
  1616. return new AST_Let({
  1617. start : prev(),
  1618. definitions : vardefs(AST_SymbolLet, no_in),
  1619. end : prev()
  1620. });
  1621. };
  1622. var var_ = function(no_in) {
  1623. return new AST_Var({
  1624. start : prev(),
  1625. definitions : vardefs(AST_SymbolVar, no_in),
  1626. end : prev()
  1627. });
  1628. };
  1629. var new_ = function(allow_calls) {
  1630. var start = S.token;
  1631. expect_token("operator", "new");
  1632. var call;
  1633. if (is("punc", ".") && is_token(peek(), "name", "target")) {
  1634. next();
  1635. next();
  1636. call = new AST_NewTarget();
  1637. } else {
  1638. var exp = expr_atom(false), args;
  1639. if (is("punc", "(")) {
  1640. next();
  1641. args = expr_list(")", !options.strict);
  1642. } else {
  1643. args = [];
  1644. }
  1645. call = new AST_New({ expression: exp, args: args });
  1646. }
  1647. call.start = start;
  1648. call.end = prev();
  1649. return subscripts(call, allow_calls);
  1650. };
  1651. function as_atom_node() {
  1652. var ret, tok = S.token, value = tok.value;
  1653. switch (tok.type) {
  1654. case "num":
  1655. if (isFinite(value)) {
  1656. ret = new AST_Number({ value: value });
  1657. } else {
  1658. ret = new AST_Infinity();
  1659. if (value < 0) ret = new AST_UnaryPrefix({ operator: "-", expression: ret });
  1660. }
  1661. break;
  1662. case "bigint":
  1663. ret = new AST_BigInt({ value: value });
  1664. break;
  1665. case "string":
  1666. ret = new AST_String({ value : value, quote : tok.quote });
  1667. break;
  1668. case "regexp":
  1669. ret = new AST_RegExp({ value: value });
  1670. break;
  1671. case "atom":
  1672. switch (value) {
  1673. case "false":
  1674. ret = new AST_False();
  1675. break;
  1676. case "true":
  1677. ret = new AST_True();
  1678. break;
  1679. case "null":
  1680. ret = new AST_Null();
  1681. break;
  1682. default:
  1683. unexpected();
  1684. }
  1685. break;
  1686. default:
  1687. unexpected();
  1688. }
  1689. next();
  1690. ret.start = ret.end = tok;
  1691. return ret;
  1692. }
  1693. var expr_atom = function(allow_calls) {
  1694. if (is("operator", "new")) {
  1695. return new_(allow_calls);
  1696. }
  1697. var start = S.token;
  1698. if (is("punc")) {
  1699. switch (start.value) {
  1700. case "`":
  1701. return subscripts(template(null), allow_calls);
  1702. case "(":
  1703. next();
  1704. if (is("punc", ")")) {
  1705. next();
  1706. return arrow([], start);
  1707. }
  1708. var ex = expression(false, true);
  1709. var len = start.comments_before.length;
  1710. [].unshift.apply(ex.start.comments_before, start.comments_before);
  1711. start.comments_before.length = 0;
  1712. start.comments_before = ex.start.comments_before;
  1713. start.comments_before_length = len;
  1714. if (len == 0 && start.comments_before.length > 0) {
  1715. var comment = start.comments_before[0];
  1716. if (!comment.nlb) {
  1717. comment.nlb = start.nlb;
  1718. start.nlb = false;
  1719. }
  1720. }
  1721. start.comments_after = ex.start.comments_after;
  1722. ex.start = start;
  1723. expect(")");
  1724. var end = prev();
  1725. end.comments_before = ex.end.comments_before;
  1726. end.comments_after.forEach(function(comment) {
  1727. ex.end.comments_after.push(comment);
  1728. if (comment.nlb) S.token.nlb = true;
  1729. });
  1730. end.comments_after.length = 0;
  1731. end.comments_after = ex.end.comments_after;
  1732. ex.end = end;
  1733. if (is("punc", "=>")) return arrow(ex instanceof AST_Sequence ? ex.expressions : [ ex ], start);
  1734. return subscripts(ex, allow_calls);
  1735. case "[":
  1736. return subscripts(array_(), allow_calls);
  1737. case "{":
  1738. return subscripts(object_(), allow_calls);
  1739. }
  1740. unexpected();
  1741. }
  1742. if (is("keyword")) switch (start.value) {
  1743. case "class":
  1744. next();
  1745. var clazz = class_(AST_ClassExpression);
  1746. clazz.start = start;
  1747. clazz.end = prev();
  1748. return subscripts(clazz, allow_calls);
  1749. case "function":
  1750. next();
  1751. var func;
  1752. if (is("operator", "*")) {
  1753. next();
  1754. func = function_(AST_GeneratorFunction);
  1755. } else {
  1756. func = function_(AST_Function);
  1757. }
  1758. func.start = start;
  1759. func.end = prev();
  1760. return subscripts(func, allow_calls);
  1761. }
  1762. if (is("name")) {
  1763. var sym = _make_symbol(AST_SymbolRef, start);
  1764. next();
  1765. if (sym.name == "async") {
  1766. if (is("keyword", "function")) {
  1767. next();
  1768. var func;
  1769. if (is("operator", "*")) {
  1770. next();
  1771. func = function_(AST_AsyncGeneratorFunction);
  1772. } else {
  1773. func = function_(AST_AsyncFunction);
  1774. }
  1775. func.start = start;
  1776. func.end = prev();
  1777. return subscripts(func, allow_calls);
  1778. }
  1779. if (is("name") && is_token(peek(), "punc", "=>")) {
  1780. start = S.token;
  1781. sym = _make_symbol(AST_SymbolRef, start);
  1782. next();
  1783. return arrow([ sym ], start, true);
  1784. }
  1785. if (is("punc", "(")) {
  1786. var call = subscripts(sym, allow_calls);
  1787. if (!is("punc", "=>")) return call;
  1788. var args = call.args;
  1789. if (args[args.length - 1] instanceof AST_Spread) {
  1790. args.rest = args.pop().expression;
  1791. }
  1792. return arrow(args, start, true);
  1793. }
  1794. }
  1795. return is("punc", "=>") ? arrow([ sym ], start) : subscripts(sym, allow_calls);
  1796. }
  1797. if (ATOMIC_START_TOKEN[S.token.type]) {
  1798. return subscripts(as_atom_node(), allow_calls);
  1799. }
  1800. unexpected();
  1801. };
  1802. function expr_list(closing, allow_trailing_comma, allow_empty, parser) {
  1803. if (!parser) parser = maybe_assign;
  1804. var first = true, a = [];
  1805. while (!is("punc", closing)) {
  1806. if (first) first = false; else expect(",");
  1807. if (allow_trailing_comma && is("punc", closing)) break;
  1808. if (allow_empty && is("punc", ",")) {
  1809. a.push(new AST_Hole({ start: S.token, end: S.token }));
  1810. } else if (!is("operator", "...")) {
  1811. a.push(parser());
  1812. } else if (parser === maybe_assign) {
  1813. a.push(new AST_Spread({
  1814. start: S.token,
  1815. expression: (next(), parser()),
  1816. end: prev(),
  1817. }));
  1818. } else {
  1819. next();
  1820. a.rest = parser();
  1821. if (a.rest instanceof AST_DefaultValue) token_error(a.rest.start, "Invalid rest parameter");
  1822. break;
  1823. }
  1824. }
  1825. expect(closing);
  1826. return a;
  1827. }
  1828. var array_ = embed_tokens(function() {
  1829. expect("[");
  1830. return new AST_Array({
  1831. elements: expr_list("]", !options.strict, true)
  1832. });
  1833. });
  1834. var create_accessor = embed_tokens(function() {
  1835. return function_(AST_Accessor);
  1836. });
  1837. var object_ = embed_tokens(function() {
  1838. expect("{");
  1839. var first = true, a = [];
  1840. while (!is("punc", "}")) {
  1841. if (first) first = false; else expect(",");
  1842. // allow trailing comma
  1843. if (!options.strict && is("punc", "}")) break;
  1844. var start = S.token;
  1845. if (is("operator", "*")) {
  1846. next();
  1847. var key = as_property_key();
  1848. var gen_start = S.token;
  1849. var gen = function_(AST_GeneratorFunction);
  1850. gen.start = gen_start;
  1851. gen.end = prev();
  1852. a.push(new AST_ObjectMethod({
  1853. start: start,
  1854. key: key,
  1855. value: gen,
  1856. end: prev(),
  1857. }));
  1858. continue;
  1859. }
  1860. if (is("operator", "...")) {
  1861. next();
  1862. a.push(new AST_Spread({
  1863. start: start,
  1864. expression: maybe_assign(),
  1865. end: prev(),
  1866. }));
  1867. continue;
  1868. }
  1869. if (is_token(peek(), "operator", "=")) {
  1870. var name = as_symbol(AST_SymbolRef);
  1871. next();
  1872. a.push(new AST_ObjectKeyVal({
  1873. start: start,
  1874. key: start.value,
  1875. value: new AST_Assign({
  1876. start: start,
  1877. left: name,
  1878. operator: "=",
  1879. right: maybe_assign(),
  1880. end: prev(),
  1881. }),
  1882. end: prev(),
  1883. }));
  1884. continue;
  1885. }
  1886. if (is_token(peek(), "punc", ",") || is_token(peek(), "punc", "}")) {
  1887. a.push(new AST_ObjectKeyVal({
  1888. start: start,
  1889. key: start.value,
  1890. value: as_symbol(AST_SymbolRef),
  1891. end: prev(),
  1892. }));
  1893. continue;
  1894. }
  1895. var key = as_property_key();
  1896. if (is("punc", "(")) {
  1897. var func_start = S.token;
  1898. var func = function_(AST_Function);
  1899. func.start = func_start;
  1900. func.end = prev();
  1901. a.push(new AST_ObjectMethod({
  1902. start: start,
  1903. key: key,
  1904. value: func,
  1905. end: prev(),
  1906. }));
  1907. continue;
  1908. }
  1909. if (is("punc", ":")) {
  1910. next();
  1911. a.push(new AST_ObjectKeyVal({
  1912. start: start,
  1913. key: key,
  1914. value: maybe_assign(),
  1915. end: prev(),
  1916. }));
  1917. continue;
  1918. }
  1919. if (start.type == "name") switch (key) {
  1920. case "async":
  1921. var is_gen = is("operator", "*") && next();
  1922. key = as_property_key();
  1923. var func_start = S.token;
  1924. var func = function_(is_gen ? AST_AsyncGeneratorFunction : AST_AsyncFunction);
  1925. func.start = func_start;
  1926. func.end = prev();
  1927. a.push(new AST_ObjectMethod({
  1928. start: start,
  1929. key: key,
  1930. value: func,
  1931. end: prev(),
  1932. }));
  1933. continue;
  1934. case "get":
  1935. a.push(new AST_ObjectGetter({
  1936. start: start,
  1937. key: as_property_key(),
  1938. value: create_accessor(),
  1939. end: prev(),
  1940. }));
  1941. continue;
  1942. case "set":
  1943. a.push(new AST_ObjectSetter({
  1944. start: start,
  1945. key: as_property_key(),
  1946. value: create_accessor(),
  1947. end: prev(),
  1948. }));
  1949. continue;
  1950. }
  1951. unexpected();
  1952. }
  1953. next();
  1954. return new AST_Object({ properties: a });
  1955. });
  1956. function as_property_key() {
  1957. var tmp = S.token;
  1958. switch (tmp.type) {
  1959. case "operator":
  1960. if (!KEYWORDS[tmp.value]) unexpected();
  1961. case "num":
  1962. case "string":
  1963. case "name":
  1964. case "keyword":
  1965. case "atom":
  1966. next();
  1967. return "" + tmp.value;
  1968. case "punc":
  1969. expect("[");
  1970. var key = maybe_assign();
  1971. expect("]");
  1972. return key;
  1973. default:
  1974. unexpected();
  1975. }
  1976. }
  1977. function as_name() {
  1978. var name = S.token.value;
  1979. expect_token("name");
  1980. return name;
  1981. }
  1982. function _make_symbol(type, token) {
  1983. var name = token.value;
  1984. switch (name) {
  1985. case "await":
  1986. if (S.in_async) unexpected(token);
  1987. break;
  1988. case "super":
  1989. type = AST_Super;
  1990. break;
  1991. case "this":
  1992. type = AST_This;
  1993. break;
  1994. case "yield":
  1995. if (S.in_generator) unexpected(token);
  1996. break;
  1997. }
  1998. return new type({
  1999. name: "" + name,
  2000. start: token,
  2001. end: token,
  2002. });
  2003. }
  2004. function strict_verify_symbol(sym) {
  2005. if (sym.name == "arguments" || sym.name == "eval" || sym.name == "let")
  2006. token_error(sym.start, "Unexpected " + sym.name + " in strict mode");
  2007. }
  2008. function as_symbol(type, noerror) {
  2009. if (!is("name")) {
  2010. if (!noerror) croak("Name expected");
  2011. return null;
  2012. }
  2013. var sym = _make_symbol(type, S.token);
  2014. if (S.input.has_directive("use strict") && sym instanceof AST_SymbolDeclaration) {
  2015. strict_verify_symbol(sym);
  2016. }
  2017. next();
  2018. return sym;
  2019. }
  2020. function maybe_destructured(type) {
  2021. var start = S.token;
  2022. if (is("punc", "[")) {
  2023. next();
  2024. var elements = expr_list("]", !options.strict, true, function() {
  2025. return maybe_default(type);
  2026. });
  2027. return new AST_DestructuredArray({
  2028. start: start,
  2029. elements: elements,
  2030. rest: elements.rest || null,
  2031. end: prev(),
  2032. });
  2033. }
  2034. if (is("punc", "{")) {
  2035. next();
  2036. var first = true, a = [], rest = null;
  2037. while (!is("punc", "}")) {
  2038. if (first) first = false; else expect(",");
  2039. // allow trailing comma
  2040. if (!options.strict && is("punc", "}")) break;
  2041. var key_start = S.token;
  2042. if (is("punc", "[") || is_token(peek(), "punc", ":")) {
  2043. var key = as_property_key();
  2044. expect(":");
  2045. a.push(new AST_DestructuredKeyVal({
  2046. start: key_start,
  2047. key: key,
  2048. value: maybe_default(type),
  2049. end: prev(),
  2050. }));
  2051. continue;
  2052. }
  2053. if (is("operator", "...")) {
  2054. next();
  2055. rest = maybe_destructured(type);
  2056. break;
  2057. }
  2058. var name = as_symbol(type);
  2059. if (is("operator", "=")) {
  2060. next();
  2061. name = new AST_DefaultValue({
  2062. start: name.start,
  2063. name: name,
  2064. value: maybe_assign(),
  2065. end: prev(),
  2066. });
  2067. }
  2068. a.push(new AST_DestructuredKeyVal({
  2069. start: key_start,
  2070. key: key_start.value,
  2071. value: name,
  2072. end: prev(),
  2073. }));
  2074. }
  2075. expect("}");
  2076. return new AST_DestructuredObject({
  2077. start: start,
  2078. properties: a,
  2079. rest: rest,
  2080. end: prev(),
  2081. });
  2082. }
  2083. return as_symbol(type);
  2084. }
  2085. function maybe_default(type) {
  2086. var start = S.token;
  2087. var name = maybe_destructured(type);
  2088. if (!is("operator", "=")) return name;
  2089. next();
  2090. return new AST_DefaultValue({
  2091. start: start,
  2092. name: name,
  2093. value: maybe_assign(),
  2094. end: prev(),
  2095. });
  2096. }
  2097. function template(tag) {
  2098. var start = tag ? tag.start : S.token;
  2099. var read = S.input.context().read_template;
  2100. var strings = [];
  2101. var expressions = [];
  2102. while (read(strings)) {
  2103. next();
  2104. expressions.push(expression());
  2105. if (!is("punc", "}")) unexpected();
  2106. }
  2107. next();
  2108. return new AST_Template({
  2109. start: start,
  2110. expressions: expressions,
  2111. strings: strings,
  2112. tag: tag,
  2113. end: prev(),
  2114. });
  2115. }
  2116. function subscripts(expr, allow_calls) {
  2117. var start = expr.start;
  2118. var optional = null;
  2119. while (true) {
  2120. if (is("operator", "?") && is_token(peek(), "punc", ".")) {
  2121. next();
  2122. next();
  2123. optional = expr;
  2124. }
  2125. if (is("punc", "[")) {
  2126. next();
  2127. var prop = expression();
  2128. expect("]");
  2129. expr = new AST_Sub({
  2130. start: start,
  2131. optional: optional === expr,
  2132. expression: expr,
  2133. property: prop,
  2134. end: prev(),
  2135. });
  2136. } else if (allow_calls && is("punc", "(")) {
  2137. next();
  2138. expr = new AST_Call({
  2139. start: start,
  2140. optional: optional === expr,
  2141. expression: expr,
  2142. args: expr_list(")", !options.strict),
  2143. end: prev(),
  2144. });
  2145. } else if (optional === expr || is("punc", ".")) {
  2146. if (optional !== expr) next();
  2147. expr = new AST_Dot({
  2148. start: start,
  2149. optional: optional === expr,
  2150. expression: expr,
  2151. property: as_name(),
  2152. end: prev(),
  2153. });
  2154. } else if (is("punc", "`")) {
  2155. if (optional) croak("Invalid template on optional chain");
  2156. expr = template(expr);
  2157. } else {
  2158. break;
  2159. }
  2160. }
  2161. if (optional) expr.terminal = true;
  2162. if (expr instanceof AST_Call && !expr.pure) {
  2163. var start = expr.start;
  2164. var comments = start.comments_before;
  2165. var i = HOP(start, "comments_before_length") ? start.comments_before_length : comments.length;
  2166. while (--i >= 0) {
  2167. if (/[@#]__PURE__/.test(comments[i].value)) {
  2168. expr.pure = true;
  2169. break;
  2170. }
  2171. }
  2172. }
  2173. return expr;
  2174. }
  2175. function maybe_unary(no_in) {
  2176. var start = S.token;
  2177. if (S.in_async && is("name", "await")) {
  2178. if (S.in_funarg === S.in_function) croak("Invalid use of await in function argument");
  2179. S.input.context().regex_allowed = true;
  2180. next();
  2181. return new AST_Await({
  2182. start: start,
  2183. expression: maybe_unary(no_in),
  2184. end: prev(),
  2185. });
  2186. }
  2187. if (S.in_generator && is("name", "yield")) {
  2188. if (S.in_funarg === S.in_function) croak("Invalid use of yield in function argument");
  2189. S.input.context().regex_allowed = true;
  2190. next();
  2191. var exp = null;
  2192. var nested = false;
  2193. if (is("operator", "*")) {
  2194. next();
  2195. exp = maybe_assign(no_in);
  2196. nested = true;
  2197. } else if (is("punc") ? !PUNC_AFTER_EXPRESSION[S.token.value] : !can_insert_semicolon()) {
  2198. exp = maybe_assign(no_in);
  2199. }
  2200. return new AST_Yield({
  2201. start: start,
  2202. expression: exp,
  2203. nested: nested,
  2204. end: prev(),
  2205. });
  2206. }
  2207. if (is("operator") && UNARY_PREFIX[start.value]) {
  2208. next();
  2209. handle_regexp();
  2210. var ex = make_unary(AST_UnaryPrefix, start, maybe_unary(no_in));
  2211. ex.start = start;
  2212. ex.end = prev();
  2213. return ex;
  2214. }
  2215. var val = expr_atom(true);
  2216. while (is("operator") && UNARY_POSTFIX[S.token.value] && !has_newline_before(S.token)) {
  2217. val = make_unary(AST_UnaryPostfix, S.token, val);
  2218. val.start = start;
  2219. val.end = S.token;
  2220. next();
  2221. }
  2222. return val;
  2223. }
  2224. function make_unary(ctor, token, expr) {
  2225. var op = token.value;
  2226. switch (op) {
  2227. case "++":
  2228. case "--":
  2229. if (!is_assignable(expr))
  2230. token_error(token, "Invalid use of " + op + " operator");
  2231. break;
  2232. case "delete":
  2233. if (expr instanceof AST_SymbolRef && S.input.has_directive("use strict"))
  2234. token_error(expr.start, "Calling delete on expression not allowed in strict mode");
  2235. break;
  2236. }
  2237. return new ctor({ operator: op, expression: expr });
  2238. }
  2239. var expr_op = function(left, min_prec, no_in) {
  2240. var op = is("operator") ? S.token.value : null;
  2241. if (op == "in" && no_in) op = null;
  2242. var prec = op != null ? PRECEDENCE[op] : null;
  2243. if (prec != null && prec > min_prec) {
  2244. next();
  2245. var right = expr_op(maybe_unary(no_in), op == "**" ? prec - 1 : prec, no_in);
  2246. return expr_op(new AST_Binary({
  2247. start : left.start,
  2248. left : left,
  2249. operator : op,
  2250. right : right,
  2251. end : right.end
  2252. }), min_prec, no_in);
  2253. }
  2254. return left;
  2255. };
  2256. function expr_ops(no_in) {
  2257. return expr_op(maybe_unary(no_in), 0, no_in);
  2258. }
  2259. var maybe_conditional = function(no_in) {
  2260. var start = S.token;
  2261. var expr = expr_ops(no_in);
  2262. if (is("operator", "?")) {
  2263. next();
  2264. var yes = maybe_assign();
  2265. expect(":");
  2266. return new AST_Conditional({
  2267. start : start,
  2268. condition : expr,
  2269. consequent : yes,
  2270. alternative : maybe_assign(no_in),
  2271. end : prev()
  2272. });
  2273. }
  2274. return expr;
  2275. };
  2276. function is_assignable(expr) {
  2277. return expr instanceof AST_PropAccess && !expr.optional || expr instanceof AST_SymbolRef;
  2278. }
  2279. function to_destructured(node) {
  2280. if (node instanceof AST_Array) {
  2281. var rest = null;
  2282. if (node.elements[node.elements.length - 1] instanceof AST_Spread) {
  2283. rest = to_destructured(node.elements.pop().expression);
  2284. if (!(rest instanceof AST_Destructured || is_assignable(rest))) return node;
  2285. }
  2286. var elements = node.elements.map(to_destructured);
  2287. return all(elements, function(node) {
  2288. return node instanceof AST_DefaultValue
  2289. || node instanceof AST_Destructured
  2290. || node instanceof AST_Hole
  2291. || is_assignable(node);
  2292. }) ? new AST_DestructuredArray({
  2293. start: node.start,
  2294. elements: elements,
  2295. rest: rest,
  2296. end: node.end,
  2297. }) : node;
  2298. }
  2299. if (node instanceof AST_Assign) {
  2300. var name = to_destructured(node.left);
  2301. return name instanceof AST_Destructured || is_assignable(name) ? new AST_DefaultValue({
  2302. start: node.start,
  2303. name: name,
  2304. value: node.right,
  2305. end: node.end,
  2306. }) : node;
  2307. }
  2308. if (!(node instanceof AST_Object)) return node;
  2309. var rest = null;
  2310. if (node.properties[node.properties.length - 1] instanceof AST_Spread) {
  2311. rest = to_destructured(node.properties.pop().expression);
  2312. if (!(rest instanceof AST_Destructured || is_assignable(rest))) return node;
  2313. }
  2314. var props = [];
  2315. for (var i = 0; i < node.properties.length; i++) {
  2316. var prop = node.properties[i];
  2317. if (!(prop instanceof AST_ObjectKeyVal)) return node;
  2318. var value = to_destructured(prop.value);
  2319. if (!(value instanceof AST_DefaultValue || value instanceof AST_Destructured || is_assignable(value))) {
  2320. return node;
  2321. }
  2322. props.push(new AST_DestructuredKeyVal({
  2323. start: prop.start,
  2324. key: prop.key,
  2325. value: value,
  2326. end: prop.end,
  2327. }));
  2328. }
  2329. return new AST_DestructuredObject({
  2330. start: node.start,
  2331. properties: props,
  2332. rest: rest,
  2333. end: node.end,
  2334. });
  2335. }
  2336. function maybe_assign(no_in) {
  2337. var start = S.token;
  2338. var left = maybe_conditional(no_in), val = S.token.value;
  2339. if (is("operator") && ASSIGNMENT[val]) {
  2340. if (is_assignable(left) || val == "=" && (left = to_destructured(left)) instanceof AST_Destructured) {
  2341. next();
  2342. return new AST_Assign({
  2343. start : start,
  2344. left : left,
  2345. operator : val,
  2346. right : maybe_assign(no_in),
  2347. end : prev()
  2348. });
  2349. }
  2350. croak("Invalid assignment");
  2351. }
  2352. return left;
  2353. }
  2354. function expression(no_in, maybe_arrow) {
  2355. var start = S.token;
  2356. var exprs = [];
  2357. while (true) {
  2358. if (maybe_arrow && is("operator", "...")) {
  2359. next();
  2360. exprs.rest = maybe_destructured(AST_SymbolFunarg);
  2361. break;
  2362. }
  2363. exprs.push(maybe_assign(no_in));
  2364. if (!is("punc", ",")) break;
  2365. next();
  2366. if (maybe_arrow && is("punc", ")") && is_token(peek(), "punc", "=>")) break;
  2367. }
  2368. return exprs.length == 1 && !exprs.rest ? exprs[0] : new AST_Sequence({
  2369. start: start,
  2370. expressions: exprs,
  2371. end: prev(),
  2372. });
  2373. }
  2374. function in_loop(cont) {
  2375. ++S.in_loop;
  2376. var ret = cont();
  2377. --S.in_loop;
  2378. return ret;
  2379. }
  2380. if (options.expression) {
  2381. handle_regexp();
  2382. var exp = expression();
  2383. expect_token("eof");
  2384. return exp;
  2385. }
  2386. return function() {
  2387. var start = S.token;
  2388. var body = [];
  2389. S.input.push_directives_stack();
  2390. while (!is("eof"))
  2391. body.push(statement());
  2392. S.input.pop_directives_stack();
  2393. var end = prev() || start;
  2394. var toplevel = options.toplevel;
  2395. if (toplevel) {
  2396. toplevel.body = toplevel.body.concat(body);
  2397. toplevel.end = end;
  2398. } else {
  2399. toplevel = new AST_Toplevel({ start: start, body: body, end: end });
  2400. }
  2401. return toplevel;
  2402. }();
  2403. }