How to use the traverse function from estraverse

Find comprehensive JavaScript estraverse.traverse code examples handpicked from public code repositorys.

estraverse.traverse is a method in the estraverse library that allows for the traversal of an abstract syntax tree (AST) generated by the esprima library. It can be used to visit each node of the AST and perform some action on it.

88
89
90
91
92
93
94
95
96
97
/**
 * @param {ModuleBuilder} modul
 */
async function traverse(modul) {
  console.debug(`[Analyzer.js] traversing AST of ${modul.path}`);
  estraverse.traverse(modul.ast, {
    enter: function (node, parent) {
      node["xParent"] = parent;
      if (helper.createsNewScope(node)) {
        currentScope += 1;
fork icon7
star icon20
watch icon4

65
66
67
68
69
70
71
72
73
74
// // 规则2:While与If代码块互换
// var while_if_swap = function(source) {
//     var ast = esprima.parse(source);
//     let source_copy = escodegen.generate(ast);
//     let flag = 0;
//     estraverse.traverse(ast, {
//         enter: function (node){
//             // 匹配不包含else的if代码块
//             //if(node.type == "IfStatement" && node.alternate == undefined){
//             if(node.type == "IfStatement"){
fork icon0
star icon1
watch icon1

+ 17 other calls in file

How does estraverse.traverse work?

estraverse.traverse is a method in the estraverse library that recursively traverses an Abstract Syntax Tree (AST) and calls the provided callback functions for each node and property in the tree, allowing for custom operations to be performed on the AST. The method accepts an AST object and an object of options that determine how the traversal should be performed.

3
4
5
6
7
8
9
10
11
12
    iterate: iterate
};

function iterate(node, cb) {
    if ('type' in node) {
        estraverse.traverse(node, {
            enter: function(node, parent) {
                var parentCollection = [];

                // parentCollection support
fork icon549
star icon0
watch icon2

175
176
177
178
179
180
181
182
183
184

function traverse(ast, lines, vertexShader, opt) {
    var insideMain = false;


    walk.traverse(ast, {
            enter: function (node) {
                try {
                    var type = node.type;
                    switch (type) {
fork icon4
star icon10
watch icon9

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const estraverse = require("estraverse");

const code = `
function square(n) {
return n * n;
}
`;

const ast = acorn.parse(code, { ecmaVersion: 2020 });
estraverse.traverse(ast, {
  enter(node) {
    if (node.type === "FunctionDeclaration") {
      console.log(`Function "${node.id.name}" found!`);
    }
  },
});

In this example, estraverse.traverse is used to traverse the abstract syntax tree (AST) of the code variable, which contains a simple JavaScript function. During the traversal, the enter function is called for each node in the tree. In this case, the function checks if the node represents a function declaration, and if so, logs its name to the console. The output of this example would be: javascript Copy code

219
220
221
222
223
224
225
226
227
228
      return nodeHandlers[node.type].exit(node, parent, state);
  }
};

// Let's do it!
estraverse.traverse(ast, state.traverser);

// Anything left in the root need to get added to provide
for (var i in state.scope['function'][0]) if (state.scope['function'][0].hasOwnProperty(i))
  provides.push(i);
fork icon1
star icon0
watch icon2

+ 7 other calls in file

0
1
2
3
4
5
6
7
8
const estraverse = require('estraverse');
const { JSX_ELEMENT, JSX_EXPRESSION_CONTAINER } = require('./constants/ast-node-types');
const { getNodeType } = require('./core-utils');

function traverse(ast, behaviors) {
    return estraverse.traverse(ast, {
        ...behaviors,
        fallback(node) {
            const nodeType = getNodeType(node);
fork icon0
star icon21
watch icon3

48
49
50
51
52
53
54
55
56
57

eval.defaultMethod((ast) => undefined)

function reduce(f, ast) {
    const nodes = []
    traverse(ast, {
        enter: node => {
            const result = f(node);
            if (result) {
                nodes.push(result);
fork icon3
star icon11
watch icon3

3
4
5
6
7
8
9
10
11
12
const estraverse = require('estraverse');

//TODO Cleanup this file to abstract traversing logic to a single method
function findScreenshotName(AST, fileName) {
    let charPos = 0;
    estraverse.traverse(AST, {
        enter: function (node, parent) {
            if (node.type == 'Literal') {
                if (node.value === fileName) {
                    charPos = node.start;
fork icon3
star icon2
watch icon8

+ 5 other calls in file

7
8
9
10
11
12
13
14
15
16
  _isMutable
} = require('./utils')

// TODO
const initialCrawl = tree => {
  traverse(tree, {
    enter (node, parent) {
      node.parent = parent

      if (node.type === 'Property' && node.shorthand && node.key === node.value) {
fork icon2
star icon1
watch icon1

+ 7 other calls in file

152
153
154
155
156
157
158
159
160
161
    'utf8'
);

const astMethods = getAST(methodsFileData);

estraverse.traverse(astMethods, {
    enter(node) {
        if (node.type === 'MethodDefinition') {
            lineRef[node.key.name] = {
                name: node.key.name,
fork icon47
star icon0
watch icon19

+ 5 other calls in file

91
92
93
94
95
96
97
98
99
100
            return quit(controller);
        }
    }
}

estraverse.traverse(tree, {
    enter: function(node) {
        var controller = this;
        _.reduce(controller.path(), access, Option.Some(from)).fold(
            function(fromNode) {
fork icon4
star icon39
watch icon5

340
341
342
343
344
345
346
347
348
349
    return stmts.concat(processed.stmts);
}

function processRecurFormIfAny(rootNode, actualArgs, yy) {
    var hasRecurForm = false;
    estraverse.traverse(rootNode, {
        enter: function (node) {
            if (node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration') {
                return estraverse.VisitorOption.Skip;
            } else if (node.type === 'BlockStatement' && node.recurBlock) {
fork icon8
star icon0
watch icon0

+ 3 other calls in file

5
6
7
8
9
10
11
12
13
14
15
16


const estraverse = require('estraverse');
// const pragmaUtil = require('./pragma');


/**
 * Wrapper for estraverse.traverse
 *
 * @param {ASTNode} ASTnode The AST node being checked
 * @param {Object} visitor Visitor Object for estraverse
 */
fork icon0
star icon0
watch icon1

+ 9 other calls in file