forked from ThinkyMiner/codeTree
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcpp.py
More file actions
373 lines (337 loc) · 16.3 KB
/
Copy pathcpp.py
File metadata and controls
373 lines (337 loc) · 16.3 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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
from tree_sitter import Language, Parser, Query
import tree_sitter_cpp as tscpp
from .c import CPlugin
from .base import _matches, _fill_docs_from_siblings
_LANGUAGE = Language(tscpp.language())
_PARSER = Parser(_LANGUAGE)
def _parse(source: bytes):
return _PARSER.parse(source)
class CppPlugin(CPlugin):
"""C++ plugin — inherits C functionality, adds classes, namespaces, methods."""
extensions = (".cpp", ".cc", ".cxx", ".hpp", ".hh")
def _get_language(self):
return _LANGUAGE
def _get_parser(self):
return _PARSER
def extract_skeleton(self, source: bytes) -> list[dict]:
lang = _LANGUAGE
tree = _parse(source)
results = []
# Classes
q = Query(lang, "(class_specifier name: (type_identifier) @name) @def")
for _, m in _matches(q, tree.root_node):
results.append({
"type": "class",
"name": m["name"].text.decode("utf-8", errors="replace"),
"line": m["name"].start_point[0] + 1,
"parent": None,
"params": "",
})
# Methods inside classes (function_definition in field_declaration_list)
q = Query(lang, """
(class_specifier
name: (type_identifier) @class_name
body: (field_declaration_list
(function_definition
declarator: (function_declarator
declarator: (field_identifier) @method_name
parameters: (parameter_list) @params))))
""")
for _, m in _matches(q, tree.root_node):
results.append({
"type": "method",
"name": m["method_name"].text.decode("utf-8", errors="replace"),
"line": m["method_name"].start_point[0] + 1,
"parent": m["class_name"].text.decode("utf-8", errors="replace"),
"params": m["params"].text.decode("utf-8", errors="replace"),
})
# Structs (C++ uses same struct_specifier as C)
q = Query(lang, "(struct_specifier name: (type_identifier) @name body: (field_declaration_list)) @def")
for _, m in _matches(q, tree.root_node):
results.append({
"type": "struct",
"name": m["name"].text.decode("utf-8", errors="replace"),
"line": m["name"].start_point[0] + 1,
"parent": None,
"params": "",
})
# Top-level functions (translation_unit direct children)
q = Query(lang, """
(translation_unit
(function_definition
declarator: (function_declarator
declarator: (identifier) @name
parameters: (parameter_list) @params)) @def)
""")
for _, m in _matches(q, tree.root_node):
results.append({
"type": "function",
"name": m["name"].text.decode("utf-8", errors="replace"),
"line": m["name"].start_point[0] + 1,
"parent": None,
"params": m["params"].text.decode("utf-8", errors="replace"),
})
# Functions inside namespaces
q = Query(lang, """
(namespace_definition
body: (declaration_list
(function_definition
declarator: (function_declarator
declarator: (identifier) @name
parameters: (parameter_list) @params)) @def))
""")
for _, m in _matches(q, tree.root_node):
results.append({
"type": "function",
"name": m["name"].text.decode("utf-8", errors="replace"),
"line": m["name"].start_point[0] + 1,
"parent": None,
"params": m["params"].text.decode("utf-8", errors="replace"),
})
# Fill doc fields
for item in results:
item.setdefault("doc", "")
_fill_docs_from_siblings(results, tree.root_node, lang, [
"(class_specifier name: (type_identifier) @name) @def",
"(struct_specifier name: (type_identifier) @name) @def",
"(function_definition declarator: (function_declarator declarator: (identifier) @name)) @def",
])
# Deduplicate
seen = set()
deduped = []
for item in results:
key = (item["name"], item["line"])
if key not in seen:
seen.add(key)
deduped.append(item)
deduped.sort(key=lambda x: x["line"])
return deduped
def extract_symbol_source(self, source: bytes, name: str) -> tuple[str, int] | None:
lang = _LANGUAGE
tree = _parse(source)
# Functions — check both identifier (top-level) and field_identifier (class methods)
q = Query(lang, "(function_definition declarator: (function_declarator declarator: [(identifier) @name (field_identifier) @name])) @def")
for _, m in _matches(q, tree.root_node):
if m["name"].text.decode("utf-8", errors="replace") == name:
node = m["def"]
return source[node.start_byte:node.end_byte].decode("utf-8", errors="replace"), node.start_point[0] + 1
# Classes
q = Query(lang, "(class_specifier name: (type_identifier) @name) @def")
for _, m in _matches(q, tree.root_node):
if m["name"].text.decode("utf-8", errors="replace") == name:
node = m["def"]
return source[node.start_byte:node.end_byte].decode("utf-8", errors="replace"), node.start_point[0] + 1
# Structs
q = Query(lang, "(struct_specifier name: (type_identifier) @name body: (field_declaration_list)) @def")
for _, m in _matches(q, tree.root_node):
if m["name"].text.decode("utf-8", errors="replace") == name:
node = m["def"]
return source[node.start_byte:node.end_byte].decode("utf-8", errors="replace"), node.start_point[0] + 1
return None
def extract_calls_in_function(self, source: bytes, fn_name: str) -> list[str]:
lang = _LANGUAGE
tree = _parse(source)
fn_node = None
q = Query(lang, "(function_definition declarator: (function_declarator declarator: [(identifier) @name (field_identifier) @name])) @def")
for _, m in _matches(q, tree.root_node):
if m["name"].text.decode("utf-8", errors="replace") == fn_name:
fn_node = m["def"]
break
if fn_node is None:
return []
q = Query(lang, """
(call_expression function: [
(identifier) @called
(field_expression field: (field_identifier) @called)
])
""")
calls = set()
for _, m in _matches(q, fn_node):
calls.add(m["called"].text.decode("utf-8", errors="replace"))
return sorted(calls)
def extract_symbol_usages(self, source: bytes, name: str) -> list[dict]:
tree = _parse(source)
usages = []
seen = set()
for node_type in ("identifier", "type_identifier", "field_identifier", "namespace_identifier"):
q = Query(_LANGUAGE, f'(({node_type}) @name (#eq? @name "{name}"))')
for _, m in _matches(q, tree.root_node):
node = m["name"]
key = (node.start_point[0], node.start_point[1])
if key not in seen:
seen.add(key)
usages.append({"line": node.start_point[0] + 1, "col": node.start_point[1]})
usages.sort(key=lambda x: (x["line"], x["col"]))
return usages
def extract_imports(self, source: bytes) -> list[dict]:
tree = _parse(source)
results = []
# #include statements
q = Query(_LANGUAGE, "(translation_unit (preproc_include) @imp)")
for _, m in _matches(q, tree.root_node):
node = m["imp"]
results.append({
"line": node.start_point[0] + 1,
"text": node.text.decode("utf-8", errors="replace").strip(),
})
# using declarations
q = Query(_LANGUAGE, "(translation_unit (using_declaration) @imp)")
for _, m in _matches(q, tree.root_node):
node = m["imp"]
results.append({
"line": node.start_point[0] + 1,
"text": node.text.decode("utf-8", errors="replace").strip(),
})
results.sort(key=lambda x: x["line"])
return results
def check_syntax(self, source: bytes) -> bool:
return _parse(source).root_node.has_error
def extract_variables(self, source: bytes, fn_name: str) -> list[dict]:
tree = _parse(source)
# Find function node — check both identifier (top-level) and field_identifier (class methods)
fn_node = None
q = Query(_LANGUAGE, "(function_definition declarator: (function_declarator declarator: [(identifier) @name (field_identifier) @name])) @def")
for _, m in _matches(q, tree.root_node):
if m["name"].text.decode("utf-8", errors="replace") == fn_name:
fn_node = m["def"]
break
if fn_node is None:
return []
results = []
seen = set()
def _add(name, line, var_type="", kind="local"):
if name not in seen:
seen.add(name)
results.append({"name": name, "line": line, "type": var_type, "kind": kind})
# Extract parameters from parameter_list
for child in fn_node.children:
if child.type == "function_declarator":
for sub in child.children:
if sub.type == "parameter_list":
for param in sub.children:
if param.type == "parameter_declaration":
id_node = None
type_parts = []
for pc in param.children:
if pc.type == "identifier":
id_node = pc
elif pc.type == "pointer_declarator":
for ppc in pc.children:
if ppc.type == "identifier":
id_node = ppc
elif pc.type == "reference_declarator":
for ppc in pc.children:
if ppc.type == "identifier":
id_node = ppc
elif pc.type not in (",", "(", ")"):
type_parts.append(pc.text.decode("utf-8", errors="replace"))
if id_node:
_add(id_node.text.decode("utf-8", errors="replace"),
id_node.start_point[0] + 1,
var_type=" ".join(type_parts), kind="parameter")
break
# Walk the function body
def walk(node):
if node.type == "declaration":
type_text = ""
for child in node.children:
if child.type in ("primitive_type", "type_identifier", "sized_type_specifier",
"template_type", "auto"):
type_text = child.text.decode("utf-8", errors="replace")
break
for child in node.children:
if child.type == "init_declarator":
for sub in child.children:
if sub.type == "identifier":
_add(sub.text.decode("utf-8", errors="replace"),
sub.start_point[0] + 1, var_type=type_text)
break
elif sub.type == "reference_declarator":
for ppc in sub.children:
if ppc.type == "identifier":
_add(ppc.text.decode("utf-8", errors="replace"),
ppc.start_point[0] + 1, var_type=type_text)
break
break
break
elif child.type == "identifier":
_add(child.text.decode("utf-8", errors="replace"),
child.start_point[0] + 1, var_type=type_text)
elif node.type == "for_range_loop":
# for (auto& item : collection)
type_text = ""
id_node = None
for child in node.children:
if child.type in ("primitive_type", "type_identifier", "auto",
"placeholder_type_specifier"):
type_text = child.text.decode("utf-8", errors="replace")
elif child.type == "identifier" and type_text and id_node is None:
id_node = child
elif child.type == "reference_declarator" and id_node is None:
for sub in child.children:
if sub.type == "identifier":
id_node = sub
break
if id_node:
_add(id_node.text.decode("utf-8", errors="replace"),
id_node.start_point[0] + 1, var_type=type_text, kind="loop_var")
elif node.type == "for_statement":
for child in node.children:
if child.type == "declaration":
type_text = ""
for sub in child.children:
if sub.type in ("primitive_type", "type_identifier", "sized_type_specifier"):
type_text = sub.text.decode("utf-8", errors="replace")
break
for sub in child.children:
if sub.type == "init_declarator":
for ssub in sub.children:
if ssub.type == "identifier":
_add(ssub.text.decode("utf-8", errors="replace"),
ssub.start_point[0] + 1, var_type=type_text, kind="loop_var")
break
break
break
for child in node.children:
walk(child)
for child in fn_node.children:
if child.type == "compound_statement":
walk(child)
break
return results
def compute_complexity(self, source: bytes, fn_name: str) -> dict | None:
tree = _parse(source)
fn_node = None
q = Query(_LANGUAGE, "(function_definition declarator: (function_declarator declarator: [(identifier) @name (field_identifier) @name])) @def")
for _, m in _matches(q, tree.root_node):
if m["name"].text.decode("utf-8", errors="replace") == fn_name:
fn_node = m["def"]
break
if fn_node is None:
return None
branch_map = {
"if_statement": "if",
"for_statement": "for",
"for_range_loop": "for_range",
"while_statement": "while",
"do_statement": "do_while",
"case_statement": "case",
"catch_clause": "catch",
}
counts: dict[str, int] = {}
def walk(node):
if node.type in branch_map:
label = branch_map[node.type]
counts[label] = counts.get(label, 0) + 1
elif node.type == "binary_expression":
op = None
for child in node.children:
if child.type in ("&&", "||"):
op = child.type
if op:
counts[op] = counts.get(op, 0) + 1
for child in node.children:
walk(child)
walk(fn_node)
total = 1 + sum(counts.values())
return {"total": total, "breakdown": counts}