visitor.js.flow 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. // @flow strict
  2. import inspect from '../jsutils/inspect';
  3. import { type TypeInfo } from '../utilities/TypeInfo';
  4. import { type ASTNode, type ASTKindToNode } from './ast';
  5. /**
  6. * A visitor is provided to visit, it contains the collection of
  7. * relevant functions to be called during the visitor's traversal.
  8. */
  9. export type ASTVisitor = Visitor<ASTKindToNode>;
  10. export type Visitor<KindToNode, Nodes = $Values<KindToNode>> =
  11. | EnterLeave<
  12. | VisitFn<Nodes>
  13. | ShapeMap<KindToNode, <Node>(Node) => VisitFn<Nodes, Node>>,
  14. >
  15. | ShapeMap<
  16. KindToNode,
  17. <Node>(Node) => VisitFn<Nodes, Node> | EnterLeave<VisitFn<Nodes, Node>>,
  18. >;
  19. type EnterLeave<T> = {| +enter?: T, +leave?: T |};
  20. type ShapeMap<O, F> = $Shape<$ObjMap<O, F>>;
  21. /**
  22. * A visitor is comprised of visit functions, which are called on each node
  23. * during the visitor's traversal.
  24. */
  25. export type VisitFn<TAnyNode, TVisitedNode: TAnyNode = TAnyNode> = (
  26. // The current node being visiting.
  27. node: TVisitedNode,
  28. // The index or key to this node from the parent node or Array.
  29. key: string | number | void,
  30. // The parent immediately above this node, which may be an Array.
  31. parent: TAnyNode | $ReadOnlyArray<TAnyNode> | void,
  32. // The key path to get to this node from the root node.
  33. path: $ReadOnlyArray<string | number>,
  34. // All nodes and Arrays visited before reaching parent of this node.
  35. // These correspond to array indices in `path`.
  36. // Note: ancestors includes arrays which contain the parent of visited node.
  37. ancestors: $ReadOnlyArray<TAnyNode | $ReadOnlyArray<TAnyNode>>,
  38. ) => any;
  39. /**
  40. * A KeyMap describes each the traversable properties of each kind of node.
  41. */
  42. export type VisitorKeyMap<KindToNode> = $ObjMap<
  43. KindToNode,
  44. <T>(T) => $ReadOnlyArray<$Keys<T>>,
  45. >;
  46. export const QueryDocumentKeys = {
  47. Name: [],
  48. Document: ['definitions'],
  49. OperationDefinition: [
  50. 'name',
  51. 'variableDefinitions',
  52. 'directives',
  53. 'selectionSet',
  54. ],
  55. VariableDefinition: ['variable', 'type', 'defaultValue', 'directives'],
  56. Variable: ['name'],
  57. SelectionSet: ['selections'],
  58. Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'],
  59. Argument: ['name', 'value'],
  60. FragmentSpread: ['name', 'directives'],
  61. InlineFragment: ['typeCondition', 'directives', 'selectionSet'],
  62. FragmentDefinition: [
  63. 'name',
  64. // Note: fragment variable definitions are experimental and may be changed
  65. // or removed in the future.
  66. 'variableDefinitions',
  67. 'typeCondition',
  68. 'directives',
  69. 'selectionSet',
  70. ],
  71. IntValue: [],
  72. FloatValue: [],
  73. StringValue: [],
  74. BooleanValue: [],
  75. NullValue: [],
  76. EnumValue: [],
  77. ListValue: ['values'],
  78. ObjectValue: ['fields'],
  79. ObjectField: ['name', 'value'],
  80. Directive: ['name', 'arguments'],
  81. NamedType: ['name'],
  82. ListType: ['type'],
  83. NonNullType: ['type'],
  84. SchemaDefinition: ['directives', 'operationTypes'],
  85. OperationTypeDefinition: ['type'],
  86. ScalarTypeDefinition: ['description', 'name', 'directives'],
  87. ObjectTypeDefinition: [
  88. 'description',
  89. 'name',
  90. 'interfaces',
  91. 'directives',
  92. 'fields',
  93. ],
  94. FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'],
  95. InputValueDefinition: [
  96. 'description',
  97. 'name',
  98. 'type',
  99. 'defaultValue',
  100. 'directives',
  101. ],
  102. InterfaceTypeDefinition: ['description', 'name', 'directives', 'fields'],
  103. UnionTypeDefinition: ['description', 'name', 'directives', 'types'],
  104. EnumTypeDefinition: ['description', 'name', 'directives', 'values'],
  105. EnumValueDefinition: ['description', 'name', 'directives'],
  106. InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'],
  107. DirectiveDefinition: ['description', 'name', 'arguments', 'locations'],
  108. SchemaExtension: ['directives', 'operationTypes'],
  109. ScalarTypeExtension: ['name', 'directives'],
  110. ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'],
  111. InterfaceTypeExtension: ['name', 'directives', 'fields'],
  112. UnionTypeExtension: ['name', 'directives', 'types'],
  113. EnumTypeExtension: ['name', 'directives', 'values'],
  114. InputObjectTypeExtension: ['name', 'directives', 'fields'],
  115. };
  116. export const BREAK = Object.freeze({});
  117. /**
  118. * visit() will walk through an AST using a depth first traversal, calling
  119. * the visitor's enter function at each node in the traversal, and calling the
  120. * leave function after visiting that node and all of its child nodes.
  121. *
  122. * By returning different values from the enter and leave functions, the
  123. * behavior of the visitor can be altered, including skipping over a sub-tree of
  124. * the AST (by returning false), editing the AST by returning a value or null
  125. * to remove the value, or to stop the whole traversal by returning BREAK.
  126. *
  127. * When using visit() to edit an AST, the original AST will not be modified, and
  128. * a new version of the AST with the changes applied will be returned from the
  129. * visit function.
  130. *
  131. * const editedAST = visit(ast, {
  132. * enter(node, key, parent, path, ancestors) {
  133. * // @return
  134. * // undefined: no action
  135. * // false: skip visiting this node
  136. * // visitor.BREAK: stop visiting altogether
  137. * // null: delete this node
  138. * // any value: replace this node with the returned value
  139. * },
  140. * leave(node, key, parent, path, ancestors) {
  141. * // @return
  142. * // undefined: no action
  143. * // false: no action
  144. * // visitor.BREAK: stop visiting altogether
  145. * // null: delete this node
  146. * // any value: replace this node with the returned value
  147. * }
  148. * });
  149. *
  150. * Alternatively to providing enter() and leave() functions, a visitor can
  151. * instead provide functions named the same as the kinds of AST nodes, or
  152. * enter/leave visitors at a named key, leading to four permutations of
  153. * visitor API:
  154. *
  155. * 1) Named visitors triggered when entering a node a specific kind.
  156. *
  157. * visit(ast, {
  158. * Kind(node) {
  159. * // enter the "Kind" node
  160. * }
  161. * })
  162. *
  163. * 2) Named visitors that trigger upon entering and leaving a node of
  164. * a specific kind.
  165. *
  166. * visit(ast, {
  167. * Kind: {
  168. * enter(node) {
  169. * // enter the "Kind" node
  170. * }
  171. * leave(node) {
  172. * // leave the "Kind" node
  173. * }
  174. * }
  175. * })
  176. *
  177. * 3) Generic visitors that trigger upon entering and leaving any node.
  178. *
  179. * visit(ast, {
  180. * enter(node) {
  181. * // enter any node
  182. * },
  183. * leave(node) {
  184. * // leave any node
  185. * }
  186. * })
  187. *
  188. * 4) Parallel visitors for entering and leaving nodes of a specific kind.
  189. *
  190. * visit(ast, {
  191. * enter: {
  192. * Kind(node) {
  193. * // enter the "Kind" node
  194. * }
  195. * },
  196. * leave: {
  197. * Kind(node) {
  198. * // leave the "Kind" node
  199. * }
  200. * }
  201. * })
  202. */
  203. export function visit(
  204. root: ASTNode,
  205. visitor: Visitor<ASTKindToNode>,
  206. visitorKeys: VisitorKeyMap<ASTKindToNode> = QueryDocumentKeys,
  207. ): any {
  208. /* eslint-disable no-undef-init */
  209. let stack: any = undefined;
  210. let inArray = Array.isArray(root);
  211. let keys: any = [root];
  212. let index = -1;
  213. let edits = [];
  214. let node: any = undefined;
  215. let key: any = undefined;
  216. let parent: any = undefined;
  217. const path: any = [];
  218. const ancestors = [];
  219. let newRoot = root;
  220. /* eslint-enable no-undef-init */
  221. do {
  222. index++;
  223. const isLeaving = index === keys.length;
  224. const isEdited = isLeaving && edits.length !== 0;
  225. if (isLeaving) {
  226. key = ancestors.length === 0 ? undefined : path[path.length - 1];
  227. node = parent;
  228. parent = ancestors.pop();
  229. if (isEdited) {
  230. if (inArray) {
  231. node = node.slice();
  232. } else {
  233. const clone = {};
  234. for (const k of Object.keys(node)) {
  235. clone[k] = node[k];
  236. }
  237. node = clone;
  238. }
  239. let editOffset = 0;
  240. for (let ii = 0; ii < edits.length; ii++) {
  241. let editKey: any = edits[ii][0];
  242. const editValue = edits[ii][1];
  243. if (inArray) {
  244. editKey -= editOffset;
  245. }
  246. if (inArray && editValue === null) {
  247. node.splice(editKey, 1);
  248. editOffset++;
  249. } else {
  250. node[editKey] = editValue;
  251. }
  252. }
  253. }
  254. index = stack.index;
  255. keys = stack.keys;
  256. edits = stack.edits;
  257. inArray = stack.inArray;
  258. stack = stack.prev;
  259. } else {
  260. key = parent ? (inArray ? index : keys[index]) : undefined;
  261. node = parent ? parent[key] : newRoot;
  262. if (node === null || node === undefined) {
  263. continue;
  264. }
  265. if (parent) {
  266. path.push(key);
  267. }
  268. }
  269. let result;
  270. if (!Array.isArray(node)) {
  271. if (!isNode(node)) {
  272. throw new Error('Invalid AST Node: ' + inspect(node));
  273. }
  274. const visitFn = getVisitFn(visitor, node.kind, isLeaving);
  275. if (visitFn) {
  276. result = visitFn.call(visitor, node, key, parent, path, ancestors);
  277. if (result === BREAK) {
  278. break;
  279. }
  280. if (result === false) {
  281. if (!isLeaving) {
  282. path.pop();
  283. continue;
  284. }
  285. } else if (result !== undefined) {
  286. edits.push([key, result]);
  287. if (!isLeaving) {
  288. if (isNode(result)) {
  289. node = result;
  290. } else {
  291. path.pop();
  292. continue;
  293. }
  294. }
  295. }
  296. }
  297. }
  298. if (result === undefined && isEdited) {
  299. edits.push([key, node]);
  300. }
  301. if (isLeaving) {
  302. path.pop();
  303. } else {
  304. stack = { inArray, index, keys, edits, prev: stack };
  305. inArray = Array.isArray(node);
  306. keys = inArray ? node : visitorKeys[node.kind] || [];
  307. index = -1;
  308. edits = [];
  309. if (parent) {
  310. ancestors.push(parent);
  311. }
  312. parent = node;
  313. }
  314. } while (stack !== undefined);
  315. if (edits.length !== 0) {
  316. newRoot = edits[edits.length - 1][1];
  317. }
  318. return newRoot;
  319. }
  320. function isNode(maybeNode): boolean %checks {
  321. return Boolean(maybeNode && typeof maybeNode.kind === 'string');
  322. }
  323. /**
  324. * Creates a new visitor instance which delegates to many visitors to run in
  325. * parallel. Each visitor will be visited for each node before moving on.
  326. *
  327. * If a prior visitor edits a node, no following visitors will see that node.
  328. */
  329. export function visitInParallel(
  330. visitors: $ReadOnlyArray<Visitor<ASTKindToNode>>,
  331. ): Visitor<ASTKindToNode> {
  332. const skipping = new Array(visitors.length);
  333. return {
  334. enter(node) {
  335. for (let i = 0; i < visitors.length; i++) {
  336. if (!skipping[i]) {
  337. const fn = getVisitFn(visitors[i], node.kind, /* isLeaving */ false);
  338. if (fn) {
  339. const result = fn.apply(visitors[i], arguments);
  340. if (result === false) {
  341. skipping[i] = node;
  342. } else if (result === BREAK) {
  343. skipping[i] = BREAK;
  344. } else if (result !== undefined) {
  345. return result;
  346. }
  347. }
  348. }
  349. }
  350. },
  351. leave(node) {
  352. for (let i = 0; i < visitors.length; i++) {
  353. if (!skipping[i]) {
  354. const fn = getVisitFn(visitors[i], node.kind, /* isLeaving */ true);
  355. if (fn) {
  356. const result = fn.apply(visitors[i], arguments);
  357. if (result === BREAK) {
  358. skipping[i] = BREAK;
  359. } else if (result !== undefined && result !== false) {
  360. return result;
  361. }
  362. }
  363. } else if (skipping[i] === node) {
  364. skipping[i] = null;
  365. }
  366. }
  367. },
  368. };
  369. }
  370. /**
  371. * Creates a new visitor instance which maintains a provided TypeInfo instance
  372. * along with visiting visitor.
  373. */
  374. export function visitWithTypeInfo(
  375. typeInfo: TypeInfo,
  376. visitor: Visitor<ASTKindToNode>,
  377. ): Visitor<ASTKindToNode> {
  378. return {
  379. enter(node) {
  380. typeInfo.enter(node);
  381. const fn = getVisitFn(visitor, node.kind, /* isLeaving */ false);
  382. if (fn) {
  383. const result = fn.apply(visitor, arguments);
  384. if (result !== undefined) {
  385. typeInfo.leave(node);
  386. if (isNode(result)) {
  387. typeInfo.enter(result);
  388. }
  389. }
  390. return result;
  391. }
  392. },
  393. leave(node) {
  394. const fn = getVisitFn(visitor, node.kind, /* isLeaving */ true);
  395. let result;
  396. if (fn) {
  397. result = fn.apply(visitor, arguments);
  398. }
  399. typeInfo.leave(node);
  400. return result;
  401. },
  402. };
  403. }
  404. /**
  405. * Given a visitor instance, if it is leaving or not, and a node kind, return
  406. * the function the visitor runtime should call.
  407. */
  408. export function getVisitFn(
  409. visitor: Visitor<any>,
  410. kind: string,
  411. isLeaving: boolean,
  412. ): ?VisitFn<any> {
  413. const kindVisitor = visitor[kind];
  414. if (kindVisitor) {
  415. if (!isLeaving && typeof kindVisitor === 'function') {
  416. // { Kind() {} }
  417. return kindVisitor;
  418. }
  419. const kindSpecificVisitor = isLeaving
  420. ? kindVisitor.leave
  421. : kindVisitor.enter;
  422. if (typeof kindSpecificVisitor === 'function') {
  423. // { Kind: { enter() {}, leave() {} } }
  424. return kindSpecificVisitor;
  425. }
  426. } else {
  427. const specificVisitor = isLeaving ? visitor.leave : visitor.enter;
  428. if (specificVisitor) {
  429. if (typeof specificVisitor === 'function') {
  430. // { enter() {}, leave() {} }
  431. return specificVisitor;
  432. }
  433. const specificKindVisitor = specificVisitor[kind];
  434. if (typeof specificKindVisitor === 'function') {
  435. // { enter: { Kind() {} }, leave: { Kind() {} } }
  436. return specificKindVisitor;
  437. }
  438. }
  439. }
  440. }