ast.js 32 KB

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