Elffuss BraidHub

kikocis/continue public

main · 7.2 KiBRawPermalink
1import { SyntaxNode } from "web-tree-sitter";
2
3import { ChunkWithoutID } from "../../index.js";
4import { countTokensAsync } from "../../llm/countTokens.js";
5import { getParserForFile } from "../../util/treeSitter.js";
6
7function collapsedReplacement(node: SyntaxNode): string {
8 if (node.type === "statement_block") {
9 return "{ ... }";
10 }
11 return "...";
12}
13
14function firstChild(
15 node: SyntaxNode,
16 grammarName: string | string[],
17): SyntaxNode | null {
18 if (Array.isArray(grammarName)) {
19 return (
20 node.children.find((child) => grammarName.includes(child.type)) || null
21 );
22 }
23 return node.children.find((child) => child.type === grammarName) || null;
24}
25
26async function collapseChildren(
27 node: SyntaxNode,
28 code: string,
29 blockTypes: string[],
30 collapseTypes: string[],
31 collapseBlockTypes: string[],
32 maxChunkSize: number,
33): Promise<string> {
34 code = code.slice(0, node.endIndex);
35 const block = firstChild(node, blockTypes);
36 const collapsedChildren = [];
37
38 if (block) {
39 const childrenToCollapse = block.children.filter((child) =>
40 collapseTypes.includes(child.type),
41 );
42 for (const child of childrenToCollapse.reverse()) {
43 const grandChild = firstChild(child, collapseBlockTypes);
44 if (grandChild) {
45 const start = grandChild.startIndex;
46 const end = grandChild.endIndex;
47 const collapsedChild =
48 code.slice(child.startIndex, start) +
49 collapsedReplacement(grandChild);
50 code =
51 code.slice(0, start) +
52 collapsedReplacement(grandChild) +
53 code.slice(end);
54
55 collapsedChildren.unshift(collapsedChild);
56 }
57 }
58 }
59 code = code.slice(node.startIndex);
60 let removedChild = false;
61 while (
62 (await countTokensAsync(code.trim())) > maxChunkSize &&
63 collapsedChildren.length > 0
64 ) {
65 removedChild = true;
66 // Remove children starting at the end - TODO: Add multiple chunks so no children are missing
67 const childCode = collapsedChildren.pop()!;
68 const index = code.lastIndexOf(childCode);
69 if (index > 0) {
70 code = code.slice(0, index) + code.slice(index + childCode.length);
71 }
72 }
73
74 if (removedChild) {
75 // Remove the extra blank lines
76 let lines = code.split("\n");
77 let firstWhiteSpaceInGroup = -1;
78 for (let i = lines.length - 1; i >= 0; i--) {
79 if (lines[i].trim() === "") {
80 if (firstWhiteSpaceInGroup < 0) {
81 firstWhiteSpaceInGroup = i;
82 }
83 } else {
84 if (firstWhiteSpaceInGroup - i > 1) {
85 // Remove the lines
86 lines = [
87 ...lines.slice(0, i + 1),
88 ...lines.slice(firstWhiteSpaceInGroup + 1),
89 ];
90 }
91 firstWhiteSpaceInGroup = -1;
92 }
93 }
94
95 code = lines.join("\n");
96 }
97
98 return code;
99}
100
101export const FUNCTION_BLOCK_NODE_TYPES = ["block", "statement_block"];
102export const FUNCTION_DECLARATION_NODE_TYPEs = [
103 "method_definition",
104 "function_definition",
105 "function_item",
106 "function_declaration",
107 "method_declaration",
108];
109
110async function constructClassDefinitionChunk(
111 node: SyntaxNode,
112 code: string,
113 maxChunkSize: number,
114): Promise<string> {
115 return collapseChildren(
116 node,
117 code,
118 ["block", "class_body", "declaration_list"],
119 FUNCTION_DECLARATION_NODE_TYPEs,
120 FUNCTION_BLOCK_NODE_TYPES,
121 maxChunkSize,
122 );
123}
124
125async function constructFunctionDefinitionChunk(
126 node: SyntaxNode,
127 code: string,
128 maxChunkSize: number,
129): Promise<string> {
130 const bodyNode = node.children[node.children.length - 1];
131 const collapsedBody = collapsedReplacement(bodyNode);
132 const signature = code.slice(node.startIndex, bodyNode.startIndex);
133 const funcText = signature + collapsedBody;
134
135 const isInClass =
136 node.parent &&
137 ["block", "declaration_list"].includes(node.parent.type) &&
138 node.parent.parent &&
139 ["class_definition", "impl_item"].includes(node.parent.parent.type);
140
141 if (isInClass) {
142 const classNode = node.parent!.parent!;
143 const classBlock = node.parent!;
144 const classHeader = code.slice(classNode.startIndex, classBlock.startIndex);
145 const indent = " ".repeat(node.startPosition.column);
146 const combined = `${classHeader}...\n\n${indent}${funcText}`;
147
148 if ((await countTokensAsync(combined)) <= maxChunkSize) {
149 return combined;
150 }
151 if ((await countTokensAsync(funcText)) <= maxChunkSize) {
152 return funcText;
153 }
154 const firstLine = signature.split("\n")[0] ?? "";
155 const minimal = `${firstLine} ${collapsedBody}`;
156 if ((await countTokensAsync(minimal)) <= maxChunkSize) {
157 return minimal;
158 }
159 return collapsedBody;
160 }
161
162 if ((await countTokensAsync(funcText)) <= maxChunkSize) {
163 return funcText;
164 }
165 const firstLine = signature.split("\n")[0] ?? "";
166 const minimal = `${firstLine} ${collapsedBody}`;
167 if ((await countTokensAsync(minimal)) <= maxChunkSize) {
168 return minimal;
169 }
170 return collapsedBody;
171}
172
173const collapsedNodeConstructors: {
174 [key: string]: (
175 node: SyntaxNode,
176 code: string,
177 maxChunkSize: number,
178 ) => Promise<string>;
179} = {
180 // Classes, structs, etc
181 class_definition: constructClassDefinitionChunk,
182 class_declaration: constructClassDefinitionChunk,
183 impl_item: constructClassDefinitionChunk,
184 // Functions
185 function_definition: constructFunctionDefinitionChunk,
186 function_declaration: constructFunctionDefinitionChunk,
187 function_item: constructFunctionDefinitionChunk,
188 // Methods
189 method_declaration: constructFunctionDefinitionChunk,
190 // Properties
191};
192
193async function maybeYieldChunk(
194 node: SyntaxNode,
195 code: string,
196 maxChunkSize: number,
197 root = true,
198): Promise<ChunkWithoutID | undefined> {
199 // Keep entire text if not over size
200 if (root || node.type in collapsedNodeConstructors) {
201 const tokenCount = await countTokensAsync(node.text);
202 if (tokenCount < maxChunkSize) {
203 return {
204 content: node.text,
205 startLine: node.startPosition.row,
206 endLine: node.endPosition.row,
207 };
208 }
209 }
210 return undefined;
211}
212
213async function* getSmartCollapsedChunks(
214 node: SyntaxNode,
215 code: string,
216 maxChunkSize: number,
217 root = true,
218): AsyncGenerator<ChunkWithoutID> {
219 const chunk = await maybeYieldChunk(node, code, maxChunkSize, root);
220 if (chunk) {
221 yield chunk;
222 return;
223 }
224 // If a collapsed form is defined, use that
225 if (node.type in collapsedNodeConstructors) {
226 yield {
227 content: await collapsedNodeConstructors[node.type](
228 node,
229 code,
230 maxChunkSize,
231 ),
232 startLine: node.startPosition.row,
233 endLine: node.endPosition.row,
234 };
235 }
236
237 // Recurse (because even if collapsed version was shown, want to show the children in full somewhere)
238 const generators = node.children.map((child) =>
239 getSmartCollapsedChunks(child, code, maxChunkSize, false),
240 );
241 for (const generator of generators) {
242 yield* generator;
243 }
244}
245
246export async function* codeChunker(
247 filepath: string,
248 contents: string,
249 maxChunkSize: number,
250): AsyncGenerator<ChunkWithoutID> {
251 if (contents.trim().length === 0) {
252 return;
253 }
254
255 const parser = await getParserForFile(filepath);
256 if (parser === undefined) {
257 throw new Error(`Failed to load parser for file ${filepath}: `);
258 }
259
260 const tree = parser.parse(contents);
261
262 yield* getSmartCollapsedChunks(tree.rootNode, contents, maxChunkSize);
263}