Elffuss BraidHub

kikocis/continue public

b334cb9dcd5e · 6.4 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 funcText =
132 code.slice(node.startIndex, bodyNode.startIndex) +
133 collapsedReplacement(bodyNode);
134
135 if (
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 inside a class, include the class header
142 const classNode = node.parent.parent;
143 const classBlock = node.parent;
144 return `${code.slice(
145 classNode.startIndex,
146 classBlock.startIndex,
147 )}...\n\n${" ".repeat(node.startPosition.column)}${funcText}`;
148 }
149 return funcText;
150}
151
152const collapsedNodeConstructors: {
153 [key: string]: (
154 node: SyntaxNode,
155 code: string,
156 maxChunkSize: number,
157 ) => Promise<string>;
158} = {
159 // Classes, structs, etc
160 class_definition: constructClassDefinitionChunk,
161 class_declaration: constructClassDefinitionChunk,
162 impl_item: constructClassDefinitionChunk,
163 // Functions
164 function_definition: constructFunctionDefinitionChunk,
165 function_declaration: constructFunctionDefinitionChunk,
166 function_item: constructFunctionDefinitionChunk,
167 // Methods
168 method_declaration: constructFunctionDefinitionChunk,
169 // Properties
170};
171
172async function maybeYieldChunk(
173 node: SyntaxNode,
174 code: string,
175 maxChunkSize: number,
176 root = true,
177): Promise<ChunkWithoutID | undefined> {
178 // Keep entire text if not over size
179 if (root || node.type in collapsedNodeConstructors) {
180 const tokenCount = await countTokensAsync(node.text);
181 if (tokenCount < maxChunkSize) {
182 return {
183 content: node.text,
184 startLine: node.startPosition.row,
185 endLine: node.endPosition.row,
186 };
187 }
188 }
189 return undefined;
190}
191
192async function* getSmartCollapsedChunks(
193 node: SyntaxNode,
194 code: string,
195 maxChunkSize: number,
196 root = true,
197): AsyncGenerator<ChunkWithoutID> {
198 const chunk = await maybeYieldChunk(node, code, maxChunkSize, root);
199 if (chunk) {
200 yield chunk;
201 return;
202 }
203 // If a collapsed form is defined, use that
204 if (node.type in collapsedNodeConstructors) {
205 yield {
206 content: await collapsedNodeConstructors[node.type](
207 node,
208 code,
209 maxChunkSize,
210 ),
211 startLine: node.startPosition.row,
212 endLine: node.endPosition.row,
213 };
214 }
215
216 // Recurse (because even if collapsed version was shown, want to show the children in full somewhere)
217 const generators = node.children.map((child) =>
218 getSmartCollapsedChunks(child, code, maxChunkSize, false),
219 );
220 for (const generator of generators) {
221 yield* generator;
222 }
223}
224
225export async function* codeChunker(
226 filepath: string,
227 contents: string,
228 maxChunkSize: number,
229): AsyncGenerator<ChunkWithoutID> {
230 if (contents.trim().length === 0) {
231 return;
232 }
233
234 const parser = await getParserForFile(filepath);
235 if (parser === undefined) {
236 throw new Error(`Failed to load parser for file ${filepath}: `);
237 }
238
239 const tree = parser.parse(contents);
240
241 yield* getSmartCollapsedChunks(tree.rootNode, contents, maxChunkSize);
242}