-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathindex.ts
96 lines (86 loc) · 2.64 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import Parser = require("tree-sitter");
import JavaScript = require("tree-sitter-javascript");
import * as g from "./generated";
let parser = new Parser() as g.Parser;
parser.setLanguage(JavaScript);
let tree = parser.parse(`
function foo() {
return function bar() {}
}
function baz() {}
class C {
f = 5;
m() {}
}
`);
function printDeclaredNames() {
let cursor = tree.walk();
do {
const c = cursor as g.TypedTreeCursor;
switch (c.nodeType) {
case g.SyntaxType.ClassDeclaration:
case g.SyntaxType.FunctionDeclaration:
case g.SyntaxType.VariableDeclarator: {
let node = c.currentNode;
console.log(node.nameNode.text);
break;
}
}
} while(gotoPreorderSucc(cursor));
}
function printFunctionNames() {
let cursor = tree.walk();
do {
const c = cursor as g.TypedTreeCursor;
switch (c.nodeType) {
case g.SyntaxType.Function:
case g.SyntaxType.FunctionDeclaration: {
let node = c.currentNode;
if (node.isNamed && node.nameNode != null) {
console.log(node.nameNode.text);
}
break;
}
case g.SyntaxType.ClassDeclaration: {
let node = c.currentNode;
console.log('Class with members: ' + getMemberNames(node).join(', '));
break;
}
}
} while(gotoPreorderSucc(cursor));
}
function getMemberNames(node: g.ClassDeclarationNode) {
let result = [];
for (let member of node.bodyNode.memberNodes) {
if (member.type === g.SyntaxType.MethodDefinition) {
result.push(member.nameNode.text);
} else {
result.push(member.propertyNode.text);
}
}
return result;
}
function gotoPreorderSucc(cursor: g.TreeCursor): boolean {
if (cursor.gotoFirstChild())
return true;
while (!cursor.gotoNextSibling()) {
if (!cursor.gotoParent()) {
return false;
}
}
return true;
}
printDeclaredNames();
printFunctionNames();
function printParameters1(node: g.SyntaxNode) {
// 'node.isNamed' is needed since there is both a named and an unnamed node whose type is 'function'.
if (node.isNamed && node.type === g.SyntaxType.Function) {
console.log(node.parametersNode.text);
}
}
function printParameters2(node: g.NamedNode) {
// If 'node' is typed as 'NamedNode' there is no need for the 'isNamed' check.
if (node.type === g.SyntaxType.Function) {
console.log(node.nameNode?.text);
}
}