forked from tmr232/function-graph-overview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcfg-cpp.ts
More file actions
241 lines (213 loc) · 6.76 KB
/
Copy pathcfg-cpp.ts
File metadata and controls
241 lines (213 loc) · 6.76 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import type { Node as SyntaxNode } from "web-tree-sitter";
import treeSitterCpp from "../../parsers/tree-sitter-cpp.wasm?url";
import { getStatementHandlers } from "./cfg-c.ts";
import type { BasicBlock, BuilderOptions, CFGBuilder } from "./cfg-defs";
import {
forEachLoopProcessor,
processReturnStatement,
processThrowStatement,
} from "./common-patterns.ts";
import {
type Context,
GenericCFGBuilder,
type StatementHandlers,
} from "./generic-cfg-builder.ts";
import { pairwise, zip } from "./itertools.ts";
import { extractTaggedValueFromTreeSitterQuery } from "./query-utils.ts";
export const cppLanguageDefinition = {
wasmPath: treeSitterCpp,
createCFGBuilder: createCFGBuilder,
functionNodeTypes: ["function_definition", "lambda_expression"],
};
export function createCFGBuilder(options: BuilderOptions): CFGBuilder {
return new GenericCFGBuilder(statementHandlers, options);
}
const processForRangeStatement = forEachLoopProcessor({
query: `
(for_range_loop
")" @close-paren
body: (_) @body
) @range-loop
`,
body: "body",
headerEnd: "close-paren",
});
const statementHandlers: StatementHandlers = getStatementHandlers();
const cppSpecificHandlers: StatementHandlers["named"] = {
try_statement: processTryStatement,
throw_statement: processThrowStatement,
co_return_statement: processReturnStatement,
co_yield_statement: processCoYieldStatement,
for_range_loop: processForRangeStatement,
};
Object.assign(statementHandlers.named, cppSpecificHandlers);
function processCoYieldStatement(
coYieldSyntax: SyntaxNode,
ctx: Context,
): BasicBlock {
const yieldNode = ctx.builder.addNode(
"YIELD",
coYieldSyntax.text,
coYieldSyntax.startIndex,
);
ctx.link.syntaxToNode(coYieldSyntax, yieldNode);
return { entry: yieldNode, exit: yieldNode };
}
function isCatchAll(catchSyntax: SyntaxNode): boolean {
return Boolean(
catchSyntax
.childForFieldName("parameters")
?.children.some((child) => child?.text === "..."),
);
}
function processTryStatement(trySyntax: SyntaxNode, ctx: Context): BasicBlock {
const { builder, matcher } = ctx;
/*
Here's an idea - I can duplicate the finally blocks!
Then if there's a return, I stick the finally before it.
In other cases, the finally is after the end of the try-body.
This is probably the best course of action.
*/
const match = matcher.match(
trySyntax,
`
(try_statement
body: (_) @try-body
(
(catch_clause body: (_) @except-body) @except
(comment)?
)*
) @try
`,
);
const bodySyntax = match.requireSyntax("try-body");
const catchSyntaxMany = match.getSyntaxMany("except-body");
const mergeNode = builder.addNode(
"MERGE",
"merge tryComplex",
trySyntax.endIndex,
);
return builder.withCluster("tryComplex", (_tryComplexCluster) => {
const bodyBlock = builder.withCluster("try", () =>
match.getBlock(bodySyntax),
);
ctx.link.syntaxToNode(trySyntax, bodyBlock.entry);
const exceptBlocks = catchSyntaxMany.map((exceptSyntax) =>
builder.withCluster("except", () => match.getBlock(exceptSyntax)),
);
// Handle segmentation
for (const [syntax, { entry }] of zip(
match.getSyntaxMany("except"),
exceptBlocks,
)) {
ctx.link.syntaxToNode(syntax, entry);
}
for (const [first, second] of pairwise(match.getSyntaxMany("except"))) {
ctx.link.offsetToSyntax(first, second, { reverse: true });
}
// We attach the except-blocks to the top of the `try` body.
// In the rendering, we will connect them to the side of the node, and use invisible lines for it.
const headNode = bodyBlock.entry;
for (const [exceptBlock, exceptSyntax] of zip(
exceptBlocks,
match.getSyntaxMany("except"),
)) {
// Yes, this is effectively a head-to-head link. But that's ok.
builder.addEdge(headNode, exceptBlock.entry, "exception");
if (isCatchAll(exceptSyntax)) {
// We reached a `catch (...)`, so the rest are unreachable.
break;
}
}
// This is the exit we get to if we don't have an exception
// We need to connect the `except` blocks to the merge node
for (const exceptBlock of exceptBlocks) {
if (exceptBlock.exit) builder.addEdge(exceptBlock.exit, mergeNode);
}
const happyExit: string | null = bodyBlock.exit;
if (happyExit) builder.addEdge(happyExit, mergeNode);
return matcher.update({
entry: bodyBlock.entry,
exit: mergeNode,
});
});
}
const functionQuery = {
functionDeclarator: `
(function_declarator
declarator: [
(identifier) @name
(type_identifier) @name
(destructor_name) @name
(operator_name) @name
(operator_cast) @name
(field_identifier) @name
(qualified_identifier
name: [
(identifier) @name
(type_identifier) @name
(destructor_name) @name
(operator_name) @name
(operator_cast) @name
])
])
`,
functionDefinitionOperator: `
(function_definition
declarator: (operator_cast
(_) @type))
(function_definition
declarator: (qualified_identifier
name: (operator_cast
(_) @type)))`,
name: "name",
type: "type",
};
/**
* Get the function_declarator node for a function_definition.
* Uses descendantsOfType to find it directly, even if wrapped
* in pointer/reference/parenthesized declarators.
*/
function getFunctionDeclarator(funcDef: SyntaxNode): SyntaxNode | null {
const body = funcDef.childForFieldName("body");
const end = body ? body.startPosition : funcDef.endPosition;
const nodes = funcDef.descendantsOfType(
"function_declarator",
funcDef.startPosition,
end,
);
for (const node of nodes) {
const decl = node?.childForFieldName("declarator");
if (
decl &&
(decl.type === "identifier" ||
decl.type === "operator_name" ||
decl.type === "operator_cast" ||
decl.type === "destructor_name" ||
decl.type === "qualified_identifier" ||
decl.type === "type_identifier" ||
decl.type === "field_identifier")
) {
return node;
}
}
return null;
}
export function extractCppFunctionName(func: SyntaxNode): string | undefined {
if (func.type !== "function_definition") return undefined; //Just for now...
const declarator = getFunctionDeclarator(func);
const name = declarator
? extractTaggedValueFromTreeSitterQuery(
declarator,
functionQuery.functionDeclarator,
functionQuery.name,
)[0]
: undefined;
if (name) return name;
const type = extractTaggedValueFromTreeSitterQuery(
func,
functionQuery.functionDefinitionOperator,
functionQuery.type,
)[0];
return type ? `operator ${type}` : undefined;
}