You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ast.js 41KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239
  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. Redistribution and use in source and binary forms, with or without
  11. modification, are permitted provided that the following conditions
  12. are met:
  13. * Redistributions of source code must retain the above
  14. copyright notice, this list of conditions and the following
  15. disclaimer.
  16. * Redistributions in binary form must reproduce the above
  17. copyright notice, this list of conditions and the following
  18. disclaimer in the documentation and/or other materials
  19. provided with the distribution.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  21. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  22. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  23. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  24. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  25. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  26. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  27. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  29. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  30. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  31. SUCH DAMAGE.
  32. ***********************************************************************/
  33. "use strict";
  34. function DEFNODE(type, props, methods, base) {
  35. if (typeof base === "undefined") base = AST_Node;
  36. props = props ? props.split(/\s+/) : [];
  37. var self_props = props;
  38. if (base && base.PROPS) props = props.concat(base.PROPS);
  39. var code = [
  40. "return function AST_", type, "(props){",
  41. "if(props){",
  42. ];
  43. props.forEach(function(prop) {
  44. code.push("this.", prop, "=props.", prop, ";");
  45. });
  46. var proto = base && new base;
  47. if (proto && proto.initialize || methods && methods.initialize) code.push("this.initialize();");
  48. code.push("}}");
  49. var ctor = new Function(code.join(""))();
  50. if (proto) {
  51. ctor.prototype = proto;
  52. ctor.BASE = base;
  53. }
  54. if (base) base.SUBCLASSES.push(ctor);
  55. ctor.prototype.CTOR = ctor;
  56. ctor.PROPS = props || null;
  57. ctor.SELF_PROPS = self_props;
  58. ctor.SUBCLASSES = [];
  59. if (type) {
  60. ctor.prototype.TYPE = ctor.TYPE = type;
  61. }
  62. if (methods) for (var name in methods) if (HOP(methods, name)) {
  63. if (/^\$/.test(name)) {
  64. ctor[name.substr(1)] = methods[name];
  65. } else {
  66. ctor.prototype[name] = methods[name];
  67. }
  68. }
  69. ctor.DEFMETHOD = function(name, method) {
  70. this.prototype[name] = method;
  71. };
  72. if (typeof exports !== "undefined") {
  73. exports["AST_" + type] = ctor;
  74. }
  75. return ctor;
  76. }
  77. var AST_Token = DEFNODE("Token", "type value line col pos endline endcol endpos nlb comments_before comments_after file raw", {
  78. }, null);
  79. var AST_Node = DEFNODE("Node", "start end", {
  80. _clone: function(deep) {
  81. if (deep) {
  82. var self = this.clone();
  83. return self.transform(new TreeTransformer(function(node) {
  84. if (node !== self) {
  85. return node.clone(true);
  86. }
  87. }));
  88. }
  89. return new this.CTOR(this);
  90. },
  91. clone: function(deep) {
  92. return this._clone(deep);
  93. },
  94. $documentation: "Base class of all AST nodes",
  95. $propdoc: {
  96. start: "[AST_Token] The first token of this node",
  97. end: "[AST_Token] The last token of this node"
  98. },
  99. walk: function(visitor) {
  100. visitor.visit(this);
  101. },
  102. _validate: noop,
  103. validate: function() {
  104. var ctor = this.CTOR;
  105. do {
  106. ctor.prototype._validate.call(this);
  107. } while (ctor = ctor.BASE);
  108. },
  109. }, null);
  110. (AST_Node.log_function = function(fn, verbose) {
  111. var printed = Object.create(null);
  112. if (fn) {
  113. AST_Node.info = verbose ? function(text, props) {
  114. log("INFO: " + string_template(text, props));
  115. } : noop;
  116. AST_Node.warn = function(text, props) {
  117. log("WARN: " + string_template(text, props));
  118. };
  119. } else {
  120. AST_Node.info = AST_Node.warn = noop;
  121. }
  122. function log(msg) {
  123. if (printed[msg]) return;
  124. printed[msg] = true;
  125. fn(msg);
  126. }
  127. })();
  128. var restore_transforms = [];
  129. AST_Node.enable_validation = function() {
  130. AST_Node.disable_validation();
  131. (function validate_transform(ctor) {
  132. var transform = ctor.prototype.transform;
  133. ctor.prototype.transform = function(tw, in_list) {
  134. var node = transform.call(this, tw, in_list);
  135. if (node instanceof AST_Node) {
  136. node.validate();
  137. } else if (!(node === null || in_list && List.is_op(node))) {
  138. throw new Error("invalid transformed value: " + node);
  139. }
  140. return node;
  141. };
  142. restore_transforms.push(function() {
  143. ctor.prototype.transform = transform;
  144. });
  145. ctor.SUBCLASSES.forEach(validate_transform);
  146. })(this);
  147. };
  148. AST_Node.disable_validation = function() {
  149. var restore;
  150. while (restore = restore_transforms.pop()) restore();
  151. };
  152. /* -----[ statements ]----- */
  153. var AST_Statement = DEFNODE("Statement", null, {
  154. $documentation: "Base class of all statements",
  155. });
  156. var AST_Debugger = DEFNODE("Debugger", null, {
  157. $documentation: "Represents a debugger statement",
  158. }, AST_Statement);
  159. var AST_Directive = DEFNODE("Directive", "value quote", {
  160. $documentation: "Represents a directive, like \"use strict\";",
  161. $propdoc: {
  162. value: "[string] The value of this directive as a plain string (it's not an AST_String!)",
  163. quote: "[string] the original quote character"
  164. },
  165. _validate: function() {
  166. if (typeof this.value != "string") throw new Error("value must be string");
  167. },
  168. }, AST_Statement);
  169. function must_be_expression(node, prop) {
  170. if (!(node[prop] instanceof AST_Node)) throw new Error(prop + " must be AST_Node");
  171. if (node[prop] instanceof AST_Statement && !(node[prop] instanceof AST_Function)) {
  172. throw new Error(prop + " cannot be AST_Statement");
  173. }
  174. }
  175. var AST_SimpleStatement = DEFNODE("SimpleStatement", "body", {
  176. $documentation: "A statement consisting of an expression, i.e. a = 1 + 2",
  177. $propdoc: {
  178. body: "[AST_Node] an expression node (should not be instanceof AST_Statement)"
  179. },
  180. walk: function(visitor) {
  181. var node = this;
  182. visitor.visit(node, function() {
  183. node.body.walk(visitor);
  184. });
  185. },
  186. _validate: function() {
  187. must_be_expression(this, "body");
  188. },
  189. }, AST_Statement);
  190. function walk_body(node, visitor) {
  191. node.body.forEach(function(node) {
  192. node.walk(visitor);
  193. });
  194. }
  195. var AST_Block = DEFNODE("Block", "body", {
  196. $documentation: "A body of statements (usually braced)",
  197. $propdoc: {
  198. body: "[AST_Statement*] an array of statements"
  199. },
  200. walk: function(visitor) {
  201. var node = this;
  202. visitor.visit(node, function() {
  203. walk_body(node, visitor);
  204. });
  205. },
  206. _validate: function() {
  207. this.body.forEach(function(node) {
  208. if (!(node instanceof AST_Statement)) throw new Error("body must be AST_Statement[]");
  209. if (node instanceof AST_Function) throw new Error("body cannot contain AST_Function");
  210. });
  211. },
  212. }, AST_Statement);
  213. var AST_BlockStatement = DEFNODE("BlockStatement", null, {
  214. $documentation: "A block statement",
  215. }, AST_Block);
  216. var AST_EmptyStatement = DEFNODE("EmptyStatement", null, {
  217. $documentation: "The empty statement (empty block or simply a semicolon)"
  218. }, AST_Statement);
  219. var AST_StatementWithBody = DEFNODE("StatementWithBody", "body", {
  220. $documentation: "Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`",
  221. $propdoc: {
  222. body: "[AST_Statement] the body; this should always be present, even if it's an AST_EmptyStatement"
  223. },
  224. _validate: function() {
  225. if (!(this.body instanceof AST_Statement)) throw new Error("body must be AST_Statement");
  226. if (this.body instanceof AST_Function) throw new Error("body cannot be AST_Function");
  227. },
  228. }, AST_Statement);
  229. var AST_LabeledStatement = DEFNODE("LabeledStatement", "label", {
  230. $documentation: "Statement with a label",
  231. $propdoc: {
  232. label: "[AST_Label] a label definition"
  233. },
  234. walk: function(visitor) {
  235. var node = this;
  236. visitor.visit(node, function() {
  237. node.label.walk(visitor);
  238. node.body.walk(visitor);
  239. });
  240. },
  241. clone: function(deep) {
  242. var node = this._clone(deep);
  243. if (deep) {
  244. var label = node.label;
  245. var def = this.label;
  246. node.walk(new TreeWalker(function(node) {
  247. if (node instanceof AST_LoopControl && node.label && node.label.thedef === def) {
  248. node.label.thedef = label;
  249. label.references.push(node);
  250. }
  251. }));
  252. }
  253. return node;
  254. },
  255. _validate: function() {
  256. if (!(this.label instanceof AST_Label)) throw new Error("label must be AST_Label");
  257. },
  258. }, AST_StatementWithBody);
  259. var AST_IterationStatement = DEFNODE("IterationStatement", null, {
  260. $documentation: "Internal class. All loops inherit from it."
  261. }, AST_StatementWithBody);
  262. var AST_DWLoop = DEFNODE("DWLoop", "condition", {
  263. $documentation: "Base class for do/while statements",
  264. $propdoc: {
  265. condition: "[AST_Node] the loop condition. Should not be instanceof AST_Statement"
  266. },
  267. _validate: function() {
  268. must_be_expression(this, "condition");
  269. },
  270. }, AST_IterationStatement);
  271. var AST_Do = DEFNODE("Do", null, {
  272. $documentation: "A `do` statement",
  273. walk: function(visitor) {
  274. var node = this;
  275. visitor.visit(node, function() {
  276. node.body.walk(visitor);
  277. node.condition.walk(visitor);
  278. });
  279. }
  280. }, AST_DWLoop);
  281. var AST_While = DEFNODE("While", null, {
  282. $documentation: "A `while` statement",
  283. walk: function(visitor) {
  284. var node = this;
  285. visitor.visit(node, function() {
  286. node.condition.walk(visitor);
  287. node.body.walk(visitor);
  288. });
  289. }
  290. }, AST_DWLoop);
  291. var AST_For = DEFNODE("For", "init condition step", {
  292. $documentation: "A `for` statement",
  293. $propdoc: {
  294. init: "[AST_Node?] the `for` initialization code, or null if empty",
  295. condition: "[AST_Node?] the `for` termination clause, or null if empty",
  296. step: "[AST_Node?] the `for` update clause, or null if empty"
  297. },
  298. walk: function(visitor) {
  299. var node = this;
  300. visitor.visit(node, function() {
  301. if (node.init) node.init.walk(visitor);
  302. if (node.condition) node.condition.walk(visitor);
  303. if (node.step) node.step.walk(visitor);
  304. node.body.walk(visitor);
  305. });
  306. },
  307. _validate: function() {
  308. if (this.init != null) {
  309. if (!(this.init instanceof AST_Node)) throw new Error("init must be AST_Node");
  310. if (this.init instanceof AST_Statement
  311. && !(this.init instanceof AST_Definitions || this.init instanceof AST_Function)) {
  312. throw new Error("init cannot be AST_Statement");
  313. }
  314. }
  315. if (this.condition != null) must_be_expression(this, "condition");
  316. if (this.step != null) must_be_expression(this, "step");
  317. },
  318. }, AST_IterationStatement);
  319. var AST_ForIn = DEFNODE("ForIn", "init object", {
  320. $documentation: "A `for ... in` statement",
  321. $propdoc: {
  322. init: "[AST_Node] the `for/in` initialization code",
  323. object: "[AST_Node] the object that we're looping through"
  324. },
  325. walk: function(visitor) {
  326. var node = this;
  327. visitor.visit(node, function() {
  328. node.init.walk(visitor);
  329. node.object.walk(visitor);
  330. node.body.walk(visitor);
  331. });
  332. },
  333. _validate: function() {
  334. if (this.init instanceof AST_Definitions) {
  335. if (this.init.definitions.length != 1) throw new Error("init must have single declaration");
  336. } else if (!(this.init instanceof AST_PropAccess || this.init instanceof AST_SymbolRef)) {
  337. throw new Error("init must be assignable");
  338. }
  339. must_be_expression(this, "object");
  340. },
  341. }, AST_IterationStatement);
  342. var AST_With = DEFNODE("With", "expression", {
  343. $documentation: "A `with` statement",
  344. $propdoc: {
  345. expression: "[AST_Node] the `with` expression"
  346. },
  347. walk: function(visitor) {
  348. var node = this;
  349. visitor.visit(node, function() {
  350. node.expression.walk(visitor);
  351. node.body.walk(visitor);
  352. });
  353. },
  354. _validate: function() {
  355. must_be_expression(this, "expression");
  356. },
  357. }, AST_StatementWithBody);
  358. /* -----[ scope and functions ]----- */
  359. var AST_Scope = DEFNODE("Scope", "variables functions uses_with uses_eval parent_scope enclosed cname", {
  360. $documentation: "Base class for all statements introducing a lexical scope",
  361. $propdoc: {
  362. variables: "[Object/S] a map of name -> SymbolDef for all variables/functions defined in this scope",
  363. functions: "[Object/S] like `variables`, but only lists function declarations",
  364. uses_with: "[boolean/S] tells whether this scope uses the `with` statement",
  365. uses_eval: "[boolean/S] tells whether this scope contains a direct call to the global `eval`",
  366. parent_scope: "[AST_Scope?/S] link to the parent scope",
  367. enclosed: "[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes",
  368. cname: "[integer/S] current index for mangling variables (used internally by the mangler)",
  369. },
  370. clone: function(deep) {
  371. var node = this._clone(deep);
  372. if (this.variables) node.variables = this.variables.clone();
  373. if (this.functions) node.functions = this.functions.clone();
  374. if (this.enclosed) node.enclosed = this.enclosed.slice();
  375. return node;
  376. },
  377. pinned: function() {
  378. return this.uses_eval || this.uses_with;
  379. },
  380. _validate: function() {
  381. if (this.parent_scope != null) {
  382. if (!(this.parent_scope instanceof AST_Scope)) throw new Error("parent_scope must be AST_Scope");
  383. }
  384. },
  385. }, AST_Block);
  386. var AST_Toplevel = DEFNODE("Toplevel", "globals", {
  387. $documentation: "The toplevel scope",
  388. $propdoc: {
  389. globals: "[Object/S] a map of name -> SymbolDef for all undeclared names",
  390. },
  391. wrap: function(name) {
  392. var body = this.body;
  393. return parse([
  394. "(function(exports){'$ORIG';})(typeof ",
  395. name,
  396. "=='undefined'?(",
  397. name,
  398. "={}):",
  399. name,
  400. ");"
  401. ].join(""), {
  402. filename: "wrap=" + JSON.stringify(name)
  403. }).transform(new TreeTransformer(function(node) {
  404. if (node instanceof AST_Directive && node.value == "$ORIG") {
  405. return List.splice(body);
  406. }
  407. }));
  408. },
  409. enclose: function(args_values) {
  410. if (typeof args_values != "string") args_values = "";
  411. var index = args_values.indexOf(":");
  412. if (index < 0) index = args_values.length;
  413. var body = this.body;
  414. return parse([
  415. "(function(",
  416. args_values.slice(0, index),
  417. '){"$ORIG"})(',
  418. args_values.slice(index + 1),
  419. ")"
  420. ].join(""), {
  421. filename: "enclose=" + JSON.stringify(args_values)
  422. }).transform(new TreeTransformer(function(node) {
  423. if (node instanceof AST_Directive && node.value == "$ORIG") {
  424. return List.splice(body);
  425. }
  426. }));
  427. }
  428. }, AST_Scope);
  429. var AST_Lambda = DEFNODE("Lambda", "name argnames uses_arguments length_read", {
  430. $documentation: "Base class for functions",
  431. $propdoc: {
  432. name: "[AST_SymbolDeclaration?] the name of this function",
  433. argnames: "[AST_SymbolFunarg*] array of function arguments",
  434. uses_arguments: "[boolean/S] tells whether this function accesses the arguments array"
  435. },
  436. walk: function(visitor) {
  437. var node = this;
  438. visitor.visit(node, function() {
  439. if (node.name) node.name.walk(visitor);
  440. node.argnames.forEach(function(argname) {
  441. argname.walk(visitor);
  442. });
  443. walk_body(node, visitor);
  444. });
  445. },
  446. _validate: function() {
  447. this.argnames.forEach(function(node) {
  448. if (!(node instanceof AST_SymbolFunarg)) throw new Error("argnames must be AST_SymbolFunarg[]");
  449. });
  450. },
  451. }, AST_Scope);
  452. var AST_Accessor = DEFNODE("Accessor", null, {
  453. $documentation: "A setter/getter function. The `name` property is always null.",
  454. _validate: function() {
  455. if (this.name != null) throw new Error("name must be null");
  456. },
  457. }, AST_Lambda);
  458. var AST_Function = DEFNODE("Function", "inlined", {
  459. $documentation: "A function expression",
  460. _validate: function() {
  461. if (this.name != null) {
  462. if (!(this.name instanceof AST_SymbolLambda)) throw new Error("name must be AST_SymbolLambda");
  463. }
  464. },
  465. }, AST_Lambda);
  466. var AST_Defun = DEFNODE("Defun", "inlined", {
  467. $documentation: "A function definition",
  468. _validate: function() {
  469. if (!(this.name instanceof AST_SymbolDefun)) throw new Error("name must be AST_SymbolDefun");
  470. },
  471. }, AST_Lambda);
  472. /* -----[ JUMPS ]----- */
  473. var AST_Jump = DEFNODE("Jump", null, {
  474. $documentation: "Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)"
  475. }, AST_Statement);
  476. var AST_Exit = DEFNODE("Exit", "value", {
  477. $documentation: "Base class for “exits” (`return` and `throw`)",
  478. $propdoc: {
  479. value: "[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return"
  480. },
  481. walk: function(visitor) {
  482. var node = this;
  483. visitor.visit(node, function() {
  484. if (node.value) node.value.walk(visitor);
  485. });
  486. }
  487. }, AST_Jump);
  488. var AST_Return = DEFNODE("Return", null, {
  489. $documentation: "A `return` statement",
  490. _validate: function() {
  491. if (this.value != null) must_be_expression(this, "value");
  492. },
  493. }, AST_Exit);
  494. var AST_Throw = DEFNODE("Throw", null, {
  495. $documentation: "A `throw` statement",
  496. _validate: function() {
  497. must_be_expression(this, "value");
  498. },
  499. }, AST_Exit);
  500. var AST_LoopControl = DEFNODE("LoopControl", "label", {
  501. $documentation: "Base class for loop control statements (`break` and `continue`)",
  502. $propdoc: {
  503. label: "[AST_LabelRef?] the label, or null if none",
  504. },
  505. walk: function(visitor) {
  506. var node = this;
  507. visitor.visit(node, function() {
  508. if (node.label) node.label.walk(visitor);
  509. });
  510. },
  511. _validate: function() {
  512. if (this.label != null) {
  513. if (!(this.label instanceof AST_LabelRef)) throw new Error("label must be AST_LabelRef");
  514. }
  515. },
  516. }, AST_Jump);
  517. var AST_Break = DEFNODE("Break", null, {
  518. $documentation: "A `break` statement"
  519. }, AST_LoopControl);
  520. var AST_Continue = DEFNODE("Continue", null, {
  521. $documentation: "A `continue` statement"
  522. }, AST_LoopControl);
  523. /* -----[ IF ]----- */
  524. var AST_If = DEFNODE("If", "condition alternative", {
  525. $documentation: "A `if` statement",
  526. $propdoc: {
  527. condition: "[AST_Node] the `if` condition",
  528. alternative: "[AST_Statement?] the `else` part, or null if not present"
  529. },
  530. walk: function(visitor) {
  531. var node = this;
  532. visitor.visit(node, function() {
  533. node.condition.walk(visitor);
  534. node.body.walk(visitor);
  535. if (node.alternative) node.alternative.walk(visitor);
  536. });
  537. },
  538. _validate: function() {
  539. must_be_expression(this, "condition");
  540. if (this.alternative != null) {
  541. if (!(this.alternative instanceof AST_Statement)) throw new Error("alternative must be AST_Statement");
  542. if (this.alternative instanceof AST_Function) throw new error("alternative cannot be AST_Function");
  543. }
  544. },
  545. }, AST_StatementWithBody);
  546. /* -----[ SWITCH ]----- */
  547. var AST_Switch = DEFNODE("Switch", "expression", {
  548. $documentation: "A `switch` statement",
  549. $propdoc: {
  550. expression: "[AST_Node] the `switch` “discriminant”"
  551. },
  552. walk: function(visitor) {
  553. var node = this;
  554. visitor.visit(node, function() {
  555. node.expression.walk(visitor);
  556. walk_body(node, visitor);
  557. });
  558. },
  559. _validate: function() {
  560. must_be_expression(this, "expression");
  561. },
  562. }, AST_Block);
  563. var AST_SwitchBranch = DEFNODE("SwitchBranch", null, {
  564. $documentation: "Base class for `switch` branches",
  565. }, AST_Block);
  566. var AST_Default = DEFNODE("Default", null, {
  567. $documentation: "A `default` switch branch",
  568. }, AST_SwitchBranch);
  569. var AST_Case = DEFNODE("Case", "expression", {
  570. $documentation: "A `case` switch branch",
  571. $propdoc: {
  572. expression: "[AST_Node] the `case` expression"
  573. },
  574. walk: function(visitor) {
  575. var node = this;
  576. visitor.visit(node, function() {
  577. node.expression.walk(visitor);
  578. walk_body(node, visitor);
  579. });
  580. },
  581. _validate: function() {
  582. must_be_expression(this, "expression");
  583. },
  584. }, AST_SwitchBranch);
  585. /* -----[ EXCEPTIONS ]----- */
  586. var AST_Try = DEFNODE("Try", "bcatch bfinally", {
  587. $documentation: "A `try` statement",
  588. $propdoc: {
  589. bcatch: "[AST_Catch?] the catch block, or null if not present",
  590. bfinally: "[AST_Finally?] the finally block, or null if not present"
  591. },
  592. walk: function(visitor) {
  593. var node = this;
  594. visitor.visit(node, function() {
  595. walk_body(node, visitor);
  596. if (node.bcatch) node.bcatch.walk(visitor);
  597. if (node.bfinally) node.bfinally.walk(visitor);
  598. });
  599. },
  600. _validate: function() {
  601. if (this.bcatch != null) {
  602. if (!(this.bcatch instanceof AST_Catch)) throw new Error("bcatch must be AST_Catch");
  603. }
  604. if (this.bfinally != null) {
  605. if (!(this.bfinally instanceof AST_Finally)) throw new Error("bfinally must be AST_Finally");
  606. }
  607. },
  608. }, AST_Block);
  609. var AST_Catch = DEFNODE("Catch", "argname", {
  610. $documentation: "A `catch` node; only makes sense as part of a `try` statement",
  611. $propdoc: {
  612. argname: "[AST_SymbolCatch] symbol for the exception"
  613. },
  614. walk: function(visitor) {
  615. var node = this;
  616. visitor.visit(node, function() {
  617. node.argname.walk(visitor);
  618. walk_body(node, visitor);
  619. });
  620. },
  621. _validate: function() {
  622. if (!(this.argname instanceof AST_SymbolCatch)) throw new Error("argname must be AST_SymbolCatch");
  623. },
  624. }, AST_Block);
  625. var AST_Finally = DEFNODE("Finally", null, {
  626. $documentation: "A `finally` node; only makes sense as part of a `try` statement"
  627. }, AST_Block);
  628. /* -----[ VAR ]----- */
  629. var AST_Definitions = DEFNODE("Definitions", "definitions", {
  630. $documentation: "Base class for `var` nodes (variable declarations/initializations)",
  631. $propdoc: {
  632. definitions: "[AST_VarDef*] array of variable definitions"
  633. },
  634. walk: function(visitor) {
  635. var node = this;
  636. visitor.visit(node, function() {
  637. node.definitions.forEach(function(defn) {
  638. defn.walk(visitor);
  639. });
  640. });
  641. }
  642. }, AST_Statement);
  643. var AST_Var = DEFNODE("Var", null, {
  644. $documentation: "A `var` statement",
  645. _validate: function() {
  646. this.definitions.forEach(function(node) {
  647. if (!(node instanceof AST_VarDef)) throw new Error("definitions must be AST_VarDef[]");
  648. });
  649. },
  650. }, AST_Definitions);
  651. var AST_VarDef = DEFNODE("VarDef", "name value", {
  652. $documentation: "A variable declaration; only appears in a AST_Definitions node",
  653. $propdoc: {
  654. name: "[AST_SymbolVar] name of the variable",
  655. value: "[AST_Node?] initializer, or null of there's no initializer"
  656. },
  657. walk: function(visitor) {
  658. var node = this;
  659. visitor.visit(node, function() {
  660. node.name.walk(visitor);
  661. if (node.value) node.value.walk(visitor);
  662. });
  663. },
  664. _validate: function() {
  665. if (!(this.name instanceof AST_SymbolVar)) throw new Error("name must be AST_SymbolVar");
  666. if (this.value != null) must_be_expression(this, "value");
  667. },
  668. });
  669. /* -----[ OTHER ]----- */
  670. function must_be_expressions(node, prop) {
  671. node[prop].forEach(function(node) {
  672. if (!(node instanceof AST_Node)) throw new Error(prop + " must be AST_Node[]");
  673. if (node instanceof AST_Statement && !(node instanceof AST_Function)) {
  674. throw new Error(prop + " cannot contain AST_Statement");
  675. }
  676. });
  677. }
  678. var AST_Call = DEFNODE("Call", "expression args pure", {
  679. $documentation: "A function call expression",
  680. $propdoc: {
  681. expression: "[AST_Node] expression to invoke as function",
  682. args: "[AST_Node*] array of arguments"
  683. },
  684. walk: function(visitor) {
  685. var node = this;
  686. visitor.visit(node, function() {
  687. node.expression.walk(visitor);
  688. node.args.forEach(function(arg) {
  689. arg.walk(visitor);
  690. });
  691. });
  692. },
  693. _validate: function() {
  694. must_be_expression(this, "expression");
  695. must_be_expressions(this, "args");
  696. },
  697. });
  698. var AST_New = DEFNODE("New", null, {
  699. $documentation: "An object instantiation. Derives from a function call since it has exactly the same properties"
  700. }, AST_Call);
  701. var AST_Sequence = DEFNODE("Sequence", "expressions", {
  702. $documentation: "A sequence expression (comma-separated expressions)",
  703. $propdoc: {
  704. expressions: "[AST_Node*] array of expressions (at least two)"
  705. },
  706. walk: function(visitor) {
  707. var node = this;
  708. visitor.visit(node, function() {
  709. node.expressions.forEach(function(expr) {
  710. expr.walk(visitor);
  711. });
  712. });
  713. },
  714. _validate: function() {
  715. if (this.expressions.length < 2) throw new Error("expressions must contain multiple elements");
  716. must_be_expressions(this, "expressions");
  717. },
  718. });
  719. var AST_PropAccess = DEFNODE("PropAccess", "expression property", {
  720. $documentation: "Base class for property access expressions, i.e. `a.foo` or `a[\"foo\"]`",
  721. $propdoc: {
  722. expression: "[AST_Node] the “container” expression",
  723. property: "[AST_Node|string] the property to access. For AST_Dot this is always a plain string, while for AST_Sub it's an arbitrary AST_Node"
  724. },
  725. getProperty: function() {
  726. var p = this.property;
  727. if (p instanceof AST_Constant) {
  728. return p.value;
  729. }
  730. if (p instanceof AST_UnaryPrefix
  731. && p.operator == "void"
  732. && p.expression instanceof AST_Constant) {
  733. return;
  734. }
  735. return p;
  736. },
  737. _validate: function() {
  738. must_be_expression(this, "expression");
  739. },
  740. });
  741. var AST_Dot = DEFNODE("Dot", null, {
  742. $documentation: "A dotted property access expression",
  743. walk: function(visitor) {
  744. var node = this;
  745. visitor.visit(node, function() {
  746. node.expression.walk(visitor);
  747. });
  748. },
  749. _validate: function() {
  750. if (typeof this.property != "string") throw new Error("property must be string");
  751. },
  752. }, AST_PropAccess);
  753. var AST_Sub = DEFNODE("Sub", null, {
  754. $documentation: "Index-style property access, i.e. `a[\"foo\"]`",
  755. walk: function(visitor) {
  756. var node = this;
  757. visitor.visit(node, function() {
  758. node.expression.walk(visitor);
  759. node.property.walk(visitor);
  760. });
  761. },
  762. _validate: function() {
  763. must_be_expression(this, "property");
  764. },
  765. }, AST_PropAccess);
  766. var AST_Unary = DEFNODE("Unary", "operator expression", {
  767. $documentation: "Base class for unary expressions",
  768. $propdoc: {
  769. operator: "[string] the operator",
  770. expression: "[AST_Node] expression that this unary operator applies to"
  771. },
  772. walk: function(visitor) {
  773. var node = this;
  774. visitor.visit(node, function() {
  775. node.expression.walk(visitor);
  776. });
  777. },
  778. _validate: function() {
  779. if (typeof this.operator != "string") throw new Error("operator must be string");
  780. must_be_expression(this, "expression");
  781. },
  782. });
  783. var AST_UnaryPrefix = DEFNODE("UnaryPrefix", null, {
  784. $documentation: "Unary prefix expression, i.e. `typeof i` or `++i`"
  785. }, AST_Unary);
  786. var AST_UnaryPostfix = DEFNODE("UnaryPostfix", null, {
  787. $documentation: "Unary postfix expression, i.e. `i++`"
  788. }, AST_Unary);
  789. var AST_Binary = DEFNODE("Binary", "operator left right", {
  790. $documentation: "Binary expression, i.e. `a + b`",
  791. $propdoc: {
  792. left: "[AST_Node] left-hand side expression",
  793. operator: "[string] the operator",
  794. right: "[AST_Node] right-hand side expression"
  795. },
  796. walk: function(visitor) {
  797. var node = this;
  798. visitor.visit(node, function() {
  799. node.left.walk(visitor);
  800. node.right.walk(visitor);
  801. });
  802. },
  803. _validate: function() {
  804. must_be_expression(this, "left");
  805. if (typeof this.operator != "string") throw new Error("operator must be string");
  806. must_be_expression(this, "right");
  807. },
  808. });
  809. var AST_Conditional = DEFNODE("Conditional", "condition consequent alternative", {
  810. $documentation: "Conditional expression using the ternary operator, i.e. `a ? b : c`",
  811. $propdoc: {
  812. condition: "[AST_Node]",
  813. consequent: "[AST_Node]",
  814. alternative: "[AST_Node]"
  815. },
  816. walk: function(visitor) {
  817. var node = this;
  818. visitor.visit(node, function() {
  819. node.condition.walk(visitor);
  820. node.consequent.walk(visitor);
  821. node.alternative.walk(visitor);
  822. });
  823. },
  824. _validate: function() {
  825. must_be_expression(this, "condition");
  826. must_be_expression(this, "consequent");
  827. must_be_expression(this, "alternative");
  828. },
  829. });
  830. var AST_Assign = DEFNODE("Assign", null, {
  831. $documentation: "An assignment expression — `a = b + 5`",
  832. _validate: function() {
  833. if (this.operator.indexOf("=") < 0) throw new Error('operator must contain "="');
  834. },
  835. }, AST_Binary);
  836. /* -----[ LITERALS ]----- */
  837. var AST_Array = DEFNODE("Array", "elements", {
  838. $documentation: "An array literal",
  839. $propdoc: {
  840. elements: "[AST_Node*] array of elements"
  841. },
  842. walk: function(visitor) {
  843. var node = this;
  844. visitor.visit(node, function() {
  845. node.elements.forEach(function(element) {
  846. element.walk(visitor);
  847. });
  848. });
  849. },
  850. _validate: function() {
  851. must_be_expressions(this, "elements");
  852. },
  853. });
  854. var AST_Object = DEFNODE("Object", "properties", {
  855. $documentation: "An object literal",
  856. $propdoc: {
  857. properties: "[AST_ObjectProperty*] array of properties"
  858. },
  859. walk: function(visitor) {
  860. var node = this;
  861. visitor.visit(node, function() {
  862. node.properties.forEach(function(prop) {
  863. prop.walk(visitor);
  864. });
  865. });
  866. },
  867. _validate: function() {
  868. this.properties.forEach(function(node) {
  869. if (!(node instanceof AST_ObjectProperty)) throw new Error("properties must be AST_ObjectProperty[]");
  870. });
  871. },
  872. });
  873. var AST_ObjectProperty = DEFNODE("ObjectProperty", "key value", {
  874. $documentation: "Base class for literal object properties",
  875. $propdoc: {
  876. key: "[string|AST_SymbolAccessor] property name. For ObjectKeyVal this is a string. For getters and setters this is an AST_SymbolAccessor.",
  877. value: "[AST_Node] property value. For getters and setters this is an AST_Accessor."
  878. },
  879. walk: function(visitor) {
  880. var node = this;
  881. visitor.visit(node, function() {
  882. node.value.walk(visitor);
  883. });
  884. }
  885. });
  886. var AST_ObjectKeyVal = DEFNODE("ObjectKeyVal", "quote", {
  887. $documentation: "A key: value object property",
  888. $propdoc: {
  889. quote: "[string] the original quote character"
  890. },
  891. _validate: function() {
  892. if (typeof this.key != "string") throw new Error("key must be string");
  893. must_be_expression(this, "value");
  894. },
  895. }, AST_ObjectProperty);
  896. var AST_ObjectSetter = DEFNODE("ObjectSetter", null, {
  897. $documentation: "An object setter property",
  898. _validate: function() {
  899. if (!(this.key instanceof AST_SymbolAccessor)) throw new Error("key must be AST_SymbolAccessor");
  900. if (!(this.value instanceof AST_Accessor)) throw new Error("value must be AST_Accessor");
  901. },
  902. }, AST_ObjectProperty);
  903. var AST_ObjectGetter = DEFNODE("ObjectGetter", null, {
  904. $documentation: "An object getter property",
  905. _validate: function() {
  906. if (!(this.key instanceof AST_SymbolAccessor)) throw new Error("key must be AST_SymbolAccessor");
  907. if (!(this.value instanceof AST_Accessor)) throw new Error("value must be AST_Accessor");
  908. },
  909. }, AST_ObjectProperty);
  910. var AST_Symbol = DEFNODE("Symbol", "scope name thedef", {
  911. $propdoc: {
  912. name: "[string] name of this symbol",
  913. scope: "[AST_Scope/S] the current scope (not necessarily the definition scope)",
  914. thedef: "[SymbolDef/S] the definition of this symbol"
  915. },
  916. $documentation: "Base class for all symbols",
  917. _validate: function() {
  918. if (typeof this.name != "string") throw new Error("name must be string");
  919. },
  920. });
  921. var AST_SymbolAccessor = DEFNODE("SymbolAccessor", null, {
  922. $documentation: "The name of a property accessor (setter/getter function)"
  923. }, AST_Symbol);
  924. var AST_SymbolDeclaration = DEFNODE("SymbolDeclaration", "init", {
  925. $documentation: "A declaration symbol (symbol in var, function name or argument, symbol in catch)",
  926. }, AST_Symbol);
  927. var AST_SymbolVar = DEFNODE("SymbolVar", null, {
  928. $documentation: "Symbol defining a variable",
  929. }, AST_SymbolDeclaration);
  930. var AST_SymbolFunarg = DEFNODE("SymbolFunarg", null, {
  931. $documentation: "Symbol naming a function argument",
  932. }, AST_SymbolVar);
  933. var AST_SymbolDefun = DEFNODE("SymbolDefun", null, {
  934. $documentation: "Symbol defining a function",
  935. }, AST_SymbolDeclaration);
  936. var AST_SymbolLambda = DEFNODE("SymbolLambda", null, {
  937. $documentation: "Symbol naming a function expression",
  938. }, AST_SymbolDeclaration);
  939. var AST_SymbolCatch = DEFNODE("SymbolCatch", null, {
  940. $documentation: "Symbol naming the exception in catch",
  941. }, AST_SymbolDeclaration);
  942. var AST_Label = DEFNODE("Label", "references", {
  943. $documentation: "Symbol naming a label (declaration)",
  944. $propdoc: {
  945. references: "[AST_LoopControl*] a list of nodes referring to this label"
  946. },
  947. initialize: function() {
  948. this.references = [];
  949. this.thedef = this;
  950. }
  951. }, AST_Symbol);
  952. var AST_SymbolRef = DEFNODE("SymbolRef", "fixed", {
  953. $documentation: "Reference to some symbol (not definition/declaration)",
  954. }, AST_Symbol);
  955. var AST_LabelRef = DEFNODE("LabelRef", null, {
  956. $documentation: "Reference to a label symbol",
  957. }, AST_Symbol);
  958. var AST_This = DEFNODE("This", null, {
  959. $documentation: "The `this` symbol",
  960. _validate: function() {
  961. if (this.name !== "this") throw new Error('name must be "this"');
  962. },
  963. }, AST_Symbol);
  964. var AST_Constant = DEFNODE("Constant", null, {
  965. $documentation: "Base class for all constants",
  966. });
  967. var AST_String = DEFNODE("String", "value quote", {
  968. $documentation: "A string literal",
  969. $propdoc: {
  970. value: "[string] the contents of this string",
  971. quote: "[string] the original quote character"
  972. },
  973. _validate: function() {
  974. if (typeof this.value != "string") throw new Error("value must be string");
  975. },
  976. }, AST_Constant);
  977. var AST_Number = DEFNODE("Number", "value", {
  978. $documentation: "A number literal",
  979. $propdoc: {
  980. value: "[number] the numeric value",
  981. },
  982. _validate: function() {
  983. if (typeof this.value != "number") throw new Error("value must be number");
  984. },
  985. }, AST_Constant);
  986. var AST_RegExp = DEFNODE("RegExp", "value", {
  987. $documentation: "A regexp literal",
  988. $propdoc: {
  989. value: "[RegExp] the actual regexp"
  990. },
  991. _validate: function() {
  992. if (!(this.value instanceof RegExp)) throw new Error("value must be RegExp");
  993. },
  994. }, AST_Constant);
  995. var AST_Atom = DEFNODE("Atom", null, {
  996. $documentation: "Base class for atoms",
  997. }, AST_Constant);
  998. var AST_Null = DEFNODE("Null", null, {
  999. $documentation: "The `null` atom",
  1000. value: null
  1001. }, AST_Atom);
  1002. var AST_NaN = DEFNODE("NaN", null, {
  1003. $documentation: "The impossible value",
  1004. value: 0/0
  1005. }, AST_Atom);
  1006. var AST_Undefined = DEFNODE("Undefined", null, {
  1007. $documentation: "The `undefined` value",
  1008. value: function(){}()
  1009. }, AST_Atom);
  1010. var AST_Hole = DEFNODE("Hole", null, {
  1011. $documentation: "A hole in an array",
  1012. value: function(){}()
  1013. }, AST_Atom);
  1014. var AST_Infinity = DEFNODE("Infinity", null, {
  1015. $documentation: "The `Infinity` value",
  1016. value: 1/0
  1017. }, AST_Atom);
  1018. var AST_Boolean = DEFNODE("Boolean", null, {
  1019. $documentation: "Base class for booleans",
  1020. }, AST_Atom);
  1021. var AST_False = DEFNODE("False", null, {
  1022. $documentation: "The `false` atom",
  1023. value: false
  1024. }, AST_Boolean);
  1025. var AST_True = DEFNODE("True", null, {
  1026. $documentation: "The `true` atom",
  1027. value: true
  1028. }, AST_Boolean);
  1029. /* -----[ TreeWalker ]----- */
  1030. function TreeWalker(callback) {
  1031. this.callback = callback;
  1032. this.directives = Object.create(null);
  1033. this.stack = [];
  1034. }
  1035. TreeWalker.prototype = {
  1036. visit: function(node, descend) {
  1037. this.push(node);
  1038. var done = this.callback(node, descend || noop);
  1039. if (!done && descend) descend();
  1040. this.pop();
  1041. },
  1042. parent: function(n) {
  1043. return this.stack[this.stack.length - 2 - (n || 0)];
  1044. },
  1045. push: function(node) {
  1046. if (node instanceof AST_Lambda) {
  1047. this.directives = Object.create(this.directives);
  1048. } else if (node instanceof AST_Directive && !this.directives[node.value]) {
  1049. this.directives[node.value] = node;
  1050. }
  1051. this.stack.push(node);
  1052. },
  1053. pop: function() {
  1054. if (this.stack.pop() instanceof AST_Lambda) {
  1055. this.directives = Object.getPrototypeOf(this.directives);
  1056. }
  1057. },
  1058. self: function() {
  1059. return this.stack[this.stack.length - 1];
  1060. },
  1061. find_parent: function(type) {
  1062. var stack = this.stack;
  1063. for (var i = stack.length; --i >= 0;) {
  1064. var x = stack[i];
  1065. if (x instanceof type) return x;
  1066. }
  1067. },
  1068. has_directive: function(type) {
  1069. var dir = this.directives[type];
  1070. if (dir) return dir;
  1071. var node = this.stack[this.stack.length - 1];
  1072. if (node instanceof AST_Scope) {
  1073. for (var i = 0; i < node.body.length; ++i) {
  1074. var st = node.body[i];
  1075. if (!(st instanceof AST_Directive)) break;
  1076. if (st.value == type) return st;
  1077. }
  1078. }
  1079. },
  1080. loopcontrol_target: function(node) {
  1081. var stack = this.stack;
  1082. if (node.label) for (var i = stack.length; --i >= 0;) {
  1083. var x = stack[i];
  1084. if (x instanceof AST_LabeledStatement && x.label.name == node.label.name)
  1085. return x.body;
  1086. } else for (var i = stack.length; --i >= 0;) {
  1087. var x = stack[i];
  1088. if (x instanceof AST_IterationStatement
  1089. || node instanceof AST_Break && x instanceof AST_Switch)
  1090. return x;
  1091. }
  1092. },
  1093. in_boolean_context: function() {
  1094. var self = this.self();
  1095. for (var i = 0, p; p = this.parent(i); i++) {
  1096. if (p instanceof AST_Conditional && p.condition === self
  1097. || p instanceof AST_DWLoop && p.condition === self
  1098. || p instanceof AST_For && p.condition === self
  1099. || p instanceof AST_If && p.condition === self
  1100. || p instanceof AST_Return && p.in_bool
  1101. || p instanceof AST_Sequence && p.tail_node() !== self
  1102. || p instanceof AST_SimpleStatement
  1103. || p instanceof AST_UnaryPrefix && p.operator == "!" && p.expression === self) {
  1104. return true;
  1105. }
  1106. if (p instanceof AST_Binary && (p.operator == "&&" || p.operator == "||")
  1107. || p instanceof AST_Conditional
  1108. || p.tail_node() === self) {
  1109. self = p;
  1110. } else if (p instanceof AST_Return) {
  1111. var fn;
  1112. do {
  1113. fn = this.parent(++i);
  1114. if (!fn) return false;
  1115. } while (!(fn instanceof AST_Lambda));
  1116. if (fn.name) return false;
  1117. self = this.parent(++i);
  1118. if (!self || self.TYPE != "Call" || self.expression !== fn) return false;
  1119. } else {
  1120. return false;
  1121. }
  1122. }
  1123. }
  1124. };