visitor.mjs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. import inspect from "../jsutils/inspect.mjs";
  2. import { isNode } from "./ast.mjs";
  3. /**
  4. * A visitor is provided to visit, it contains the collection of
  5. * relevant functions to be called during the visitor's traversal.
  6. */
  7. export var QueryDocumentKeys = {
  8. Name: [],
  9. Document: ['definitions'],
  10. OperationDefinition: ['name', 'variableDefinitions', 'directives', 'selectionSet'],
  11. VariableDefinition: ['variable', 'type', 'defaultValue', 'directives'],
  12. Variable: ['name'],
  13. SelectionSet: ['selections'],
  14. Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'],
  15. Argument: ['name', 'value'],
  16. FragmentSpread: ['name', 'directives'],
  17. InlineFragment: ['typeCondition', 'directives', 'selectionSet'],
  18. FragmentDefinition: ['name', // Note: fragment variable definitions are experimental and may be changed
  19. // or removed in the future.
  20. 'variableDefinitions', 'typeCondition', 'directives', 'selectionSet'],
  21. IntValue: [],
  22. FloatValue: [],
  23. StringValue: [],
  24. BooleanValue: [],
  25. NullValue: [],
  26. EnumValue: [],
  27. ListValue: ['values'],
  28. ObjectValue: ['fields'],
  29. ObjectField: ['name', 'value'],
  30. Directive: ['name', 'arguments'],
  31. NamedType: ['name'],
  32. ListType: ['type'],
  33. NonNullType: ['type'],
  34. SchemaDefinition: ['description', 'directives', 'operationTypes'],
  35. OperationTypeDefinition: ['type'],
  36. ScalarTypeDefinition: ['description', 'name', 'directives'],
  37. ObjectTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'],
  38. FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'],
  39. InputValueDefinition: ['description', 'name', 'type', 'defaultValue', 'directives'],
  40. InterfaceTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'],
  41. UnionTypeDefinition: ['description', 'name', 'directives', 'types'],
  42. EnumTypeDefinition: ['description', 'name', 'directives', 'values'],
  43. EnumValueDefinition: ['description', 'name', 'directives'],
  44. InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'],
  45. DirectiveDefinition: ['description', 'name', 'arguments', 'locations'],
  46. SchemaExtension: ['directives', 'operationTypes'],
  47. ScalarTypeExtension: ['name', 'directives'],
  48. ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'],
  49. InterfaceTypeExtension: ['name', 'interfaces', 'directives', 'fields'],
  50. UnionTypeExtension: ['name', 'directives', 'types'],
  51. EnumTypeExtension: ['name', 'directives', 'values'],
  52. InputObjectTypeExtension: ['name', 'directives', 'fields']
  53. };
  54. export var BREAK = Object.freeze({});
  55. /**
  56. * visit() will walk through an AST using a depth-first traversal, calling
  57. * the visitor's enter function at each node in the traversal, and calling the
  58. * leave function after visiting that node and all of its child nodes.
  59. *
  60. * By returning different values from the enter and leave functions, the
  61. * behavior of the visitor can be altered, including skipping over a sub-tree of
  62. * the AST (by returning false), editing the AST by returning a value or null
  63. * to remove the value, or to stop the whole traversal by returning BREAK.
  64. *
  65. * When using visit() to edit an AST, the original AST will not be modified, and
  66. * a new version of the AST with the changes applied will be returned from the
  67. * visit function.
  68. *
  69. * const editedAST = visit(ast, {
  70. * enter(node, key, parent, path, ancestors) {
  71. * // @return
  72. * // undefined: no action
  73. * // false: skip visiting this node
  74. * // visitor.BREAK: stop visiting altogether
  75. * // null: delete this node
  76. * // any value: replace this node with the returned value
  77. * },
  78. * leave(node, key, parent, path, ancestors) {
  79. * // @return
  80. * // undefined: no action
  81. * // false: no action
  82. * // visitor.BREAK: stop visiting altogether
  83. * // null: delete this node
  84. * // any value: replace this node with the returned value
  85. * }
  86. * });
  87. *
  88. * Alternatively to providing enter() and leave() functions, a visitor can
  89. * instead provide functions named the same as the kinds of AST nodes, or
  90. * enter/leave visitors at a named key, leading to four permutations of the
  91. * visitor API:
  92. *
  93. * 1) Named visitors triggered when entering a node of a specific kind.
  94. *
  95. * visit(ast, {
  96. * Kind(node) {
  97. * // enter the "Kind" node
  98. * }
  99. * })
  100. *
  101. * 2) Named visitors that trigger upon entering and leaving a node of
  102. * a specific kind.
  103. *
  104. * visit(ast, {
  105. * Kind: {
  106. * enter(node) {
  107. * // enter the "Kind" node
  108. * }
  109. * leave(node) {
  110. * // leave the "Kind" node
  111. * }
  112. * }
  113. * })
  114. *
  115. * 3) Generic visitors that trigger upon entering and leaving any node.
  116. *
  117. * visit(ast, {
  118. * enter(node) {
  119. * // enter any node
  120. * },
  121. * leave(node) {
  122. * // leave any node
  123. * }
  124. * })
  125. *
  126. * 4) Parallel visitors for entering and leaving nodes of a specific kind.
  127. *
  128. * visit(ast, {
  129. * enter: {
  130. * Kind(node) {
  131. * // enter the "Kind" node
  132. * }
  133. * },
  134. * leave: {
  135. * Kind(node) {
  136. * // leave the "Kind" node
  137. * }
  138. * }
  139. * })
  140. */
  141. export function visit(root, visitor) {
  142. var visitorKeys = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : QueryDocumentKeys;
  143. /* eslint-disable no-undef-init */
  144. var stack = undefined;
  145. var inArray = Array.isArray(root);
  146. var keys = [root];
  147. var index = -1;
  148. var edits = [];
  149. var node = undefined;
  150. var key = undefined;
  151. var parent = undefined;
  152. var path = [];
  153. var ancestors = [];
  154. var newRoot = root;
  155. /* eslint-enable no-undef-init */
  156. do {
  157. index++;
  158. var isLeaving = index === keys.length;
  159. var isEdited = isLeaving && edits.length !== 0;
  160. if (isLeaving) {
  161. key = ancestors.length === 0 ? undefined : path[path.length - 1];
  162. node = parent;
  163. parent = ancestors.pop();
  164. if (isEdited) {
  165. if (inArray) {
  166. node = node.slice();
  167. } else {
  168. var clone = {};
  169. for (var _i2 = 0, _Object$keys2 = Object.keys(node); _i2 < _Object$keys2.length; _i2++) {
  170. var k = _Object$keys2[_i2];
  171. clone[k] = node[k];
  172. }
  173. node = clone;
  174. }
  175. var editOffset = 0;
  176. for (var ii = 0; ii < edits.length; ii++) {
  177. var editKey = edits[ii][0];
  178. var editValue = edits[ii][1];
  179. if (inArray) {
  180. editKey -= editOffset;
  181. }
  182. if (inArray && editValue === null) {
  183. node.splice(editKey, 1);
  184. editOffset++;
  185. } else {
  186. node[editKey] = editValue;
  187. }
  188. }
  189. }
  190. index = stack.index;
  191. keys = stack.keys;
  192. edits = stack.edits;
  193. inArray = stack.inArray;
  194. stack = stack.prev;
  195. } else {
  196. key = parent ? inArray ? index : keys[index] : undefined;
  197. node = parent ? parent[key] : newRoot;
  198. if (node === null || node === undefined) {
  199. continue;
  200. }
  201. if (parent) {
  202. path.push(key);
  203. }
  204. }
  205. var result = void 0;
  206. if (!Array.isArray(node)) {
  207. if (!isNode(node)) {
  208. throw new Error("Invalid AST Node: ".concat(inspect(node), "."));
  209. }
  210. var visitFn = getVisitFn(visitor, node.kind, isLeaving);
  211. if (visitFn) {
  212. result = visitFn.call(visitor, node, key, parent, path, ancestors);
  213. if (result === BREAK) {
  214. break;
  215. }
  216. if (result === false) {
  217. if (!isLeaving) {
  218. path.pop();
  219. continue;
  220. }
  221. } else if (result !== undefined) {
  222. edits.push([key, result]);
  223. if (!isLeaving) {
  224. if (isNode(result)) {
  225. node = result;
  226. } else {
  227. path.pop();
  228. continue;
  229. }
  230. }
  231. }
  232. }
  233. }
  234. if (result === undefined && isEdited) {
  235. edits.push([key, node]);
  236. }
  237. if (isLeaving) {
  238. path.pop();
  239. } else {
  240. var _visitorKeys$node$kin;
  241. stack = {
  242. inArray: inArray,
  243. index: index,
  244. keys: keys,
  245. edits: edits,
  246. prev: stack
  247. };
  248. inArray = Array.isArray(node);
  249. keys = inArray ? node : (_visitorKeys$node$kin = visitorKeys[node.kind]) !== null && _visitorKeys$node$kin !== void 0 ? _visitorKeys$node$kin : [];
  250. index = -1;
  251. edits = [];
  252. if (parent) {
  253. ancestors.push(parent);
  254. }
  255. parent = node;
  256. }
  257. } while (stack !== undefined);
  258. if (edits.length !== 0) {
  259. newRoot = edits[edits.length - 1][1];
  260. }
  261. return newRoot;
  262. }
  263. /**
  264. * Creates a new visitor instance which delegates to many visitors to run in
  265. * parallel. Each visitor will be visited for each node before moving on.
  266. *
  267. * If a prior visitor edits a node, no following visitors will see that node.
  268. */
  269. export function visitInParallel(visitors) {
  270. var skipping = new Array(visitors.length);
  271. return {
  272. enter: function enter(node) {
  273. for (var i = 0; i < visitors.length; i++) {
  274. if (skipping[i] == null) {
  275. var fn = getVisitFn(visitors[i], node.kind,
  276. /* isLeaving */
  277. false);
  278. if (fn) {
  279. var result = fn.apply(visitors[i], arguments);
  280. if (result === false) {
  281. skipping[i] = node;
  282. } else if (result === BREAK) {
  283. skipping[i] = BREAK;
  284. } else if (result !== undefined) {
  285. return result;
  286. }
  287. }
  288. }
  289. }
  290. },
  291. leave: function leave(node) {
  292. for (var i = 0; i < visitors.length; i++) {
  293. if (skipping[i] == null) {
  294. var fn = getVisitFn(visitors[i], node.kind,
  295. /* isLeaving */
  296. true);
  297. if (fn) {
  298. var result = fn.apply(visitors[i], arguments);
  299. if (result === BREAK) {
  300. skipping[i] = BREAK;
  301. } else if (result !== undefined && result !== false) {
  302. return result;
  303. }
  304. }
  305. } else if (skipping[i] === node) {
  306. skipping[i] = null;
  307. }
  308. }
  309. }
  310. };
  311. }
  312. /**
  313. * Given a visitor instance, if it is leaving or not, and a node kind, return
  314. * the function the visitor runtime should call.
  315. */
  316. export function getVisitFn(visitor, kind, isLeaving) {
  317. var kindVisitor = visitor[kind];
  318. if (kindVisitor) {
  319. if (!isLeaving && typeof kindVisitor === 'function') {
  320. // { Kind() {} }
  321. return kindVisitor;
  322. }
  323. var kindSpecificVisitor = isLeaving ? kindVisitor.leave : kindVisitor.enter;
  324. if (typeof kindSpecificVisitor === 'function') {
  325. // { Kind: { enter() {}, leave() {} } }
  326. return kindSpecificVisitor;
  327. }
  328. } else {
  329. var specificVisitor = isLeaving ? visitor.leave : visitor.enter;
  330. if (specificVisitor) {
  331. if (typeof specificVisitor === 'function') {
  332. // { enter() {}, leave() {} }
  333. return specificVisitor;
  334. }
  335. var specificKindVisitor = specificVisitor[kind];
  336. if (typeof specificKindVisitor === 'function') {
  337. // { enter: { Kind() {} }, leave: { Kind() {} } }
  338. return specificKindVisitor;
  339. }
  340. }
  341. }
  342. }