@open-cr-agent/code-graph 0.0.0-stage → 0.8.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.
- package/LICENSE +202 -0
- package/README.md +2 -2
- package/dist/cache.d.ts +7 -0
- package/dist/cache.js +55 -0
- package/dist/extractor.d.ts +6 -0
- package/dist/extractor.js +38 -0
- package/dist/graph.d.ts +35 -0
- package/dist/graph.js +159 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/languages.d.ts +8 -0
- package/dist/languages.js +125 -0
- package/dist/parse.d.ts +3 -0
- package/dist/parse.js +132 -0
- package/dist/scip.d.ts +6 -0
- package/dist/scip.js +150 -0
- package/dist/stored.d.ts +18 -0
- package/dist/stored.js +26 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +10 -0
- package/package.json +42 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
202
|
+
|
package/README.md
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @open-cr-agent/code-graph
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The tree-sitter symbol extractor of [Open-CR-Agent](https://github.com/jma49/Open-CR-Agent), the multi-agent code reviewer: definitions and uses per file, for the impact analysis, cached by git blob id. Most users want [`@open-cr-agent/cli`](https://www.npmjs.com/package/@open-cr-agent/cli) (the `ocra` command) and the [manual](https://ocracloud.com). All packages share one version. Apache-2.0.
|
package/dist/cache.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { FileSymbols } from "@open-cr-agent/core";
|
|
2
|
+
export interface SymbolCache {
|
|
3
|
+
get(key: string): Promise<FileSymbols | undefined>;
|
|
4
|
+
set(key: string, symbols: FileSymbols): Promise<void>;
|
|
5
|
+
}
|
|
6
|
+
export declare function gitBlobId(content: string): string;
|
|
7
|
+
export declare function directoryCache(dir: string): SymbolCache;
|
package/dist/cache.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { mkdir, readFile, rename, rm, utimes, writeFile } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { fromStored, storedSymbols, toStored } from "./stored.js";
|
|
5
|
+
// Git's object id of a file with this content, so a server that lists a
|
|
6
|
+
// tree's blobs can look its files up without reading them. Content that was
|
|
7
|
+
// not valid UTF-8 hashes differently from the blob and only misses the cache.
|
|
8
|
+
export function gitBlobId(content) {
|
|
9
|
+
const bytes = Buffer.from(content, "utf8");
|
|
10
|
+
return createHash("sha1").update(`blob ${bytes.length}\0`).update(bytes).digest("hex");
|
|
11
|
+
}
|
|
12
|
+
function deserialize(text) {
|
|
13
|
+
let json;
|
|
14
|
+
try {
|
|
15
|
+
json = JSON.parse(text);
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
const parsed = storedSymbols.safeParse(json);
|
|
21
|
+
return parsed.success ? fromStored(parsed.data) : undefined;
|
|
22
|
+
}
|
|
23
|
+
// One JSON file per key under `dir`. Every failure reads as a miss or a
|
|
24
|
+
// skipped write: the cache only saves parsing. Writes go through a temporary
|
|
25
|
+
// file, so concurrent runs never read half an entry. A hit touches its
|
|
26
|
+
// entry, so a cache kept between CI runs can drop what no run read lately
|
|
27
|
+
// by modification time.
|
|
28
|
+
export function directoryCache(dir) {
|
|
29
|
+
const path = (key) => join(dir, key.slice(0, 2), `${key}.json`);
|
|
30
|
+
return {
|
|
31
|
+
async get(key) {
|
|
32
|
+
const file = path(key);
|
|
33
|
+
const text = await readFile(file, "utf8").catch(() => undefined);
|
|
34
|
+
const symbols = text === undefined ? undefined : deserialize(text);
|
|
35
|
+
if (symbols) {
|
|
36
|
+
const now = new Date();
|
|
37
|
+
await utimes(file, now, now).catch(() => { });
|
|
38
|
+
}
|
|
39
|
+
return symbols;
|
|
40
|
+
},
|
|
41
|
+
async set(key, symbols) {
|
|
42
|
+
const target = path(key);
|
|
43
|
+
const temporary = `${target}.${randomUUID()}.tmp`;
|
|
44
|
+
try {
|
|
45
|
+
await mkdir(join(dir, key.slice(0, 2)), { recursive: true });
|
|
46
|
+
await writeFile(temporary, JSON.stringify(toStored(symbols)));
|
|
47
|
+
await rename(temporary, target);
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
// A full or read-only disk costs only the cache.
|
|
51
|
+
await rm(temporary, { force: true }).catch(() => { });
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { gitBlobId } from "./cache.js";
|
|
3
|
+
import { languageOf } from "./languages.js";
|
|
4
|
+
import { parseSymbols } from "./parse.js";
|
|
5
|
+
import { VERSION } from "./version.js";
|
|
6
|
+
// Larger files are generated or data more often than code a change calls.
|
|
7
|
+
const MAX_FILE_CHARS = 1_000_000;
|
|
8
|
+
export function treeSitterSymbols(options = {}) {
|
|
9
|
+
const memo = new Map();
|
|
10
|
+
return {
|
|
11
|
+
symbols(path, content) {
|
|
12
|
+
const spec = languageOf(path);
|
|
13
|
+
if (!spec || content.length > MAX_FILE_CHARS)
|
|
14
|
+
return Promise.resolve(undefined);
|
|
15
|
+
const key = cacheKey(spec, content);
|
|
16
|
+
let symbols = memo.get(key);
|
|
17
|
+
if (!symbols) {
|
|
18
|
+
symbols = lookup(spec, content, key, options.cache);
|
|
19
|
+
memo.set(key, symbols);
|
|
20
|
+
}
|
|
21
|
+
return symbols;
|
|
22
|
+
},
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
function cacheKey(spec, content) {
|
|
26
|
+
return createHash("sha256")
|
|
27
|
+
.update(`${VERSION}\0${spec.id}\0${gitBlobId(content)}`)
|
|
28
|
+
.digest("hex");
|
|
29
|
+
}
|
|
30
|
+
async function lookup(spec, content, key, cache) {
|
|
31
|
+
const cached = await cache?.get(key);
|
|
32
|
+
if (cached)
|
|
33
|
+
return cached;
|
|
34
|
+
const symbols = await parseSymbols(spec, content);
|
|
35
|
+
if (symbols)
|
|
36
|
+
await cache?.set(key, symbols);
|
|
37
|
+
return symbols;
|
|
38
|
+
}
|
package/dist/graph.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { FileSymbols, ReferenceIndex } from "@open-cr-agent/core";
|
|
2
|
+
export interface CodeGraph {
|
|
3
|
+
parser: string;
|
|
4
|
+
revision?: string;
|
|
5
|
+
files: ReadonlyMap<string, string>;
|
|
6
|
+
symbols: ReadonlyMap<string, FileSymbols>;
|
|
7
|
+
}
|
|
8
|
+
export interface TreeEntry {
|
|
9
|
+
path: string;
|
|
10
|
+
blobId: string;
|
|
11
|
+
size?: number;
|
|
12
|
+
}
|
|
13
|
+
type SkipReason = "too-large" | "unreadable" | "not-text" | "unparsed" | "over-limit";
|
|
14
|
+
export interface UpdateOptions {
|
|
15
|
+
revision?: string;
|
|
16
|
+
concurrency?: number;
|
|
17
|
+
signal?: AbortSignal;
|
|
18
|
+
maxFiles?: number;
|
|
19
|
+
maxBlobBytes?: number;
|
|
20
|
+
}
|
|
21
|
+
export interface GraphUpdate {
|
|
22
|
+
graph: CodeGraph;
|
|
23
|
+
parsed: number;
|
|
24
|
+
reused: number;
|
|
25
|
+
skipped: {
|
|
26
|
+
path: string;
|
|
27
|
+
reason: SkipReason;
|
|
28
|
+
}[];
|
|
29
|
+
}
|
|
30
|
+
export type ReadBlob = (blobId: string, path: string) => Promise<Uint8Array | undefined>;
|
|
31
|
+
export declare function updateGraph(previous: CodeGraph | undefined, tree: readonly TreeEntry[], readBlob: ReadBlob, options?: UpdateOptions): Promise<GraphUpdate>;
|
|
32
|
+
export declare function graphReferences(graph: CodeGraph): ReferenceIndex;
|
|
33
|
+
export declare function serializeGraph(graph: CodeGraph): string;
|
|
34
|
+
export declare function parseGraph(text: string): CodeGraph | undefined;
|
|
35
|
+
export {};
|
package/dist/graph.js
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { mapWithConcurrency } from "@open-cr-agent/core/internal";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { languageOf } from "./languages.js";
|
|
4
|
+
import { parseSymbols } from "./parse.js";
|
|
5
|
+
import { fromStored, storedSymbols, toStored } from "./stored.js";
|
|
6
|
+
import { VERSION } from "./version.js";
|
|
7
|
+
const DEFAULTS = { concurrency: 8, maxFiles: 100_000, maxBlobBytes: 1_000_000 };
|
|
8
|
+
// Parses only the files whose key `previous` lacks. A file that cannot be
|
|
9
|
+
// read or parsed is skipped and recorded, never fatal, and tried again on
|
|
10
|
+
// the next update.
|
|
11
|
+
export async function updateGraph(previous, tree, readBlob, options = {}) {
|
|
12
|
+
const { concurrency, maxFiles, maxBlobBytes } = { ...DEFAULTS, ...options };
|
|
13
|
+
const reusable = previous?.parser === VERSION ? previous.symbols : new Map();
|
|
14
|
+
const files = new Map();
|
|
15
|
+
const symbols = new Map();
|
|
16
|
+
const skipped = [];
|
|
17
|
+
const toParse = new Map();
|
|
18
|
+
const sorted = [...tree].sort((a, b) => compare(a.path, b.path));
|
|
19
|
+
for (const entry of sorted) {
|
|
20
|
+
const spec = languageOf(entry.path);
|
|
21
|
+
if (!spec)
|
|
22
|
+
continue;
|
|
23
|
+
if (files.size >= maxFiles) {
|
|
24
|
+
skipped.push({ path: entry.path, reason: "over-limit" });
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
const key = `${spec.id}:${entry.blobId}`;
|
|
28
|
+
files.set(entry.path, key);
|
|
29
|
+
const known = reusable.get(key);
|
|
30
|
+
if (known)
|
|
31
|
+
symbols.set(key, known);
|
|
32
|
+
else if (!toParse.has(key))
|
|
33
|
+
toParse.set(key, entry);
|
|
34
|
+
}
|
|
35
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
36
|
+
const decode = (bytes) => {
|
|
37
|
+
try {
|
|
38
|
+
return decoder.decode(bytes);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
const outcomes = await mapWithConcurrency([...toParse], concurrency, async ([key, entry]) => {
|
|
45
|
+
options.signal?.throwIfAborted();
|
|
46
|
+
const outcome = await parseEntry(entry, readBlob, decode, maxBlobBytes);
|
|
47
|
+
if (typeof outcome !== "string")
|
|
48
|
+
symbols.set(key, outcome);
|
|
49
|
+
return outcome;
|
|
50
|
+
});
|
|
51
|
+
options.signal?.throwIfAborted();
|
|
52
|
+
const failed = new Map();
|
|
53
|
+
[...toParse.keys()].forEach((key, i) => {
|
|
54
|
+
const outcome = outcomes[i];
|
|
55
|
+
if (typeof outcome === "string")
|
|
56
|
+
failed.set(key, outcome);
|
|
57
|
+
});
|
|
58
|
+
for (const [path, key] of files) {
|
|
59
|
+
const reason = failed.get(key);
|
|
60
|
+
if (!reason)
|
|
61
|
+
continue;
|
|
62
|
+
files.delete(path);
|
|
63
|
+
skipped.push({ path, reason });
|
|
64
|
+
}
|
|
65
|
+
skipped.sort((a, b) => compare(a.path, b.path));
|
|
66
|
+
return {
|
|
67
|
+
graph: { parser: VERSION, ...optional("revision", options.revision), files, symbols },
|
|
68
|
+
parsed: toParse.size - failed.size,
|
|
69
|
+
reused: symbols.size - (toParse.size - failed.size),
|
|
70
|
+
skipped,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
async function parseEntry(entry, readBlob, decode, maxBlobBytes) {
|
|
74
|
+
if (entry.size !== undefined && entry.size > maxBlobBytes)
|
|
75
|
+
return "too-large";
|
|
76
|
+
const bytes = await readBlob(entry.blobId, entry.path).catch(() => undefined);
|
|
77
|
+
if (!bytes)
|
|
78
|
+
return "unreadable";
|
|
79
|
+
if (bytes.byteLength > maxBlobBytes)
|
|
80
|
+
return "too-large";
|
|
81
|
+
const content = decode(bytes);
|
|
82
|
+
if (content === undefined)
|
|
83
|
+
return "not-text";
|
|
84
|
+
const spec = languageOf(entry.path);
|
|
85
|
+
const symbols = spec && (await parseSymbols(spec, content));
|
|
86
|
+
return symbols ?? "unparsed";
|
|
87
|
+
}
|
|
88
|
+
// Callers by name across the revision the graph describes: matched, not
|
|
89
|
+
// resolved. Undefined when the graph does not know `path` defines `name`,
|
|
90
|
+
// so the review searches instead.
|
|
91
|
+
export function graphReferences(graph) {
|
|
92
|
+
return {
|
|
93
|
+
async usesOf(path, name) {
|
|
94
|
+
const own = graph.symbols.get(graph.files.get(path) ?? "");
|
|
95
|
+
if (!own?.definitions.some((d) => d.name === name))
|
|
96
|
+
return undefined;
|
|
97
|
+
const uses = [];
|
|
98
|
+
for (const [file, key] of graph.files) {
|
|
99
|
+
if (file === path)
|
|
100
|
+
continue;
|
|
101
|
+
for (const line of graph.symbols.get(key)?.uses.get(name) ?? []) {
|
|
102
|
+
uses.push({ path: file, line });
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return uses;
|
|
106
|
+
},
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
const GRAPH_FORMAT = 1;
|
|
110
|
+
const graphSchema = z.object({
|
|
111
|
+
format: z.literal(GRAPH_FORMAT),
|
|
112
|
+
parser: z.string(),
|
|
113
|
+
revision: z.string().optional(),
|
|
114
|
+
files: z.array(z.tuple([z.string(), z.string()])),
|
|
115
|
+
symbols: z.array(z.tuple([z.string(), storedSymbols])),
|
|
116
|
+
});
|
|
117
|
+
// Deterministic: the same graph always serializes to the same text, so
|
|
118
|
+
// stored graphs dedupe and diff.
|
|
119
|
+
export function serializeGraph(graph) {
|
|
120
|
+
const files = [...graph.files].sort(([a], [b]) => compare(a, b));
|
|
121
|
+
const used = new Set(files.map(([, key]) => key));
|
|
122
|
+
const symbols = [...graph.symbols]
|
|
123
|
+
.filter(([key]) => used.has(key))
|
|
124
|
+
.sort(([a], [b]) => compare(a, b))
|
|
125
|
+
.map(([key, s]) => [key, toStored(s)]);
|
|
126
|
+
return JSON.stringify({
|
|
127
|
+
format: GRAPH_FORMAT,
|
|
128
|
+
parser: graph.parser,
|
|
129
|
+
...optional("revision", graph.revision),
|
|
130
|
+
files,
|
|
131
|
+
symbols,
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
// Undefined for text that is not a graph of a format this version reads.
|
|
135
|
+
export function parseGraph(text) {
|
|
136
|
+
let json;
|
|
137
|
+
try {
|
|
138
|
+
json = JSON.parse(text);
|
|
139
|
+
}
|
|
140
|
+
catch {
|
|
141
|
+
return undefined;
|
|
142
|
+
}
|
|
143
|
+
const parsed = graphSchema.safeParse(json);
|
|
144
|
+
if (!parsed.success)
|
|
145
|
+
return undefined;
|
|
146
|
+
const { parser, revision, files, symbols } = parsed.data;
|
|
147
|
+
return {
|
|
148
|
+
parser,
|
|
149
|
+
...optional("revision", revision),
|
|
150
|
+
files: new Map(files),
|
|
151
|
+
symbols: new Map(symbols.map(([key, s]) => [key, fromStored(s)])),
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
function compare(a, b) {
|
|
155
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
156
|
+
}
|
|
157
|
+
function optional(key, value) {
|
|
158
|
+
return (value === undefined ? {} : { [key]: value });
|
|
159
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { directoryCache, gitBlobId, type SymbolCache } from "./cache.js";
|
|
2
|
+
export { type TreeSitterOptions, treeSitterSymbols } from "./extractor.js";
|
|
3
|
+
export { type CodeGraph, type GraphUpdate, graphReferences, parseGraph, type ReadBlob, serializeGraph, type TreeEntry, type UpdateOptions, updateGraph, } from "./graph.js";
|
|
4
|
+
export { type ScipOptions, scipReferences } from "./scip.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { extname } from "node:path";
|
|
2
|
+
const TYPESCRIPT_DEFINITIONS = `
|
|
3
|
+
(function_declaration name: (identifier) @name) @definition.function
|
|
4
|
+
(generator_function_declaration name: (identifier) @name) @definition.function
|
|
5
|
+
(function_signature name: (identifier) @name) @definition.function
|
|
6
|
+
(variable_declarator name: (identifier) @name value: [(arrow_function) (function_expression)]) @definition.function
|
|
7
|
+
(class_declaration name: (type_identifier) @name) @definition.class
|
|
8
|
+
(abstract_class_declaration name: (type_identifier) @name) @definition.class
|
|
9
|
+
(method_definition name: (property_identifier) @name) @definition.method
|
|
10
|
+
(method_signature name: (property_identifier) @name) @definition.method
|
|
11
|
+
(abstract_method_signature name: (property_identifier) @name) @definition.method
|
|
12
|
+
(public_field_definition name: (property_identifier) @name value: [(arrow_function) (function_expression)]) @definition.method
|
|
13
|
+
(interface_declaration name: (type_identifier) @name) @definition.interface
|
|
14
|
+
(type_alias_declaration name: (type_identifier) @name) @definition.type
|
|
15
|
+
(enum_declaration name: (identifier) @name) @definition.enum
|
|
16
|
+
(internal_module name: (identifier) @name) @definition.module
|
|
17
|
+
(program (lexical_declaration (variable_declarator name: (identifier) @name) @definition.variable))
|
|
18
|
+
(program (export_statement (lexical_declaration (variable_declarator name: (identifier) @name) @definition.variable)))
|
|
19
|
+
`;
|
|
20
|
+
const TYPESCRIPT_USES = `
|
|
21
|
+
[(identifier) (property_identifier) (type_identifier) (shorthand_property_identifier) (shorthand_property_identifier_pattern)] @use
|
|
22
|
+
`;
|
|
23
|
+
const JAVASCRIPT_DEFINITIONS = `
|
|
24
|
+
(function_declaration name: (identifier) @name) @definition.function
|
|
25
|
+
(generator_function_declaration name: (identifier) @name) @definition.function
|
|
26
|
+
(variable_declarator name: (identifier) @name value: [(arrow_function) (function_expression)]) @definition.function
|
|
27
|
+
(class_declaration name: (identifier) @name) @definition.class
|
|
28
|
+
(method_definition name: (property_identifier) @name) @definition.method
|
|
29
|
+
(field_definition property: (property_identifier) @name value: [(arrow_function) (function_expression)]) @definition.method
|
|
30
|
+
(program (lexical_declaration (variable_declarator name: (identifier) @name) @definition.variable))
|
|
31
|
+
(program (export_statement (lexical_declaration (variable_declarator name: (identifier) @name) @definition.variable)))
|
|
32
|
+
`;
|
|
33
|
+
const JAVASCRIPT_USES = `
|
|
34
|
+
[(identifier) (property_identifier) (shorthand_property_identifier) (shorthand_property_identifier_pattern)] @use
|
|
35
|
+
`;
|
|
36
|
+
const PYTHON_DEFINITIONS = `
|
|
37
|
+
(function_definition name: (identifier) @name) @definition.function
|
|
38
|
+
(class_definition name: (identifier) @name) @definition.class
|
|
39
|
+
(module (expression_statement (assignment left: (identifier) @name)) @definition.variable)
|
|
40
|
+
`;
|
|
41
|
+
const GO_DEFINITIONS = `
|
|
42
|
+
(function_declaration name: (identifier) @name) @definition.function
|
|
43
|
+
(method_declaration name: (field_identifier) @name) @definition.method
|
|
44
|
+
(type_spec name: (type_identifier) @name type: (struct_type)) @definition.class
|
|
45
|
+
(type_spec name: (type_identifier) @name type: (interface_type)) @definition.interface
|
|
46
|
+
(type_spec name: (type_identifier) @name) @definition.type
|
|
47
|
+
(method_elem name: (field_identifier) @name) @definition.method
|
|
48
|
+
(source_file (var_declaration (var_spec name: (identifier) @name) @definition.variable))
|
|
49
|
+
(source_file (const_declaration (const_spec name: (identifier) @name) @definition.variable))
|
|
50
|
+
`;
|
|
51
|
+
const RUST_DEFINITIONS = `
|
|
52
|
+
(declaration_list (function_item name: (identifier) @name) @definition.method)
|
|
53
|
+
(declaration_list (function_signature_item name: (identifier) @name) @definition.method)
|
|
54
|
+
(function_item name: (identifier) @name) @definition.function
|
|
55
|
+
(struct_item name: (type_identifier) @name) @definition.class
|
|
56
|
+
(union_item name: (type_identifier) @name) @definition.class
|
|
57
|
+
(enum_item name: (type_identifier) @name) @definition.enum
|
|
58
|
+
(type_item name: (type_identifier) @name) @definition.type
|
|
59
|
+
(trait_item name: (type_identifier) @name) @definition.interface
|
|
60
|
+
(mod_item name: (identifier) @name) @definition.module
|
|
61
|
+
(macro_definition name: (identifier) @name) @definition.function
|
|
62
|
+
(source_file (const_item name: (identifier) @name) @definition.variable)
|
|
63
|
+
(source_file (static_item name: (identifier) @name) @definition.variable)
|
|
64
|
+
`;
|
|
65
|
+
const JAVA_DEFINITIONS = `
|
|
66
|
+
(class_declaration name: (identifier) @name) @definition.class
|
|
67
|
+
(record_declaration name: (identifier) @name) @definition.class
|
|
68
|
+
(interface_declaration name: (identifier) @name) @definition.interface
|
|
69
|
+
(annotation_type_declaration name: (identifier) @name) @definition.interface
|
|
70
|
+
(enum_declaration name: (identifier) @name) @definition.enum
|
|
71
|
+
(method_declaration name: (identifier) @name) @definition.method
|
|
72
|
+
(constructor_declaration name: (identifier) @name) @definition.method
|
|
73
|
+
`;
|
|
74
|
+
const TYPESCRIPT = {
|
|
75
|
+
id: "typescript",
|
|
76
|
+
grammar: "tree-sitter-typescript.wasm",
|
|
77
|
+
definitions: TYPESCRIPT_DEFINITIONS,
|
|
78
|
+
uses: TYPESCRIPT_USES,
|
|
79
|
+
};
|
|
80
|
+
const LANGUAGES = {
|
|
81
|
+
".ts": TYPESCRIPT,
|
|
82
|
+
".mts": TYPESCRIPT,
|
|
83
|
+
".cts": TYPESCRIPT,
|
|
84
|
+
".tsx": { ...TYPESCRIPT, id: "tsx", grammar: "tree-sitter-tsx.wasm" },
|
|
85
|
+
...Object.fromEntries([".js", ".jsx", ".mjs", ".cjs"].map((extension) => [
|
|
86
|
+
extension,
|
|
87
|
+
{
|
|
88
|
+
id: "javascript",
|
|
89
|
+
grammar: "tree-sitter-javascript.wasm",
|
|
90
|
+
definitions: JAVASCRIPT_DEFINITIONS,
|
|
91
|
+
uses: JAVASCRIPT_USES,
|
|
92
|
+
},
|
|
93
|
+
])),
|
|
94
|
+
".py": {
|
|
95
|
+
id: "python",
|
|
96
|
+
grammar: "tree-sitter-python.wasm",
|
|
97
|
+
definitions: PYTHON_DEFINITIONS,
|
|
98
|
+
uses: "(identifier) @use",
|
|
99
|
+
},
|
|
100
|
+
".go": {
|
|
101
|
+
id: "go",
|
|
102
|
+
grammar: "tree-sitter-go.wasm",
|
|
103
|
+
definitions: GO_DEFINITIONS,
|
|
104
|
+
uses: "[(identifier) (field_identifier) (type_identifier) (package_identifier)] @use",
|
|
105
|
+
},
|
|
106
|
+
".rs": {
|
|
107
|
+
id: "rust",
|
|
108
|
+
grammar: "tree-sitter-rust.wasm",
|
|
109
|
+
definitions: RUST_DEFINITIONS,
|
|
110
|
+
uses: "[(identifier) (field_identifier) (type_identifier)] @use",
|
|
111
|
+
},
|
|
112
|
+
".java": {
|
|
113
|
+
id: "java",
|
|
114
|
+
grammar: "tree-sitter-java.wasm",
|
|
115
|
+
definitions: JAVA_DEFINITIONS,
|
|
116
|
+
uses: "[(identifier) (type_identifier)] @use",
|
|
117
|
+
},
|
|
118
|
+
};
|
|
119
|
+
export function languageOf(path) {
|
|
120
|
+
const extension = extname(path).toLowerCase();
|
|
121
|
+
return Object.hasOwn(LANGUAGES, extension) ? LANGUAGES[extension] : undefined;
|
|
122
|
+
}
|
|
123
|
+
export function allLanguages() {
|
|
124
|
+
return [...new Map(Object.values(LANGUAGES).map((spec) => [spec.id, spec])).values()];
|
|
125
|
+
}
|
package/dist/parse.d.ts
ADDED
package/dist/parse.js
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { SYMBOL_KINDS } from "@open-cr-agent/core";
|
|
4
|
+
// The package is a UMD bundle, which Node's ESM loader cannot read named
|
|
5
|
+
// exports from.
|
|
6
|
+
const require = createRequire(import.meta.url);
|
|
7
|
+
const GRAMMARS = dirname(require.resolve("@vscode/tree-sitter-wasm"));
|
|
8
|
+
// A parse and its queries that take longer give up: the file goes without
|
|
9
|
+
// symbols, and nothing is cached, rather than hold the review on hostile or
|
|
10
|
+
// pathological input.
|
|
11
|
+
const PARSE_BUDGET_MS = 1_000;
|
|
12
|
+
// When two patterns match one node (a Go struct is also a type spec), the
|
|
13
|
+
// more specific kind wins.
|
|
14
|
+
const KIND_RANK = [
|
|
15
|
+
"class",
|
|
16
|
+
"interface",
|
|
17
|
+
"enum",
|
|
18
|
+
"method",
|
|
19
|
+
"function",
|
|
20
|
+
"type",
|
|
21
|
+
"module",
|
|
22
|
+
"variable",
|
|
23
|
+
];
|
|
24
|
+
let runtime;
|
|
25
|
+
const languages = new Map();
|
|
26
|
+
function treeSitter() {
|
|
27
|
+
runtime ??= (async () => {
|
|
28
|
+
const module = require("@vscode/tree-sitter-wasm");
|
|
29
|
+
await module.Parser.init({ locateFile: (file) => join(GRAMMARS, file) });
|
|
30
|
+
return module;
|
|
31
|
+
})();
|
|
32
|
+
return runtime;
|
|
33
|
+
}
|
|
34
|
+
function load(spec) {
|
|
35
|
+
let loaded = languages.get(spec.id);
|
|
36
|
+
if (!loaded) {
|
|
37
|
+
loaded = (async () => {
|
|
38
|
+
const { Language, Parser, Query } = await treeSitter();
|
|
39
|
+
const language = await Language.load(join(GRAMMARS, spec.grammar));
|
|
40
|
+
const parser = new Parser();
|
|
41
|
+
parser.setLanguage(language);
|
|
42
|
+
return {
|
|
43
|
+
parser,
|
|
44
|
+
definitions: new Query(language, spec.definitions),
|
|
45
|
+
uses: new Query(language, spec.uses),
|
|
46
|
+
};
|
|
47
|
+
})();
|
|
48
|
+
languages.set(spec.id, loaded);
|
|
49
|
+
}
|
|
50
|
+
return loaded;
|
|
51
|
+
}
|
|
52
|
+
export async function parseSymbols(spec, content, budgetMs = PARSE_BUDGET_MS) {
|
|
53
|
+
const { parser, definitions, uses } = await load(spec);
|
|
54
|
+
const deadline = performance.now() + budgetMs;
|
|
55
|
+
let late = false;
|
|
56
|
+
const progressCallback = () => {
|
|
57
|
+
late ||= performance.now() > deadline;
|
|
58
|
+
return late;
|
|
59
|
+
};
|
|
60
|
+
const tree = parser.parse(content, null, { progressCallback });
|
|
61
|
+
if (!tree)
|
|
62
|
+
return undefined;
|
|
63
|
+
try {
|
|
64
|
+
const matches = definitions.matches(tree.rootNode, { progressCallback });
|
|
65
|
+
const captures = uses.captures(tree.rootNode, { progressCallback });
|
|
66
|
+
if (late)
|
|
67
|
+
return undefined;
|
|
68
|
+
const found = collectDefinitions(matches);
|
|
69
|
+
const nameStarts = new Set(found.map((d) => d.nameStart));
|
|
70
|
+
const lines = new Map();
|
|
71
|
+
for (const { node } of captures) {
|
|
72
|
+
if (nameStarts.has(node.startIndex))
|
|
73
|
+
continue;
|
|
74
|
+
const seen = lines.get(node.text) ?? new Set();
|
|
75
|
+
seen.add(node.startPosition.row + 1);
|
|
76
|
+
lines.set(node.text, seen);
|
|
77
|
+
}
|
|
78
|
+
return {
|
|
79
|
+
definitions: asMethods(found.map(({ nameStart: _, ...definition }) => definition)),
|
|
80
|
+
uses: new Map([...lines].map(([name, rows]) => [name, [...rows].sort((a, b) => a - b)])),
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
finally {
|
|
84
|
+
tree.delete();
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
function collectDefinitions(matches) {
|
|
88
|
+
const byNode = new Map();
|
|
89
|
+
for (const { captures } of matches) {
|
|
90
|
+
const name = captures.find((c) => c.name === "name")?.node;
|
|
91
|
+
const definition = captures.find((c) => c.name.startsWith("definition."));
|
|
92
|
+
if (!name || !definition)
|
|
93
|
+
continue;
|
|
94
|
+
const kind = definition.name.slice("definition.".length);
|
|
95
|
+
if (!SYMBOL_KINDS.includes(kind))
|
|
96
|
+
continue;
|
|
97
|
+
const id = definition.node.startIndex;
|
|
98
|
+
const previous = byNode.get(id);
|
|
99
|
+
if (previous && KIND_RANK.indexOf(previous.kind) <= KIND_RANK.indexOf(kind))
|
|
100
|
+
continue;
|
|
101
|
+
byNode.set(id, {
|
|
102
|
+
name: name.text,
|
|
103
|
+
kind,
|
|
104
|
+
startLine: definition.node.startPosition.row + 1,
|
|
105
|
+
endLine: definition.node.endPosition.row + 1,
|
|
106
|
+
nameStart: name.startIndex,
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
return [...byNode.values()].sort((a, b) => a.startLine - b.startLine || b.endLine - a.endLine);
|
|
110
|
+
}
|
|
111
|
+
// A function defined inside a class or interface is its method, whatever the
|
|
112
|
+
// grammar calls it (Python has only function definitions).
|
|
113
|
+
function asMethods(definitions) {
|
|
114
|
+
return definitions.map((definition) => {
|
|
115
|
+
if (definition.kind !== "function")
|
|
116
|
+
return definition;
|
|
117
|
+
const owner = innermostAround(definitions, definition);
|
|
118
|
+
return owner && (owner.kind === "class" || owner.kind === "interface")
|
|
119
|
+
? { ...definition, kind: "method" }
|
|
120
|
+
: definition;
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
function innermostAround(definitions, inner) {
|
|
124
|
+
let best;
|
|
125
|
+
for (const d of definitions) {
|
|
126
|
+
if (d === inner || d.startLine > inner.startLine || d.endLine < inner.endLine)
|
|
127
|
+
continue;
|
|
128
|
+
if (!best || d.endLine - d.startLine < best.endLine - best.startLine)
|
|
129
|
+
best = d;
|
|
130
|
+
}
|
|
131
|
+
return best;
|
|
132
|
+
}
|
package/dist/scip.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type ReferenceIndex } from "@open-cr-agent/core";
|
|
2
|
+
export interface ScipOptions {
|
|
3
|
+
warn?: (message: string) => void;
|
|
4
|
+
}
|
|
5
|
+
export declare function scipReferences(file: string, options?: ScipOptions): ReferenceIndex;
|
|
6
|
+
export declare function symbolName(symbol: string): string | undefined;
|
package/dist/scip.js
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { readFile, stat } from "node:fs/promises";
|
|
2
|
+
import { posix } from "node:path";
|
|
3
|
+
import { fromBinary } from "@bufbuild/protobuf";
|
|
4
|
+
import { errorMessage } from "@open-cr-agent/core";
|
|
5
|
+
import { IndexSchema, SymbolRole } from "@scip-code/scip";
|
|
6
|
+
// Larger indexes would not fit in memory once decoded.
|
|
7
|
+
const MAX_INDEX_BYTES = 512 * 1024 * 1024;
|
|
8
|
+
// A SCIP index (scip-typescript, scip-java, scip-python, …) built at the
|
|
9
|
+
// repository root, read once on first use. Its positions are those of the
|
|
10
|
+
// revision it was built from; callers check each line still names the
|
|
11
|
+
// symbol.
|
|
12
|
+
export function scipReferences(file, options = {}) {
|
|
13
|
+
let loaded;
|
|
14
|
+
return {
|
|
15
|
+
async usesOf(path, name) {
|
|
16
|
+
loaded ??= load(file).catch((error) => {
|
|
17
|
+
options.warn?.(`SCIP index ${file} could not be read (${errorMessage(error)}); callers are found by search`);
|
|
18
|
+
return undefined;
|
|
19
|
+
});
|
|
20
|
+
const index = await loaded;
|
|
21
|
+
const symbols = index?.definitions.get(path)?.get(name);
|
|
22
|
+
if (!index || !symbols)
|
|
23
|
+
return undefined;
|
|
24
|
+
const seen = new Set();
|
|
25
|
+
return symbols
|
|
26
|
+
.flatMap((symbol) => index.uses.get(symbol) ?? [])
|
|
27
|
+
.filter((use) => {
|
|
28
|
+
const key = `${use.path}:${use.line}`;
|
|
29
|
+
if (use.path === path || seen.has(key))
|
|
30
|
+
return false;
|
|
31
|
+
seen.add(key);
|
|
32
|
+
return true;
|
|
33
|
+
});
|
|
34
|
+
},
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
async function load(file) {
|
|
38
|
+
const { size } = await stat(file);
|
|
39
|
+
if (size > MAX_INDEX_BYTES)
|
|
40
|
+
throw new Error(`${size} bytes, more than ${MAX_INDEX_BYTES}`);
|
|
41
|
+
const index = fromBinary(IndexSchema, await readFile(file));
|
|
42
|
+
const loaded = { definitions: new Map(), uses: new Map() };
|
|
43
|
+
for (const document of index.documents)
|
|
44
|
+
addDocument(loaded, document);
|
|
45
|
+
return loaded;
|
|
46
|
+
}
|
|
47
|
+
function addDocument(loaded, document) {
|
|
48
|
+
const path = posix.normalize(document.relativePath.replaceAll("\\", "/"));
|
|
49
|
+
const displayNames = new Map(document.symbols.filter((s) => s.displayName).map((s) => [s.symbol, s.displayName]));
|
|
50
|
+
for (const occurrence of document.occurrences) {
|
|
51
|
+
const { symbol } = occurrence;
|
|
52
|
+
if (symbol === "" || symbol.startsWith("local "))
|
|
53
|
+
continue;
|
|
54
|
+
if (occurrence.symbolRoles & SymbolRole.Definition) {
|
|
55
|
+
const name = displayNames.get(symbol) ?? symbolName(symbol);
|
|
56
|
+
if (!name)
|
|
57
|
+
continue;
|
|
58
|
+
const names = loaded.definitions.get(path) ?? new Map();
|
|
59
|
+
names.set(name, [...(names.get(name) ?? []), symbol]);
|
|
60
|
+
loaded.definitions.set(path, names);
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
const uses = loaded.uses.get(symbol) ?? [];
|
|
64
|
+
uses.push({ path, line: startLine(occurrence) + 1 });
|
|
65
|
+
loaded.uses.set(symbol, uses);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
function startLine(occurrence) {
|
|
69
|
+
const { typedRange, range } = occurrence;
|
|
70
|
+
if (typedRange.case === "singleLineRange")
|
|
71
|
+
return typedRange.value.line;
|
|
72
|
+
if (typedRange.case === "multiLineRange")
|
|
73
|
+
return typedRange.value.startLine;
|
|
74
|
+
return range[0] ?? 0;
|
|
75
|
+
}
|
|
76
|
+
// The name of a symbol's last descriptor (SCIP's symbol grammar): `Retry#`,
|
|
77
|
+
// `parse().`, `limit.` or a backquoted name; undefined when the symbol ends
|
|
78
|
+
// in a parameter or type parameter, which nothing outside calls.
|
|
79
|
+
export function symbolName(symbol) {
|
|
80
|
+
const descriptors = afterFields(symbol, 4);
|
|
81
|
+
if (descriptors === undefined)
|
|
82
|
+
return undefined;
|
|
83
|
+
let last;
|
|
84
|
+
let i = 0;
|
|
85
|
+
while (i < descriptors.length) {
|
|
86
|
+
const opening = descriptors[i];
|
|
87
|
+
if (opening === "(" || opening === "[") {
|
|
88
|
+
const close = descriptors.indexOf(opening === "(" ? ")" : "]", i);
|
|
89
|
+
if (close < 0)
|
|
90
|
+
return undefined;
|
|
91
|
+
last = undefined;
|
|
92
|
+
i = close + 1;
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
const [name, next] = readName(descriptors, i);
|
|
96
|
+
if (name === undefined)
|
|
97
|
+
return undefined;
|
|
98
|
+
i = next;
|
|
99
|
+
if (descriptors[i] === "(") {
|
|
100
|
+
const close = descriptors.indexOf(")", i);
|
|
101
|
+
if (close < 0)
|
|
102
|
+
return undefined;
|
|
103
|
+
i = close + 1;
|
|
104
|
+
}
|
|
105
|
+
if (!"/#.:!".includes(descriptors[i] ?? ""))
|
|
106
|
+
return undefined;
|
|
107
|
+
last = name;
|
|
108
|
+
i += 1;
|
|
109
|
+
}
|
|
110
|
+
return last;
|
|
111
|
+
}
|
|
112
|
+
// The rest of the symbol after `count` space-separated fields, where a
|
|
113
|
+
// field's own space is written twice.
|
|
114
|
+
function afterFields(symbol, count) {
|
|
115
|
+
let i = 0;
|
|
116
|
+
for (let field = 0; field < count; field++) {
|
|
117
|
+
for (;;) {
|
|
118
|
+
const space = symbol.indexOf(" ", i);
|
|
119
|
+
if (space < 0)
|
|
120
|
+
return undefined;
|
|
121
|
+
if (symbol[space + 1] === " ") {
|
|
122
|
+
i = space + 2;
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
i = space + 1;
|
|
126
|
+
break;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return symbol.slice(i);
|
|
130
|
+
}
|
|
131
|
+
function readName(text, start) {
|
|
132
|
+
if (text[start] === "`") {
|
|
133
|
+
let name = "";
|
|
134
|
+
let i = start + 1;
|
|
135
|
+
while (i < text.length) {
|
|
136
|
+
if (text[i] === "`") {
|
|
137
|
+
if (text[i + 1] !== "`")
|
|
138
|
+
return [name, i + 1];
|
|
139
|
+
name += "`";
|
|
140
|
+
i += 2;
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
name += text[i];
|
|
144
|
+
i += 1;
|
|
145
|
+
}
|
|
146
|
+
return [undefined, i];
|
|
147
|
+
}
|
|
148
|
+
const match = /^[\w+$-]+/.exec(text.slice(start));
|
|
149
|
+
return match ? [match[0], start + match[0].length] : [undefined, start];
|
|
150
|
+
}
|
package/dist/stored.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { FileSymbols } from "@open-cr-agent/core";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
export declare const storedSymbols: z.ZodObject<{
|
|
4
|
+
definitions: z.ZodArray<z.ZodTuple<[z.ZodString, z.ZodEnum<{
|
|
5
|
+
class: "class";
|
|
6
|
+
enum: "enum";
|
|
7
|
+
function: "function";
|
|
8
|
+
interface: "interface";
|
|
9
|
+
method: "method";
|
|
10
|
+
module: "module";
|
|
11
|
+
type: "type";
|
|
12
|
+
variable: "variable";
|
|
13
|
+
}>, z.ZodNumber, z.ZodNumber], null>>;
|
|
14
|
+
uses: z.ZodArray<z.ZodTuple<[z.ZodString, z.ZodArray<z.ZodNumber>], null>>;
|
|
15
|
+
}, z.core.$strip>;
|
|
16
|
+
export type StoredSymbols = z.infer<typeof storedSymbols>;
|
|
17
|
+
export declare function toStored(symbols: FileSymbols): StoredSymbols;
|
|
18
|
+
export declare function fromStored(stored: StoredSymbols): FileSymbols;
|
package/dist/stored.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { SYMBOL_KINDS } from "@open-cr-agent/core";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
// A file's symbols as the cache and the graph keep them: tuples, so a
|
|
4
|
+
// repository's worth stays small.
|
|
5
|
+
const line = z.number().int().positive();
|
|
6
|
+
export const storedSymbols = z.object({
|
|
7
|
+
definitions: z.array(z.tuple([z.string(), z.enum(SYMBOL_KINDS), line, line])),
|
|
8
|
+
uses: z.array(z.tuple([z.string(), z.array(line)])),
|
|
9
|
+
});
|
|
10
|
+
export function toStored(symbols) {
|
|
11
|
+
return {
|
|
12
|
+
definitions: symbols.definitions.map((d) => [d.name, d.kind, d.startLine, d.endLine]),
|
|
13
|
+
uses: [...symbols.uses].map(([name, lines]) => [name, [...lines]]),
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
export function fromStored(stored) {
|
|
17
|
+
return {
|
|
18
|
+
definitions: stored.definitions.map(([name, kind, startLine, endLine]) => ({
|
|
19
|
+
name,
|
|
20
|
+
kind,
|
|
21
|
+
startLine,
|
|
22
|
+
endLine,
|
|
23
|
+
})),
|
|
24
|
+
uses: new Map(stored.uses),
|
|
25
|
+
};
|
|
26
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const VERSION: string;
|
package/dist/version.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { allLanguages } from "./languages.js";
|
|
4
|
+
// Changes whenever a query or the grammars do, so no cached entry or graph
|
|
5
|
+
// outlives the parser that made it.
|
|
6
|
+
export const VERSION = createHash("sha256")
|
|
7
|
+
.update(createRequire(import.meta.url)("@vscode/tree-sitter-wasm/package.json")
|
|
8
|
+
.version)
|
|
9
|
+
.update(JSON.stringify(allLanguages()))
|
|
10
|
+
.digest("hex");
|
package/package.json
CHANGED
|
@@ -1,6 +1,44 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-cr-agent/code-graph",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.8.1",
|
|
4
|
+
"description": "Tree-sitter symbols for Open-CR-Agent's impact analysis, cached by git blob id",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"code-review",
|
|
7
|
+
"tree-sitter"
|
|
8
|
+
],
|
|
9
|
+
"license": "Apache-2.0",
|
|
10
|
+
"homepage": "https://ocracloud.com",
|
|
11
|
+
"repository": {
|
|
12
|
+
"type": "git",
|
|
13
|
+
"url": "git+https://github.com/jma49/Open-CR-Agent.git",
|
|
14
|
+
"directory": "packages/code-graph"
|
|
15
|
+
},
|
|
16
|
+
"bugs": "https://github.com/jma49/Open-CR-Agent/issues",
|
|
17
|
+
"engines": {
|
|
18
|
+
"node": ">=22.19"
|
|
19
|
+
},
|
|
20
|
+
"type": "module",
|
|
21
|
+
"sideEffects": false,
|
|
22
|
+
"exports": {
|
|
23
|
+
".": {
|
|
24
|
+
"@open-cr-agent/source": "./src/index.ts",
|
|
25
|
+
"types": "./dist/index.d.ts",
|
|
26
|
+
"default": "./dist/index.js"
|
|
27
|
+
},
|
|
28
|
+
"./package.json": "./package.json"
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"dist",
|
|
32
|
+
"!dist/**/*.map"
|
|
33
|
+
],
|
|
34
|
+
"dependencies": {
|
|
35
|
+
"@bufbuild/protobuf": "2.17.0",
|
|
36
|
+
"@open-cr-agent/core": "0.8.0",
|
|
37
|
+
"@scip-code/scip": "0.10.0",
|
|
38
|
+
"@vscode/tree-sitter-wasm": "0.3.1",
|
|
39
|
+
"zod": "^4.6.6"
|
|
40
|
+
},
|
|
41
|
+
"publishConfig": {
|
|
42
|
+
"access": "public"
|
|
43
|
+
}
|
|
44
|
+
}
|