estraverse.js 27 KB

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