estraverse.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. /*
  2. Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>
  3. Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are met:
  6. * Redistributions of source code must retain the above copyright
  7. notice, this list of conditions and the following disclaimer.
  8. * Redistributions in binary form must reproduce the above copyright
  9. notice, this list of conditions and the following disclaimer in the
  10. documentation and/or other materials provided with the distribution.
  11. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  12. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  13. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  14. ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  15. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  16. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  17. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  18. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  19. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  20. THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  21. */
  22. /*jslint vars:false, bitwise:true*/
  23. /*jshint indent:4*/
  24. /*global exports:true, define:true*/
  25. (function (root, factory) {
  26. 'use strict';
  27. // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
  28. // and plain browser loading,
  29. if (typeof define === 'function' && define.amd) {
  30. define(['exports'], factory);
  31. } else if (typeof exports !== 'undefined') {
  32. factory(exports);
  33. } else {
  34. factory((root.estraverse = {}));
  35. }
  36. }(this, function (exports) {
  37. 'use strict';
  38. var Syntax,
  39. isArray,
  40. VisitorOption,
  41. VisitorKeys,
  42. BREAK,
  43. SKIP;
  44. Syntax = {
  45. AssignmentExpression: 'AssignmentExpression',
  46. ArrayExpression: 'ArrayExpression',
  47. ArrayPattern: 'ArrayPattern',
  48. ArrowFunctionExpression: 'ArrowFunctionExpression',
  49. BlockStatement: 'BlockStatement',
  50. BinaryExpression: 'BinaryExpression',
  51. BreakStatement: 'BreakStatement',
  52. CallExpression: 'CallExpression',
  53. CatchClause: 'CatchClause',
  54. ClassBody: 'ClassBody',
  55. ClassDeclaration: 'ClassDeclaration',
  56. ClassExpression: 'ClassExpression',
  57. ConditionalExpression: 'ConditionalExpression',
  58. ContinueStatement: 'ContinueStatement',
  59. DebuggerStatement: 'DebuggerStatement',
  60. DirectiveStatement: 'DirectiveStatement',
  61. DoWhileStatement: 'DoWhileStatement',
  62. EmptyStatement: 'EmptyStatement',
  63. ExpressionStatement: 'ExpressionStatement',
  64. ForStatement: 'ForStatement',
  65. ForInStatement: 'ForInStatement',
  66. FunctionDeclaration: 'FunctionDeclaration',
  67. FunctionExpression: 'FunctionExpression',
  68. Identifier: 'Identifier',
  69. IfStatement: 'IfStatement',
  70. Literal: 'Literal',
  71. LabeledStatement: 'LabeledStatement',
  72. LogicalExpression: 'LogicalExpression',
  73. MemberExpression: 'MemberExpression',
  74. MethodDefinition: 'MethodDefinition',
  75. NewExpression: 'NewExpression',
  76. ObjectExpression: 'ObjectExpression',
  77. ObjectPattern: 'ObjectPattern',
  78. Program: 'Program',
  79. Property: 'Property',
  80. ReturnStatement: 'ReturnStatement',
  81. SequenceExpression: 'SequenceExpression',
  82. SwitchStatement: 'SwitchStatement',
  83. SwitchCase: 'SwitchCase',
  84. ThisExpression: 'ThisExpression',
  85. ThrowStatement: 'ThrowStatement',
  86. TryStatement: 'TryStatement',
  87. UnaryExpression: 'UnaryExpression',
  88. UpdateExpression: 'UpdateExpression',
  89. VariableDeclaration: 'VariableDeclaration',
  90. VariableDeclarator: 'VariableDeclarator',
  91. WhileStatement: 'WhileStatement',
  92. WithStatement: 'WithStatement',
  93. YieldExpression: 'YieldExpression'
  94. };
  95. function ignoreJSHintError() { }
  96. isArray = Array.isArray;
  97. if (!isArray) {
  98. isArray = function isArray(array) {
  99. return Object.prototype.toString.call(array) === '[object Array]';
  100. };
  101. }
  102. function deepCopy(obj) {
  103. var ret = {}, key, val;
  104. for (key in obj) {
  105. if (obj.hasOwnProperty(key)) {
  106. val = obj[key];
  107. if (typeof val === 'object' && val !== null) {
  108. ret[key] = deepCopy(val);
  109. } else {
  110. ret[key] = val;
  111. }
  112. }
  113. }
  114. return ret;
  115. }
  116. function shallowCopy(obj) {
  117. var ret = {}, key;
  118. for (key in obj) {
  119. if (obj.hasOwnProperty(key)) {
  120. ret[key] = obj[key];
  121. }
  122. }
  123. return ret;
  124. }
  125. ignoreJSHintError(shallowCopy);
  126. // based on LLVM libc++ upper_bound / lower_bound
  127. // MIT License
  128. function upperBound(array, func) {
  129. var diff, len, i, current;
  130. len = array.length;
  131. i = 0;
  132. while (len) {
  133. diff = len >>> 1;
  134. current = i + diff;
  135. if (func(array[current])) {
  136. len = diff;
  137. } else {
  138. i = current + 1;
  139. len -= diff + 1;
  140. }
  141. }
  142. return i;
  143. }
  144. function lowerBound(array, func) {
  145. var diff, len, i, current;
  146. len = array.length;
  147. i = 0;
  148. while (len) {
  149. diff = len >>> 1;
  150. current = i + diff;
  151. if (func(array[current])) {
  152. i = current + 1;
  153. len -= diff + 1;
  154. } else {
  155. len = diff;
  156. }
  157. }
  158. return i;
  159. }
  160. ignoreJSHintError(lowerBound);
  161. VisitorKeys = {
  162. AssignmentExpression: ['left', 'right'],
  163. ArrayExpression: ['elements'],
  164. ArrayPattern: ['elements'],
  165. ArrowFunctionExpression: ['params', 'defaults', 'rest', 'body'],
  166. BlockStatement: ['body'],
  167. BinaryExpression: ['left', 'right'],
  168. BreakStatement: ['label'],
  169. CallExpression: ['callee', 'arguments'],
  170. CatchClause: ['param', 'body'],
  171. ClassBody: ['body'],
  172. ClassDeclaration: ['id', 'body', 'superClass'],
  173. ClassExpression: ['id', 'body', 'superClass'],
  174. ConditionalExpression: ['test', 'consequent', 'alternate'],
  175. ContinueStatement: ['label'],
  176. DebuggerStatement: [],
  177. DirectiveStatement: [],
  178. DoWhileStatement: ['body', 'test'],
  179. EmptyStatement: [],
  180. ExpressionStatement: ['expression'],
  181. ForStatement: ['init', 'test', 'update', 'body'],
  182. ForInStatement: ['left', 'right', 'body'],
  183. ForOfStatement: ['left', 'right', 'body'],
  184. FunctionDeclaration: ['id', 'params', 'defaults', 'rest', 'body'],
  185. FunctionExpression: ['id', 'params', 'defaults', 'rest', 'body'],
  186. Identifier: [],
  187. IfStatement: ['test', 'consequent', 'alternate'],
  188. Literal: [],
  189. LabeledStatement: ['label', 'body'],
  190. LogicalExpression: ['left', 'right'],
  191. MemberExpression: ['object', 'property'],
  192. MethodDefinition: ['key', 'value'],
  193. NewExpression: ['callee', 'arguments'],
  194. ObjectExpression: ['properties'],
  195. ObjectPattern: ['properties'],
  196. Program: ['body'],
  197. Property: ['key', 'value'],
  198. ReturnStatement: ['argument'],
  199. SequenceExpression: ['expressions'],
  200. SwitchStatement: ['discriminant', 'cases'],
  201. SwitchCase: ['test', 'consequent'],
  202. ThisExpression: [],
  203. ThrowStatement: ['argument'],
  204. TryStatement: ['block', 'handlers', 'handler', 'guardedHandlers', 'finalizer'],
  205. UnaryExpression: ['argument'],
  206. UpdateExpression: ['argument'],
  207. VariableDeclaration: ['declarations'],
  208. VariableDeclarator: ['id', 'init'],
  209. WhileStatement: ['test', 'body'],
  210. WithStatement: ['object', 'body'],
  211. YieldExpression: ['argument']
  212. };
  213. // unique id
  214. BREAK = {};
  215. SKIP = {};
  216. VisitorOption = {
  217. Break: BREAK,
  218. Skip: SKIP
  219. };
  220. function Reference(parent, key) {
  221. this.parent = parent;
  222. this.key = key;
  223. }
  224. Reference.prototype.replace = function replace(node) {
  225. this.parent[this.key] = node;
  226. };
  227. function Element(node, path, wrap, ref) {
  228. this.node = node;
  229. this.path = path;
  230. this.wrap = wrap;
  231. this.ref = ref;
  232. }
  233. function Controller() { }
  234. // API:
  235. // return property path array from root to current node
  236. Controller.prototype.path = function path() {
  237. var i, iz, j, jz, result, element;
  238. function addToPath(result, path) {
  239. if (isArray(path)) {
  240. for (j = 0, jz = path.length; j < jz; ++j) {
  241. result.push(path[j]);
  242. }
  243. } else {
  244. result.push(path);
  245. }
  246. }
  247. // root node
  248. if (!this.__current.path) {
  249. return null;
  250. }
  251. // first node is sentinel, second node is root element
  252. result = [];
  253. for (i = 2, iz = this.__leavelist.length; i < iz; ++i) {
  254. element = this.__leavelist[i];
  255. addToPath(result, element.path);
  256. }
  257. addToPath(result, this.__current.path);
  258. return result;
  259. };
  260. // API:
  261. // return array of parent elements
  262. Controller.prototype.parents = function parents() {
  263. var i, iz, result;
  264. // first node is sentinel
  265. result = [];
  266. for (i = 1, iz = this.__leavelist.length; i < iz; ++i) {
  267. result.push(this.__leavelist[i].node);
  268. }
  269. return result;
  270. };
  271. // API:
  272. // return current node
  273. Controller.prototype.current = function current() {
  274. return this.__current.node;
  275. };
  276. Controller.prototype.__execute = function __execute(callback, element) {
  277. var previous, result;
  278. result = undefined;
  279. previous = this.__current;
  280. this.__current = element;
  281. this.__state = null;
  282. if (callback) {
  283. result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node);
  284. }
  285. this.__current = previous;
  286. return result;
  287. };
  288. // API:
  289. // notify control skip / break
  290. Controller.prototype.notify = function notify(flag) {
  291. this.__state = flag;
  292. };
  293. // API:
  294. // skip child nodes of current node
  295. Controller.prototype.skip = function () {
  296. this.notify(SKIP);
  297. };
  298. // API:
  299. // break traversals
  300. Controller.prototype['break'] = function () {
  301. this.notify(BREAK);
  302. };
  303. Controller.prototype.__initialize = function(root, visitor) {
  304. this.visitor = visitor;
  305. this.root = root;
  306. this.__worklist = [];
  307. this.__leavelist = [];
  308. this.__current = null;
  309. this.__state = null;
  310. };
  311. Controller.prototype.traverse = function traverse(root, visitor) {
  312. var worklist,
  313. leavelist,
  314. element,
  315. node,
  316. nodeType,
  317. ret,
  318. key,
  319. current,
  320. current2,
  321. candidates,
  322. candidate,
  323. sentinel;
  324. this.__initialize(root, visitor);
  325. sentinel = {};
  326. // reference
  327. worklist = this.__worklist;
  328. leavelist = this.__leavelist;
  329. // initialize
  330. worklist.push(new Element(root, null, null, null));
  331. leavelist.push(new Element(null, null, null, null));
  332. while (worklist.length) {
  333. element = worklist.pop();
  334. if (element === sentinel) {
  335. element = leavelist.pop();
  336. ret = this.__execute(visitor.leave, element);
  337. if (this.__state === BREAK || ret === BREAK) {
  338. return;
  339. }
  340. continue;
  341. }
  342. if (element.node) {
  343. ret = this.__execute(visitor.enter, element);
  344. if (this.__state === BREAK || ret === BREAK) {
  345. return;
  346. }
  347. worklist.push(sentinel);
  348. leavelist.push(element);
  349. if (this.__state === SKIP || ret === SKIP) {
  350. continue;
  351. }
  352. node = element.node;
  353. nodeType = element.wrap || node.type;
  354. candidates = VisitorKeys[nodeType];
  355. current = candidates.length;
  356. while ((current -= 1) >= 0) {
  357. key = candidates[current];
  358. candidate = node[key];
  359. if (!candidate) {
  360. continue;
  361. }
  362. if (!isArray(candidate)) {
  363. worklist.push(new Element(candidate, key, null, null));
  364. continue;
  365. }
  366. current2 = candidate.length;
  367. while ((current2 -= 1) >= 0) {
  368. if (!candidate[current2]) {
  369. continue;
  370. }
  371. if ((nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === candidates[current]) {
  372. element = new Element(candidate[current2], [key, current2], 'Property', null);
  373. } else {
  374. element = new Element(candidate[current2], [key, current2], null, null);
  375. }
  376. worklist.push(element);
  377. }
  378. }
  379. }
  380. }
  381. };
  382. Controller.prototype.replace = function replace(root, visitor) {
  383. var worklist,
  384. leavelist,
  385. node,
  386. nodeType,
  387. target,
  388. element,
  389. current,
  390. current2,
  391. candidates,
  392. candidate,
  393. sentinel,
  394. outer,
  395. key;
  396. this.__initialize(root, visitor);
  397. sentinel = {};
  398. // reference
  399. worklist = this.__worklist;
  400. leavelist = this.__leavelist;
  401. // initialize
  402. outer = {
  403. root: root
  404. };
  405. element = new Element(root, null, null, new Reference(outer, 'root'));
  406. worklist.push(element);
  407. leavelist.push(element);
  408. while (worklist.length) {
  409. element = worklist.pop();
  410. if (element === sentinel) {
  411. element = leavelist.pop();
  412. target = this.__execute(visitor.leave, element);
  413. // node may be replaced with null,
  414. // so distinguish between undefined and null in this place
  415. if (target !== undefined && target !== BREAK && target !== SKIP) {
  416. // replace
  417. element.ref.replace(target);
  418. }
  419. if (this.__state === BREAK || target === BREAK) {
  420. return outer.root;
  421. }
  422. continue;
  423. }
  424. target = this.__execute(visitor.enter, element);
  425. // node may be replaced with null,
  426. // so distinguish between undefined and null in this place
  427. if (target !== undefined && target !== BREAK && target !== SKIP) {
  428. // replace
  429. element.ref.replace(target);
  430. element.node = target;
  431. }
  432. if (this.__state === BREAK || target === BREAK) {
  433. return outer.root;
  434. }
  435. // node may be null
  436. node = element.node;
  437. if (!node) {
  438. continue;
  439. }
  440. worklist.push(sentinel);
  441. leavelist.push(element);
  442. if (this.__state === SKIP || target === SKIP) {
  443. continue;
  444. }
  445. nodeType = element.wrap || node.type;
  446. candidates = VisitorKeys[nodeType];
  447. current = candidates.length;
  448. while ((current -= 1) >= 0) {
  449. key = candidates[current];
  450. candidate = node[key];
  451. if (!candidate) {
  452. continue;
  453. }
  454. if (!isArray(candidate)) {
  455. worklist.push(new Element(candidate, key, null, new Reference(node, key)));
  456. continue;
  457. }
  458. current2 = candidate.length;
  459. while ((current2 -= 1) >= 0) {
  460. if (!candidate[current2]) {
  461. continue;
  462. }
  463. if (nodeType === Syntax.ObjectExpression && 'properties' === candidates[current]) {
  464. element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2));
  465. } else {
  466. element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2));
  467. }
  468. worklist.push(element);
  469. }
  470. }
  471. }
  472. return outer.root;
  473. };
  474. function traverse(root, visitor) {
  475. var controller = new Controller();
  476. return controller.traverse(root, visitor);
  477. }
  478. function replace(root, visitor) {
  479. var controller = new Controller();
  480. return controller.replace(root, visitor);
  481. }
  482. function extendCommentRange(comment, tokens) {
  483. var target;
  484. target = upperBound(tokens, function search(token) {
  485. return token.range[0] > comment.range[0];
  486. });
  487. comment.extendedRange = [comment.range[0], comment.range[1]];
  488. if (target !== tokens.length) {
  489. comment.extendedRange[1] = tokens[target].range[0];
  490. }
  491. target -= 1;
  492. if (target >= 0) {
  493. comment.extendedRange[0] = tokens[target].range[1];
  494. }
  495. return comment;
  496. }
  497. function attachComments(tree, providedComments, tokens) {
  498. // At first, we should calculate extended comment ranges.
  499. var comments = [], comment, len, i, cursor;
  500. if (!tree.range) {
  501. throw new Error('attachComments needs range information');
  502. }
  503. // tokens array is empty, we attach comments to tree as 'leadingComments'
  504. if (!tokens.length) {
  505. if (providedComments.length) {
  506. for (i = 0, len = providedComments.length; i < len; i += 1) {
  507. comment = deepCopy(providedComments[i]);
  508. comment.extendedRange = [0, tree.range[0]];
  509. comments.push(comment);
  510. }
  511. tree.leadingComments = comments;
  512. }
  513. return tree;
  514. }
  515. for (i = 0, len = providedComments.length; i < len; i += 1) {
  516. comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens));
  517. }
  518. // This is based on John Freeman's implementation.
  519. cursor = 0;
  520. traverse(tree, {
  521. enter: function (node) {
  522. var comment;
  523. while (cursor < comments.length) {
  524. comment = comments[cursor];
  525. if (comment.extendedRange[1] > node.range[0]) {
  526. break;
  527. }
  528. if (comment.extendedRange[1] === node.range[0]) {
  529. if (!node.leadingComments) {
  530. node.leadingComments = [];
  531. }
  532. node.leadingComments.push(comment);
  533. comments.splice(cursor, 1);
  534. } else {
  535. cursor += 1;
  536. }
  537. }
  538. // already out of owned node
  539. if (cursor === comments.length) {
  540. return VisitorOption.Break;
  541. }
  542. if (comments[cursor].extendedRange[0] > node.range[1]) {
  543. return VisitorOption.Skip;
  544. }
  545. }
  546. });
  547. cursor = 0;
  548. traverse(tree, {
  549. leave: function (node) {
  550. var comment;
  551. while (cursor < comments.length) {
  552. comment = comments[cursor];
  553. if (node.range[1] < comment.extendedRange[0]) {
  554. break;
  555. }
  556. if (node.range[1] === comment.extendedRange[0]) {
  557. if (!node.trailingComments) {
  558. node.trailingComments = [];
  559. }
  560. node.trailingComments.push(comment);
  561. comments.splice(cursor, 1);
  562. } else {
  563. cursor += 1;
  564. }
  565. }
  566. // already out of owned node
  567. if (cursor === comments.length) {
  568. return VisitorOption.Break;
  569. }
  570. if (comments[cursor].extendedRange[0] > node.range[1]) {
  571. return VisitorOption.Skip;
  572. }
  573. }
  574. });
  575. return tree;
  576. }
  577. exports.version = '1.5.1-dev';
  578. exports.Syntax = Syntax;
  579. exports.traverse = traverse;
  580. exports.replace = replace;
  581. exports.attachComments = attachComments;
  582. exports.VisitorKeys = VisitorKeys;
  583. exports.VisitorOption = VisitorOption;
  584. exports.Controller = Controller;
  585. }));
  586. /* vim: set sw=4 ts=4 et tw=80 : */