ast.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  1. /***********************************************************************
  2. A JavaScript tokenizer / parser / beautifier / compressor.
  3. https://github.com/mishoo/UglifyJS2
  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. return visitor._visit(this);
  101. },
  102. walk: function(visitor) {
  103. return this._walk(visitor); // not sure the indirection will be any help
  104. }
  105. }, null);
  106. (AST_Node.log_function = function(fn, verbose) {
  107. var printed = Object.create(null);
  108. if (fn) {
  109. AST_Node.info = verbose ? function(text, props) {
  110. log("INFO: " + string_template(text, props));
  111. } : noop;
  112. AST_Node.warn = function(text, props) {
  113. log("WARN: " + string_template(text, props));
  114. };
  115. } else {
  116. AST_Node.info = AST_Node.warn = noop;
  117. }
  118. function log(msg) {
  119. if (printed[msg]) return;
  120. printed[msg] = true;
  121. fn(msg);
  122. }
  123. })();
  124. /* -----[ statements ]----- */
  125. var AST_Statement = DEFNODE("Statement", null, {
  126. $documentation: "Base class of all statements",
  127. });
  128. var AST_Debugger = DEFNODE("Debugger", null, {
  129. $documentation: "Represents a debugger statement",
  130. }, AST_Statement);
  131. var AST_Directive = DEFNODE("Directive", "value quote", {
  132. $documentation: "Represents a directive, like \"use strict\";",
  133. $propdoc: {
  134. value: "[string] The value of this directive as a plain string (it's not an AST_String!)",
  135. quote: "[string] the original quote character"
  136. },
  137. }, AST_Statement);
  138. var AST_SimpleStatement = DEFNODE("SimpleStatement", "body", {
  139. $documentation: "A statement consisting of an expression, i.e. a = 1 + 2",
  140. $propdoc: {
  141. body: "[AST_Node] an expression node (should not be instanceof AST_Statement)"
  142. },
  143. _walk: function(visitor) {
  144. return visitor._visit(this, function() {
  145. this.body._walk(visitor);
  146. });
  147. }
  148. }, AST_Statement);
  149. function walk_body(node, visitor) {
  150. var body = node.body;
  151. if (body instanceof AST_Statement) {
  152. body._walk(visitor);
  153. } else body.forEach(function(node) {
  154. node._walk(visitor);
  155. });
  156. }
  157. var AST_Block = DEFNODE("Block", "body", {
  158. $documentation: "A body of statements (usually braced)",
  159. $propdoc: {
  160. body: "[AST_Statement*] an array of statements"
  161. },
  162. _walk: function(visitor) {
  163. return visitor._visit(this, function() {
  164. walk_body(this, visitor);
  165. });
  166. }
  167. }, AST_Statement);
  168. var AST_BlockStatement = DEFNODE("BlockStatement", null, {
  169. $documentation: "A block statement",
  170. }, AST_Block);
  171. var AST_EmptyStatement = DEFNODE("EmptyStatement", null, {
  172. $documentation: "The empty statement (empty block or simply a semicolon)"
  173. }, AST_Statement);
  174. var AST_StatementWithBody = DEFNODE("StatementWithBody", "body", {
  175. $documentation: "Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`",
  176. $propdoc: {
  177. body: "[AST_Statement] the body; this should always be present, even if it's an AST_EmptyStatement"
  178. }
  179. }, AST_Statement);
  180. var AST_LabeledStatement = DEFNODE("LabeledStatement", "label", {
  181. $documentation: "Statement with a label",
  182. $propdoc: {
  183. label: "[AST_Label] a label definition"
  184. },
  185. _walk: function(visitor) {
  186. return visitor._visit(this, function() {
  187. this.label._walk(visitor);
  188. this.body._walk(visitor);
  189. });
  190. },
  191. clone: function(deep) {
  192. var node = this._clone(deep);
  193. if (deep) {
  194. var label = node.label;
  195. var def = this.label;
  196. node.walk(new TreeWalker(function(node) {
  197. if (node instanceof AST_LoopControl && node.label && node.label.thedef === def) {
  198. node.label.thedef = label;
  199. label.references.push(node);
  200. }
  201. }));
  202. }
  203. return node;
  204. }
  205. }, AST_StatementWithBody);
  206. var AST_IterationStatement = DEFNODE("IterationStatement", null, {
  207. $documentation: "Internal class. All loops inherit from it."
  208. }, AST_StatementWithBody);
  209. var AST_DWLoop = DEFNODE("DWLoop", "condition", {
  210. $documentation: "Base class for do/while statements",
  211. $propdoc: {
  212. condition: "[AST_Node] the loop condition. Should not be instanceof AST_Statement"
  213. }
  214. }, AST_IterationStatement);
  215. var AST_Do = DEFNODE("Do", null, {
  216. $documentation: "A `do` statement",
  217. _walk: function(visitor) {
  218. return visitor._visit(this, function() {
  219. this.body._walk(visitor);
  220. this.condition._walk(visitor);
  221. });
  222. }
  223. }, AST_DWLoop);
  224. var AST_While = DEFNODE("While", null, {
  225. $documentation: "A `while` statement",
  226. _walk: function(visitor) {
  227. return visitor._visit(this, function() {
  228. this.condition._walk(visitor);
  229. this.body._walk(visitor);
  230. });
  231. }
  232. }, AST_DWLoop);
  233. var AST_For = DEFNODE("For", "init condition step", {
  234. $documentation: "A `for` statement",
  235. $propdoc: {
  236. init: "[AST_Node?] the `for` initialization code, or null if empty",
  237. condition: "[AST_Node?] the `for` termination clause, or null if empty",
  238. step: "[AST_Node?] the `for` update clause, or null if empty"
  239. },
  240. _walk: function(visitor) {
  241. return visitor._visit(this, function() {
  242. if (this.init) this.init._walk(visitor);
  243. if (this.condition) this.condition._walk(visitor);
  244. if (this.step) this.step._walk(visitor);
  245. this.body._walk(visitor);
  246. });
  247. }
  248. }, AST_IterationStatement);
  249. var AST_ForIn = DEFNODE("ForIn", "init object", {
  250. $documentation: "A `for ... in` statement",
  251. $propdoc: {
  252. init: "[AST_Node] the `for/in` initialization code",
  253. object: "[AST_Node] the object that we're looping through"
  254. },
  255. _walk: function(visitor) {
  256. return visitor._visit(this, function() {
  257. this.init._walk(visitor);
  258. this.object._walk(visitor);
  259. this.body._walk(visitor);
  260. });
  261. }
  262. }, AST_IterationStatement);
  263. var AST_With = DEFNODE("With", "expression", {
  264. $documentation: "A `with` statement",
  265. $propdoc: {
  266. expression: "[AST_Node] the `with` expression"
  267. },
  268. _walk: function(visitor) {
  269. return visitor._visit(this, function() {
  270. this.expression._walk(visitor);
  271. this.body._walk(visitor);
  272. });
  273. }
  274. }, AST_StatementWithBody);
  275. /* -----[ scope and functions ]----- */
  276. var AST_Scope = DEFNODE("Scope", "variables functions uses_with uses_eval parent_scope enclosed cname", {
  277. $documentation: "Base class for all statements introducing a lexical scope",
  278. $propdoc: {
  279. variables: "[Object/S] a map of name -> SymbolDef for all variables/functions defined in this scope",
  280. functions: "[Object/S] like `variables`, but only lists function declarations",
  281. uses_with: "[boolean/S] tells whether this scope uses the `with` statement",
  282. uses_eval: "[boolean/S] tells whether this scope contains a direct call to the global `eval`",
  283. parent_scope: "[AST_Scope?/S] link to the parent scope",
  284. enclosed: "[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes",
  285. cname: "[integer/S] current index for mangling variables (used internally by the mangler)",
  286. },
  287. clone: function(deep) {
  288. var node = this._clone(deep);
  289. if (this.variables) node.variables = this.variables.clone();
  290. if (this.functions) node.functions = this.functions.clone();
  291. if (this.enclosed) node.enclosed = this.enclosed.slice();
  292. return node;
  293. },
  294. pinned: function() {
  295. return this.uses_eval || this.uses_with;
  296. }
  297. }, AST_Block);
  298. var AST_Toplevel = DEFNODE("Toplevel", "globals", {
  299. $documentation: "The toplevel scope",
  300. $propdoc: {
  301. globals: "[Object/S] a map of name -> SymbolDef for all undeclared names",
  302. },
  303. wrap: function(name) {
  304. var body = this.body;
  305. return parse([
  306. "(function(exports){'$ORIG';})(typeof ",
  307. name,
  308. "=='undefined'?(",
  309. name,
  310. "={}):",
  311. name,
  312. ");"
  313. ].join(""), {
  314. filename: "wrap=" + JSON.stringify(name)
  315. }).transform(new TreeTransformer(function(node) {
  316. if (node instanceof AST_Directive && node.value == "$ORIG") {
  317. return MAP.splice(body);
  318. }
  319. }));
  320. },
  321. enclose: function(args_values) {
  322. if (typeof args_values != "string") args_values = "";
  323. var index = args_values.indexOf(":");
  324. if (index < 0) index = args_values.length;
  325. var body = this.body;
  326. return parse([
  327. "(function(",
  328. args_values.slice(0, index),
  329. '){"$ORIG"})(',
  330. args_values.slice(index + 1),
  331. ")"
  332. ].join(""), {
  333. filename: "enclose=" + JSON.stringify(args_values)
  334. }).transform(new TreeTransformer(function(node) {
  335. if (node instanceof AST_Directive && node.value == "$ORIG") {
  336. return MAP.splice(body);
  337. }
  338. }));
  339. }
  340. }, AST_Scope);
  341. var AST_Lambda = DEFNODE("Lambda", "name argnames uses_arguments", {
  342. $documentation: "Base class for functions",
  343. $propdoc: {
  344. name: "[AST_SymbolDeclaration?] the name of this function",
  345. argnames: "[AST_SymbolFunarg*] array of function arguments",
  346. uses_arguments: "[boolean/S] tells whether this function accesses the arguments array"
  347. },
  348. _walk: function(visitor) {
  349. return visitor._visit(this, function() {
  350. if (this.name) this.name._walk(visitor);
  351. this.argnames.forEach(function(argname) {
  352. argname._walk(visitor);
  353. });
  354. walk_body(this, visitor);
  355. });
  356. }
  357. }, AST_Scope);
  358. var AST_Accessor = DEFNODE("Accessor", null, {
  359. $documentation: "A setter/getter function. The `name` property is always null."
  360. }, AST_Lambda);
  361. var AST_Function = DEFNODE("Function", "inlined", {
  362. $documentation: "A function expression"
  363. }, AST_Lambda);
  364. var AST_Defun = DEFNODE("Defun", "inlined", {
  365. $documentation: "A function definition"
  366. }, AST_Lambda);
  367. /* -----[ JUMPS ]----- */
  368. var AST_Jump = DEFNODE("Jump", null, {
  369. $documentation: "Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)"
  370. }, AST_Statement);
  371. var AST_Exit = DEFNODE("Exit", "value", {
  372. $documentation: "Base class for “exits” (`return` and `throw`)",
  373. $propdoc: {
  374. value: "[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return"
  375. },
  376. _walk: function(visitor) {
  377. return visitor._visit(this, this.value && function() {
  378. this.value._walk(visitor);
  379. });
  380. }
  381. }, AST_Jump);
  382. var AST_Return = DEFNODE("Return", null, {
  383. $documentation: "A `return` statement"
  384. }, AST_Exit);
  385. var AST_Throw = DEFNODE("Throw", null, {
  386. $documentation: "A `throw` statement"
  387. }, AST_Exit);
  388. var AST_LoopControl = DEFNODE("LoopControl", "label", {
  389. $documentation: "Base class for loop control statements (`break` and `continue`)",
  390. $propdoc: {
  391. label: "[AST_LabelRef?] the label, or null if none",
  392. },
  393. _walk: function(visitor) {
  394. return visitor._visit(this, this.label && function() {
  395. this.label._walk(visitor);
  396. });
  397. }
  398. }, AST_Jump);
  399. var AST_Break = DEFNODE("Break", null, {
  400. $documentation: "A `break` statement"
  401. }, AST_LoopControl);
  402. var AST_Continue = DEFNODE("Continue", null, {
  403. $documentation: "A `continue` statement"
  404. }, AST_LoopControl);
  405. /* -----[ IF ]----- */
  406. var AST_If = DEFNODE("If", "condition alternative", {
  407. $documentation: "A `if` statement",
  408. $propdoc: {
  409. condition: "[AST_Node] the `if` condition",
  410. alternative: "[AST_Statement?] the `else` part, or null if not present"
  411. },
  412. _walk: function(visitor) {
  413. return visitor._visit(this, function() {
  414. this.condition._walk(visitor);
  415. this.body._walk(visitor);
  416. if (this.alternative) this.alternative._walk(visitor);
  417. });
  418. }
  419. }, AST_StatementWithBody);
  420. /* -----[ SWITCH ]----- */
  421. var AST_Switch = DEFNODE("Switch", "expression", {
  422. $documentation: "A `switch` statement",
  423. $propdoc: {
  424. expression: "[AST_Node] the `switch` “discriminant”"
  425. },
  426. _walk: function(visitor) {
  427. return visitor._visit(this, function() {
  428. this.expression._walk(visitor);
  429. walk_body(this, visitor);
  430. });
  431. }
  432. }, AST_Block);
  433. var AST_SwitchBranch = DEFNODE("SwitchBranch", null, {
  434. $documentation: "Base class for `switch` branches",
  435. }, AST_Block);
  436. var AST_Default = DEFNODE("Default", null, {
  437. $documentation: "A `default` switch branch",
  438. }, AST_SwitchBranch);
  439. var AST_Case = DEFNODE("Case", "expression", {
  440. $documentation: "A `case` switch branch",
  441. $propdoc: {
  442. expression: "[AST_Node] the `case` expression"
  443. },
  444. _walk: function(visitor) {
  445. return visitor._visit(this, function() {
  446. this.expression._walk(visitor);
  447. walk_body(this, visitor);
  448. });
  449. }
  450. }, AST_SwitchBranch);
  451. /* -----[ EXCEPTIONS ]----- */
  452. var AST_Try = DEFNODE("Try", "bcatch bfinally", {
  453. $documentation: "A `try` statement",
  454. $propdoc: {
  455. bcatch: "[AST_Catch?] the catch block, or null if not present",
  456. bfinally: "[AST_Finally?] the finally block, or null if not present"
  457. },
  458. _walk: function(visitor) {
  459. return visitor._visit(this, function() {
  460. walk_body(this, visitor);
  461. if (this.bcatch) this.bcatch._walk(visitor);
  462. if (this.bfinally) this.bfinally._walk(visitor);
  463. });
  464. }
  465. }, AST_Block);
  466. var AST_Catch = DEFNODE("Catch", "argname", {
  467. $documentation: "A `catch` node; only makes sense as part of a `try` statement",
  468. $propdoc: {
  469. argname: "[AST_SymbolCatch] symbol for the exception"
  470. },
  471. _walk: function(visitor) {
  472. return visitor._visit(this, function() {
  473. this.argname._walk(visitor);
  474. walk_body(this, visitor);
  475. });
  476. }
  477. }, AST_Block);
  478. var AST_Finally = DEFNODE("Finally", null, {
  479. $documentation: "A `finally` node; only makes sense as part of a `try` statement"
  480. }, AST_Block);
  481. /* -----[ VAR ]----- */
  482. var AST_Definitions = DEFNODE("Definitions", "definitions", {
  483. $documentation: "Base class for `var` nodes (variable declarations/initializations)",
  484. $propdoc: {
  485. definitions: "[AST_VarDef*] array of variable definitions"
  486. },
  487. _walk: function(visitor) {
  488. return visitor._visit(this, function() {
  489. this.definitions.forEach(function(defn) {
  490. defn._walk(visitor);
  491. });
  492. });
  493. }
  494. }, AST_Statement);
  495. var AST_Var = DEFNODE("Var", null, {
  496. $documentation: "A `var` statement"
  497. }, AST_Definitions);
  498. var AST_VarDef = DEFNODE("VarDef", "name value", {
  499. $documentation: "A variable declaration; only appears in a AST_Definitions node",
  500. $propdoc: {
  501. name: "[AST_SymbolVar] name of the variable",
  502. value: "[AST_Node?] initializer, or null of there's no initializer"
  503. },
  504. _walk: function(visitor) {
  505. return visitor._visit(this, function() {
  506. this.name._walk(visitor);
  507. if (this.value) this.value._walk(visitor);
  508. });
  509. }
  510. });
  511. /* -----[ OTHER ]----- */
  512. var AST_Call = DEFNODE("Call", "expression args", {
  513. $documentation: "A function call expression",
  514. $propdoc: {
  515. expression: "[AST_Node] expression to invoke as function",
  516. args: "[AST_Node*] array of arguments"
  517. },
  518. _walk: function(visitor) {
  519. return visitor._visit(this, function() {
  520. this.expression._walk(visitor);
  521. this.args.forEach(function(node) {
  522. node._walk(visitor);
  523. });
  524. });
  525. }
  526. });
  527. var AST_New = DEFNODE("New", null, {
  528. $documentation: "An object instantiation. Derives from a function call since it has exactly the same properties"
  529. }, AST_Call);
  530. var AST_Sequence = DEFNODE("Sequence", "expressions", {
  531. $documentation: "A sequence expression (comma-separated expressions)",
  532. $propdoc: {
  533. expressions: "[AST_Node*] array of expressions (at least two)"
  534. },
  535. _walk: function(visitor) {
  536. return visitor._visit(this, function() {
  537. this.expressions.forEach(function(node) {
  538. node._walk(visitor);
  539. });
  540. });
  541. }
  542. });
  543. var AST_PropAccess = DEFNODE("PropAccess", "expression property", {
  544. $documentation: "Base class for property access expressions, i.e. `a.foo` or `a[\"foo\"]`",
  545. $propdoc: {
  546. expression: "[AST_Node] the “container” expression",
  547. 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"
  548. }
  549. });
  550. var AST_Dot = DEFNODE("Dot", null, {
  551. $documentation: "A dotted property access expression",
  552. _walk: function(visitor) {
  553. return visitor._visit(this, function() {
  554. this.expression._walk(visitor);
  555. });
  556. }
  557. }, AST_PropAccess);
  558. var AST_Sub = DEFNODE("Sub", null, {
  559. $documentation: "Index-style property access, i.e. `a[\"foo\"]`",
  560. _walk: function(visitor) {
  561. return visitor._visit(this, function() {
  562. this.expression._walk(visitor);
  563. this.property._walk(visitor);
  564. });
  565. }
  566. }, AST_PropAccess);
  567. var AST_Unary = DEFNODE("Unary", "operator expression", {
  568. $documentation: "Base class for unary expressions",
  569. $propdoc: {
  570. operator: "[string] the operator",
  571. expression: "[AST_Node] expression that this unary operator applies to"
  572. },
  573. _walk: function(visitor) {
  574. return visitor._visit(this, function() {
  575. this.expression._walk(visitor);
  576. });
  577. }
  578. });
  579. var AST_UnaryPrefix = DEFNODE("UnaryPrefix", null, {
  580. $documentation: "Unary prefix expression, i.e. `typeof i` or `++i`"
  581. }, AST_Unary);
  582. var AST_UnaryPostfix = DEFNODE("UnaryPostfix", null, {
  583. $documentation: "Unary postfix expression, i.e. `i++`"
  584. }, AST_Unary);
  585. var AST_Binary = DEFNODE("Binary", "operator left right", {
  586. $documentation: "Binary expression, i.e. `a + b`",
  587. $propdoc: {
  588. left: "[AST_Node] left-hand side expression",
  589. operator: "[string] the operator",
  590. right: "[AST_Node] right-hand side expression"
  591. },
  592. _walk: function(visitor) {
  593. return visitor._visit(this, function() {
  594. this.left._walk(visitor);
  595. this.right._walk(visitor);
  596. });
  597. }
  598. });
  599. var AST_Conditional = DEFNODE("Conditional", "condition consequent alternative", {
  600. $documentation: "Conditional expression using the ternary operator, i.e. `a ? b : c`",
  601. $propdoc: {
  602. condition: "[AST_Node]",
  603. consequent: "[AST_Node]",
  604. alternative: "[AST_Node]"
  605. },
  606. _walk: function(visitor) {
  607. return visitor._visit(this, function() {
  608. this.condition._walk(visitor);
  609. this.consequent._walk(visitor);
  610. this.alternative._walk(visitor);
  611. });
  612. }
  613. });
  614. var AST_Assign = DEFNODE("Assign", null, {
  615. $documentation: "An assignment expression — `a = b + 5`",
  616. }, AST_Binary);
  617. /* -----[ LITERALS ]----- */
  618. var AST_Array = DEFNODE("Array", "elements", {
  619. $documentation: "An array literal",
  620. $propdoc: {
  621. elements: "[AST_Node*] array of elements"
  622. },
  623. _walk: function(visitor) {
  624. return visitor._visit(this, function() {
  625. this.elements.forEach(function(element) {
  626. element._walk(visitor);
  627. });
  628. });
  629. }
  630. });
  631. var AST_Object = DEFNODE("Object", "properties", {
  632. $documentation: "An object literal",
  633. $propdoc: {
  634. properties: "[AST_ObjectProperty*] array of properties"
  635. },
  636. _walk: function(visitor) {
  637. return visitor._visit(this, function() {
  638. this.properties.forEach(function(prop) {
  639. prop._walk(visitor);
  640. });
  641. });
  642. }
  643. });
  644. var AST_ObjectProperty = DEFNODE("ObjectProperty", "key value", {
  645. $documentation: "Base class for literal object properties",
  646. $propdoc: {
  647. key: "[string|AST_SymbolAccessor] property name. For ObjectKeyVal this is a string. For getters and setters this is an AST_SymbolAccessor.",
  648. value: "[AST_Node] property value. For getters and setters this is an AST_Accessor."
  649. },
  650. _walk: function(visitor) {
  651. return visitor._visit(this, function() {
  652. this.value._walk(visitor);
  653. });
  654. }
  655. });
  656. var AST_ObjectKeyVal = DEFNODE("ObjectKeyVal", "quote", {
  657. $documentation: "A key: value object property",
  658. $propdoc: {
  659. quote: "[string] the original quote character"
  660. }
  661. }, AST_ObjectProperty);
  662. var AST_ObjectSetter = DEFNODE("ObjectSetter", null, {
  663. $documentation: "An object setter property",
  664. }, AST_ObjectProperty);
  665. var AST_ObjectGetter = DEFNODE("ObjectGetter", null, {
  666. $documentation: "An object getter property",
  667. }, AST_ObjectProperty);
  668. var AST_Symbol = DEFNODE("Symbol", "scope name thedef", {
  669. $propdoc: {
  670. name: "[string] name of this symbol",
  671. scope: "[AST_Scope/S] the current scope (not necessarily the definition scope)",
  672. thedef: "[SymbolDef/S] the definition of this symbol"
  673. },
  674. $documentation: "Base class for all symbols",
  675. });
  676. var AST_SymbolAccessor = DEFNODE("SymbolAccessor", null, {
  677. $documentation: "The name of a property accessor (setter/getter function)"
  678. }, AST_Symbol);
  679. var AST_SymbolDeclaration = DEFNODE("SymbolDeclaration", "init", {
  680. $documentation: "A declaration symbol (symbol in var, function name or argument, symbol in catch)",
  681. }, AST_Symbol);
  682. var AST_SymbolVar = DEFNODE("SymbolVar", null, {
  683. $documentation: "Symbol defining a variable",
  684. }, AST_SymbolDeclaration);
  685. var AST_SymbolFunarg = DEFNODE("SymbolFunarg", null, {
  686. $documentation: "Symbol naming a function argument",
  687. }, AST_SymbolVar);
  688. var AST_SymbolDefun = DEFNODE("SymbolDefun", null, {
  689. $documentation: "Symbol defining a function",
  690. }, AST_SymbolDeclaration);
  691. var AST_SymbolLambda = DEFNODE("SymbolLambda", null, {
  692. $documentation: "Symbol naming a function expression",
  693. }, AST_SymbolDeclaration);
  694. var AST_SymbolCatch = DEFNODE("SymbolCatch", null, {
  695. $documentation: "Symbol naming the exception in catch",
  696. }, AST_SymbolDeclaration);
  697. var AST_Label = DEFNODE("Label", "references", {
  698. $documentation: "Symbol naming a label (declaration)",
  699. $propdoc: {
  700. references: "[AST_LoopControl*] a list of nodes referring to this label"
  701. },
  702. initialize: function() {
  703. this.references = [];
  704. this.thedef = this;
  705. }
  706. }, AST_Symbol);
  707. var AST_SymbolRef = DEFNODE("SymbolRef", "fixed", {
  708. $documentation: "Reference to some symbol (not definition/declaration)",
  709. }, AST_Symbol);
  710. var AST_LabelRef = DEFNODE("LabelRef", null, {
  711. $documentation: "Reference to a label symbol",
  712. }, AST_Symbol);
  713. var AST_This = DEFNODE("This", null, {
  714. $documentation: "The `this` symbol",
  715. }, AST_Symbol);
  716. var AST_Constant = DEFNODE("Constant", null, {
  717. $documentation: "Base class for all constants",
  718. getValue: function() {
  719. return this.value;
  720. }
  721. });
  722. var AST_String = DEFNODE("String", "value quote", {
  723. $documentation: "A string literal",
  724. $propdoc: {
  725. value: "[string] the contents of this string",
  726. quote: "[string] the original quote character"
  727. }
  728. }, AST_Constant);
  729. var AST_Number = DEFNODE("Number", "value literal", {
  730. $documentation: "A number literal",
  731. $propdoc: {
  732. value: "[number] the numeric value",
  733. literal: "[string] numeric value as string (optional)"
  734. }
  735. }, AST_Constant);
  736. var AST_RegExp = DEFNODE("RegExp", "value", {
  737. $documentation: "A regexp literal",
  738. $propdoc: {
  739. value: "[RegExp] the actual regexp"
  740. }
  741. }, AST_Constant);
  742. var AST_Atom = DEFNODE("Atom", null, {
  743. $documentation: "Base class for atoms",
  744. }, AST_Constant);
  745. var AST_Null = DEFNODE("Null", null, {
  746. $documentation: "The `null` atom",
  747. value: null
  748. }, AST_Atom);
  749. var AST_NaN = DEFNODE("NaN", null, {
  750. $documentation: "The impossible value",
  751. value: 0/0
  752. }, AST_Atom);
  753. var AST_Undefined = DEFNODE("Undefined", null, {
  754. $documentation: "The `undefined` value",
  755. value: function(){}()
  756. }, AST_Atom);
  757. var AST_Hole = DEFNODE("Hole", null, {
  758. $documentation: "A hole in an array",
  759. value: function(){}()
  760. }, AST_Atom);
  761. var AST_Infinity = DEFNODE("Infinity", null, {
  762. $documentation: "The `Infinity` value",
  763. value: 1/0
  764. }, AST_Atom);
  765. var AST_Boolean = DEFNODE("Boolean", null, {
  766. $documentation: "Base class for booleans",
  767. }, AST_Atom);
  768. var AST_False = DEFNODE("False", null, {
  769. $documentation: "The `false` atom",
  770. value: false
  771. }, AST_Boolean);
  772. var AST_True = DEFNODE("True", null, {
  773. $documentation: "The `true` atom",
  774. value: true
  775. }, AST_Boolean);
  776. /* -----[ TreeWalker ]----- */
  777. function TreeWalker(callback) {
  778. this.visit = callback;
  779. this.stack = [];
  780. this.directives = Object.create(null);
  781. }
  782. TreeWalker.prototype = {
  783. _visit: function(node, descend) {
  784. this.push(node);
  785. var ret = this.visit(node, descend ? function() {
  786. descend.call(node);
  787. } : noop);
  788. if (!ret && descend) {
  789. descend.call(node);
  790. }
  791. this.pop();
  792. return ret;
  793. },
  794. parent: function(n) {
  795. return this.stack[this.stack.length - 2 - (n || 0)];
  796. },
  797. push: function(node) {
  798. if (node instanceof AST_Lambda) {
  799. this.directives = Object.create(this.directives);
  800. } else if (node instanceof AST_Directive && !this.directives[node.value]) {
  801. this.directives[node.value] = node;
  802. }
  803. this.stack.push(node);
  804. },
  805. pop: function() {
  806. if (this.stack.pop() instanceof AST_Lambda) {
  807. this.directives = Object.getPrototypeOf(this.directives);
  808. }
  809. },
  810. self: function() {
  811. return this.stack[this.stack.length - 1];
  812. },
  813. find_parent: function(type) {
  814. var stack = this.stack;
  815. for (var i = stack.length; --i >= 0;) {
  816. var x = stack[i];
  817. if (x instanceof type) return x;
  818. }
  819. },
  820. has_directive: function(type) {
  821. var dir = this.directives[type];
  822. if (dir) return dir;
  823. var node = this.stack[this.stack.length - 1];
  824. if (node instanceof AST_Scope) {
  825. for (var i = 0; i < node.body.length; ++i) {
  826. var st = node.body[i];
  827. if (!(st instanceof AST_Directive)) break;
  828. if (st.value == type) return st;
  829. }
  830. }
  831. },
  832. loopcontrol_target: function(node) {
  833. var stack = this.stack;
  834. if (node.label) for (var i = stack.length; --i >= 0;) {
  835. var x = stack[i];
  836. if (x instanceof AST_LabeledStatement && x.label.name == node.label.name)
  837. return x.body;
  838. } else for (var i = stack.length; --i >= 0;) {
  839. var x = stack[i];
  840. if (x instanceof AST_IterationStatement
  841. || node instanceof AST_Break && x instanceof AST_Switch)
  842. return x;
  843. }
  844. },
  845. in_boolean_context: function() {
  846. var self = this.self();
  847. for (var i = 0, p; p = this.parent(i); i++) {
  848. if (p instanceof AST_SimpleStatement
  849. || p instanceof AST_Conditional && p.condition === self
  850. || p instanceof AST_DWLoop && p.condition === self
  851. || p instanceof AST_For && p.condition === self
  852. || p instanceof AST_If && p.condition === self
  853. || p instanceof AST_UnaryPrefix && p.operator == "!" && p.expression === self) {
  854. return true;
  855. }
  856. if (p instanceof AST_Binary && (p.operator == "&&" || p.operator == "||")
  857. || p instanceof AST_Conditional
  858. || p.tail_node() === self) {
  859. self = p;
  860. } else {
  861. return false;
  862. }
  863. }
  864. }
  865. };