Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

estraverse.js 26KB

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