Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

estraverse.js 26KB

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