Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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' ]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading