index.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. /**
  2. * The MIT License (MIT)
  3. * Copyright (c) 2017-present Dmitry Soshnikov <dmitry.soshnikov@gmail.com>
  4. */
  5. 'use strict';
  6. var NodePath = require('./node-path');
  7. /**
  8. * Does an actual AST traversal, using visitor pattern,
  9. * and calling set of callbacks.
  10. *
  11. * Based on https://github.com/olov/ast-traverse
  12. *
  13. * Expects AST in Mozilla Parser API: nodes which are supposed to be
  14. * handled should have `type` property.
  15. *
  16. * @param Object root - a root node to start traversal from.
  17. *
  18. * @param Object options - an object with set of callbacks:
  19. *
  20. * - `pre(node, parent, prop, index)` - a hook called on node enter
  21. * - `post`(node, parent, prop, index) - a hook called on node exit
  22. * - `skipProperty(prop)` - a predicated whether a property should be skipped
  23. */
  24. function astTraverse(root) {
  25. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  26. var pre = options.pre;
  27. var post = options.post;
  28. var skipProperty = options.skipProperty;
  29. function visit(node, parent, prop, idx) {
  30. if (!node || typeof node.type !== 'string') {
  31. return;
  32. }
  33. var res = undefined;
  34. if (pre) {
  35. res = pre(node, parent, prop, idx);
  36. }
  37. if (res !== false) {
  38. // A node can be replaced during traversal, so we have to
  39. // recalculate it from the parent, to avoid traversing "dead" nodes.
  40. if (parent && parent[prop]) {
  41. if (!isNaN(idx)) {
  42. node = parent[prop][idx];
  43. } else {
  44. node = parent[prop];
  45. }
  46. }
  47. for (var _prop in node) {
  48. if (node.hasOwnProperty(_prop)) {
  49. if (skipProperty ? skipProperty(_prop, node) : _prop[0] === '$') {
  50. continue;
  51. }
  52. var child = node[_prop];
  53. // Collection node.
  54. //
  55. // NOTE: a node (or several nodes) can be removed or inserted
  56. // during traversal.
  57. //
  58. // Current traversing index is stored on top of the
  59. // `NodePath.traversingIndexStack`. The stack is used to support
  60. // recursive nature of the traversal.
  61. //
  62. // In this case `NodePath.traversingIndex` (which we use here) is
  63. // updated in the NodePath remove/insert methods.
  64. //
  65. if (Array.isArray(child)) {
  66. var index = 0;
  67. NodePath.traversingIndexStack.push(index);
  68. while (index < child.length) {
  69. visit(child[index], node, _prop, index);
  70. index = NodePath.updateTraversingIndex(+1);
  71. }
  72. NodePath.traversingIndexStack.pop();
  73. }
  74. // Simple node.
  75. else {
  76. visit(child, node, _prop);
  77. }
  78. }
  79. }
  80. }
  81. if (post) {
  82. post(node, parent, prop, idx);
  83. }
  84. }
  85. visit(root, null);
  86. }
  87. module.exports = {
  88. /**
  89. * Traverses an AST.
  90. *
  91. * @param Object ast - an AST node
  92. *
  93. * @param Object | Array<Object> handlers:
  94. *
  95. * an object (or an array of objects)
  96. *
  97. * Each such object contains a handler function per node.
  98. * In case of an array of handlers, they are applied in order.
  99. * A handler may return a transformed node (or a different type).
  100. *
  101. * The per-node function may instead be an object with functions pre and post.
  102. * pre is called before visiting the node, post after.
  103. * If a handler is a function, it is treated as the pre function, with an empty post.
  104. *
  105. * @param Object options:
  106. *
  107. * a config object, specifying traversal options:
  108. *
  109. * `asNodes`: boolean - whether handlers should receives raw AST nodes
  110. * (false by default), instead of a `NodePath` wrapper. Note, by default
  111. * `NodePath` wrapper provides a set of convenient method to manipulate
  112. * a traversing AST, and also has access to all parents list. A raw
  113. * nodes traversal should be used in rare cases, when no `NodePath`
  114. * features are needed.
  115. *
  116. * Special hooks:
  117. *
  118. * - `shouldRun(ast)` - a predicate determining whether the handler
  119. * should be applied.
  120. *
  121. * NOTE: Multiple handlers are used as an optimization of applying all of
  122. * them in one AST traversal pass.
  123. */
  124. traverse: function traverse(ast, handlers) {
  125. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { asNodes: false };
  126. if (!Array.isArray(handlers)) {
  127. handlers = [handlers];
  128. }
  129. // Filter out handlers by result of `shouldRun`, if the method is present.
  130. handlers = handlers.filter(function (handler) {
  131. if (typeof handler.shouldRun !== 'function') {
  132. return true;
  133. }
  134. return handler.shouldRun(ast);
  135. });
  136. NodePath.initRegistry();
  137. // Allow handlers to initializer themselves.
  138. handlers.forEach(function (handler) {
  139. if (typeof handler.init === 'function') {
  140. handler.init(ast);
  141. }
  142. });
  143. function getPathFor(node, parent, prop, index) {
  144. var parentPath = NodePath.getForNode(parent);
  145. var nodePath = NodePath.getForNode(node, parentPath, prop, index);
  146. return nodePath;
  147. }
  148. // Handle actual nodes.
  149. astTraverse(ast, {
  150. /**
  151. * Handler on node enter.
  152. */
  153. pre: function pre(node, parent, prop, index) {
  154. var nodePath = void 0;
  155. if (!options.asNodes) {
  156. nodePath = getPathFor(node, parent, prop, index);
  157. }
  158. var _iteratorNormalCompletion = true;
  159. var _didIteratorError = false;
  160. var _iteratorError = undefined;
  161. try {
  162. for (var _iterator = handlers[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  163. var handler = _step.value;
  164. // "Catch-all" `*` handler.
  165. if (typeof handler['*'] === 'function') {
  166. if (nodePath) {
  167. // A path/node can be removed by some previous handler.
  168. if (!nodePath.isRemoved()) {
  169. var handlerResult = handler['*'](nodePath);
  170. // Explicitly stop traversal.
  171. if (handlerResult === false) {
  172. return false;
  173. }
  174. }
  175. } else {
  176. handler['*'](node, parent, prop, index);
  177. }
  178. }
  179. // Per-node handler.
  180. var handlerFuncPre = void 0;
  181. if (typeof handler[node.type] === 'function') {
  182. handlerFuncPre = handler[node.type];
  183. } else if (typeof handler[node.type] === 'object' && typeof handler[node.type].pre === 'function') {
  184. handlerFuncPre = handler[node.type].pre;
  185. }
  186. if (handlerFuncPre) {
  187. if (nodePath) {
  188. // A path/node can be removed by some previous handler.
  189. if (!nodePath.isRemoved()) {
  190. var _handlerResult = handlerFuncPre.call(handler, nodePath);
  191. // Explicitly stop traversal.
  192. if (_handlerResult === false) {
  193. return false;
  194. }
  195. }
  196. } else {
  197. handlerFuncPre.call(handler, node, parent, prop, index);
  198. }
  199. }
  200. } // Loop over handlers
  201. } catch (err) {
  202. _didIteratorError = true;
  203. _iteratorError = err;
  204. } finally {
  205. try {
  206. if (!_iteratorNormalCompletion && _iterator.return) {
  207. _iterator.return();
  208. }
  209. } finally {
  210. if (_didIteratorError) {
  211. throw _iteratorError;
  212. }
  213. }
  214. }
  215. },
  216. // pre func
  217. /**
  218. * Handler on node exit.
  219. */
  220. post: function post(node, parent, prop, index) {
  221. if (!node) {
  222. return;
  223. }
  224. var nodePath = void 0;
  225. if (!options.asNodes) {
  226. nodePath = getPathFor(node, parent, prop, index);
  227. }
  228. var _iteratorNormalCompletion2 = true;
  229. var _didIteratorError2 = false;
  230. var _iteratorError2 = undefined;
  231. try {
  232. for (var _iterator2 = handlers[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
  233. var handler = _step2.value;
  234. // Per-node handler.
  235. var handlerFuncPost = void 0;
  236. if (typeof handler[node.type] === 'object' && typeof handler[node.type].post === 'function') {
  237. handlerFuncPost = handler[node.type].post;
  238. }
  239. if (handlerFuncPost) {
  240. if (nodePath) {
  241. // A path/node can be removed by some previous handler.
  242. if (!nodePath.isRemoved()) {
  243. var handlerResult = handlerFuncPost.call(handler, nodePath);
  244. // Explicitly stop traversal.
  245. if (handlerResult === false) {
  246. return false;
  247. }
  248. }
  249. } else {
  250. handlerFuncPost.call(handler, node, parent, prop, index);
  251. }
  252. }
  253. } // Loop over handlers
  254. } catch (err) {
  255. _didIteratorError2 = true;
  256. _iteratorError2 = err;
  257. } finally {
  258. try {
  259. if (!_iteratorNormalCompletion2 && _iterator2.return) {
  260. _iterator2.return();
  261. }
  262. } finally {
  263. if (_didIteratorError2) {
  264. throw _iteratorError2;
  265. }
  266. }
  267. }
  268. },
  269. // post func
  270. /**
  271. * Skip locations by default.
  272. */
  273. skipProperty: function skipProperty(prop) {
  274. return prop === 'loc';
  275. }
  276. });
  277. }
  278. };