visitor.mjs 12 KB

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