2

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

Aadesh
  • 403
  • 3
  • 13

1 Answers1

2

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' ]
NullDev
  • 6,739
  • 4
  • 30
  • 54
  • An easier way to get the name is: `const name = node.childForFieldName('name').text`. The fields can be found by running `console.log(node.toString())` and looking for things ending in a colon e.g. `parameters:`. Also, `node.fields` might work but not on the wasm api. – vaughan Aug 22 '23 at 20:01