You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

104 lines
2.5 KiB

4 years ago
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.traverse = traverse;
  6. var _nodePath = require("./node-path");
  7. var _nodes = require("./nodes");
  8. // recursively walks the AST starting at the given node. The callback is invoked for
  9. // and object that has a 'type' property.
  10. function walk(context, callback) {
  11. var stop = false;
  12. function innerWalk(context, callback) {
  13. if (stop) {
  14. return;
  15. }
  16. var node = context.node;
  17. if (node === undefined) {
  18. console.warn("traversing with an empty context");
  19. return;
  20. }
  21. if (node._deleted === true) {
  22. return;
  23. }
  24. var path = (0, _nodePath.createPath)(context);
  25. callback(node.type, path);
  26. if (path.shouldStop) {
  27. stop = true;
  28. return;
  29. }
  30. Object.keys(node).forEach(function (prop) {
  31. var value = node[prop];
  32. if (value === null || value === undefined) {
  33. return;
  34. }
  35. var valueAsArray = Array.isArray(value) ? value : [value];
  36. valueAsArray.forEach(function (childNode) {
  37. if (typeof childNode.type === "string") {
  38. var childContext = {
  39. node: childNode,
  40. parentKey: prop,
  41. parentPath: path,
  42. shouldStop: false,
  43. inList: Array.isArray(value)
  44. };
  45. innerWalk(childContext, callback);
  46. }
  47. });
  48. });
  49. }
  50. innerWalk(context, callback);
  51. }
  52. var noop = function noop() {};
  53. function traverse(node, visitors) {
  54. var before = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : noop;
  55. var after = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : noop;
  56. Object.keys(visitors).forEach(function (visitor) {
  57. if (!_nodes.nodeAndUnionTypes.includes(visitor)) {
  58. throw new Error("Unexpected visitor ".concat(visitor));
  59. }
  60. });
  61. var context = {
  62. node: node,
  63. inList: false,
  64. shouldStop: false,
  65. parentPath: null,
  66. parentKey: null
  67. };
  68. walk(context, function (type, path) {
  69. if (typeof visitors[type] === "function") {
  70. before(type, path);
  71. visitors[type](path);
  72. after(type, path);
  73. }
  74. var unionTypes = _nodes.unionTypesMap[type];
  75. if (!unionTypes) {
  76. throw new Error("Unexpected node type ".concat(type));
  77. }
  78. unionTypes.forEach(function (unionType) {
  79. if (typeof visitors[unionType] === "function") {
  80. before(unionType, path);
  81. visitors[unionType](path);
  82. after(unionType, path);
  83. }
  84. });
  85. });
  86. }