estraverse-bundle.js 27 KB

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