estraverse.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  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 clone(exports) {
  37. 'use strict';
  38. var Syntax,
  39. isArray,
  40. VisitorOption,
  41. VisitorKeys,
  42. objectCreate,
  43. objectKeys,
  44. BREAK,
  45. SKIP,
  46. REMOVE;
  47. function ignoreJSHintError() { }
  48. isArray = Array.isArray;
  49. if (!isArray) {
  50. isArray = function isArray(array) {
  51. return Object.prototype.toString.call(array) === '[object Array]';
  52. };
  53. }
  54. function deepCopy(obj) {
  55. var ret = {}, key, val;
  56. for (key in obj) {
  57. if (obj.hasOwnProperty(key)) {
  58. val = obj[key];
  59. if (typeof val === 'object' && val !== null) {
  60. ret[key] = deepCopy(val);
  61. } else {
  62. ret[key] = val;
  63. }
  64. }
  65. }
  66. return ret;
  67. }
  68. function shallowCopy(obj) {
  69. var ret = {}, key;
  70. for (key in obj) {
  71. if (obj.hasOwnProperty(key)) {
  72. ret[key] = obj[key];
  73. }
  74. }
  75. return ret;
  76. }
  77. ignoreJSHintError(shallowCopy);
  78. // based on LLVM libc++ upper_bound / lower_bound
  79. // MIT License
  80. function upperBound(array, func) {
  81. var diff, len, i, current;
  82. len = array.length;
  83. i = 0;
  84. while (len) {
  85. diff = len >>> 1;
  86. current = i + diff;
  87. if (func(array[current])) {
  88. len = diff;
  89. } else {
  90. i = current + 1;
  91. len -= diff + 1;
  92. }
  93. }
  94. return i;
  95. }
  96. function lowerBound(array, func) {
  97. var diff, len, i, current;
  98. len = array.length;
  99. i = 0;
  100. while (len) {
  101. diff = len >>> 1;
  102. current = i + diff;
  103. if (func(array[current])) {
  104. i = current + 1;
  105. len -= diff + 1;
  106. } else {
  107. len = diff;
  108. }
  109. }
  110. return i;
  111. }
  112. ignoreJSHintError(lowerBound);
  113. objectCreate = Object.create || (function () {
  114. function F() { }
  115. return function (o) {
  116. F.prototype = o;
  117. return new F();
  118. };
  119. })();
  120. objectKeys = Object.keys || function (o) {
  121. var keys = [], key;
  122. for (key in o) {
  123. keys.push(key);
  124. }
  125. return keys;
  126. };
  127. function extend(to, from) {
  128. objectKeys(from).forEach(function (key) {
  129. to[key] = from[key];
  130. });
  131. return to;
  132. }
  133. Syntax = {
  134. AssignmentExpression: 'AssignmentExpression',
  135. ArrayExpression: 'ArrayExpression',
  136. ArrayPattern: 'ArrayPattern',
  137. ArrowFunctionExpression: 'ArrowFunctionExpression',
  138. AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7.
  139. BlockStatement: 'BlockStatement',
  140. BinaryExpression: 'BinaryExpression',
  141. BreakStatement: 'BreakStatement',
  142. CallExpression: 'CallExpression',
  143. CatchClause: 'CatchClause',
  144. ClassBody: 'ClassBody',
  145. ClassDeclaration: 'ClassDeclaration',
  146. ClassExpression: 'ClassExpression',
  147. ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7.
  148. ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7.
  149. ConditionalExpression: 'ConditionalExpression',
  150. ContinueStatement: 'ContinueStatement',
  151. DebuggerStatement: 'DebuggerStatement',
  152. DirectiveStatement: 'DirectiveStatement',
  153. DoWhileStatement: 'DoWhileStatement',
  154. EmptyStatement: 'EmptyStatement',
  155. ExportBatchSpecifier: 'ExportBatchSpecifier',
  156. ExportDeclaration: 'ExportDeclaration',
  157. ExportSpecifier: 'ExportSpecifier',
  158. ExpressionStatement: 'ExpressionStatement',
  159. ForStatement: 'ForStatement',
  160. ForInStatement: 'ForInStatement',
  161. ForOfStatement: 'ForOfStatement',
  162. FunctionDeclaration: 'FunctionDeclaration',
  163. FunctionExpression: 'FunctionExpression',
  164. GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7.
  165. Identifier: 'Identifier',
  166. IfStatement: 'IfStatement',
  167. ImportDeclaration: 'ImportDeclaration',
  168. ImportDefaultSpecifier: 'ImportDefaultSpecifier',
  169. ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
  170. ImportSpecifier: 'ImportSpecifier',
  171. Literal: 'Literal',
  172. LabeledStatement: 'LabeledStatement',
  173. LogicalExpression: 'LogicalExpression',
  174. MemberExpression: 'MemberExpression',
  175. MethodDefinition: 'MethodDefinition',
  176. ModuleSpecifier: 'ModuleSpecifier',
  177. NewExpression: 'NewExpression',
  178. ObjectExpression: 'ObjectExpression',
  179. ObjectPattern: 'ObjectPattern',
  180. Program: 'Program',
  181. Property: 'Property',
  182. ReturnStatement: 'ReturnStatement',
  183. SequenceExpression: 'SequenceExpression',
  184. SpreadElement: 'SpreadElement',
  185. SwitchStatement: 'SwitchStatement',
  186. SwitchCase: 'SwitchCase',
  187. TaggedTemplateExpression: 'TaggedTemplateExpression',
  188. TemplateElement: 'TemplateElement',
  189. TemplateLiteral: 'TemplateLiteral',
  190. ThisExpression: 'ThisExpression',
  191. ThrowStatement: 'ThrowStatement',
  192. TryStatement: 'TryStatement',
  193. UnaryExpression: 'UnaryExpression',
  194. UpdateExpression: 'UpdateExpression',
  195. VariableDeclaration: 'VariableDeclaration',
  196. VariableDeclarator: 'VariableDeclarator',
  197. WhileStatement: 'WhileStatement',
  198. WithStatement: 'WithStatement',
  199. YieldExpression: 'YieldExpression'
  200. };
  201. VisitorKeys = {
  202. AssignmentExpression: ['left', 'right'],
  203. ArrayExpression: ['elements'],
  204. ArrayPattern: ['elements'],
  205. ArrowFunctionExpression: ['params', 'defaults', 'rest', 'body'],
  206. AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7.
  207. BlockStatement: ['body'],
  208. BinaryExpression: ['left', 'right'],
  209. BreakStatement: ['label'],
  210. CallExpression: ['callee', 'arguments'],
  211. CatchClause: ['param', 'body'],
  212. ClassBody: ['body'],
  213. ClassDeclaration: ['id', 'body', 'superClass'],
  214. ClassExpression: ['id', 'body', 'superClass'],
  215. ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7.
  216. ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7.
  217. ConditionalExpression: ['test', 'consequent', 'alternate'],
  218. ContinueStatement: ['label'],
  219. DebuggerStatement: [],
  220. DirectiveStatement: [],
  221. DoWhileStatement: ['body', 'test'],
  222. EmptyStatement: [],
  223. ExportBatchSpecifier: [],
  224. ExportDeclaration: ['declaration', 'specifiers', 'source'],
  225. ExportSpecifier: ['id', 'name'],
  226. ExpressionStatement: ['expression'],
  227. ForStatement: ['init', 'test', 'update', 'body'],
  228. ForInStatement: ['left', 'right', 'body'],
  229. ForOfStatement: ['left', 'right', 'body'],
  230. FunctionDeclaration: ['id', 'params', 'defaults', 'rest', 'body'],
  231. FunctionExpression: ['id', 'params', 'defaults', 'rest', 'body'],
  232. GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7.
  233. Identifier: [],
  234. IfStatement: ['test', 'consequent', 'alternate'],
  235. ImportDeclaration: ['specifiers', 'source'],
  236. ImportDefaultSpecifier: ['id'],
  237. ImportNamespaceSpecifier: ['id'],
  238. ImportSpecifier: ['id', 'name'],
  239. Literal: [],
  240. LabeledStatement: ['label', 'body'],
  241. LogicalExpression: ['left', 'right'],
  242. MemberExpression: ['object', 'property'],
  243. MethodDefinition: ['key', 'value'],
  244. ModuleSpecifier: [],
  245. NewExpression: ['callee', 'arguments'],
  246. ObjectExpression: ['properties'],
  247. ObjectPattern: ['properties'],
  248. Program: ['body'],
  249. Property: ['key', 'value'],
  250. ReturnStatement: ['argument'],
  251. SequenceExpression: ['expressions'],
  252. SpreadElement: ['argument'],
  253. SwitchStatement: ['discriminant', 'cases'],
  254. SwitchCase: ['test', 'consequent'],
  255. TaggedTemplateExpression: ['tag', 'quasi'],
  256. TemplateElement: [],
  257. TemplateLiteral: ['quasis', 'expressions'],
  258. ThisExpression: [],
  259. ThrowStatement: ['argument'],
  260. TryStatement: ['block', 'handlers', 'handler', 'guardedHandlers', 'finalizer'],
  261. UnaryExpression: ['argument'],
  262. UpdateExpression: ['argument'],
  263. VariableDeclaration: ['declarations'],
  264. VariableDeclarator: ['id', 'init'],
  265. WhileStatement: ['test', 'body'],
  266. WithStatement: ['object', 'body'],
  267. YieldExpression: ['argument']
  268. };
  269. // unique id
  270. BREAK = {};
  271. SKIP = {};
  272. REMOVE = {};
  273. VisitorOption = {
  274. Break: BREAK,
  275. Skip: SKIP,
  276. Remove: REMOVE
  277. };
  278. function Reference(parent, key) {
  279. this.parent = parent;
  280. this.key = key;
  281. }
  282. Reference.prototype.replace = function replace(node) {
  283. this.parent[this.key] = node;
  284. };
  285. Reference.prototype.remove = function remove() {
  286. if (isArray(this.parent)) {
  287. this.parent.splice(this.key, 1);
  288. return true;
  289. } else {
  290. this.replace(null);
  291. return false;
  292. }
  293. };
  294. function Element(node, path, wrap, ref) {
  295. this.node = node;
  296. this.path = path;
  297. this.wrap = wrap;
  298. this.ref = ref;
  299. }
  300. function Controller() { }
  301. // API:
  302. // return property path array from root to current node
  303. Controller.prototype.path = function path() {
  304. var i, iz, j, jz, result, element;
  305. function addToPath(result, path) {
  306. if (isArray(path)) {
  307. for (j = 0, jz = path.length; j < jz; ++j) {
  308. result.push(path[j]);
  309. }
  310. } else {
  311. result.push(path);
  312. }
  313. }
  314. // root node
  315. if (!this.__current.path) {
  316. return null;
  317. }
  318. // first node is sentinel, second node is root element
  319. result = [];
  320. for (i = 2, iz = this.__leavelist.length; i < iz; ++i) {
  321. element = this.__leavelist[i];
  322. addToPath(result, element.path);
  323. }
  324. addToPath(result, this.__current.path);
  325. return result;
  326. };
  327. // API:
  328. // return type of current node
  329. Controller.prototype.type = function () {
  330. var node = this.current();
  331. return node.type || this.__current.wrap;
  332. };
  333. // API:
  334. // return array of parent elements
  335. Controller.prototype.parents = function parents() {
  336. var i, iz, result;
  337. // first node is sentinel
  338. result = [];
  339. for (i = 1, iz = this.__leavelist.length; i < iz; ++i) {
  340. result.push(this.__leavelist[i].node);
  341. }
  342. return result;
  343. };
  344. // API:
  345. // return current node
  346. Controller.prototype.current = function current() {
  347. return this.__current.node;
  348. };
  349. Controller.prototype.__execute = function __execute(callback, element) {
  350. var previous, result;
  351. result = undefined;
  352. previous = this.__current;
  353. this.__current = element;
  354. this.__state = null;
  355. if (callback) {
  356. result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node);
  357. }
  358. this.__current = previous;
  359. return result;
  360. };
  361. // API:
  362. // notify control skip / break
  363. Controller.prototype.notify = function notify(flag) {
  364. this.__state = flag;
  365. };
  366. // API:
  367. // skip child nodes of current node
  368. Controller.prototype.skip = function () {
  369. this.notify(SKIP);
  370. };
  371. // API:
  372. // break traversals
  373. Controller.prototype['break'] = function () {
  374. this.notify(BREAK);
  375. };
  376. // API:
  377. // remove node
  378. Controller.prototype.remove = function () {
  379. this.notify(REMOVE);
  380. };
  381. Controller.prototype.__initialize = function(root, visitor) {
  382. this.visitor = visitor;
  383. this.root = root;
  384. this.__worklist = [];
  385. this.__leavelist = [];
  386. this.__current = null;
  387. this.__state = null;
  388. this.__fallback = visitor.fallback === 'iteration';
  389. this.__keys = VisitorKeys;
  390. if (visitor.keys) {
  391. this.__keys = extend(objectCreate(this.__keys), visitor.keys);
  392. }
  393. };
  394. function isNode(node) {
  395. if (node == null) {
  396. return false;
  397. }
  398. return typeof node === 'object' && typeof node.type === 'string';
  399. }
  400. function isProperty(nodeType, key) {
  401. return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key;
  402. }
  403. Controller.prototype.traverse = function traverse(root, visitor) {
  404. var worklist,
  405. leavelist,
  406. element,
  407. node,
  408. nodeType,
  409. ret,
  410. key,
  411. current,
  412. current2,
  413. candidates,
  414. candidate,
  415. sentinel;
  416. this.__initialize(root, visitor);
  417. sentinel = {};
  418. // reference
  419. worklist = this.__worklist;
  420. leavelist = this.__leavelist;
  421. // initialize
  422. worklist.push(new Element(root, null, null, null));
  423. leavelist.push(new Element(null, null, null, null));
  424. while (worklist.length) {
  425. element = worklist.pop();
  426. if (element === sentinel) {
  427. element = leavelist.pop();
  428. ret = this.__execute(visitor.leave, element);
  429. if (this.__state === BREAK || ret === BREAK) {
  430. return;
  431. }
  432. continue;
  433. }
  434. if (element.node) {
  435. ret = this.__execute(visitor.enter, element);
  436. if (this.__state === BREAK || ret === BREAK) {
  437. return;
  438. }
  439. worklist.push(sentinel);
  440. leavelist.push(element);
  441. if (this.__state === SKIP || ret === SKIP) {
  442. continue;
  443. }
  444. node = element.node;
  445. nodeType = element.wrap || node.type;
  446. candidates = this.__keys[nodeType];
  447. if (!candidates) {
  448. if (this.__fallback) {
  449. candidates = objectKeys(node);
  450. } else {
  451. throw new Error('Unknown node type ' + nodeType + '.');
  452. }
  453. }
  454. current = candidates.length;
  455. while ((current -= 1) >= 0) {
  456. key = candidates[current];
  457. candidate = node[key];
  458. if (!candidate) {
  459. continue;
  460. }
  461. if (isArray(candidate)) {
  462. current2 = candidate.length;
  463. while ((current2 -= 1) >= 0) {
  464. if (!candidate[current2]) {
  465. continue;
  466. }
  467. if (isProperty(nodeType, candidates[current])) {
  468. element = new Element(candidate[current2], [key, current2], 'Property', null);
  469. } else if (isNode(candidate[current2])) {
  470. element = new Element(candidate[current2], [key, current2], null, null);
  471. } else {
  472. continue;
  473. }
  474. worklist.push(element);
  475. }
  476. } else if (isNode(candidate)) {
  477. worklist.push(new Element(candidate, key, null, null));
  478. }
  479. }
  480. }
  481. }
  482. };
  483. Controller.prototype.replace = function replace(root, visitor) {
  484. function removeElem(element) {
  485. var i,
  486. key,
  487. nextElem,
  488. parent;
  489. if (element.ref.remove()) {
  490. // When the reference is an element of an array.
  491. key = element.ref.key;
  492. parent = element.ref.parent;
  493. // If removed from array, then decrease following items' keys.
  494. i = worklist.length;
  495. while (i--) {
  496. nextElem = worklist[i];
  497. if (nextElem.ref && nextElem.ref.parent === parent) {
  498. if (nextElem.ref.key < key) {
  499. break;
  500. }
  501. --nextElem.ref.key;
  502. }
  503. }
  504. }
  505. }
  506. var worklist,
  507. leavelist,
  508. node,
  509. nodeType,
  510. target,
  511. element,
  512. current,
  513. current2,
  514. candidates,
  515. candidate,
  516. sentinel,
  517. outer,
  518. key;
  519. this.__initialize(root, visitor);
  520. sentinel = {};
  521. // reference
  522. worklist = this.__worklist;
  523. leavelist = this.__leavelist;
  524. // initialize
  525. outer = {
  526. root: root
  527. };
  528. element = new Element(root, null, null, new Reference(outer, 'root'));
  529. worklist.push(element);
  530. leavelist.push(element);
  531. while (worklist.length) {
  532. element = worklist.pop();
  533. if (element === sentinel) {
  534. element = leavelist.pop();
  535. target = this.__execute(visitor.leave, element);
  536. // node may be replaced with null,
  537. // so distinguish between undefined and null in this place
  538. if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {
  539. // replace
  540. element.ref.replace(target);
  541. }
  542. if (this.__state === REMOVE || target === REMOVE) {
  543. removeElem(element);
  544. }
  545. if (this.__state === BREAK || target === BREAK) {
  546. return outer.root;
  547. }
  548. continue;
  549. }
  550. target = this.__execute(visitor.enter, element);
  551. // node may be replaced with null,
  552. // so distinguish between undefined and null in this place
  553. if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) {
  554. // replace
  555. element.ref.replace(target);
  556. element.node = target;
  557. }
  558. if (this.__state === REMOVE || target === REMOVE) {
  559. removeElem(element);
  560. element.node = null;
  561. }
  562. if (this.__state === BREAK || target === BREAK) {
  563. return outer.root;
  564. }
  565. // node may be null
  566. node = element.node;
  567. if (!node) {
  568. continue;
  569. }
  570. worklist.push(sentinel);
  571. leavelist.push(element);
  572. if (this.__state === SKIP || target === SKIP) {
  573. continue;
  574. }
  575. nodeType = element.wrap || node.type;
  576. candidates = this.__keys[nodeType];
  577. if (!candidates) {
  578. if (this.__fallback) {
  579. candidates = objectKeys(node);
  580. } else {
  581. throw new Error('Unknown node type ' + nodeType + '.');
  582. }
  583. }
  584. current = candidates.length;
  585. while ((current -= 1) >= 0) {
  586. key = candidates[current];
  587. candidate = node[key];
  588. if (!candidate) {
  589. continue;
  590. }
  591. if (isArray(candidate)) {
  592. current2 = candidate.length;
  593. while ((current2 -= 1) >= 0) {
  594. if (!candidate[current2]) {
  595. continue;
  596. }
  597. if (isProperty(nodeType, candidates[current])) {
  598. element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2));
  599. } else if (isNode(candidate[current2])) {
  600. element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2));
  601. } else {
  602. continue;
  603. }
  604. worklist.push(element);
  605. }
  606. } else if (isNode(candidate)) {
  607. worklist.push(new Element(candidate, key, null, new Reference(node, key)));
  608. }
  609. }
  610. }
  611. return outer.root;
  612. };
  613. function traverse(root, visitor) {
  614. var controller = new Controller();
  615. return controller.traverse(root, visitor);
  616. }
  617. function replace(root, visitor) {
  618. var controller = new Controller();
  619. return controller.replace(root, visitor);
  620. }
  621. function extendCommentRange(comment, tokens) {
  622. var target;
  623. target = upperBound(tokens, function search(token) {
  624. return token.range[0] > comment.range[0];
  625. });
  626. comment.extendedRange = [comment.range[0], comment.range[1]];
  627. if (target !== tokens.length) {
  628. comment.extendedRange[1] = tokens[target].range[0];
  629. }
  630. target -= 1;
  631. if (target >= 0) {
  632. comment.extendedRange[0] = tokens[target].range[1];
  633. }
  634. return comment;
  635. }
  636. function attachComments(tree, providedComments, tokens) {
  637. // At first, we should calculate extended comment ranges.
  638. var comments = [], comment, len, i, cursor;
  639. if (!tree.range) {
  640. throw new Error('attachComments needs range information');
  641. }
  642. // tokens array is empty, we attach comments to tree as 'leadingComments'
  643. if (!tokens.length) {
  644. if (providedComments.length) {
  645. for (i = 0, len = providedComments.length; i < len; i += 1) {
  646. comment = deepCopy(providedComments[i]);
  647. comment.extendedRange = [0, tree.range[0]];
  648. comments.push(comment);
  649. }
  650. tree.leadingComments = comments;
  651. }
  652. return tree;
  653. }
  654. for (i = 0, len = providedComments.length; i < len; i += 1) {
  655. comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens));
  656. }
  657. // This is based on John Freeman's implementation.
  658. cursor = 0;
  659. traverse(tree, {
  660. enter: function (node) {
  661. var comment;
  662. while (cursor < comments.length) {
  663. comment = comments[cursor];
  664. if (comment.extendedRange[1] > node.range[0]) {
  665. break;
  666. }
  667. if (comment.extendedRange[1] === node.range[0]) {
  668. if (!node.leadingComments) {
  669. node.leadingComments = [];
  670. }
  671. node.leadingComments.push(comment);
  672. comments.splice(cursor, 1);
  673. } else {
  674. cursor += 1;
  675. }
  676. }
  677. // already out of owned node
  678. if (cursor === comments.length) {
  679. return VisitorOption.Break;
  680. }
  681. if (comments[cursor].extendedRange[0] > node.range[1]) {
  682. return VisitorOption.Skip;
  683. }
  684. }
  685. });
  686. cursor = 0;
  687. traverse(tree, {
  688. leave: function (node) {
  689. var comment;
  690. while (cursor < comments.length) {
  691. comment = comments[cursor];
  692. if (node.range[1] < comment.extendedRange[0]) {
  693. break;
  694. }
  695. if (node.range[1] === comment.extendedRange[0]) {
  696. if (!node.trailingComments) {
  697. node.trailingComments = [];
  698. }
  699. node.trailingComments.push(comment);
  700. comments.splice(cursor, 1);
  701. } else {
  702. cursor += 1;
  703. }
  704. }
  705. // already out of owned node
  706. if (cursor === comments.length) {
  707. return VisitorOption.Break;
  708. }
  709. if (comments[cursor].extendedRange[0] > node.range[1]) {
  710. return VisitorOption.Skip;
  711. }
  712. }
  713. });
  714. return tree;
  715. }
  716. exports.version = '1.8.1-dev';
  717. exports.Syntax = Syntax;
  718. exports.traverse = traverse;
  719. exports.replace = replace;
  720. exports.attachComments = attachComments;
  721. exports.VisitorKeys = VisitorKeys;
  722. exports.VisitorOption = VisitorOption;
  723. exports.Controller = Controller;
  724. exports.cloneEnvironment = function () { return clone({}); };
  725. return exports;
  726. }));
  727. /* vim: set sw=4 ts=4 et tw=80 : */