Created
January 4, 2025 16:56
-
-
Save shreyassanthu77/70545c35092549c790c1738089971392 to your computer and use it in GitHub Desktop.
ts function extraction using tree sitter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Parser from "npm:tree-sitter"; | |
import treeSitterTypescript from "npm:tree-sitter-typescript"; | |
const code = ` | |
/** | |
* This is a doc comment | |
* | |
* alsdkfjlkj | |
*/ | |
function foo(a: A): void; | |
function bar(b: B): void; | |
`; | |
const parser = new Parser(); | |
// @ts-ignore .. | |
parser.setLanguage(treeSitterTypescript.typescript); | |
const tree = parser.parse(code); | |
function getFunctionsWithDocComment(tree: Parser.Tree) { | |
const cursor = tree.walk(); | |
const res: { | |
name: string; | |
params: { | |
name: string; | |
type: string; | |
}[]; | |
returnType: string; | |
docComment: string; | |
}[] = []; | |
function visit() { | |
const node = cursor.currentNode; | |
if (node.type === "function_signature") { | |
const [name, params, returnType] = node.namedChildren; | |
const paramsParsed: { | |
name: string; | |
type: string; | |
}[] = []; | |
for (const param of params.namedChildren) { | |
const [name, type] = param.namedChildren; | |
paramsParsed.push({ | |
name: name.text, | |
type: type.text.slice(1).trim(), | |
}); | |
} | |
let docComment = ""; | |
if (node.previousSibling) { | |
const prevNode = node.previousSibling; | |
if (prevNode.type === "comment") { | |
docComment = prevNode.text | |
.replace(/^\/\*\*/, "") | |
.replace(/\*\/$/, "") | |
.split("\n") | |
.map((line) => line.trim().replace(/^\* ?/, "")) // Remove leading * and spaces | |
.join("\n") | |
.trim(); | |
} | |
} | |
res.push({ | |
name: name.text, | |
params: paramsParsed, | |
returnType: returnType.text.slice(1).trim(), | |
docComment, | |
}); | |
} | |
if (cursor.gotoFirstChild()) { | |
do { | |
visit(); | |
} while (cursor.gotoNextSibling()); | |
cursor.gotoParent(); | |
} | |
} | |
visit(); | |
return res; | |
} | |
console.log(getFunctionsWithDocComment(tree)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment