visitor.js 12 KB

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