-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcpp_project_index.py
More file actions
3280 lines (2629 loc) · 103 KB
/
cpp_project_index.py
File metadata and controls
3280 lines (2629 loc) · 103 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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import json
import re
import os
import shutil
import subprocess
import time
from collections import defaultdict
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable, AbstractSet, Iterable
from fnmatch import fnmatchcase
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, as_completed
from cpp_file_index import build_file_index
from cpp_index_sqlite import (
ThreadLocalIndexConnections,
build_sqlite_index,
row_json,
sqlite_index_path,
)
from cpp_index_utils import save_json
from cpp_lexer import find_matching_token, tokenize_lines, token_values
from cpp_structural_scan import extract_function_name
from cpp_comment_context import extract_file_header_comment, extract_leading_comment
from cpp_comment_context import format_source_lines
DEFAULT_SOURCE_EXTENSIONS = {
".c",
".cc",
".cpp",
".cxx",
".h",
".hh",
".hpp",
".hxx",
".ixx",
".cppm",
".mm",
}
DEFAULT_EXCLUDED_DIR_NAMES = {
".git",
".mcp-cpp-project-indexer",
".vs",
".vscode",
"build",
"out",
"bin",
"obj",
"x64",
"x86",
"arm64",
"Debug",
"Release",
"RelWithDebInfo",
"MinSizeRel",
"node_modules",
"__pycache__",
}
INDEXER_CONFIG_FILE_NAME = "indexer_config.json"
@dataclass(frozen=True, slots=True)
class DiscoveryConfig:
extensions: frozenset[str]
excluded_dir_names: frozenset[str]
include_extensionless_headers: bool
use_git_ignore: bool
def normalize_extension_item(value: Any) -> str | None:
if not isinstance(value, str):
return None
item = value.strip()
if not item:
return None
if not item.startswith("."):
item = "." + item
return item.casefold()
def normalize_extension_values(value: Any) -> set[str] | None:
if value is None:
return None
raw_items: list[Any]
if isinstance(value, str):
raw_items = [
part
for part in value.split(",")
]
elif isinstance(value, list):
raw_items = value
else:
return None
result: set[str] = set()
for item in raw_items:
normalized = normalize_extension_item(item)
if normalized is not None:
result.add(normalized)
return result
def normalize_name_values(value: Any) -> set[str] | None:
if value is None:
return None
raw_items: list[Any]
if isinstance(value, str):
raw_items = [
part
for part in value.split(",")
]
elif isinstance(value, list):
raw_items = value
else:
return None
result: set[str] = set()
for item in raw_items:
if not isinstance(item, str):
continue
normalized = item.strip().casefold()
if normalized:
result.add(normalized)
return result
PROJECT_INDEX_SCHEMA = "cpp.project_index.v1"
UPDATE_STATE_SCHEMA = "cpp.project_index.update_state.v1"
SYMBOL_COMPACT_FIELDS = {
"symbolId",
"type",
"shortName",
"qualifiedName",
"container",
"relativePath",
"startLine",
"endLine",
"signature",
"matchKind",
}
CODE_ENTITY_TYPE_SYMBOL_TYPES = {
"class",
"struct",
"enum",
"class_declaration",
"struct_declaration",
"type_alias",
"type_alias_template",
"typedef_declaration",
}
CODE_ENTITY_CALLABLE_SYMBOL_TYPES = {
"function",
"method",
"constructor",
"destructor",
"operator",
"function_declaration",
"method_declaration",
"constructor_declaration",
"destructor_declaration",
"operator_declaration",
}
def symbol_matches_type_filter(symbol: dict[str, Any], symbol_types: set[str] | None) -> bool:
if not symbol_types:
return True
return str(symbol.get("type") or "") in symbol_types
def symbol_matches_query_type_filter(
symbol: dict[str, Any],
symbol_types: set[str] | None,
*,
query: str,
container: str | None,
) -> bool:
if not symbol_types:
return True
symbol_type = str(symbol.get("type") or "")
if symbol_type in symbol_types:
return True
if "method" in symbol_types and symbol_type == "method_declaration":
return True
if "function" in symbol_types and symbol_type == "function_declaration":
return True
if "method" in symbol_types and symbol_type == "function":
qualified_name = str(symbol.get("qualifiedName") or "")
short_name = str(symbol.get("shortName") or "")
query_tail = query.rsplit("::", 1)[-1]
if not qualified_name or "::" not in qualified_name:
return False
if container and symbol_matches_container_filter(symbol, container):
return True
return (
short_name.casefold() == query_tail.casefold()
and (
"::" in query
or bool(container)
or qualified_name.count("::") >= 2
)
)
return False
def symbol_matches_namespace_filter(symbol: dict[str, Any], hide_namespaces: bool) -> bool:
if not hide_namespaces:
return True
return str(symbol.get("type") or "") != "namespace"
def symbol_matches_container_filter(symbol: dict[str, Any], container: str | None) -> bool:
if not container:
return True
item_container = str(symbol.get("container") or "")
qualified_name = str(symbol.get("qualifiedName") or "")
container_folded = container.casefold()
return (
item_container.casefold() == container_folded
or item_container.casefold().endswith("::" + container_folded)
or qualified_name.casefold().startswith(container_folded + "::")
)
def compact_symbol_ref(symbol: dict[str, Any]) -> dict[str, Any]:
return {
key: symbol.get(key)
for key in SYMBOL_COMPACT_FIELDS
if key in symbol
}
def code_entity_symbol_kind(symbol_type: str) -> str:
if symbol_type in CODE_ENTITY_TYPE_SYMBOL_TYPES:
return "type_symbol"
if symbol_type in CODE_ENTITY_CALLABLE_SYMBOL_TYPES:
return "callable_symbol"
return "symbol"
def code_entity_data_kind(item: dict[str, Any]) -> str:
declaration_kind = str(item.get("declarationKind") or "")
if declaration_kind == "field":
return "data_member"
if declaration_kind == "enum_value":
return "enum_value"
if declaration_kind == "concept":
return "concept"
if declaration_kind == "variable_template":
return "variable_template"
return "data_declaration"
FILE_STRUCTURE_SYMBOL_COMPACT_FIELDS = {
"kind",
"symbolId",
"type",
"name",
"shortName",
"container",
"relativePath",
"startLine",
"endLine",
"signature",
}
FILE_STRUCTURE_DATA_COMPACT_FIELDS = {
"kind",
"dataId",
"declarationKind",
"scopeKind",
"name",
"shortName",
"container",
"typeText",
"relativePath",
"startLine",
"endLine",
"signature",
}
def compact_file_structure_item(item: dict[str, Any]) -> dict[str, Any]:
if item.get("kind") == "data":
fields = FILE_STRUCTURE_DATA_COMPACT_FIELDS
else:
fields = FILE_STRUCTURE_SYMBOL_COMPACT_FIELDS
return {
key: item.get(key)
for key in fields
if key in item
}
FILE_DEBUG_COMPACT_FIELDS = {
"kind",
"name",
"qualifiedName",
"startLine",
"endLine",
"startCol0",
"endCol0Exclusive",
"signature",
"fragment",
"scopeKind",
"parent",
"bodyStartLine",
"bodyEndLine",
"message",
"severity",
"code",
}
FILE_DEBUG_KINDS = {
"diagnostics",
"structuralEvents",
"scopeIntervals",
"functionBodyRanges",
}
def compact_file_debug_item(item: dict[str, Any]) -> dict[str, Any]:
return {
key: item.get(key)
for key in FILE_DEBUG_COMPACT_FIELDS
if key in item
}
def item_line_range(item: dict[str, Any]) -> tuple[int, int] | None:
range_item = item.get("range")
if isinstance(range_item, dict):
start_line = int(range_item.get("startLine") or 0)
end_line = int(range_item.get("endLine") or start_line or 0)
else:
start_line = int(
item.get("startLine")
or item.get("line")
or item.get("bodyStartLine")
or 0
)
end_line = int(
item.get("endLine")
or item.get("line")
or item.get("bodyEndLine")
or start_line
or 0
)
if start_line <= 0 and end_line <= 0:
return None
if end_line <= 0:
end_line = start_line
return start_line, end_line
def item_overlaps_line_filter(
item: dict[str, Any],
start_line: int | None,
end_line: int | None,
) -> bool:
if start_line is None and end_line is None:
return True
item_range = item_line_range(item)
if item_range is None:
return True
item_start, item_end = item_range
filter_start = start_line if start_line is not None else item_start
filter_end = end_line if end_line is not None else item_end
return item_start <= filter_end and filter_start <= item_end
def normalize_debug_item(item: dict[str, Any]) -> dict[str, Any]:
range_item = item.get("range")
if isinstance(range_item, dict):
result = {
key: value
for key, value in item.items()
if key != "range"
}
result.setdefault("startLine", range_item.get("startLine"))
result.setdefault("endLine", range_item.get("endLine"))
result.setdefault("startCol0", range_item.get("startCol0"))
result.setdefault("endCol0Exclusive", range_item.get("endCol0Exclusive"))
return result
return dict(item)
def data_matches_kind_filter(item: dict[str, Any], data_kinds: set[str] | None) -> bool:
if not data_kinds:
return True
return str(item.get("declarationKind") or "") in data_kinds
def symbol_match_kind(symbol: dict[str, Any], query: str) -> str:
query_folded = query.casefold()
short_name = str(symbol.get("shortName") or "")
qualified_name = str(symbol.get("qualifiedName") or "")
signature = str(symbol.get("signature") or "")
if qualified_name and qualified_name == query:
return "exact_qualified_name"
if short_name and short_name == query:
return "exact_short_name"
if qualified_name and qualified_name.casefold() == query_folded:
return "case_insensitive_qualified_name"
if short_name and short_name.casefold() == query_folded:
return "case_insensitive_short_name"
if qualified_name and query_folded in qualified_name.casefold():
return "qualified_name_substring"
if short_name and query_folded in short_name.casefold():
return "short_name_substring"
if signature and query_folded in signature.casefold():
return "signature_substring"
return "metadata_match"
def symbol_match_rank(match_kind: str) -> int:
ranks = {
"exact_qualified_name": 0,
"exact_short_name": 1,
"case_insensitive_qualified_name": 2,
"case_insensitive_short_name": 3,
"qualified_name_substring": 4,
"short_name_substring": 5,
"signature_substring": 6,
"metadata_match": 7,
}
return ranks.get(match_kind, 100)
def is_exact_symbol_match(symbol: dict[str, Any], query: str) -> bool:
match_kind = symbol_match_kind(symbol, query)
return match_kind in {
"exact_qualified_name",
"exact_short_name",
"case_insensitive_qualified_name",
"case_insensitive_short_name",
}
def project_stats_from_manifest_files(files: list[dict[str, Any]]) -> dict[str, int]:
return {
"totalCodeLines": sum(int(item.get("lineCount") or 0) for item in files),
"totalTokens": sum(int(item.get("tokenCount") or 0) for item in files),
}
def project_stats_from_manifest(manifest: dict[str, Any]) -> dict[str, int]:
stats = manifest.get("stats")
if isinstance(stats, dict):
return {
"totalCodeLines": int(stats.get("totalCodeLines") or 0),
"totalTokens": int(stats.get("totalTokens") or 0),
}
files = manifest.get("files")
if isinstance(files, list):
return project_stats_from_manifest_files(files)
return {
"totalCodeLines": 0,
"totalTokens": 0,
}
@dataclass(slots=True)
class ProjectIndexBuildResult:
root: Path
output_root: Path
files_count: int
symbols_count: int
names_count: int
data_count: int
data_names_count: int
modules_count: int
diagnostics_count: int
total_code_lines: int
total_tokens: int
timings: list[dict[str, Any]]
BuildPhaseCallback = Callable[[str, str, float | None], None]
# ---------------------------------------------------------------------------
# File discovery
# ---------------------------------------------------------------------------
def should_skip_dir(path: Path, excluded_dir_names: AbstractSet[str]) -> bool:
return any(part in excluded_dir_names for part in path.parts)
def _is_excluded_dir_name(name: str, excluded_dir_names: AbstractSet[str]) -> bool:
return name.startswith(".") or name.casefold() in excluded_dir_names
def git_ignored_source_files(root: Path, files: list[Path]) -> set[Path]:
if not files:
return set()
root = root.resolve()
git_executable = shutil.which("git")
if git_executable is None:
return set()
try:
inside_worktree = subprocess.run(
[git_executable, "-C", str(root), "rev-parse", "--is-inside-work-tree"],
check=False,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
encoding="utf-8",
errors="replace",
timeout=10,
)
except (OSError, subprocess.SubprocessError):
return set()
if inside_worktree.returncode != 0 or inside_worktree.stdout.strip() != "true":
return set()
relative_paths = [
path.resolve().relative_to(root).as_posix()
for path in files
]
try:
ignored = subprocess.run(
[git_executable, "-C", str(root), "check-ignore", "--stdin"],
input="\n".join(relative_paths),
check=False,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
encoding="utf-8",
errors="replace",
timeout=30,
)
except (OSError, subprocess.SubprocessError):
return set()
if ignored.returncode not in {0, 1}:
return set()
ignored_paths = {
item.strip()
for item in ignored.stdout.splitlines()
if item.strip()
}
return {
root / relative_path
for relative_path in ignored_paths
}
def load_discovery_config(directory: Path, parent: DiscoveryConfig) -> DiscoveryConfig:
config_path = directory / INDEXER_CONFIG_FILE_NAME
try:
raw = json.loads(config_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return parent
if not isinstance(raw, dict):
return parent
extensions = set(parent.extensions)
excluded_dir_names = set(parent.excluded_dir_names)
include_extensionless_headers = parent.include_extensionless_headers
replacement_extensions = normalize_extension_values(raw.get("extensions"))
if replacement_extensions is not None:
extensions = replacement_extensions
add_extensions = normalize_extension_values(raw.get("addExtensions"))
if add_extensions is not None:
extensions.update(add_extensions)
remove_extensions = normalize_extension_values(raw.get("removeExtensions"))
if remove_extensions is not None:
extensions.difference_update(remove_extensions)
replacement_excluded_dirs = normalize_name_values(raw.get("excludeDirs"))
if replacement_excluded_dirs is not None:
excluded_dir_names = replacement_excluded_dirs
add_excluded_dirs = normalize_name_values(raw.get("addExcludeDirs"))
if add_excluded_dirs is not None:
excluded_dir_names.update(add_excluded_dirs)
remove_excluded_dirs = normalize_name_values(raw.get("removeExcludeDirs"))
if remove_excluded_dirs is not None:
excluded_dir_names.difference_update(remove_excluded_dirs)
include_extensionless_value = raw.get("includeExtensionlessHeaders")
if isinstance(include_extensionless_value, bool):
include_extensionless_headers = include_extensionless_value
use_git_ignore = parent.use_git_ignore
use_git_ignore_value = raw.get("useGitIgnore")
if isinstance(use_git_ignore_value, bool):
use_git_ignore = use_git_ignore_value
return DiscoveryConfig(
extensions=frozenset(extensions),
excluded_dir_names=frozenset(excluded_dir_names),
include_extensionless_headers=include_extensionless_headers,
use_git_ignore=use_git_ignore,
)
def discover_source_files(
root: Path,
*,
extensions: set[str] | None = None,
excluded_dir_names: set[str] | None = None,
include_extensionless_headers: bool = False,
use_git_ignore: bool = True,
progress_callback: Callable[[int, Path], None] | None = None,
) -> list[Path]:
base_config = DiscoveryConfig(
extensions=frozenset(
item.casefold()
for item in (extensions or DEFAULT_SOURCE_EXTENSIONS)
),
excluded_dir_names=frozenset(
item.casefold()
for item in (excluded_dir_names or DEFAULT_EXCLUDED_DIR_NAMES)
),
include_extensionless_headers=include_extensionless_headers,
use_git_ignore=use_git_ignore,
)
files: list[Path] = []
git_ignore_enabled = False
visited = 0
def walk(directory: Path, inherited_config: DiscoveryConfig) -> None:
nonlocal visited, git_ignore_enabled
config = load_discovery_config(directory, inherited_config)
git_ignore_enabled = git_ignore_enabled or config.use_git_ignore
try:
entries = list(os.scandir(directory))
except OSError:
return
for entry in entries:
try:
if entry.is_dir(follow_symlinks=False):
if not _is_excluded_dir_name(entry.name, config.excluded_dir_names):
walk(Path(entry.path), config)
continue
if not entry.is_file(follow_symlinks=False):
continue
except OSError:
continue
visited += 1
suffix = os.path.splitext(entry.name)[1].casefold()
if suffix not in config.extensions:
if suffix or not config.include_extensionless_headers:
continue
path = Path(entry.path)
if not looks_like_extensionless_cpp_header(path):
continue
else:
path = Path(entry.path)
if progress_callback is not None:
progress_callback(visited, path)
files.append(path)
walk(root, base_config)
ignored_files = git_ignored_source_files(root, files) if git_ignore_enabled else set()
if ignored_files:
ignored_resolved = {
path.resolve()
for path in ignored_files
}
files = [
path
for path in files
if path.resolve() not in ignored_resolved
]
files.sort(key=lambda item: item.as_posix().casefold())
return files
def looks_like_extensionless_cpp_header(path: Path) -> bool:
try:
data = path.read_bytes()[:32768]
except OSError:
return False
if b"\0" in data:
return False
try:
text = data.decode("utf-8")
except UnicodeDecodeError:
try:
text = data.decode("latin-1")
except UnicodeDecodeError:
return False
lines = text.splitlines()[:80]
if not lines:
return False
joined = "\n".join(lines)
stripped_lines = [
line.strip()
for line in lines
if line.strip() and not line.strip().startswith(("//", "/*", "*"))
]
if not stripped_lines:
return False
positive_patterns = [
r"^\s*#\s*pragma\s+once\b",
r"^\s*#\s*ifndef\s+\w+",
r"^\s*#\s*define\s+\w+",
r"^\s*#\s*include\s+[<\"]",
r"^\s*(export\s+)?module\s+[\w.:]+",
r"^\s*(export\s+)?import\s+[\w.:<\"]",
r"^\s*namespace\s+[\w:]+",
r"^\s*(template\s*<|class\s+\w+|struct\s+\w+|enum\s+(class\s+)?\w+)",
r"^\s*(using|typedef)\s+.+[;=]",
]
negative_patterns = [
r"^\s*#!",
r"^\s*<\?xml\b",
r"^\s*[{[]",
r"^\s*(FROM|SELECT|INSERT|UPDATE|DELETE)\b",
]
for pattern in negative_patterns:
if re.search(pattern, joined, re.IGNORECASE | re.MULTILINE):
return False
score = 0
for pattern in positive_patterns:
if re.search(pattern, joined, re.MULTILINE):
score += 1
first_code_line = stripped_lines[0]
if first_code_line.startswith("#") and score >= 1:
return True
return score >= 2
def update_state_path(index_root: Path) -> Path:
return index_root / "update_state.json"
def save_update_state_from_file_indexes(
*,
index_root: Path,
root: Path,
file_indexes: list[dict[str, Any]],
case_insensitive_paths: bool,
) -> None:
files: dict[str, dict[str, Any]] = {}
for file_index in file_indexes:
relative_path = str(file_index["relativePath"])
key = relative_path.casefold() if case_insensitive_paths else relative_path
path = root / relative_path
try:
stat = path.stat()
mtime_ns = stat.st_mtime_ns
size = stat.st_size
except OSError:
mtime_ns = None
size = None
files[key] = {
"relativePath": relative_path,
"fileId": file_index["fileId"],
"rawContentHash": file_index["contentHash"],
"mtimeNs": mtime_ns,
"size": size,
}
save_json(
update_state_path(index_root),
{
"schema": UPDATE_STATE_SCHEMA,
"root": root.resolve().as_posix(),
"files": dict(sorted(files.items(), key=lambda item: item[0].casefold())),
},
)
# ---------------------------------------------------------------------------
# Name extraction from minimal runtime symbols
# ---------------------------------------------------------------------------
def _signature_tokens(signature: str):
return tokenize_lines([signature])
def _extract_type_name_from_signature(signature: str, keyword: str) -> str | None:
tokens = _signature_tokens(signature)
values = token_values(tokens)
if keyword not in values:
return None
index = values.index(keyword) + 1
# enum class / enum struct
if keyword == "enum" and index < len(tokens) and tokens[index].value in {"class", "struct"}:
index += 1
if index < len(tokens) and tokens[index].kind == "identifier":
return tokens[index].value
return None
def _extract_function_name_from_signature(signature: str) -> str | None:
tokens = _signature_tokens(signature)
candidates: list[int] = []
for index, token in enumerate(tokens):
if token.value != "(":
continue
if index == 0:
continue
close = find_matching_token(tokens, index, "(", ")")
if close is None:
continue
previous = tokens[index - 1]
if previous.value in {"decltype", "sizeof", "alignof", "noexcept", "requires"}:
continue
candidates.append(index)
if not candidates:
return None
paren_index = candidates[-1]
short_name, visible_name = extract_function_name(tokens, paren_index)
return visible_name or short_name or None
def derive_short_name(symbol: dict[str, Any]) -> str | None:
existing = symbol.get("shortName") or symbol.get("name")
if isinstance(existing, str) and existing:
return existing
symbol_type = symbol.get("type", "")
signature = str(symbol.get("signature", ""))
if symbol_type in {"class", "class_declaration"}:
return _extract_type_name_from_signature(signature, "class")
if symbol_type in {"struct", "struct_declaration"}:
return _extract_type_name_from_signature(signature, "struct")
if symbol_type == "enum":
return _extract_type_name_from_signature(signature, "enum")
if symbol_type == "namespace":
name = _extract_type_name_from_signature(signature, "namespace")
return name or "<anonymous>"
if symbol_type in {
"function",
"function_declaration",
"method",
"method_declaration",
"constructor",
"constructor_declaration",
"destructor",
"destructor_declaration",
"operator",
"operator_declaration",
}:
return _extract_function_name_from_signature(signature)
return None
def qualify_name(container: str | None, short_name: str | None) -> str | None:
if not short_name:
return None
if "::" in short_name:
return short_name
if container:
return f"{container}::{short_name}"
return short_name
def search_aliases_for_symbol(symbol: dict[str, Any]) -> list[str]:
short_name = derive_short_name(symbol)
container = symbol.get("container")
qualified_name = qualify_name(container, short_name)
aliases: list[str] = []
if short_name:
aliases.append(short_name)
if qualified_name and qualified_name not in aliases:
aliases.append(qualified_name)
# Anonymous namespace convenience alias:
# UI::<anonymous@25>::Helper -> UI::Helper
# This is for search only. The runtime symbol keeps the real container.
if qualified_name and "::<anonymous" in qualified_name:
simplified = qualified_name
while "::<anonymous" in simplified:
prefix, rest = simplified.split("::<anonymous", 1)
after = rest.split(">", 1)
if len(after) != 2:
break
simplified = prefix + after[1]
if simplified and simplified not in aliases:
aliases.append(simplified)