javascriptnode.jstreesitter

Fetch function names from a file using tree-sitter-javascript


Using tree-sitter-javascript library, I'm trying to fetch all function names from a Javascript code (in string format) and storing it in a functionNames array.

const Parser = require('tree-sitter');
const JavaScript = require('tree-sitter-javascript');

const parser = new Parser();
parser.setLanguage(JavaScript);

const sourceCode = `function foo() {
    console.log('hello world');
  }
  
  function bar() {
    console.log('bye world');
  }`;

const tree = parser.parse(sourceCode);

const functionNames = [];
tree.walk(()=>{
    console.log("Node: ", node);
    if (node.type === 'function_declaration') {
        functionNames.push(node.child(1).text);
      }
    
})

console.log(functionNames); 

// Expected output ['foo', 'bar']
// Actual output []

However, the callback to tree.walk() is not executing at all. Nothing gets printed in the log. just an empty array []

What is wrong with this code ? I couldn't find much documentation on this in the official docs (https://github.com/tree-sitter/tree-sitter-javascript)

Is there an alternate way to do this ? Thanks in advance


Solution

  • That's because parser.parse already gives you the parsed result. There is no .walk() function on that object. To get all the function names you can traverse the rootNode recursively:

    const tree = parser.parse(sourceCode);
    const rootNode = tree.rootNode;
    
    const functionNames = [];
    function findFunctionNames(node) {
        if (node.type === 'function_declaration') {
            for (let child of node.namedChildren) {
                if (child.type === 'identifier') {
                    functionNames.push(child.text);
                }
            }
        }
    
        for (let child of node.namedChildren) {
            findFunctionNames(child);
        }
    }
    
    findFunctionNames(rootNode);
    
    console.log(functionNames);
    // -> [ 'foo', 'bar' ]