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

huangapple go评论62阅读模式
英文:

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

问题

Using the tree-sitter-javascript库,我正在尝试从JavaScript代码(以字符串格式)中提取所有函数名称,并将其存储在functionNames数组中。

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((node) => {
    console.log("Node: ", node);
    if (node.type === 'function_declaration') {
        functionNames.push(node.child(1).text);
    }
})

console.log(functionNames); 

// 期望输出 ['foo', 'bar']
// 实际输出 []

然而,tree.walk()的回调根本不执行。
日志中什么都不打印,只是一个空数组[]。

这段代码有什么问题?
我在官方文档(https://github.com/tree-sitter/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

答案1

得分: 2

parser.parse已经给你解析好的结果。该对象上没有.walk()函数。要获取所有函数名称,你可以递归遍历rootNode

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' ]
英文:

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' ]

huangapple
  • 本文由 发表于 2023年5月22日 18:19:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76305172.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定