Closed bramses closed 3 years ago
Note: I can DFS the tree normally, but it's just Tree Cursor that doesn't seem to work. My guess is its because the boolean of gotoNextChild()
and gotoNextSibling()
also move the cursor.
Running DFS without TreeCursor
:
const nodeWalk = (node) => {
if (!node || node === undefined) return
while (node) {
console.log(node.text)
if (node.children && node.children.length > 0) {
nodeWalk(node.children[0])
}
node = node.nextSibling
}
}
Here is one usage of TreeCursor in php https://github.com/talbergs/php-tree-sitter/blob/master/examples/04-walking-tree/example.php
, maybe this helps / inspires.
this should be in examples ...
// https://github.com/tree-sitter/node-tree-sitter/blob/master/tree-sitter.d.ts
const TreeSitter = require('tree-sitter');
const TreeSitterC = require('tree-sitter-c');
const fs = require('fs');
process.argv.shift(); // argv[0] is node interpreter ...
const inputPath = process.argv[1];
const basename = path => path.split("/").pop();
if (inputPath == undefined) {
console.log(`usage: node ${basename(process.argv[0])} path/to/inputfile.c`)
process.exit(1);
}
if (!fs.existsSync(inputPath)) {
console.log(`no such file: ${inputPath}`)
process.exit(1);
}
const sourceCode = fs.readFileSync(inputPath, 'utf8');
const parser = new TreeSitter();
parser.setLanguage(TreeSitterC);
const tree = parser.parse(sourceCode);
const textStartLength = 50;
const walk_cursor = (cursor, level = 0) => {
// top-down = handle node -> go to next node
// depth-first = gotoFirstChild -> gotoNextSibling
while (true) {
// handle this node
const textEscaped = cursor.nodeText.replace(/\n/g, '\\n');
const typeEscaped = cursor.nodeType.replace('\n', '\\n');
const textStart = (textEscaped.length < textStartLength)
? textEscaped : (textEscaped.slice(0, textStartLength) + ' ...');
const textLocation = `${cursor.startIndex} ${cursor.endIndex}`; // offset in utf8 chars (or offset in bytes? which is it?)
//const textLocation = `${cursor.startPosition.row}:${cursor.startPosition.column} ${cursor.endPosition.row}:${cursor.endPosition.column}`;
const levelString = Array.from({ length: (level + 1) }).map(_ => '+').join('');
console.log(`${levelString} ${textLocation} ${typeEscaped}: ${textStart}`);
// go to next node
if (cursor.gotoFirstChild()) {
walk_cursor(cursor, level + 1);
cursor.gotoParent();
}
if (!cursor.gotoNextSibling()) break;
}
}
var cursor = tree.walk();
walk_cursor(cursor);
Oh! I wouldn't have thought to use while (true)
, thank you for the code block @milahu
Hi,
I'm trying to walk the entire tree and "visit" each node but I can't figure it out using a traditional DFS algortihm. Neither of the below work:
Case 1 - Infinite Loop:
Case 2 - Incomplete Tree: