claude-db 0.11.1 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.md +5 -4
  3. package/dist/cli/commands/graph.js +104 -80
  4. package/dist/cli/commands/languages.d.ts +1 -0
  5. package/dist/cli/commands/languages.js +22 -0
  6. package/dist/cli/commands/pick.js +4 -2
  7. package/dist/cli/index.js +4 -0
  8. package/dist/cli/usage.js +3 -1
  9. package/dist/graph/ast.d.ts +4 -0
  10. package/dist/graph/ast.js +11 -0
  11. package/dist/graph/grammars.d.ts +14 -0
  12. package/dist/graph/grammars.js +58 -0
  13. package/dist/graph/index.d.ts +2 -2
  14. package/dist/graph/index.js +2 -2
  15. package/dist/graph/languages/basic.js +5 -1
  16. package/dist/graph/languages/ecmascript.js +7 -0
  17. package/dist/graph/languages/go.js +0 -1
  18. package/dist/graph/languages/index.d.ts +1 -1
  19. package/dist/graph/languages/index.js +34 -9
  20. package/dist/graph/languages/java.d.ts +2 -0
  21. package/dist/graph/languages/java.js +38 -0
  22. package/dist/graph/languages/kotlin.d.ts +2 -0
  23. package/dist/graph/languages/kotlin.js +19 -0
  24. package/dist/graph/languages/python.js +10 -2
  25. package/dist/graph/languages/rules.d.ts +11 -0
  26. package/dist/graph/languages/rust.js +2 -1
  27. package/dist/graph/modules/binding.d.ts +61 -0
  28. package/dist/graph/modules/binding.js +43 -0
  29. package/dist/graph/modules/ecmascript/bind.d.ts +4 -0
  30. package/dist/graph/modules/ecmascript/bind.js +17 -0
  31. package/dist/graph/modules/ecmascript/contexts.d.ts +6 -0
  32. package/dist/graph/modules/ecmascript/contexts.js +86 -0
  33. package/dist/graph/modules/ecmascript/exports.d.ts +9 -0
  34. package/dist/graph/modules/ecmascript/exports.js +91 -0
  35. package/dist/graph/modules/ecmascript/imports.d.ts +4 -0
  36. package/dist/graph/modules/ecmascript/imports.js +73 -0
  37. package/dist/graph/modules/ecmascript/package-resolver.d.ts +4 -0
  38. package/dist/graph/modules/ecmascript/package-resolver.js +73 -0
  39. package/dist/graph/modules/ecmascript/resolver.d.ts +2 -0
  40. package/dist/graph/modules/ecmascript/resolver.js +22 -0
  41. package/dist/graph/modules/ecmascript/specifiers.d.ts +3 -0
  42. package/dist/graph/modules/ecmascript/specifiers.js +15 -0
  43. package/dist/graph/modules/ecmascript/system.d.ts +2 -0
  44. package/dist/graph/modules/ecmascript/system.js +18 -0
  45. package/dist/graph/modules/ecmascript/workspace-resolver.d.ts +5 -0
  46. package/dist/graph/modules/ecmascript/workspace-resolver.js +38 -0
  47. package/dist/graph/modules/go/grammar.d.ts +2 -0
  48. package/dist/graph/modules/go/grammar.js +54 -0
  49. package/dist/graph/modules/go/imports.d.ts +4 -0
  50. package/dist/graph/modules/go/imports.js +32 -0
  51. package/dist/graph/modules/go/resolver.d.ts +2 -0
  52. package/dist/graph/modules/go/resolver.js +54 -0
  53. package/dist/graph/modules/go/system.d.ts +2 -0
  54. package/dist/graph/modules/go/system.js +16 -0
  55. package/dist/graph/modules/java/declarations.d.ts +9 -0
  56. package/dist/graph/modules/java/declarations.js +108 -0
  57. package/dist/graph/modules/java/grammar.d.ts +2 -0
  58. package/dist/graph/modules/java/grammar.js +135 -0
  59. package/dist/graph/modules/java/imports.d.ts +4 -0
  60. package/dist/graph/modules/java/imports.js +13 -0
  61. package/dist/graph/modules/java/receivers.d.ts +3 -0
  62. package/dist/graph/modules/java/receivers.js +139 -0
  63. package/dist/graph/modules/java/system.d.ts +1 -0
  64. package/dist/graph/modules/java/system.js +13 -0
  65. package/dist/graph/modules/jvm/linking.d.ts +20 -0
  66. package/dist/graph/modules/jvm/linking.js +64 -0
  67. package/dist/graph/modules/jvm/packages.d.ts +5 -0
  68. package/dist/graph/modules/jvm/packages.js +58 -0
  69. package/dist/graph/modules/jvm/receivers.d.ts +44 -0
  70. package/dist/graph/modules/jvm/receivers.js +77 -0
  71. package/dist/graph/modules/jvm/system.d.ts +18 -0
  72. package/dist/graph/modules/jvm/system.js +29 -0
  73. package/dist/graph/modules/jvm/types.d.ts +3 -0
  74. package/dist/graph/modules/jvm/types.js +11 -0
  75. package/dist/graph/modules/kotlin/declarations.d.ts +8 -0
  76. package/dist/graph/modules/kotlin/declarations.js +69 -0
  77. package/dist/graph/modules/kotlin/grammar.d.ts +2 -0
  78. package/dist/graph/modules/kotlin/grammar.js +78 -0
  79. package/dist/graph/modules/kotlin/imports.d.ts +4 -0
  80. package/dist/graph/modules/kotlin/imports.js +25 -0
  81. package/dist/graph/modules/kotlin/receivers.d.ts +3 -0
  82. package/dist/graph/modules/kotlin/receivers.js +105 -0
  83. package/dist/graph/modules/kotlin/references.d.ts +8 -0
  84. package/dist/graph/modules/kotlin/references.js +69 -0
  85. package/dist/graph/modules/kotlin/system.d.ts +1 -0
  86. package/dist/graph/modules/kotlin/system.js +15 -0
  87. package/dist/graph/modules/members.d.ts +17 -0
  88. package/dist/graph/modules/members.js +30 -0
  89. package/dist/graph/modules/module-index.d.ts +9 -0
  90. package/dist/graph/modules/module-index.js +62 -0
  91. package/dist/graph/modules/names.d.ts +2 -0
  92. package/dist/graph/modules/names.js +3 -0
  93. package/dist/graph/modules/python/grammar.d.ts +2 -0
  94. package/dist/graph/modules/python/grammar.js +100 -0
  95. package/dist/graph/modules/python/imports.d.ts +3 -0
  96. package/dist/graph/modules/python/imports.js +72 -0
  97. package/dist/graph/modules/python/resolver.d.ts +2 -0
  98. package/dist/graph/modules/python/resolver.js +78 -0
  99. package/dist/graph/modules/python/system.d.ts +2 -0
  100. package/dist/graph/modules/python/system.js +16 -0
  101. package/dist/graph/modules/rebind.d.ts +8 -0
  102. package/dist/graph/modules/rebind.js +51 -0
  103. package/dist/graph/modules/registry.d.ts +5 -0
  104. package/dist/graph/modules/registry.js +47 -0
  105. package/dist/graph/modules/rust/grammar.d.ts +2 -0
  106. package/dist/graph/modules/rust/grammar.js +94 -0
  107. package/dist/graph/modules/rust/imports.d.ts +3 -0
  108. package/dist/graph/modules/rust/imports.js +90 -0
  109. package/dist/graph/modules/rust/resolver.d.ts +3 -0
  110. package/dist/graph/modules/rust/resolver.js +153 -0
  111. package/dist/graph/modules/rust/system.d.ts +2 -0
  112. package/dist/graph/modules/rust/system.js +16 -0
  113. package/dist/graph/modules/shadowing.d.ts +17 -0
  114. package/dist/graph/modules/shadowing.js +65 -0
  115. package/dist/graph/modules/system.d.ts +39 -0
  116. package/dist/graph/modules/system.js +1 -0
  117. package/dist/graph/modules/uses.d.ts +14 -0
  118. package/dist/graph/modules/uses.js +62 -0
  119. package/dist/graph/parser.d.ts +9 -11
  120. package/dist/graph/parser.js +5 -4
  121. package/dist/graph/query/answer.d.ts +15 -0
  122. package/dist/graph/query/answer.js +22 -0
  123. package/dist/graph/query/format.d.ts +8 -1
  124. package/dist/graph/query/format.js +103 -30
  125. package/dist/graph/query/groups.d.ts +14 -0
  126. package/dist/graph/query/groups.js +51 -0
  127. package/dist/graph/query/index.d.ts +2 -1
  128. package/dist/graph/query/index.js +2 -1
  129. package/dist/graph/query/lookup.d.ts +2 -0
  130. package/dist/graph/query/lookup.js +19 -2
  131. package/dist/graph/query/refresh.js +17 -18
  132. package/dist/graph/query/stale.d.ts +2 -0
  133. package/dist/graph/query/stale.js +39 -0
  134. package/dist/graph/query/text.d.ts +12 -0
  135. package/dist/graph/query/text.js +26 -0
  136. package/dist/graph/scan/binder.d.ts +13 -0
  137. package/dist/graph/scan/binder.js +210 -0
  138. package/dist/graph/scan/cache.d.ts +11 -0
  139. package/dist/graph/scan/cache.js +140 -0
  140. package/dist/graph/scan/extract.d.ts +4 -17
  141. package/dist/graph/scan/extract.js +105 -83
  142. package/dist/graph/scan/files.d.ts +3 -9
  143. package/dist/graph/scan/files.js +3 -2
  144. package/dist/graph/scan/index.d.ts +8 -3
  145. package/dist/graph/scan/index.js +96 -36
  146. package/dist/graph/scan/job.d.ts +1 -0
  147. package/dist/graph/scan/job.js +1 -0
  148. package/dist/graph/scan/persist.d.ts +3 -0
  149. package/dist/graph/scan/persist.js +22 -0
  150. package/dist/graph/scan/receivers.d.ts +21 -0
  151. package/dist/graph/scan/receivers.js +87 -0
  152. package/dist/graph/scan/resolve.d.ts +8 -2
  153. package/dist/graph/scan/resolve.js +50 -56
  154. package/dist/graph/scan/spans.d.ts +13 -0
  155. package/dist/graph/scan/spans.js +42 -0
  156. package/dist/graph/symbols.d.ts +10 -0
  157. package/dist/graph/symbols.js +30 -0
  158. package/dist/graph/types.d.ts +56 -0
  159. package/dist/graph/types.js +1 -0
  160. package/dist/hooks/background.js +1 -16
  161. package/dist/hooks/detached.d.ts +3 -0
  162. package/dist/hooks/detached.js +16 -0
  163. package/dist/hooks/graph-refresh.d.ts +1 -0
  164. package/dist/hooks/graph-refresh.js +9 -0
  165. package/dist/hooks/prefer-usages.js +53 -12
  166. package/dist/hooks/session-start.js +8 -8
  167. package/dist/mcp/tools/usages.js +40 -31
  168. package/dist/pick/run.d.ts +6 -0
  169. package/dist/pick/run.js +8 -1
  170. package/dist/types.d.ts +1 -1
  171. package/dist/usages/find.js +1 -0
  172. package/dist/util/claude-cli.d.ts +1 -0
  173. package/dist/util/claude-cli.js +15 -3
  174. package/docs/how-it-works.md +10 -8
  175. package/package.json +16 -5
@@ -0,0 +1,94 @@
1
+ import { sameNode } from '../../ast.js';
2
+ import { memberAccess } from '../members.js';
3
+ import { shadowing } from '../shadowing.js';
4
+ const valuePath = memberAccess({
5
+ member: 'scoped_identifier',
6
+ object: 'path',
7
+ name: 'name',
8
+ call: 'call_expression',
9
+ callee: 'function',
10
+ });
11
+ const typePath = memberAccess({ member: 'scoped_type_identifier', object: 'path', name: 'name' });
12
+ const BINDING_PARENTS = new Set([
13
+ 'parameter',
14
+ 'let_declaration',
15
+ 'closure_parameters',
16
+ 'for_expression',
17
+ 'tuple_pattern',
18
+ 'reference_pattern',
19
+ 'mut_pattern',
20
+ 'slice_pattern',
21
+ 'or_pattern',
22
+ 'captured_pattern',
23
+ 'field_pattern',
24
+ 'tuple_struct_pattern',
25
+ 'match_pattern',
26
+ 'let_condition',
27
+ ]);
28
+ const EXPRESSION_SLOTS = ['value', 'type', 'body', 'alternative', 'condition'];
29
+ const USE_PARTS = new Set([
30
+ 'scoped_identifier',
31
+ 'scoped_use_list',
32
+ 'use_list',
33
+ 'use_as_clause',
34
+ 'use_wildcard',
35
+ ]);
36
+ const OTHER_SLOTS = {
37
+ call_expression: ['function'],
38
+ macro_invocation: ['macro'],
39
+ function_item: ['name'],
40
+ struct_item: ['name'],
41
+ enum_item: ['name'],
42
+ trait_item: ['name'],
43
+ type_item: ['name'],
44
+ mod_item: ['name'],
45
+ const_item: ['name'],
46
+ static_item: ['name'],
47
+ union_item: ['name'],
48
+ enum_variant: ['name'],
49
+ type_parameter: ['name'],
50
+ };
51
+ const SCOPES = new Set(['function_item', 'closure_expression']);
52
+ const ITEMS = new Set(['function_item', 'struct_item', 'enum_item', 'trait_item', 'type_item']);
53
+ const isBinding = (node, parent) => BINDING_PARENTS.has(parent.kind()) &&
54
+ !EXPRESSION_SLOTS.some((slot) => sameNode(parent.field(slot), node));
55
+ function inUse(parent) {
56
+ let up = parent;
57
+ while (up && USE_PARTS.has(up.kind()))
58
+ up = up.parent();
59
+ return up?.kind() === 'use_declaration';
60
+ }
61
+ const isUse = (node, parent) => !isBinding(node, parent) &&
62
+ !inUse(parent) &&
63
+ !(OTHER_SLOTS[parent.kind()]?.some((slot) => sameNode(parent.field(slot), node)) ?? false);
64
+ const isMemberObject = (node, parent) => valuePath.isMemberObject(node, parent) || typePath.isMemberObject(node, parent);
65
+ function localNames(root) {
66
+ const names = new Set();
67
+ const visit = (scope) => {
68
+ for (const item of scope.children()) {
69
+ const name = ITEMS.has(item.kind()) && item.field('name');
70
+ if (name)
71
+ names.add(name.text());
72
+ if (item.kind() === 'mod_item') {
73
+ const body = item.field('body');
74
+ if (body)
75
+ visit(body);
76
+ }
77
+ }
78
+ };
79
+ visit(root);
80
+ return names;
81
+ }
82
+ export const grammar = {
83
+ kinds: ['identifier', 'type_identifier'],
84
+ isUse,
85
+ isLocalUse: isUse,
86
+ isMemberObject,
87
+ memberChain: (parent) => (parent.kind() === 'scoped_type_identifier' ? typePath : valuePath).memberChain(parent),
88
+ localNames,
89
+ shadowing: shadowing({
90
+ scopes: SCOPES,
91
+ isBinding,
92
+ runsInside: (scope, child) => sameNode(scope.field('body'), child),
93
+ }),
94
+ };
@@ -0,0 +1,3 @@
1
+ import type { AstNode } from '../../parser.js';
2
+ import type { ImportFacts } from '../binding.js';
3
+ export declare function readImports(root: AstNode, source: string): ImportFacts;
@@ -0,0 +1,90 @@
1
+ import { addNamed, addSpace, newFacts } from '../binding.js';
2
+ import { segmentsOf } from '../names.js';
3
+ const USES = /\buse\b/;
4
+ const PATHS = new Set(['identifier', 'scoped_identifier', 'self', 'crate', 'super']);
5
+ const EVERYTHING = '*';
6
+ const SELF = 'self';
7
+ const ANONYMOUS = '_';
8
+ const pathOf = (node) => segmentsOf(node.text().replace(/\s+/g, ''));
9
+ function leavesOf(node, prefix, span = node) {
10
+ const kind = node.kind();
11
+ if (PATHS.has(kind))
12
+ return [{ path: [...prefix, ...pathOf(node)], glob: false, at: node, span }];
13
+ if (kind === 'use_list')
14
+ return node.children().flatMap((child) => leavesOf(child, prefix));
15
+ if (kind === 'scoped_use_list') {
16
+ const head = node.field('path');
17
+ const list = node.field('list');
18
+ const base = [...prefix, ...(head ? pathOf(head) : [])];
19
+ return list ? leavesOf(list, base) : [];
20
+ }
21
+ if (kind === 'use_wildcard') {
22
+ const head = node.children().find((child) => PATHS.has(child.kind()));
23
+ const path = [...prefix, ...(head ? pathOf(head) : [])];
24
+ return [{ path, glob: true, at: node, span: node }];
25
+ }
26
+ if (kind === 'use_as_clause') {
27
+ const head = node.field('path');
28
+ const alias = node.field('alias')?.text();
29
+ if (!head)
30
+ return [];
31
+ return [
32
+ {
33
+ path: [...prefix, ...pathOf(head)],
34
+ ...(alias ? { alias } : {}),
35
+ glob: false,
36
+ at: head,
37
+ span: node,
38
+ },
39
+ ];
40
+ }
41
+ return [];
42
+ }
43
+ function enclosing(statement) {
44
+ for (let up = statement.parent(); up; up = up.parent()) {
45
+ if (up.kind() !== 'function_item')
46
+ continue;
47
+ const { start, end } = up.range();
48
+ return { start: start.line + 1, end: end.line + 1 };
49
+ }
50
+ return undefined;
51
+ }
52
+ function readLeaf(facts, leaf, within) {
53
+ const scope = within ? { within } : {};
54
+ const path = leaf.path.at(-1) === SELF ? leaf.path.slice(0, -1) : leaf.path;
55
+ const name = path.at(-1);
56
+ if (!name)
57
+ return;
58
+ const specifier = path.slice(0, -1).join('::');
59
+ if (leaf.glob) {
60
+ const link = { specifier: path.join('::'), exported: EVERYTHING };
61
+ facts.sites.push({ at: leaf.at, span: leaf.span, imported: { name: EVERYTHING, link } });
62
+ }
63
+ else if (specifier === '') {
64
+ if (leaf.alias === ANONYMOUS)
65
+ return;
66
+ addSpace(facts, leaf.alias ?? name, { specifier: name, ...scope });
67
+ }
68
+ else {
69
+ const local = leaf.alias ?? name;
70
+ if (local !== ANONYMOUS)
71
+ addNamed(facts, local, { name, link: { specifier }, ...scope });
72
+ const published = within || local === ANONYMOUS ? {} : { exported: local };
73
+ const link = { specifier, ...published };
74
+ facts.sites.push({ at: leaf.at, span: leaf.span, imported: { name, link } });
75
+ }
76
+ }
77
+ export function readImports(root, source) {
78
+ const facts = newFacts();
79
+ if (!USES.test(source))
80
+ return facts;
81
+ for (const statement of root.findAll({ rule: { kind: 'use_declaration' } })) {
82
+ const argument = statement.field('argument');
83
+ if (!argument)
84
+ continue;
85
+ const within = enclosing(statement);
86
+ for (const leaf of leavesOf(argument, []))
87
+ readLeaf(facts, leaf, within);
88
+ }
89
+ return facts;
90
+ }
@@ -0,0 +1,3 @@
1
+ import type { ModuleResolver } from '../system.js';
2
+ export declare function rustResolver(root: string, files: ReadonlySet<string>): ModuleResolver;
3
+ export declare const isRelative: (specifier: string) => boolean;
@@ -0,0 +1,153 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ const RELATIVE = new Set(['crate', 'self', 'super']);
4
+ const STANDARD = new Set(['std', 'core', 'alloc', 'proc_macro', 'test']);
5
+ const DEPENDENCY_TABLE = /(?:^|\.)(?:dev-|build-)?dependencies(?:\.([\w-]+))?$/;
6
+ const ENTRY = /^\s*([\w-]+)\s*(?:=|\.)/gm;
7
+ const TARGET = /^(?:src\/bin|tests|examples|benches)\/([^/]+)(?:\.rs|\/main\.rs)$/;
8
+ const crateName = (name) => name.replace(/-/g, '_');
9
+ const dirOf = (file) => file.slice(0, Math.max(file.lastIndexOf('/'), 0));
10
+ const joinPath = (...parts) => parts.filter(Boolean).join('/');
11
+ const stem = (file) => file.slice(file.lastIndexOf('/') + 1).replace(/\.rs$/, '');
12
+ const field = (section, name) => new RegExp(`^\\s*${name}\\s*=\\s*"([^"]+)"`, 'm').exec(section)?.[1];
13
+ const sectionOf = (text, name) => new RegExp(`^\\[${name}\\][ \\t]*$([\\s\\S]*?)(?=^\\[|(?![\\s\\S]))`, 'm').exec(text)?.[1] ?? '';
14
+ function readManifest(root, manifest) {
15
+ try {
16
+ return readFileSync(join(root, manifest), 'utf8');
17
+ }
18
+ catch {
19
+ return undefined;
20
+ }
21
+ }
22
+ function dependenciesOf(text) {
23
+ const found = new Set();
24
+ for (const block of text.split(/^(?=\[)/m)) {
25
+ const header = /^\[([^\]]+)\]/.exec(block)?.[1] ?? '';
26
+ const table = DEPENDENCY_TABLE.exec(header);
27
+ if (!table)
28
+ continue;
29
+ if (table[1])
30
+ found.add(crateName(table[1]));
31
+ else
32
+ for (const entry of block.matchAll(ENTRY))
33
+ found.add(crateName(entry[1] ?? ''));
34
+ }
35
+ return found;
36
+ }
37
+ function targetsOf(dir, files) {
38
+ const found = [];
39
+ for (const file of files) {
40
+ if (dir && !file.startsWith(`${dir}/`))
41
+ continue;
42
+ const rel = dir ? file.slice(dir.length + 1) : file;
43
+ const target = TARGET.exec(rel);
44
+ if (!target)
45
+ continue;
46
+ const owner = rel.startsWith('src/') ? 'src/bin' : (rel.split('/')[0] ?? '');
47
+ found.push({ file, dir: joinPath(dir, owner, target[1] ?? stem(file)) });
48
+ }
49
+ return found;
50
+ }
51
+ function cratesOf(root, files) {
52
+ const crates = [];
53
+ for (const manifest of files) {
54
+ if (manifest !== 'Cargo.toml' && !manifest.endsWith('/Cargo.toml'))
55
+ continue;
56
+ const text = readManifest(root, manifest);
57
+ if (text === undefined)
58
+ continue;
59
+ const base = field(sectionOf(text, 'package'), 'name');
60
+ if (!base)
61
+ continue;
62
+ const dir = dirOf(manifest);
63
+ const lib = sectionOf(text, 'lib');
64
+ const libRoot = joinPath(dir, field(lib, 'path') ?? 'src/lib.rs');
65
+ const main = joinPath(dir, 'src/main.rs');
66
+ const dependencies = dependenciesOf(text);
67
+ if (files.has(libRoot)) {
68
+ const name = crateName(field(lib, 'name') ?? base);
69
+ crates.push({ root: libRoot, dir: dirOf(libRoot), name, dependencies });
70
+ }
71
+ if (files.has(main)) {
72
+ crates.push({ root: main, dir: dirOf(main), name: crateName(base), dependencies });
73
+ }
74
+ for (const target of targetsOf(dir, files)) {
75
+ crates.push({ root: target.file, dir: target.dir, name: stem(target.file), dependencies });
76
+ }
77
+ }
78
+ return crates;
79
+ }
80
+ export function rustResolver(root, files) {
81
+ const crates = cratesOf(root, files);
82
+ const libs = new Map(crates.filter((crate) => crate.root.endsWith('lib.rs')).map((crate) => [crate.name, crate]));
83
+ const crateOf = (file) => {
84
+ const own = crates.find((crate) => crate.root === file);
85
+ if (own)
86
+ return own;
87
+ const inside = crates.filter((crate) => file.startsWith(`${crate.dir}/`));
88
+ return inside.sort((a, b) => b.dir.length - a.dir.length)[0];
89
+ };
90
+ const pathOf = (file, crate) => {
91
+ if (file === crate.root)
92
+ return [];
93
+ const parts = file
94
+ .slice(crate.dir.length + 1)
95
+ .replace(/\.rs$/, '')
96
+ .split('/');
97
+ if (parts.at(-1) === 'mod')
98
+ parts.pop();
99
+ return parts;
100
+ };
101
+ const moduleFile = (crate, path) => {
102
+ if (path.length === 0)
103
+ return crate.root;
104
+ const base = joinPath(crate.dir, ...path);
105
+ return [`${base}.rs`, `${base}/mod.rs`].find((candidate) => files.has(candidate)) ?? null;
106
+ };
107
+ return {
108
+ resolve(from, specifier) {
109
+ let crate = crateOf(from);
110
+ if (!crate)
111
+ return null;
112
+ const parts = specifier.split('::');
113
+ let path = pathOf(from, crate);
114
+ let at = 0;
115
+ if (parts[0] === 'crate') {
116
+ path = [];
117
+ at = 1;
118
+ }
119
+ else if (parts[0] === 'self') {
120
+ at = 1;
121
+ }
122
+ else if (parts[0] === 'super') {
123
+ while (parts[at] === 'super') {
124
+ path = path.slice(0, -1);
125
+ at += 1;
126
+ }
127
+ }
128
+ else if (!moduleFile(crate, [...path, parts[0] ?? ''])) {
129
+ const external = libs.get(parts[0] ?? '');
130
+ if (!external)
131
+ return null;
132
+ crate = external;
133
+ path = [];
134
+ at = 1;
135
+ }
136
+ for (const part of parts.slice(at)) {
137
+ path = [...path, part];
138
+ if (!moduleFile(crate, path))
139
+ return null;
140
+ }
141
+ return moduleFile(crate, path);
142
+ },
143
+ foreign(from, specifier) {
144
+ const first = specifier.split('::')[0] ?? '';
145
+ return STANDARD.has(first) || (crateOf(from)?.dependencies.has(first) ?? false);
146
+ },
147
+ child(module, segment) {
148
+ const crate = crateOf(module);
149
+ return crate ? moduleFile(crate, [...pathOf(module, crate), segment]) : null;
150
+ },
151
+ };
152
+ }
153
+ export const isRelative = (specifier) => RELATIVE.has(specifier.split('::')[0] ?? '');
@@ -0,0 +1,2 @@
1
+ import type { ModuleSystem } from '../system.js';
2
+ export declare const rust: ModuleSystem;
@@ -0,0 +1,16 @@
1
+ import { rust as spec } from '../../languages/rust.js';
2
+ import { bindModule } from '../binding.js';
3
+ import { grammar } from './grammar.js';
4
+ import { readImports } from './imports.js';
5
+ import { isRelative, rustResolver } from './resolver.js';
6
+ export const rust = {
7
+ languages: [spec.label],
8
+ read({ root, file, symbols, references, owner }) {
9
+ const facts = readImports(root, file.source);
10
+ const input = { root, path: file.path, references, symbols, owner };
11
+ return { added: [], references: bindModule(input, facts, grammar) };
12
+ },
13
+ resolver: rustResolver,
14
+ isExternal: (specifier) => !isRelative(specifier),
15
+ importsNames: true,
16
+ };
@@ -0,0 +1,17 @@
1
+ import type { AstNode } from '../parser.js';
2
+ import type { InContext } from './binding.js';
3
+ export interface ShadowRules {
4
+ scopes: ReadonlySet<string>;
5
+ isBinding: InContext;
6
+ isReleased?: InContext;
7
+ scopeOf?: (node: AstNode, parent: AstNode) => AstNode | null;
8
+ runsInside: (scope: AstNode, child: AstNode) => boolean;
9
+ }
10
+ export interface Shadows {
11
+ node: (node: AstNode) => boolean;
12
+ at: (name: string, line: number) => boolean;
13
+ }
14
+ type Shadowing = (nodes: readonly AstNode[]) => Shadows;
15
+ export declare const NOTHING: Shadows;
16
+ export declare function shadowing(rules: ShadowRules): Shadowing;
17
+ export {};
@@ -0,0 +1,65 @@
1
+ export const NOTHING = { node: () => false, at: () => false };
2
+ const keyOf = (node) => {
3
+ const { line, column } = node.range().start;
4
+ return `${line}:${column}`;
5
+ };
6
+ export function shadowing(rules) {
7
+ const nearest = (from) => {
8
+ for (let up = from; up; up = up.parent())
9
+ if (rules.scopes.has(up.kind()))
10
+ return up;
11
+ return null;
12
+ };
13
+ const scopeOf = rules.scopeOf ?? ((_node, parent) => nearest(parent));
14
+ return (nodes) => {
15
+ const bound = new Map();
16
+ const released = new Map();
17
+ const extent = new Map();
18
+ const note = (into, scope, name) => {
19
+ const key = keyOf(scope);
20
+ into.set(key, (into.get(key) ?? new Set()).add(name));
21
+ const { start, end } = scope.range();
22
+ extent.set(key, { start: start.line + 1, end: end.line + 1 });
23
+ };
24
+ for (const node of nodes) {
25
+ const parent = node.parent();
26
+ if (!parent)
27
+ continue;
28
+ const table = rules.isBinding(node, parent)
29
+ ? bound
30
+ : rules.isReleased?.(node, parent)
31
+ ? released
32
+ : null;
33
+ const scope = table && scopeOf(node, parent);
34
+ if (table && scope)
35
+ note(table, scope, node.text());
36
+ }
37
+ if (bound.size === 0)
38
+ return NOTHING;
39
+ const holds = (key, name) => !!bound.get(key)?.has(name) && !released.get(key)?.has(name);
40
+ const scopesOf = new Map();
41
+ for (const [key, names] of bound) {
42
+ for (const name of names)
43
+ scopesOf.set(name, [...(scopesOf.get(name) ?? []), key]);
44
+ }
45
+ return {
46
+ node(node) {
47
+ const name = node.text();
48
+ if (!scopesOf.has(name))
49
+ return false;
50
+ let child = node;
51
+ for (let up = node.parent(); up; child = up, up = up.parent()) {
52
+ if (!rules.scopes.has(up.kind()) || !rules.runsInside(up, child))
53
+ continue;
54
+ if (holds(keyOf(up), name))
55
+ return true;
56
+ }
57
+ return false;
58
+ },
59
+ at: (name, line) => (scopesOf.get(name) ?? []).some((key) => {
60
+ const lines = extent.get(key);
61
+ return !!lines && line >= lines.start && line <= lines.end && holds(key, name);
62
+ }),
63
+ };
64
+ };
65
+ }
@@ -0,0 +1,39 @@
1
+ import type { CodeSymbol } from '../../types.js';
2
+ import type { AstNode } from '../parser.js';
3
+ import type { Declare } from '../symbols.js';
4
+ import type { Reference, SourceFile } from '../types.js';
5
+ export interface ModuleResolver {
6
+ resolve: (from: string, specifier: string) => string | null;
7
+ child?: (module: string, segment: string) => string | null;
8
+ unit?: (file: string) => string;
9
+ foreign?: (from: string, specifier: string) => boolean;
10
+ }
11
+ export interface ModuleContext {
12
+ files: ReadonlySet<string>;
13
+ resolve(from: string, specifier: string): string | null;
14
+ child(module: string, segment: string): string | null;
15
+ unit(file: string): string;
16
+ isExternal(from: string, specifier: string): boolean;
17
+ isForeign(from: string, specifier: string): boolean;
18
+ }
19
+ export interface ReadInput {
20
+ root: AstNode;
21
+ nodes: ReadonlyMap<string, AstNode[]>;
22
+ file: SourceFile;
23
+ declare: Declare;
24
+ symbols: CodeSymbol[];
25
+ references: Reference[];
26
+ owner: (line: number) => CodeSymbol | null;
27
+ }
28
+ export interface ModuleFacts {
29
+ added: CodeSymbol[];
30
+ references: Reference[];
31
+ }
32
+ export interface ModuleSystem {
33
+ readonly languages: readonly string[];
34
+ read(input: ReadInput): ModuleFacts;
35
+ resolver(root: string, files: ReadonlySet<string>): ModuleResolver;
36
+ isExternal(specifier: string): boolean;
37
+ importsNames: boolean;
38
+ nodeKinds?: readonly string[];
39
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,14 @@
1
+ import type { CodeSymbol, EdgeRelation } from '../../types.js';
2
+ import type { AstNode } from '../parser.js';
3
+ import type { Reference } from '../types.js';
4
+ import type { Grammar, ImportFacts, Target } from './binding.js';
5
+ import type { Shadows } from './shadowing.js';
6
+ export type Make = (node: AstNode, target: Target, relation: EdgeRelation, span?: AstNode) => Reference;
7
+ export interface Scope {
8
+ facts: ImportFacts;
9
+ locals: Set<string>;
10
+ objects: Set<string>;
11
+ }
12
+ export declare function scopeOf(root: AstNode, symbols: CodeSymbol[], facts: ImportFacts, grammar: Grammar): Scope;
13
+ export declare function usesIn(found: AstNode[], scope: Scope, grammar: Grammar, make: Make, shadows: Shadows): Reference[];
14
+ export declare function findUses(root: AstNode, scope: Scope, grammar: Grammar): AstNode[];
@@ -0,0 +1,62 @@
1
+ import { targetOf, visible } from './rebind.js';
2
+ const OBJECT_KINDS = new Set(['enum', 'class']);
3
+ const escaped = (name) => name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
4
+ export function scopeOf(root, symbols, facts, grammar) {
5
+ const bare = symbols.filter((symbol) => symbol.kind !== 'method');
6
+ const locals = grammar.localNames?.(root) ?? new Set(bare.map((symbol) => symbol.name));
7
+ const objects = new Set(bare.filter((symbol) => OBJECT_KINDS.has(symbol.kind)).map((symbol) => symbol.name));
8
+ return { facts, locals, objects };
9
+ }
10
+ export function usesIn(found, scope, grammar, make, shadows) {
11
+ const { facts, locals, objects } = scope;
12
+ const through = (node, parent, specifier, entered) => {
13
+ const chain = grammar.memberChain(parent);
14
+ return chain.map((name, at) => {
15
+ const link = { specifier, via: [...entered, ...chain.slice(0, at)], strict: true };
16
+ return make(node, { name, link }, 'references');
17
+ });
18
+ };
19
+ const useOf = (node) => {
20
+ const text = node.text();
21
+ const parent = node.parent();
22
+ if (!parent)
23
+ return [];
24
+ const line = () => node.range().start.line + 1;
25
+ if (grammar.unbound?.claims?.(node, parent)) {
26
+ const claimed = grammar.unbound.target(node, parent, facts);
27
+ return claimed ? [make(node, claimed, 'references')] : [];
28
+ }
29
+ const imported = visible(facts.named.get(text), line);
30
+ if (node.kind() === grammar.shorthand) {
31
+ return imported ? [make(node, targetOf(imported, text), 'references')] : [];
32
+ }
33
+ if (imported && grammar.isUse(node, parent)) {
34
+ const used = make(node, targetOf(imported, text), 'references');
35
+ const reached = grammar.isMemberObject(node, parent)
36
+ ? through(node, parent, imported.link.specifier, [imported.name])
37
+ : [];
38
+ return [used, ...reached];
39
+ }
40
+ const space = visible(facts.spaces.get(text), line);
41
+ if (space && grammar.isMemberObject(node, parent)) {
42
+ return through(node, parent, space.specifier, []);
43
+ }
44
+ const known = imported ?? space ?? (locals.has(text) || objects.has(text));
45
+ if (!known) {
46
+ const free = grammar.unbound?.target(node, parent, facts);
47
+ return free ? [make(node, free, 'references')] : [];
48
+ }
49
+ const local = (locals.has(text) && grammar.isLocalUse(node, parent)) ||
50
+ (objects.has(text) && grammar.isMemberObject(node, parent));
51
+ return local ? [make(node, { name: text }, 'references')] : [];
52
+ };
53
+ return found.filter((node) => !shadows.node(node)).flatMap(useOf);
54
+ }
55
+ export function findUses(root, scope, grammar) {
56
+ const { facts, locals } = scope;
57
+ const names = [...facts.named.keys(), ...facts.spaces.keys(), ...locals].map(escaped).join('|');
58
+ const known = { any: grammar.kinds.map((kind) => ({ kind })), regex: `^(?:${names})$` };
59
+ if (!grammar.unbound)
60
+ return root.findAll({ rule: known });
61
+ return root.findAll({ rule: { any: [known, ...grammar.unbound.rules] } });
62
+ }
@@ -1,12 +1,11 @@
1
+ export interface AstPosition {
2
+ line: number;
3
+ column: number;
4
+ index: number;
5
+ }
1
6
  export interface AstRange {
2
- start: {
3
- line: number;
4
- column: number;
5
- };
6
- end: {
7
- line: number;
8
- column: number;
9
- };
7
+ start: AstPosition;
8
+ end: AstPosition;
10
9
  }
11
10
  export interface AstNode {
12
11
  text(): string;
@@ -14,10 +13,9 @@ export interface AstNode {
14
13
  range(): AstRange;
15
14
  field(name: string): AstNode | null;
16
15
  parent(): AstNode | null;
16
+ children(): AstNode[];
17
17
  findAll(matcher: {
18
- rule: {
19
- kind: string;
20
- };
18
+ rule: Record<string, unknown>;
21
19
  }): AstNode[];
22
20
  }
23
21
  interface AstGrepModule {
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'node:module';
2
- import { DYNAMIC_LANGUAGES } from './languages/index.js';
2
+ import { GRAMMARS, loadGrammar } from './grammars.js';
3
3
  let cached = null;
4
4
  export function loadParser() {
5
5
  if (cached)
@@ -16,9 +16,10 @@ export function loadParser() {
16
16
  `(${error instanceof Error ? error.message.split('\n')[0] : String(error)})`, { cause: error });
17
17
  }
18
18
  const dynamic = {};
19
- for (const name of DYNAMIC_LANGUAGES) {
20
- const mod = require(`@ast-grep/lang-${name}`);
21
- dynamic[name] = mod.default ?? mod;
19
+ for (const name of GRAMMARS) {
20
+ const grammar = loadGrammar(name);
21
+ if (grammar)
22
+ dynamic[name] = grammar;
22
23
  }
23
24
  parser.registerDynamicLanguage(dynamic);
24
25
  cached = parser;
@@ -0,0 +1,15 @@
1
+ import type { MemoryStore } from '../../store/adapter.js';
2
+ import type { GraphAnswer, GraphQuery } from './lookup.js';
3
+ export declare const NO_GRAPH: string;
4
+ export declare const NO_GRAPH_FOR_PATH: string;
5
+ export interface AnswerRequest {
6
+ store: MemoryStore;
7
+ root: string;
8
+ project: string;
9
+ query: GraphQuery;
10
+ refresh: boolean;
11
+ text?: boolean;
12
+ }
13
+ export declare function addText(answer: GraphAnswer, root: string): void;
14
+ export declare const hasGraph: (store: MemoryStore, project: string) => Promise<boolean>;
15
+ export declare function answerQuery(request: AnswerRequest): Promise<GraphAnswer>;
@@ -0,0 +1,22 @@
1
+ import { queryGraph } from './lookup.js';
2
+ import { refreshGraph } from './refresh.js';
3
+ import { unlinkedText } from './text.js';
4
+ export const NO_GRAPH = 'No code graph for this project yet (run `claude-db scan` to build one), so this is a ' +
5
+ 'plain text search:';
6
+ export const NO_GRAPH_FOR_PATH = 'No code graph for this project yet. Run `claude-db scan` to build one, then ask for the ' +
7
+ 'path again.';
8
+ export function addText(answer, root) {
9
+ if (answer.mode === 'path')
10
+ return;
11
+ answer.text = unlinkedText(root, answer.symbol, answer.definitions, answer.inbound);
12
+ }
13
+ export const hasGraph = async (store, project) => (await store.scannedFiles(project)).length > 0;
14
+ export async function answerQuery(request) {
15
+ const { store, root, project, query } = request;
16
+ const refreshed = request.refresh ? await refreshGraph(store, root, project) : [];
17
+ const answer = await queryGraph(store, project, query);
18
+ answer.refreshed = refreshed;
19
+ if (request.text !== false)
20
+ addText(answer, root);
21
+ return answer;
22
+ }