Repository navigation
Expand file tree
/
Copy pathcode_context.py
More file actions
1833 lines (1717 loc) · 77.5 KB
/
Copy pathcode_context.py
File metadata and controls
1833 lines (1717 loc) · 77.5 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
"""Persistent code facts. SQLite is the source of truth, packs are disposable views.
Python relationships are conservative static references, NOT a dynamic call graph.
C/C++/CUDA/Rust/JS declarations are explicitly heuristic. Unresolved calls remain
unresolved rather than being joined to unrelated same-name methods.
"""
from infinicoder._resources import package_root
import argparse
import ast
from collections import Counter
import hashlib
import json
import math
from pathlib import Path
import re
import sqlite3
IGNORED = {
".git",
".infinicoder",
".kb",
"__pycache__",
"node_modules",
".venv",
"venv",
"dist",
"build",
".pytest_cache",
}
LANGUAGES = {
".py": "python",
".c": "c",
".h": "c",
".cc": "cpp",
".cpp": "cpp",
".cxx": "cpp",
".hh": "cpp",
".hpp": "cpp",
".cu": "cuda",
".cuh": "cuda",
".rs": "rust",
".js": "javascript",
".ts": "typescript",
".tsx": "typescript",
".md": "markdown",
".rst": "restructuredtext",
".txt": "text",
".ipynb": "notebook",
".json": "json",
".toml": "toml",
".yaml": "yaml",
".yml": "yaml",
".ini": "config",
".cfg": "config",
".sh": "shell",
}
def digest(data):
return hashlib.sha256(data).hexdigest()
def dataflow_identity():
"""On-demand views have an analysis identity even with unchanged source."""
return digest((package_root() / "analysis/dataflow.py").read_bytes())
def words(text):
# Split snake/camel identifiers and preserve Chinese terms/bigrams.
text = re.sub(r"([a-z0-9])([A-Z])", r"\1 \2", text)
tokens = re.findall(r"[a-zA-Z0-9]+|[\u4e00-\u9fff]+", text.lower())
return [
part
for token in tokens
for part in (
[token] + [token[i : i + 2] for i in range(len(token) - 1)]
if re.search(r"[\u4e00-\u9fff]", token)
else [token]
)
]
def python_facts(path, source):
tree = ast.parse(source)
symbols, refs, binding_sites = [], [], []
imports = {}
def local_names(function):
names, globals_ = set(), set()
class Locals(ast.NodeVisitor):
def visit_Name(self, node):
if isinstance(node.ctx, (ast.Store, ast.Del)):
names.add(node.id)
def visit_FunctionDef(self, node):
names.add(node.name)
visit_AsyncFunctionDef = visit_FunctionDef
def visit_ClassDef(self, node):
names.add(node.name)
def visit_Lambda(self, node):
pass
def visit_Global(self, node):
globals_.update(node.names)
def visit_Import(self, node):
names.update(a.asname or a.name.split(".")[0] for a in node.names)
def visit_ImportFrom(self, node):
names.update(a.asname or a.name for a in node.names if a.name != "*")
def visit_ExceptHandler(self, node):
if node.name:
names.add(node.name)
self.generic_visit(node)
collector = Locals()
for statement in function.body:
collector.visit(statement)
return names - globals_
class Visitor(ast.NodeVisitor):
def __init__(self):
self.scope = []
self.owner = path + "::<module>"
self.classes = []
# lexical bindings per function scope (params, locals,
# local imports) so calls through local names never link to globals.
self.bindings = [set()]
def _bind(self, names):
for n in names:
if isinstance(n, str):
self.bindings[-1].add(n)
def visit_Import(self, node):
inside_function = len(self.bindings) > 1
for a in node.names:
name = a.asname or a.name.split(".")[0]
if not inside_function:
imports[name] = a.name if a.asname else a.name.split(".")[0]
if inside_function:
self._bind([name]) # function-local import shadows globals
self.generic_visit(node)
def visit_ImportFrom(self, node):
module = "." * node.level + (node.module or "")
for a in node.names:
if a.name != "*":
if len(self.bindings) == 1:
imports[a.asname or a.name] = module + ("." if node.module else "") + a.name
if len(self.bindings) > 1:
self._bind([a.asname or a.name])
def visit_ClassDef(self, node):
qual = ".".join(self.scope + [node.name])
fields = []
for child in node.body:
if isinstance(child, ast.AnnAssign) and isinstance(child.target, ast.Name):
fields.append({"name": child.target.id, "type": ast.unparse(child.annotation)})
symbols.append(
{
"id": path + "::" + qual,
"name": node.name,
"qualname": qual,
"kind": "class",
"line": node.lineno,
"end": node.end_lineno,
"signature": "class "
+ qual
+ "("
+ ", ".join(ast.unparse(b) for b in node.bases)
+ ")",
"doc": (ast.get_docstring(node) or "")[:600],
"fields": fields,
"confidence": "syntax",
}
)
old = self.owner
self.scope.append(node.name)
self.classes.append(qual)
self.owner = path + "::" + qual
self.generic_visit(node)
self.scope.pop()
self.classes.pop()
self.owner = old
def visit_FunctionDef(self, node):
qual = ".".join(self.scope + [node.name])
sig = (
("async " if isinstance(node, ast.AsyncFunctionDef) else "")
+ "def "
+ qual
+ "("
+ ast.unparse(node.args)
+ ")"
)
if node.returns:
sig += " -> " + ast.unparse(node.returns)
symbols.append(
{
"id": path + "::" + qual,
"name": node.name,
"qualname": qual,
"kind": "function",
"line": node.lineno,
"end": node.end_lineno,
"signature": sig,
"doc": (ast.get_docstring(node) or "")[:600],
"fields": [],
"confidence": "syntax",
}
)
old = self.owner
self.owner = path + "::" + qual
self.scope.append(node.name)
# parameters are bindings of this function scope.
argnames = [
a.arg for a in node.args.args + node.args.posonlyargs + node.args.kwonlyargs
]
if node.args.vararg:
argnames.append(node.args.vararg.arg)
if node.args.kwarg:
argnames.append(node.args.kwarg.arg)
# Python determines locals for the entire function, not in source
# visitation order (a later assignment shadows an earlier call).
self.bindings.append(set(argnames) | local_names(node))
for child in node.body:
self.visit(child)
self.scope.pop()
self.bindings.pop()
self.owner = old
visit_AsyncFunctionDef = visit_FunctionDef
def _assigned_names(self, target):
"""Collect simple names bound by an assignment/for/with/except target."""
if isinstance(target, ast.Name):
self._bind([target.id])
elif isinstance(target, (ast.Tuple, ast.List)):
for elt in target.elts:
self._assigned_names(elt)
elif isinstance(target, ast.Starred):
self._assigned_names(target.value)
def visit_Assign(self, node):
for t in node.targets:
self._assigned_names(t)
self._binding_symbols(t, node)
self.generic_visit(node)
def visit_AnnAssign(self, node):
if node.value is not None:
self._assigned_names(node.target)
self._binding_symbols(node.target, node)
self.generic_visit(node)
def _binding_symbols(self, target, node):
if len(self.bindings) > 1:
return
if isinstance(target, (ast.Tuple, ast.List)):
for item in target.elts:
self._binding_symbols(item, node)
return
if not isinstance(target, ast.Name):
return
qual = ".".join(self.scope + [target.id])
sid = path + "::" + qual
kind = "class_field" if self.classes else "variable"
symbols.append(
{
"id": sid,
"name": target.id,
"qualname": qual,
"kind": kind,
"line": node.lineno,
"end": node.end_lineno,
"signature": ast.unparse(node)[:500],
"doc": "",
"fields": [],
"confidence": "syntax-binding-candidate",
}
)
binding_sites.append(
{"symbol_id": sid, "line": node.lineno, "end": node.end_lineno, "kind": kind}
)
def visit_AugAssign(self, node):
self._assigned_names(node.target)
self.generic_visit(node)
def visit_For(self, node):
self._assigned_names(node.target)
self.generic_visit(node)
visit_AsyncFor = visit_For
def visit_With(self, node):
for item in node.items:
if item.optional_vars is not None:
self._assigned_names(item.optional_vars)
self.generic_visit(node)
visit_AsyncWith = visit_With
def visit_ExceptHandler(self, node):
if node.name:
self._bind([node.name])
self.generic_visit(node)
def visit_Global(self, node):
# explicit global: remove from local bindings so globals resolve
for name in node.names:
self.bindings[-1].discard(name)
self.generic_visit(node)
def visit_Call(self, node):
target = ast.unparse(node.func)
# a call through a locally bound name (parameter,
# local variable, local import) is NOT a global symbol reference.
# Only BARE-name calls can be mis-linked to same-name globals;
# attribute calls on unknown objects stay unresolved naturally.
shadowed = "." not in target and len(self.bindings) > 1 and target in self.bindings[-1]
refs.append(
{
"src": self.owner,
"target": target,
"kind": "calls",
"line": node.lineno,
"class_scope": self.classes[-1] if self.classes else "",
"shadowed": bool(shadowed),
}
)
self.generic_visit(node)
def visit_Attribute(self, node):
if (
self.classes
and isinstance(node.value, ast.Name)
and node.value.id in ("self", "cls")
):
cls = next(s for s in symbols if s["id"] == path + "::" + self.classes[-1])
kind = "writes" if isinstance(node.ctx, ast.Store) else "reads"
if kind == "writes" and not any(f["name"] == node.attr for f in cls["fields"]):
cls["fields"].append({"name": node.attr, "type": "unknown"})
refs.append(
{
"src": self.owner,
"target": cls["id"] + "." + node.attr,
"kind": kind,
"line": node.lineno,
"class_scope": self.classes[-1],
}
)
self.generic_visit(node)
Visitor().visit(tree)
definitions = _collect_definitions(path, tree) + binding_sites
return symbols, refs, imports, definitions
def _collect_definitions(path, tree):
"""every definition SITE (getter+setter overloads coexist)."""
defs = []
def walk(node, scope):
for child in ast.iter_child_nodes(node):
if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
qual = ".".join(scope + [child.name])
kind = "class" if isinstance(child, ast.ClassDef) else "function"
defs.append(
{
"symbol_id": path + "::" + qual,
"line": child.lineno,
"end": child.end_lineno,
"kind": kind,
}
)
walk(child, scope + [child.name])
else:
walk(child, scope)
walk(tree, [])
return defs
def heuristic_facts(path, source):
symbols = []
# Deliberately no guessed call edges: a token match does not establish dispatch.
pattern = re.compile(
r"^\s*(?:(?:pub\s+)?(?:struct|class|enum|trait)\s+(\w+)|"
r"(?:export\s+)?(?:async\s+)?(?:function|fn)\s+(\w+)\s*\(|"
r"(?:[\w:*<>]+\s+)+([\w:]+)\s*\([^;]*\)\s*(?:const\s*)?\{)"
)
for line, text in enumerate(source.splitlines(), 1):
match = pattern.search(text)
if match:
name = next(g for g in match.groups() if g)
symbols.append(
{
"id": f"{path}::{name}@{line}",
"name": name,
"qualname": name,
"kind": "type" if match.group(1) else "function",
"line": line,
"end": line,
"signature": text.strip()[:400],
"doc": "",
"fields": [],
"confidence": "heuristic",
}
)
return symbols, [], {}, []
class CodeIndex:
def __init__(
self,
root,
database,
*,
native_index_policy="eager",
native_resources=None,
remaining=None,
native_timeout=5,
native_parent_guard=False,
):
if native_index_policy not in ("eager", "on_demand"):
raise ValueError("Unknown native index policy")
if remaining is not None and not callable(remaining):
raise ValueError("remaining must be a callable")
if not 0 < native_timeout <= 30:
raise ValueError("native_timeout must be 0..30 seconds")
if type(native_parent_guard) is not bool:
raise ValueError("native_parent_guard must be bool")
self.native_parent_guard = native_parent_guard
self.native_index_policy = native_index_policy
self.native_resources = native_resources
self.remaining = remaining
self.native_timeout = native_timeout
self.root = Path(root).resolve()
self.database = Path(database).resolve()
self.database.parent.mkdir(parents=True, exist_ok=True)
self.db = sqlite3.connect(self.database, timeout=20)
self.db.row_factory = sqlite3.Row
self.db.executescript("""
PRAGMA journal_mode=WAL;
CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY, value TEXT);
CREATE TABLE IF NOT EXISTS files(path TEXT PRIMARY KEY, hash TEXT, language TEXT,
source TEXT, error TEXT, imports TEXT);
CREATE TABLE IF NOT EXISTS symbols(id TEXT PRIMARY KEY, path TEXT, name TEXT,
qualname TEXT, kind TEXT, line INTEGER, end INTEGER, signature TEXT,
doc TEXT, fields TEXT, confidence TEXT);
CREATE INDEX IF NOT EXISTS symbol_path ON symbols(path);
CREATE TABLE IF NOT EXISTS refs(path TEXT, src TEXT, target TEXT, kind TEXT,
line INTEGER, class_scope TEXT, dst TEXT, confidence TEXT, shadowed INTEGER DEFAULT 0);
CREATE TABLE IF NOT EXISTS definitions(symbol_id TEXT, path TEXT, line INTEGER,
end INTEGER, kind TEXT);
CREATE INDEX IF NOT EXISTS def_symbol ON definitions(symbol_id);
CREATE INDEX IF NOT EXISTS ref_src ON refs(src);
CREATE INDEX IF NOT EXISTS ref_dst ON refs(dst);
CREATE TABLE IF NOT EXISTS native_inputs(path TEXT,file TEXT,hash TEXT,
PRIMARY KEY(path,file));
CREATE TABLE IF NOT EXISTS native_input_state(path TEXT PRIMARY KEY,
revision TEXT,complete INTEGER,generation INTEGER);
CREATE TABLE IF NOT EXISTS partial_source_refresh(path TEXT PRIMARY KEY,analysis TEXT);
""")
previous = self.db.execute("SELECT value FROM metadata WHERE key='root'").fetchone()
if previous and previous[0] != str(self.root):
self.db.close()
raise ValueError("Index belongs to a different workspace")
# Schema migration: older databases lack refs.shadowed.
cols = {r[1] for r in self.db.execute("PRAGMA table_info(refs)")}
if "shadowed" not in cols:
self.db.execute("ALTER TABLE refs ADD COLUMN shadowed INTEGER DEFAULT 0")
self.db.commit()
fcols = {r[1] for r in self.db.execute("PRAGMA table_info(files)")}
if "build" not in fcols:
self.db.execute("ALTER TABLE files ADD COLUMN build TEXT")
self.db.commit()
self.db.execute("INSERT OR REPLACE INTO metadata VALUES ('root', ?)", (str(self.root),))
self.db.commit()
def close(self):
self.db.close()
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
def _check_analysis_budget(self):
if self.remaining is not None and self.remaining() <= 0:
from infinicoder.analysis.native_analysis import IndexBudgetExceeded
self._search_cache = None
raise IndexBudgetExceeded("Code analysis exhausted its original runtime budget")
def expand_native(self, path):
from infinicoder.languages.native_adapter import NATIVE_EXTS
from infinicoder.execution.workspace_tools import Workspace
Workspace(self.root).path(path)
if self.native_index_policy != "on_demand" or Path(path).suffix.lower() not in NATIVE_EXTS:
return None
self.refresh(_native_paths=(path,))
row = self.db.execute("SELECT build FROM files WHERE path=?", (path,)).fetchone()
if not row:
raise ValueError("path is not indexed")
return json.loads(row[0] or "{}")
def refresh_paths(self, paths, *, read_source):
"""Observe just the requested files; unseen rows are never deleted.
The caller supplies a safe versioned read in its declared namespace.
Native declarations stay heuristic here; semantic expansion retains its
separate build/dependency contract. Full refresh will revisit these
rows, even when their bytes match an older full-index generation.
"""
from infinicoder.execution.workspace_tools import Workspace
from infinicoder.languages.native_adapter import BuildProfile, native_context, NATIVE_EXTS
paths = tuple(dict.fromkeys(paths))
if len(paths) > 32 or not callable(read_source):
raise ValueError("bounded explicit source paths required")
analysis = digest(Path(__file__).read_bytes())
changed = []
deleted = []
observed = []
build = None
with self.db:
for path in paths:
self._check_analysis_budget()
Workspace(self.root).path(path)
try:
raw, text, sha = read_source(path)
except FileNotFoundError:
for table in (
"files",
"symbols",
"refs",
"definitions",
"native_inputs",
"native_input_state",
"partial_source_refresh",
):
self.db.execute(f"DELETE FROM {table} WHERE path=?", (path,))
deleted.append(path)
continue
if digest(raw) != sha or raw.decode("utf-8-sig") != text:
raise ValueError("exact observed source bytes and hash required")
observed.append(path)
suffix = Path(path).suffix.lower()
error = ""
info = None
old = self.db.execute("SELECT hash FROM files WHERE path=?", (path,)).fetchone()
partial = self.db.execute(
"SELECT analysis FROM partial_source_refresh WHERE path=?", (path,)
).fetchone()
if (
suffix not in NATIVE_EXTS
and old
and old[0] == sha
and partial
and partial[0] == analysis
):
continue
syms, refs, imports, definitions = [], [], {}, []
try:
if suffix in (".py", ".pyi"):
syms, refs, imports, definitions = python_facts(path, text)
elif suffix in NATIVE_EXTS:
if build is None:
build = BuildProfile(self.root)
syms, refs, imports, definitions, info = native_context(
path, text, build, semantic=False
)
elif suffix == ".ipynb":
syms, refs, imports, definitions = [], [], {}, []
else:
syms, refs, imports, definitions = heuristic_facts(path, text)
except SyntaxError as exc:
error = f"{exc.msg} at line {exc.lineno}"
for table in (
"symbols",
"refs",
"definitions",
"native_inputs",
"native_input_state",
):
self.db.execute(f"DELETE FROM {table} WHERE path=?", (path,))
self.db.execute(
"INSERT OR REPLACE INTO files VALUES(?,?,?,?,?,?,?)",
(
path,
sha,
LANGUAGES.get(suffix, "other"),
text,
error,
json.dumps(imports),
json.dumps(info) if info else None,
),
)
self.db.executemany(
"INSERT OR REPLACE INTO symbols VALUES(?,?,?,?,?,?,?,?,?,?,?)",
[
(
s["id"],
path,
s["name"],
s["qualname"],
s["kind"],
s["line"],
s["end"],
s["signature"],
s["doc"],
json.dumps(s["fields"]),
s["confidence"],
)
for s in syms
],
)
self.db.executemany(
"INSERT INTO refs VALUES(?,?,?,?,?,?,?,?,?)",
[
(
path,
r["src"],
r["target"],
r["kind"],
r["line"],
r["class_scope"],
None,
"unresolved",
int(bool(r.get("shadowed"))),
)
for r in refs
],
)
self.db.executemany(
"INSERT INTO definitions VALUES(?,?,?,?,?)",
[(d["symbol_id"], path, d["line"], d["end"], d["kind"]) for d in definitions],
)
self.db.execute(
"INSERT OR REPLACE INTO partial_source_refresh VALUES(?,?)", (path, analysis)
)
changed.append(path)
# Older callers of a changed target remain unknown until refreshed.
for path in changed + deleted:
self.db.execute(
"UPDATE refs SET dst=NULL,confidence=? WHERE substr(dst,1,?)=?",
("target_changed;refresh_required", len(path) + 2, path + "::"),
)
# A source-preserving reread can restore a relation invalidated by
# a changed target. Unobserved callers must remain unknown.
if observed:
self._resolve(paths=observed)
self._search_cache = None
return dict(
changed=changed, deleted=deleted, coverage="selected_paths_only;unseen_paths_unchanged"
)
def refresh(
self, max_bytes=1_000_000, _force_native=False, _already_native=(), _native_paths=()
):
from infinicoder.languages.native_adapter import BuildProfile, native_context, NATIVE_EXTS
bp = BuildProfile(self.root)
import importlib.metadata
try:
clang_version = importlib.metadata.version("libclang")
except importlib.metadata.PackageNotFoundError:
clang_version = None
parser_identity = digest(
Path(__file__).read_bytes()
+ (package_root() / "analysis/qualified_symbols.py").read_bytes()
+ (package_root() / "analysis/native_effects.py").read_bytes()
+ str(clang_version).encode()
+ b"".join(
(package_root() / "languages" / name).read_bytes()
for name in ["native_adapter.py", "clang_adapter.py"]
)
)
from infinicoder.analysis.native_analysis import policy_identity
parser_identity = digest(
(
parser_identity
+ ":"
+ self.native_index_policy
+ ":"
+ str(self.native_parent_guard)
+ ":"
+ policy_identity(self.native_resources)
).encode()
+ (package_root() / "analysis/native_analysis.py").read_bytes()
)
previous_parser = self.db.execute(
"SELECT value FROM metadata WHERE key='parser_identity'"
).fetchone()
parser_changed = not previous_parser or previous_parser[0] != parser_identity
previous_build = self.db.execute(
"SELECT value FROM metadata WHERE key='build_identity'"
).fetchone()
build_changed = not previous_build or previous_build[0] != bp.identity
import os
seen, changed, skipped = set(), [], []
header_changed = False
parsed_native = set()
with self.db:
for folder, dirs, names in os.walk(self.root, followlinks=False):
excluded = getattr(self, "excluded_paths", ())
dirs[:] = sorted(
d
for d in dirs
if d not in IGNORED
and not Path(folder, d).is_symlink()
and not any(Path(folder, d).resolve().is_relative_to(p) for p in excluded)
)
self._check_analysis_budget()
for name in sorted(names):
self._check_analysis_budget()
p = Path(folder, name)
# A source-looking FIFO/device is not a readable source
# fact. Never block the caller while opening such entries.
if p.suffix.lower() not in LANGUAGES or p.is_symlink() or not p.is_file():
continue
if not p.resolve().is_relative_to(self.root) or p.resolve() == self.database:
continue
if any(p.resolve().is_relative_to(q) for q in excluded):
continue
rel = p.relative_to(self.root).as_posix()
if p.stat().st_size > max_bytes:
skipped.append(rel)
continue
raw = p.read_bytes()
if b"\x00" in raw:
skipped.append(rel)
continue
seen.add(rel)
sha = digest(raw)
old = self.db.execute("SELECT hash FROM files WHERE path=?", (rel,)).fetchone()
if p.suffix.lower() in (".h", ".hh", ".hpp", ".cuh") and (
not old or old[0] != sha
):
header_changed = True
partial = self.db.execute(
"SELECT 1 FROM partial_source_refresh WHERE path=?", (rel,)
).fetchone()
if (
old
and old[0] == sha
and not partial
and not parser_changed
and not (build_changed and p.suffix.lower() in NATIVE_EXTS)
):
if p.suffix.lower() not in NATIVE_EXTS:
continue
if _force_native and rel in _already_native:
continue
dependency = self.db.execute(
"SELECT complete FROM native_input_state WHERE path=?", (rel,)
).fetchone()
if dependency:
from infinicoder.languages.clang_adapter import header_fingerprint
same = bool(dependency[0])
for filename, expected in self.db.execute(
"SELECT file,hash FROM native_inputs WHERE path=?", (rel,)
):
current = header_fingerprint(filename, bp.dependency_cache)
if current is None or current[0] != expected:
same = False
break
if same:
continue
elif not (_force_native or rel in _native_paths):
continue
changed.append(rel)
text = raw.decode("utf-8-sig", errors="replace")
error, syms, refs, imports, definitions = "", [], [], {}, []
build_info = None
try:
if p.suffix == ".py":
syms, refs, imports, definitions = python_facts(rel, text)
elif p.suffix.lower() == ".ipynb":
syms, refs, imports, definitions = [], [], {}, []
elif p.suffix.lower() in NATIVE_EXTS:
if self.native_index_policy == "on_demand" and rel in _native_paths:
from infinicoder.analysis.native_analysis import expand
seconds = (
min(self.native_timeout, self.remaining())
if self.remaining is not None
else self.native_timeout
)
syms, refs, imports, definitions, build_info = expand(
rel,
text,
bp,
resources=self.native_resources,
timeout=seconds,
guard_parent=self.native_parent_guard,
)
elif (
self.native_index_policy == "eager"
and self.native_resources is None
):
syms, refs, imports, definitions, build_info = native_context(
rel, text, bp
)
else:
syms, refs, imports, definitions, build_info = native_context(
rel,
text,
bp,
semantic=self.native_index_policy == "eager",
resource_dir=self.native_resources,
)
else:
syms, refs, imports, definitions = heuristic_facts(rel, text)
except SyntaxError as e:
error = f"{e.msg} at line {e.lineno}"
if p.suffix.lower() in NATIVE_EXTS:
parsed_native.add(rel)
inputs = build_info.pop("_native_inputs", None) if build_info else None
prior = self.db.execute(
"SELECT generation FROM native_input_state WHERE path=?", (rel,)
).fetchone()
if inputs is not None:
self.db.execute("DELETE FROM native_inputs WHERE path=?", (rel,))
self.db.executemany(
"INSERT INTO native_inputs VALUES(?,?,?)",
[(rel, name, value) for name, value in inputs["files"].items()],
)
elif build_info and build_info.get("mode") == "compile_commands" and prior:
# Retain dependency candidates after a parse error so
# restoring a deleted/generated include can recover.
from infinicoder.languages.clang_adapter import header_fingerprint
observed = []
for filename, _ in self.db.execute(
"SELECT file,hash FROM native_inputs WHERE path=?", (rel,)
):
value = header_fingerprint(filename, bp.dependency_cache)
observed.append((filename, value[0] if value else None))
inputs = dict(
files={},
complete=False,
unknown=[
dict(
reason="semantic parse unavailable;previous dependency candidates retained"
)
],
unknown_count=1,
revision=digest(json.dumps(observed).encode()),
)
else:
self.db.execute("DELETE FROM native_inputs WHERE path=?", (rel,))
self.db.execute("DELETE FROM native_input_state WHERE path=?", (rel,))
if inputs is not None:
generation = (prior[0] if prior else 0) + 1
dependency_revision = (
inputs["revision"]
if inputs["complete"]
else digest(
(
inputs["revision"] + ":unversioned:" + str(generation)
).encode()
)
)
self.db.execute(
"INSERT OR REPLACE INTO native_input_state VALUES(?,?,?,?)",
(rel, dependency_revision, int(inputs["complete"]), generation),
)
build_info.update(
native_dependency_revision=dependency_revision,
native_dependency_count=len(inputs["files"]),
native_dependency_complete=inputs["complete"],
)
if not inputs["complete"]:
build_info.update(
native_dependency_unknown=inputs["unknown"],
native_dependency_unknown_count=inputs["unknown_count"],
)
self.db.execute("DELETE FROM symbols WHERE path=?", (rel,))
self.db.execute("DELETE FROM refs WHERE path=?", (rel,))
self.db.execute("DELETE FROM definitions WHERE path=?", (rel,))
self.db.execute(
"INSERT OR REPLACE INTO files VALUES(?,?,?,?,?,?,?)",
(
rel,
sha,
LANGUAGES.get(p.suffix.lower(), "other"),
text,
error,
json.dumps(imports),
json.dumps(build_info) if build_info else None,
),
)
for s in syms:
self.db.execute(
"INSERT OR REPLACE INTO symbols VALUES(?,?,?,?,?,?,?,?,?,?,?)",
(
s["id"],
rel,
s["name"],
s["qualname"],
s["kind"],
s["line"],
s["end"],
s["signature"],
s["doc"],
json.dumps(s["fields"]),
s["confidence"],
),
)
for r in refs:
self.db.execute(
"INSERT INTO refs VALUES(?,?,?,?,?,?,?,?,?)",
(
rel,
r["src"],
r["target"],
r["kind"],
r["line"],
r["class_scope"],
None,
"unresolved",
1 if r.get("shadowed") else 0,
),
)
for d in definitions:
self.db.execute(
"INSERT INTO definitions VALUES(?,?,?,?,?)",
(d["symbol_id"], rel, d["line"], d["end"], d["kind"]),
)
self.db.execute("DELETE FROM partial_source_refresh WHERE path=?", (rel,))
deleted = [r[0] for r in self.db.execute("SELECT path FROM files") if r[0] not in seen]
for rel in deleted:
if Path(rel).suffix.lower() in (".h", ".hh", ".hpp", ".cuh"):
header_changed = True
for table in (
"files",
"symbols",
"refs",
"definitions",
"native_inputs",
"native_input_state",
"partial_source_refresh",
):
self.db.execute(f"DELETE FROM {table} WHERE path=?", (rel,))
self._check_analysis_budget()
self._resolve()
self._check_analysis_budget()
self.db.execute(
"INSERT OR REPLACE INTO metadata VALUES ('build_identity', ?)", (bp.identity,)
)
self.db.execute(
"INSERT OR REPLACE INTO metadata VALUES ('parser_identity', ?)", (parser_identity,)
)
# Initial/parser/build refresh already parsed every native source
# against current headers. Only an otherwise incremental refresh needs
# the second pass for unchanged translation units that include a header.
if (
self.native_index_policy == "eager"
and header_changed
and not (_force_native or parser_changed or build_changed)
):
refreshed = self.refresh(max_bytes, _force_native=True, _already_native=parsed_native)
changed = list(dict.fromkeys(changed + refreshed["changed"]))
if changed or deleted or parser_changed or build_changed:
self._search_cache = None
return {
"changed": changed,
"deleted": deleted,
"skipped": skipped,
"files": len(seen),
"revision": self.revision(),
"native_headers_invalidated": header_changed,
"native_index_policy": self.native_index_policy,
"native_requested_paths": list(_native_paths),
}
def revision(self):
rows = self.db.execute("SELECT path,hash FROM files ORDER BY path").fetchall()
identity = self.db.execute(
"SELECT key,value FROM metadata WHERE key IN ('build_identity','parser_identity') ORDER BY key"
).fetchall()
native = self.db.execute(
"SELECT path,revision,complete FROM native_input_state ORDER BY path"