visit.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. import { isDocument, isNode, isPair, isCollection, isMap, isSeq, isScalar, isAlias } from './nodes/identity.js';
  2. const BREAK = Symbol('break visit');
  3. const SKIP = Symbol('skip children');
  4. const REMOVE = Symbol('remove node');
  5. /**
  6. * Apply a visitor to an AST node or document.
  7. *
  8. * Walks through the tree (depth-first) starting from `node`, calling a
  9. * `visitor` function with three arguments:
  10. * - `key`: For sequence values and map `Pair`, the node's index in the
  11. * collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.
  12. * `null` for the root node.
  13. * - `node`: The current node.
  14. * - `path`: The ancestry of the current node.
  15. *
  16. * The return value of the visitor may be used to control the traversal:
  17. * - `undefined` (default): Do nothing and continue
  18. * - `visit.SKIP`: Do not visit the children of this node, continue with next
  19. * sibling
  20. * - `visit.BREAK`: Terminate traversal completely
  21. * - `visit.REMOVE`: Remove the current node, then continue with the next one
  22. * - `Node`: Replace the current node, then continue by visiting it
  23. * - `number`: While iterating the items of a sequence or map, set the index
  24. * of the next step. This is useful especially if the index of the current
  25. * node has changed.
  26. *
  27. * If `visitor` is a single function, it will be called with all values
  28. * encountered in the tree, including e.g. `null` values. Alternatively,
  29. * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,
  30. * `Alias` and `Scalar` node. To define the same visitor function for more than
  31. * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)
  32. * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most
  33. * specific defined one will be used for each node.
  34. */
  35. function visit(node, visitor) {
  36. const visitor_ = initVisitor(visitor);
  37. if (isDocument(node)) {
  38. const cd = visit_(null, node.contents, visitor_, Object.freeze([node]));
  39. if (cd === REMOVE)
  40. node.contents = null;
  41. }
  42. else
  43. visit_(null, node, visitor_, Object.freeze([]));
  44. }
  45. // Without the `as symbol` casts, TS declares these in the `visit`
  46. // namespace using `var`, but then complains about that because
  47. // `unique symbol` must be `const`.
  48. /** Terminate visit traversal completely */
  49. visit.BREAK = BREAK;
  50. /** Do not visit the children of the current node */
  51. visit.SKIP = SKIP;
  52. /** Remove the current node */
  53. visit.REMOVE = REMOVE;
  54. function visit_(key, node, visitor, path) {
  55. const ctrl = callVisitor(key, node, visitor, path);
  56. if (isNode(ctrl) || isPair(ctrl)) {
  57. replaceNode(key, path, ctrl);
  58. return visit_(key, ctrl, visitor, path);
  59. }
  60. if (typeof ctrl !== 'symbol') {
  61. if (isCollection(node)) {
  62. path = Object.freeze(path.concat(node));
  63. for (let i = 0; i < node.items.length; ++i) {
  64. const ci = visit_(i, node.items[i], visitor, path);
  65. if (typeof ci === 'number')
  66. i = ci - 1;
  67. else if (ci === BREAK)
  68. return BREAK;
  69. else if (ci === REMOVE) {
  70. node.items.splice(i, 1);
  71. i -= 1;
  72. }
  73. }
  74. }
  75. else if (isPair(node)) {
  76. path = Object.freeze(path.concat(node));
  77. const ck = visit_('key', node.key, visitor, path);
  78. if (ck === BREAK)
  79. return BREAK;
  80. else if (ck === REMOVE)
  81. node.key = null;
  82. const cv = visit_('value', node.value, visitor, path);
  83. if (cv === BREAK)
  84. return BREAK;
  85. else if (cv === REMOVE)
  86. node.value = null;
  87. }
  88. }
  89. return ctrl;
  90. }
  91. /**
  92. * Apply an async visitor to an AST node or document.
  93. *
  94. * Walks through the tree (depth-first) starting from `node`, calling a
  95. * `visitor` function with three arguments:
  96. * - `key`: For sequence values and map `Pair`, the node's index in the
  97. * collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.
  98. * `null` for the root node.
  99. * - `node`: The current node.
  100. * - `path`: The ancestry of the current node.
  101. *
  102. * The return value of the visitor may be used to control the traversal:
  103. * - `Promise`: Must resolve to one of the following values
  104. * - `undefined` (default): Do nothing and continue
  105. * - `visit.SKIP`: Do not visit the children of this node, continue with next
  106. * sibling
  107. * - `visit.BREAK`: Terminate traversal completely
  108. * - `visit.REMOVE`: Remove the current node, then continue with the next one
  109. * - `Node`: Replace the current node, then continue by visiting it
  110. * - `number`: While iterating the items of a sequence or map, set the index
  111. * of the next step. This is useful especially if the index of the current
  112. * node has changed.
  113. *
  114. * If `visitor` is a single function, it will be called with all values
  115. * encountered in the tree, including e.g. `null` values. Alternatively,
  116. * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,
  117. * `Alias` and `Scalar` node. To define the same visitor function for more than
  118. * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)
  119. * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most
  120. * specific defined one will be used for each node.
  121. */
  122. async function visitAsync(node, visitor) {
  123. const visitor_ = initVisitor(visitor);
  124. if (isDocument(node)) {
  125. const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node]));
  126. if (cd === REMOVE)
  127. node.contents = null;
  128. }
  129. else
  130. await visitAsync_(null, node, visitor_, Object.freeze([]));
  131. }
  132. // Without the `as symbol` casts, TS declares these in the `visit`
  133. // namespace using `var`, but then complains about that because
  134. // `unique symbol` must be `const`.
  135. /** Terminate visit traversal completely */
  136. visitAsync.BREAK = BREAK;
  137. /** Do not visit the children of the current node */
  138. visitAsync.SKIP = SKIP;
  139. /** Remove the current node */
  140. visitAsync.REMOVE = REMOVE;
  141. async function visitAsync_(key, node, visitor, path) {
  142. const ctrl = await callVisitor(key, node, visitor, path);
  143. if (isNode(ctrl) || isPair(ctrl)) {
  144. replaceNode(key, path, ctrl);
  145. return visitAsync_(key, ctrl, visitor, path);
  146. }
  147. if (typeof ctrl !== 'symbol') {
  148. if (isCollection(node)) {
  149. path = Object.freeze(path.concat(node));
  150. for (let i = 0; i < node.items.length; ++i) {
  151. const ci = await visitAsync_(i, node.items[i], visitor, path);
  152. if (typeof ci === 'number')
  153. i = ci - 1;
  154. else if (ci === BREAK)
  155. return BREAK;
  156. else if (ci === REMOVE) {
  157. node.items.splice(i, 1);
  158. i -= 1;
  159. }
  160. }
  161. }
  162. else if (isPair(node)) {
  163. path = Object.freeze(path.concat(node));
  164. const ck = await visitAsync_('key', node.key, visitor, path);
  165. if (ck === BREAK)
  166. return BREAK;
  167. else if (ck === REMOVE)
  168. node.key = null;
  169. const cv = await visitAsync_('value', node.value, visitor, path);
  170. if (cv === BREAK)
  171. return BREAK;
  172. else if (cv === REMOVE)
  173. node.value = null;
  174. }
  175. }
  176. return ctrl;
  177. }
  178. function initVisitor(visitor) {
  179. if (typeof visitor === 'object' &&
  180. (visitor.Collection || visitor.Node || visitor.Value)) {
  181. return Object.assign({
  182. Alias: visitor.Node,
  183. Map: visitor.Node,
  184. Scalar: visitor.Node,
  185. Seq: visitor.Node
  186. }, visitor.Value && {
  187. Map: visitor.Value,
  188. Scalar: visitor.Value,
  189. Seq: visitor.Value
  190. }, visitor.Collection && {
  191. Map: visitor.Collection,
  192. Seq: visitor.Collection
  193. }, visitor);
  194. }
  195. return visitor;
  196. }
  197. function callVisitor(key, node, visitor, path) {
  198. if (typeof visitor === 'function')
  199. return visitor(key, node, path);
  200. if (isMap(node))
  201. return visitor.Map?.(key, node, path);
  202. if (isSeq(node))
  203. return visitor.Seq?.(key, node, path);
  204. if (isPair(node))
  205. return visitor.Pair?.(key, node, path);
  206. if (isScalar(node))
  207. return visitor.Scalar?.(key, node, path);
  208. if (isAlias(node))
  209. return visitor.Alias?.(key, node, path);
  210. return undefined;
  211. }
  212. function replaceNode(key, path, node) {
  213. const parent = path[path.length - 1];
  214. if (isCollection(parent)) {
  215. parent.items[key] = node;
  216. }
  217. else if (isPair(parent)) {
  218. if (key === 'key')
  219. parent.key = node;
  220. else
  221. parent.value = node;
  222. }
  223. else if (isDocument(parent)) {
  224. parent.contents = node;
  225. }
  226. else {
  227. const pt = isAlias(parent) ? 'alias' : 'scalar';
  228. throw new Error(`Cannot replace node with ${pt} parent`);
  229. }
  230. }
  231. export { visit, visitAsync };