Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
84 lines (71 loc) · 2.04 KB
/
Copy pathindex.ts
File metadata and controls
84 lines (71 loc) · 2.04 KB
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
import Graph from 'graphology';
import Parser, { type SyntaxNode, type TreeCursor } from 'tree-sitter';
import JavaScript from 'tree-sitter-javascript';
import C from 'tree-sitter-c';
import fs from 'node:fs';
const parser = new Parser();
parser.setLanguage(C);
const sourceCode = `
#include <stdio.h>
int main() {
int a[] = {5,2,8,1,9}, n = 5;
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-1-i; j++)
if (a[j] > a[j+1]) {
int t = a[j];
a[j] = a[j+1];
a[j+1] = t;
}
for (int i = 0; i < n; i++) printf("%d ", [i]);
return 0;
}
`;
const tree = parser.parse(sourceCode);
function astToGraph(rootCursor: TreeCursor): Graph {
const graph = new Graph({ type: 'directed', multi: false });
function isLeaf(node: SyntaxNode): boolean {
return node.childCount === 0;
}
function addNodeToGraph(key: string, node: SyntaxNode) {
graph.addNode(key, {
nodeKind: node.type,
isNamed: node.isNamed,
text: isLeaf(node) ? node.text : undefined,
position: [
node.startPosition.row,
node.startPosition.column,
node.endPosition.row,
node.endPosition.column,
node.startIndex,
node.endIndex,
],
isLeaf: node.childCount === 0,
});
}
function traverse(cursor: TreeCursor, parentKey: string | null) {
const node = cursor.currentNode;
const key = node.id.toString();
addNodeToGraph(key, node);
if (parentKey !== null) {
const fieldName = cursor.currentFieldName ?? undefined;
graph.addEdge(parentKey, key, {
nodeKind: 'ast',
field: fieldName,
});
}
if (cursor.gotoFirstChild()) {
do {
traverse(cursor, key);
} while (cursor.gotoNextSibling());
cursor.gotoParent();
}
}
traverse(rootCursor, null);
return graph;
}
const cursor = tree.walk();
const graph = astToGraph(cursor);
const exported = graph.export();
console.log('nodes:', graph.order);
console.log('edges:', graph.size);
fs.writeFileSync('ast_graph.t.json', JSON.stringify(exported, null, 2));