Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fardjad/798b399804f391f57a76a993c6c892cd to your computer and use it in GitHub Desktop.
Save fardjad/798b399804f391f57a76a993c6c892cd to your computer and use it in GitHub Desktop.
[Find node by line-number in node-tree-sitter] An example of finding a node by line-number with node-tree-sitter #TreeSitter #Node

Example

Requirements

  • Node.js 18+
  • tree-sitter
  • tree-sitter-cpp

index.mjs

import Parser from "tree-sitter";
import Cpp from "tree-sitter-cpp";

import fs from "node:fs";

const { Query } = Parser;

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

const sourceCode = fs.readFileSync("/path/to/file.cpp", "utf8");

const tree = parser.parse(sourceCode);

// [Optional] Explore the tree in the play-ground https://tree-sitter.github.io/tree-sitter/playground

const lineNumber = 317;

const query = `(_) @node`;
const parserQuery = new Query(Cpp, query);
const matches = parserQuery
  .matches(tree.rootNode)
  .flatMap(({ captures }) => captures)
  .map(({ node }) => node)
  .filter((node) => node.startPosition.row === lineNumber));

console.log(matches.toString());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment