Projekt

Obecné

Profil

Stáhnout (2.35 KB) Statistiky
| Větev: | Revize:
1
import { createPath } from "./node-path";
2
import { unionTypesMap, nodeAndUnionTypes } from "./nodes"; // recursively walks the AST starting at the given node. The callback is invoked for
3
// and object that has a 'type' property.
4

    
5
function walk(context, callback) {
6
  var stop = false;
7

    
8
  function innerWalk(context, callback) {
9
    if (stop) {
10
      return;
11
    }
12

    
13
    var node = context.node;
14

    
15
    if (node === undefined) {
16
      console.warn("traversing with an empty context");
17
      return;
18
    }
19

    
20
    if (node._deleted === true) {
21
      return;
22
    }
23

    
24
    var path = createPath(context);
25
    callback(node.type, path);
26

    
27
    if (path.shouldStop) {
28
      stop = true;
29
      return;
30
    }
31

    
32
    Object.keys(node).forEach(function (prop) {
33
      var value = node[prop];
34

    
35
      if (value === null || value === undefined) {
36
        return;
37
      }
38

    
39
      var valueAsArray = Array.isArray(value) ? value : [value];
40
      valueAsArray.forEach(function (childNode) {
41
        if (typeof childNode.type === "string") {
42
          var childContext = {
43
            node: childNode,
44
            parentKey: prop,
45
            parentPath: path,
46
            shouldStop: false,
47
            inList: Array.isArray(value)
48
          };
49
          innerWalk(childContext, callback);
50
        }
51
      });
52
    });
53
  }
54

    
55
  innerWalk(context, callback);
56
}
57

    
58
var noop = function noop() {};
59

    
60
export function traverse(node, visitors) {
61
  var before = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : noop;
62
  var after = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : noop;
63
  Object.keys(visitors).forEach(function (visitor) {
64
    if (!nodeAndUnionTypes.includes(visitor)) {
65
      throw new Error("Unexpected visitor ".concat(visitor));
66
    }
67
  });
68
  var context = {
69
    node: node,
70
    inList: false,
71
    shouldStop: false,
72
    parentPath: null,
73
    parentKey: null
74
  };
75
  walk(context, function (type, path) {
76
    if (typeof visitors[type] === "function") {
77
      before(type, path);
78
      visitors[type](path);
79
      after(type, path);
80
    }
81

    
82
    var unionTypes = unionTypesMap[type];
83

    
84
    if (!unionTypes) {
85
      throw new Error("Unexpected node type ".concat(type));
86
    }
87

    
88
    unionTypes.forEach(function (unionType) {
89
      if (typeof visitors[unionType] === "function") {
90
        before(unionType, path);
91
        visitors[unionType](path);
92
        after(unionType, path);
93
      }
94
    });
95
  });
96
}
(8-8/9)