estraverse.js 26 KB

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