-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathast-search-service.ts
More file actions
680 lines (583 loc) · 18.4 KB
/
Copy pathast-search-service.ts
File metadata and controls
680 lines (583 loc) · 18.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
/**
* AST search service using ast-grep NAPI for structural code search
* Uses bundled native binaries and language packages - no external installation required
*/
import { parse, Lang, registerDynamicLanguage } from '@ast-grep/napi';
import langBash = require('@ast-grep/lang-bash');
import langC = require('@ast-grep/lang-c');
import langCpp = require('@ast-grep/lang-cpp');
import langCsharp = require('@ast-grep/lang-csharp');
import langGo = require('@ast-grep/lang-go');
import langJava = require('@ast-grep/lang-java');
import langJson = require('@ast-grep/lang-json');
import langKotlin = require('@ast-grep/lang-kotlin');
import langPython = require('@ast-grep/lang-python');
import langRust = require('@ast-grep/lang-rust');
import langScala = require('@ast-grep/lang-scala');
import langSwift = require('@ast-grep/lang-swift');
import langTsx = require('@ast-grep/lang-tsx');
import langTypeScript = require('@ast-grep/lang-typescript');
import langYaml = require('@ast-grep/lang-yaml');
import { promises as fs } from 'fs';
import path from 'path';
import fastGlob from 'fast-glob';
import type {
ASTPatternSearchOptions,
ASTRuleSearchOptions,
ASTSearchResult,
ASTMatch,
ASTGrepInfo,
ASTRule,
ASTLanguage,
} from '../types/ast-search.js';
// Type for ast-grep language (built-in or custom string)
type NapiLang = Lang | string;
// Register dynamic languages once
let languagesRegistered = false;
function ensureLanguagesRegistered() {
if (!languagesRegistered) {
registerDynamicLanguage({
bash: langBash as any,
c: langC as any,
cpp: langCpp as any,
csharp: langCsharp as any,
go: langGo as any,
java: langJava as any,
json: langJson as any,
kotlin: langKotlin as any,
python: langPython as any,
rust: langRust as any,
scala: langScala as any,
swift: langSwift as any,
tsx: langTsx as any,
typescript: langTypeScript as any,
yaml: langYaml as any,
});
languagesRegistered = true;
}
}
// Language mapping from our types to ast-grep NapiLang
// Includes built-in languages and dynamically registered language packages
const LANGUAGE_MAP: Record<ASTLanguage, NapiLang> = {
bash: 'bash',
c: 'c',
cpp: 'cpp',
csharp: 'csharp',
css: Lang.Css,
go: 'go',
html: Lang.Html,
java: 'java',
javascript: Lang.JavaScript,
json: 'json',
kotlin: 'kotlin',
python: 'python',
rust: 'rust',
scala: 'scala',
swift: 'swift',
tsx: 'tsx',
typescript: 'typescript',
yaml: 'yaml',
};
// File extension to language mapping
const EXTENSION_MAP: Record<string, ASTLanguage> = {
'.c': 'c',
'.h': 'c',
'.cpp': 'cpp',
'.cc': 'cpp',
'.cxx': 'cpp',
'.hpp': 'cpp',
'.hxx': 'cpp',
'.cs': 'csharp',
'.css': 'css',
'.go': 'go',
'.html': 'html',
'.htm': 'html',
'.java': 'java',
'.js': 'javascript',
'.mjs': 'javascript',
'.cjs': 'javascript',
'.jsx': 'javascript',
'.json': 'json',
'.kt': 'kotlin',
'.kts': 'kotlin',
'.py': 'python',
'.pyw': 'python',
'.rs': 'rust',
'.scala': 'scala',
'.sc': 'scala',
'.sh': 'bash',
'.bash': 'bash',
'.swift': 'swift',
'.ts': 'typescript',
'.mts': 'typescript',
'.cts': 'typescript',
'.tsx': 'tsx',
'.yaml': 'yaml',
'.yml': 'yaml',
};
export class ASTSearchService {
/**
* Check if ast-grep is available (always true since it's bundled)
*/
async isAvailable(): Promise<ASTGrepInfo> {
try {
// Ensure dynamic languages are registered
ensureLanguagesRegistered();
// Try to access the Lang enum and language packages to verify modules load
const testBuiltIn = Lang.JavaScript;
const testPython = langPython;
const testGo = langGo;
const testJava = langJava;
if (testBuiltIn !== undefined && testPython !== undefined && testGo !== undefined && testJava !== undefined) {
const supportedLangs = Object.keys(LANGUAGE_MAP).sort().join(', ');
return {
available: true,
version: '0.40.0', // @ast-grep packages version
path: `bundled (15 languages: ${supportedLangs})`,
};
}
throw new Error('Failed to load ast-grep modules');
} catch (error) {
return {
available: false,
error: error instanceof Error ? error.message : String(error),
};
}
}
/**
* Search using a simple pattern
*/
async searchPattern(
workspaceId: string,
workspacePath: string,
options: ASTPatternSearchOptions
): Promise<ASTSearchResult> {
// Ensure dynamic languages are registered
ensureLanguagesRegistered();
const startTime = Date.now();
// Get files to search
const files = await this.getFilesToSearch(
workspacePath,
options.language,
options.paths
);
const matches: ASTMatch[] = [];
const astLang = LANGUAGE_MAP[options.language];
if (!astLang) {
throw new Error(`Unsupported language: ${options.language}`);
}
// Search each file
for (const file of files) {
try {
const content = await fs.readFile(file, 'utf-8');
const ast = parse(astLang, content);
const root = ast.root();
// Find all matches
const nodes = root.findAll(options.pattern);
for (const node of nodes) {
const range = node.range();
const fullText = node.text();
const { truncated, totalLines } = this.truncateText(fullText, options.maxLines ?? 3);
const match: ASTMatch = {
file,
line: range.start.line + 1, // Convert to 1-indexed
column: range.start.column + 1,
endLine: range.end.line + 1,
endColumn: range.end.column + 1,
text: truncated,
totalLines,
};
// Extract metavariables if present
const metaVars = this.extractMetavariables(node, options.pattern);
if (metaVars && Object.keys(metaVars).length > 0) {
match.metaVariables = metaVars;
}
matches.push(match);
// Apply limit
if (options.limit && matches.length >= options.limit) {
break;
}
}
if (options.limit && matches.length >= options.limit) {
break;
}
} catch {
// Skip files that fail to parse
}
}
return {
workspaceId,
matches,
totalMatches: matches.length,
searchTime: Date.now() - startTime,
language: options.language,
};
}
/**
* Search using a complex rule
*/
async searchRule(
workspaceId: string,
workspacePath: string,
options: ASTRuleSearchOptions
): Promise<ASTSearchResult> {
// Ensure dynamic languages are registered
ensureLanguagesRegistered();
const startTime = Date.now();
// Get files to search
const files = await this.getFilesToSearch(
workspacePath,
options.language,
options.paths
);
const matches: ASTMatch[] = [];
const astLang = LANGUAGE_MAP[options.language];
if (!astLang) {
throw new Error(`Unsupported language: ${options.language}`);
}
// Search each file
for (const file of files) {
try {
const content = await fs.readFile(file, 'utf-8');
const ast = parse(astLang, content);
const root = ast.root();
// Apply rule
const nodes = this.applyRule(root, options.rule);
for (const node of nodes) {
const range = node.range();
const fullText = node.text();
const { truncated, totalLines } = this.truncateText(fullText, options.maxLines ?? 3);
const match: ASTMatch = {
file,
line: range.start.line + 1, // Convert to 1-indexed
column: range.start.column + 1,
endLine: range.end.line + 1,
endColumn: range.end.column + 1,
text: truncated,
totalLines,
};
// Try to extract metavariables
const metaVars = this.extractMetavariablesFromRule(node, options.rule);
if (metaVars && Object.keys(metaVars).length > 0) {
match.metaVariables = metaVars;
}
matches.push(match);
// Apply limit
if (options.limit && matches.length >= options.limit) {
break;
}
}
if (options.limit && matches.length >= options.limit) {
break;
}
} catch {
// Skip files that fail to parse
}
}
return {
workspaceId,
matches,
totalMatches: matches.length,
searchTime: Date.now() - startTime,
language: options.language,
};
}
/**
* Apply AST rule to find matching nodes
*/
private applyRule(root: any, rule: ASTRule): any[] {
let results: any[] = [];
// Handle composite rules
if (rule.all) {
// AND: Start with first rule, filter with rest
results = this.applyRule(root, rule.all[0]);
for (let i = 1; i < rule.all.length; i++) {
results = results.filter(node => this.nodeMatchesRule(node, rule.all![i]));
}
return results;
}
if (rule.any) {
// OR: Combine all results
const allResults = new Set<any>();
for (const subRule of rule.any) {
const nodes = this.applyRule(root, subRule);
nodes.forEach(n => allResults.add(n));
}
return Array.from(allResults);
}
if (rule.not) {
// NOT: Find all nodes, exclude those matching not rule
const allNodes = root.findAll('$_'); // Match everything
const excludeNodes = new Set(this.applyRule(root, rule.not));
return allNodes.filter((n: any) => !excludeNodes.has(n));
}
// Handle atomic rules
if (rule.pattern) {
const pattern = typeof rule.pattern === 'string' ? rule.pattern : rule.pattern.selector || rule.pattern.context || '';
let nodes = root.findAll(pattern);
// Apply relational filters
if (rule.inside) {
nodes = nodes.filter((n: any) => this.checkInside(n, rule.inside!));
}
if (rule.has) {
nodes = nodes.filter((n: any) => this.checkHas(n, rule.has!));
}
if (rule.precedes) {
nodes = nodes.filter((n: any) => this.checkPrecedes(n, rule.precedes!));
}
if (rule.follows) {
nodes = nodes.filter((n: any) => this.checkFollows(n, rule.follows!));
}
return nodes;
}
if (rule.kind) {
// Find by node kind
let nodes = root.findAll('$_'); // Find all nodes
nodes = nodes.filter((n: any) => n.kind() === rule.kind);
// Apply relational filters
if (rule.inside) {
nodes = nodes.filter((n: any) => this.checkInside(n, rule.inside!));
}
if (rule.has) {
nodes = nodes.filter((n: any) => this.checkHas(n, rule.has!));
}
return nodes;
}
if (rule.regex) {
// Find by regex
const regex = new RegExp(rule.regex);
let nodes = root.findAll('$_');
nodes = nodes.filter((n: any) => regex.test(n.text()));
// Apply relational filters
if (rule.inside) {
nodes = nodes.filter((n: any) => this.checkInside(n, rule.inside!));
}
if (rule.has) {
nodes = nodes.filter((n: any) => this.checkHas(n, rule.has!));
}
return nodes;
}
// If only relational rules, find all and filter
if (rule.inside || rule.has || rule.precedes || rule.follows) {
let nodes = root.findAll('$_');
if (rule.inside) {
nodes = nodes.filter((n: any) => this.checkInside(n, rule.inside!));
}
if (rule.has) {
nodes = nodes.filter((n: any) => this.checkHas(n, rule.has!));
}
if (rule.precedes) {
nodes = nodes.filter((n: any) => this.checkPrecedes(n, rule.precedes!));
}
if (rule.follows) {
nodes = nodes.filter((n: any) => this.checkFollows(n, rule.follows!));
}
return nodes;
}
return [];
}
/**
* Check if node matches a rule
*/
private nodeMatchesRule(node: any, rule: ASTRule): boolean {
if (rule.pattern) {
const pattern = typeof rule.pattern === 'string' ? rule.pattern : rule.pattern.selector || '';
if (!node.matches(pattern)) return false;
}
if (rule.kind && node.kind() !== rule.kind) {
return false;
}
if (rule.regex) {
const regex = new RegExp(rule.regex);
if (!regex.test(node.text())) return false;
}
if (rule.inside && !this.checkInside(node, rule.inside)) {
return false;
}
if (rule.has && !this.checkHas(node, rule.has)) {
return false;
}
if (rule.precedes && !this.checkPrecedes(node, rule.precedes)) {
return false;
}
if (rule.follows && !this.checkFollows(node, rule.follows)) {
return false;
}
if (rule.not) {
if (this.nodeMatchesRule(node, rule.not)) {
return false;
}
}
if (rule.all) {
return rule.all.every(r => this.nodeMatchesRule(node, r));
}
if (rule.any) {
return rule.any.some(r => this.nodeMatchesRule(node, r));
}
return true;
}
/**
* Check inside relational rule
*/
private checkInside(node: any, rule: ASTRule | any): boolean {
const pattern = typeof rule === 'string' ? rule : rule.pattern || '';
if (!pattern) return true;
return node.inside(pattern);
}
/**
* Check has relational rule
*/
private checkHas(node: any, rule: ASTRule | any): boolean {
const pattern = typeof rule === 'string' ? rule : rule.pattern || '';
if (!pattern) return true;
return node.has(pattern);
}
/**
* Check precedes relational rule
*/
private checkPrecedes(node: any, rule: ASTRule | any): boolean {
const pattern = typeof rule === 'string' ? rule : rule.pattern || '';
if (!pattern) return true;
return node.precedes(pattern);
}
/**
* Check follows relational rule
*/
private checkFollows(node: any, rule: ASTRule | any): boolean {
const pattern = typeof rule === 'string' ? rule : rule.pattern || '';
if (!pattern) return true;
return node.follows(pattern);
}
/**
* Extract metavariables from a matched node
*/
private extractMetavariables(node: any, pattern: string): Record<string, any> | undefined {
// Extract variable names from pattern ($VAR, $$VAR, $$$VAR)
const varPattern = /\$(\$?\$?[A-Z_][A-Z0-9_]*)/g;
const vars = new Set<string>();
let match;
while ((match = varPattern.exec(pattern)) !== null) {
const varName = match[1].replace(/^\$+/, ''); // Remove leading $
vars.add(varName);
}
if (vars.size === 0) return undefined;
const metaVars: Record<string, any> = {};
for (const varName of vars) {
try {
const matchedNode = node.getMatch(varName);
if (matchedNode) {
const range = matchedNode.range();
metaVars[varName] = {
text: matchedNode.text(),
line: range.start.line + 1,
column: range.start.column + 1,
};
}
} catch {
// Variable not found, skip
}
}
return Object.keys(metaVars).length > 0 ? metaVars : undefined;
}
/**
* Extract metavariables from rule
*/
private extractMetavariablesFromRule(node: any, rule: ASTRule): Record<string, any> | undefined {
if (rule.pattern) {
const pattern = typeof rule.pattern === 'string' ? rule.pattern : rule.pattern.selector || '';
return this.extractMetavariables(node, pattern);
}
return undefined;
}
/**
* Get files to search based on language and paths
*/
private async getFilesToSearch(
workspacePath: string,
language: ASTLanguage,
paths?: string[]
): Promise<string[]> {
// If specific paths provided, use those
if (paths && paths.length > 0) {
const resolvedPaths: string[] = [];
for (const p of paths) {
const fullPath = path.isAbsolute(p) ? p : path.join(workspacePath, p);
const globbed = await fastGlob(fullPath, {
cwd: workspacePath,
absolute: true,
onlyFiles: true,
});
resolvedPaths.push(...globbed);
}
return resolvedPaths;
}
// Otherwise, find all files for the language
const extensions = Object.entries(EXTENSION_MAP)
.filter(([, lang]) => lang === language)
.map(([ext]) => ext);
if (extensions.length === 0) {
return [];
}
const patterns = extensions.map(ext => `**/*${ext}`);
return await fastGlob(patterns, {
cwd: workspacePath,
absolute: true,
onlyFiles: true,
ignore: ['**/node_modules/**', '**/dist/**', '**/build/**', '**/.git/**'],
});
}
/**
* Validate AST rule
*/
validateRule(rule: ASTRule): { valid: boolean; errors: string[] } {
const errors: string[] = [];
// Check for at least one positive condition
const hasPositive =
rule.pattern !== undefined ||
rule.kind !== undefined ||
rule.regex !== undefined ||
rule.inside !== undefined ||
rule.has !== undefined ||
rule.all !== undefined ||
rule.any !== undefined;
if (!hasPositive) {
errors.push('Rule must have at least one positive condition (pattern, kind, regex, inside, has, all, or any)');
}
// Validate relational rules with stopBy
if (rule.inside && typeof rule.inside === 'object') {
if ('stopBy' in rule.inside && rule.inside.stopBy && rule.inside.stopBy !== 'neighbor' && rule.inside.stopBy !== 'end') {
errors.push('inside.stopBy must be either "neighbor" or "end"');
}
}
if (rule.has && typeof rule.has === 'object') {
if ('stopBy' in rule.has && rule.has.stopBy && rule.has.stopBy !== 'neighbor' && rule.has.stopBy !== 'end') {
errors.push('has.stopBy must be either "neighbor" or "end"');
}
}
// Validate composite rules
if (rule.all && (!Array.isArray(rule.all) || rule.all.length === 0)) {
errors.push('all must be a non-empty array of rules');
}
if (rule.any && (!Array.isArray(rule.any) || rule.any.length === 0)) {
errors.push('any must be a non-empty array of rules');
}
return {
valid: errors.length === 0,
errors,
};
}
/**
* Truncate match text to specified number of lines
*/
private truncateText(text: string, maxLines = 3): { truncated: string; totalLines: number } {
const lines = text.split('\n');
const totalLines = lines.length;
if (totalLines <= maxLines) {
return { truncated: text, totalLines };
}
// Return first maxLines lines
const truncatedLines = lines.slice(0, maxLines);
const truncated = truncatedLines.join('\n');
return { truncated, totalLines };
}
}