@criogaid/pi-hashline-edit 0.6.1 → 0.7.0
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/README.md +161 -304
- package/THIRD_PARTY_NOTICES.md +80 -0
- package/package.json +10 -6
- package/src/core/AGENTS.md +20 -0
- package/src/core/apply.test.ts +189 -60
- package/src/core/apply.ts +110 -74
- package/src/core/case-fold.test.ts +40 -0
- package/src/core/case-fold.ts +81 -0
- package/src/core/character-set.test.ts +103 -0
- package/src/core/character-set.ts +170 -0
- package/src/core/errors.test.ts +23 -0
- package/src/core/errors.ts +70 -4
- package/src/core/lines.ts +7 -0
- package/src/core/regex.ts +21 -0
- package/src/core/replace-schema.ts +34 -0
- package/src/core/replace.ts +37 -54
- package/src/core/search-analysis.test.ts +199 -0
- package/src/core/search-analysis.ts +375 -0
- package/src/core/search-matrix.test.ts +64 -0
- package/src/core/search-matrix.testing.ts +183 -0
- package/src/core/search-schema.ts +18 -0
- package/src/core/search.test.ts +145 -0
- package/src/core/search.ts +119 -0
- package/src/core/text.test.ts +16 -8
- package/src/core/text.ts +26 -6
- package/src/core/types.ts +16 -11
- package/src/index.ts +25 -15
- package/src/integration/config-registration.test.ts +30 -24
- package/src/integration/forget-grep.test.ts +52 -2
- package/src/integration/fusion-dispatch.test.ts +21 -105
- package/src/integration/grep-errors.test.ts +50 -0
- package/src/integration/grep-flags.test.ts +280 -0
- package/src/integration/grep-js-completeness.test.ts +208 -0
- package/src/integration/grep-line-candidates.test.ts +233 -0
- package/src/integration/grep-matrix.test.ts +121 -0
- package/src/integration/grep-path-matrix.test.ts +132 -0
- package/src/integration/grep-prefilter-coverage.test.ts +189 -0
- package/src/integration/grep-regex.test.ts +410 -0
- package/src/integration/grep-rg.test.ts +220 -402
- package/src/integration/grep-scan-budget.test.ts +89 -0
- package/src/integration/grep-translation.test.ts +206 -0
- package/src/integration/large-text.test.ts +57 -1
- package/src/integration/model-budget-lifecycle.test.ts +128 -0
- package/src/integration/mutation-file-types.test.ts +12 -25
- package/src/integration/mutation-file-types.testing.ts +33 -0
- package/src/integration/npm-package.test.ts +17 -0
- package/src/integration/npm-package.testing.ts +123 -0
- package/src/integration/publication-read-changes.test.ts +344 -0
- package/src/integration/read-changes.test.ts +98 -0
- package/src/integration/replace-package.test.ts +17 -36
- package/src/integration/replace-package.testing.ts +33 -0
- package/src/integration/replace-worker-boundary.test.ts +107 -0
- package/src/integration/report-replay.test.ts +90 -0
- package/src/integration/utf8-errors.test.ts +46 -0
- package/src/pi/AGENTS.md +55 -0
- package/src/pi/action-fusion.test.ts +253 -103
- package/src/pi/action-fusion.ts +116 -290
- package/src/pi/anchor-format.ts +9 -0
- package/src/pi/argument-diagnostics.ts +478 -0
- package/src/pi/argument-error.testing.ts +43 -0
- package/src/pi/argument-error.ts +78 -0
- package/src/pi/argument-format.test.ts +208 -0
- package/src/pi/argument-validation.test.ts +742 -45
- package/src/pi/argument-validation.ts +55 -57
- package/src/pi/budgets.ts +45 -16
- package/src/pi/codemode.test.ts +96 -0
- package/src/pi/config.test.ts +14 -10
- package/src/pi/config.ts +21 -7
- package/src/pi/diagnostic-buffer.test.ts +52 -16
- package/src/pi/diagnostic-buffer.ts +11 -14
- package/src/pi/directory-sync.test.ts +4 -1
- package/src/pi/edit-tool.ts +100 -93
- package/src/pi/error-text.ts +39 -16
- package/src/pi/execute.test.ts +362 -315
- package/src/pi/extension-loading.test.ts +7 -27
- package/src/pi/extension-loading.testing.ts +2 -14
- package/src/pi/failure-context.test.ts +220 -88
- package/src/pi/failure-context.ts +161 -180
- package/src/pi/failure-path.test.ts +85 -88
- package/src/pi/file-commit.test.ts +78 -45
- package/src/pi/file-commit.ts +218 -151
- package/src/pi/file-read.test.ts +29 -0
- package/src/pi/file-read.ts +60 -0
- package/src/pi/file-snapshot.test.ts +1 -1
- package/src/pi/forget-tool.ts +189 -90
- package/src/pi/forget.test.ts +309 -22
- package/src/pi/forget.testing.ts +41 -113
- package/src/pi/fusion-card.test.ts +40 -14
- package/src/pi/fusion-card.ts +84 -50
- package/src/pi/grep-candidates.test.ts +127 -0
- package/src/pi/grep-candidates.ts +193 -0
- package/src/pi/grep-matrix.test.ts +83 -0
- package/src/pi/grep-output.ts +181 -138
- package/src/pi/grep-render.ts +28 -25
- package/src/pi/grep-scope.ts +61 -53
- package/src/pi/grep-search.ts +299 -242
- package/src/pi/grep-tool.ts +150 -140
- package/src/pi/grep-worker.mjs +4 -0
- package/src/pi/grep-worker.ts +14 -0
- package/src/pi/grep.test.ts +631 -632
- package/src/pi/model-budgets.test.ts +43 -0
- package/src/pi/model-budgets.ts +44 -0
- package/src/pi/mutation-outcome.testing.ts +5 -5
- package/src/pi/mutation-result.test.ts +21 -74
- package/src/pi/mutation-result.ts +74 -87
- package/src/pi/mutation-runner.ts +83 -75
- package/src/pi/output-budgets.test.ts +166 -0
- package/src/pi/path.ts +7 -0
- package/src/pi/read-tool.ts +151 -137
- package/src/pi/read.test.ts +39 -33
- package/src/pi/regex-worker-contract.ts +73 -0
- package/src/pi/regex-worker.ts +101 -0
- package/src/pi/registration.test.ts +111 -92
- package/src/pi/render.test.ts +193 -19
- package/src/pi/render.ts +137 -29
- package/src/pi/replace-regex.ts +11 -44
- package/src/pi/replace-tool.ts +38 -145
- package/src/pi/replace-worker-contract.ts +19 -0
- package/src/pi/replace-worker.ts +12 -8
- package/src/pi/replace.test.ts +93 -160
- package/src/pi/report-cause.ts +99 -0
- package/src/pi/report-failure.testing.ts +20 -0
- package/src/pi/report-schema.ts +512 -0
- package/src/pi/report.test.ts +276 -0
- package/src/pi/report.ts +288 -0
- package/src/pi/result-safety.test.ts +122 -427
- package/src/pi/rg-process.test.ts +78 -79
- package/src/pi/rg-process.ts +124 -177
- package/src/pi/rg-regex.test.ts +50 -0
- package/src/pi/rg-regex.ts +709 -0
- package/src/pi/text-stream.test.ts +67 -38
- package/src/pi/text-stream.ts +96 -75
- package/src/pi/tool-call.testing.ts +3 -39
- package/src/pi/write-tool.ts +45 -34
- package/src/pi/write.test.ts +45 -37
- package/src/testing/extension-loader.testing.ts +24 -0
- package/src/testing/installation.testing.ts +77 -0
- package/src/testing/process.testing.ts +33 -0
- package/src/testing/regex-host.testing.ts +20 -0
- package/src/testing/regex-translation-corpus.ts +308 -0
- package/src/testing/rg-line-listing.fixture.mjs +7 -0
- package/src/testing/run-tests.ts +47 -0
- package/src/testing/session.testing.ts +127 -0
- package/src/pi/rg-line-ranges.test.ts +0 -66
- package/src/pi/rg-line-ranges.ts +0 -75
- package/src/pi/rg-match-bytes.ts +0 -95
- package/src/pi/rg-text-view.ts +0 -192
- package/src/pi/tool-prompts.ts +0 -15
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Static analysis of grep queries: smart case, and the necessary literals of grep's
|
|
3
|
+
* candidate-file prefilter. Every JavaScript match of the query, on the LF view of a
|
|
4
|
+
* file without NUL, satisfies every returned clause by containing one of its literals; that text
|
|
5
|
+
* appears unchanged in the file's original bytes. Native RegExp still decides every
|
|
6
|
+
* match; an unknown construct only widens the candidate set, down to every file.
|
|
7
|
+
*
|
|
8
|
+
* @module pi-hashline-edit/core
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { RegExpParser, visitRegExpAST, type AST } from "@eslint-community/regexpp";
|
|
12
|
+
import { caseVariants } from "./case-fold.ts";
|
|
13
|
+
import {
|
|
14
|
+
nativeCharacterRanges,
|
|
15
|
+
classStrings,
|
|
16
|
+
membership,
|
|
17
|
+
total,
|
|
18
|
+
type CharacterNode,
|
|
19
|
+
surrogatePair,
|
|
20
|
+
} from "./character-set.ts";
|
|
21
|
+
import { regexSource } from "./regex.ts";
|
|
22
|
+
import type { GrepQuery } from "./search.ts";
|
|
23
|
+
|
|
24
|
+
/** One literal position: the characters JavaScript may match there. */
|
|
25
|
+
export type LiteralChar = readonly string[];
|
|
26
|
+
export type Literal = readonly LiteralChar[];
|
|
27
|
+
export interface LiteralFilter {
|
|
28
|
+
readonly kind: "literals";
|
|
29
|
+
readonly literals: readonly Literal[];
|
|
30
|
+
}
|
|
31
|
+
export type Prefilter =
|
|
32
|
+
| { readonly kind: "all" }
|
|
33
|
+
| LiteralFilter
|
|
34
|
+
| { readonly kind: "and"; readonly filters: readonly LiteralFilter[] };
|
|
35
|
+
|
|
36
|
+
const ALL: Prefilter = { kind: "all" };
|
|
37
|
+
const MAX_SEQUENCES = 16;
|
|
38
|
+
const MAX_SEQUENCE_LENGTH = 64;
|
|
39
|
+
const MAX_CLASS_CHARS = 64;
|
|
40
|
+
const MAX_LITERALS = 64;
|
|
41
|
+
/** Dropping an AND clause widens safely; no OR alternative may be discarded. */
|
|
42
|
+
const MAX_PREFILTER_CLAUSES = 8;
|
|
43
|
+
|
|
44
|
+
/** Text of unknown length and content: a literal never spans it. */
|
|
45
|
+
const GAP = null;
|
|
46
|
+
type Unit = LiteralChar | typeof GAP;
|
|
47
|
+
type Sequence = readonly Unit[];
|
|
48
|
+
|
|
49
|
+
/** A node's bounded exact texts and necessary AND/OR conditions on original bytes. */
|
|
50
|
+
interface Info {
|
|
51
|
+
readonly exact?: readonly Sequence[];
|
|
52
|
+
readonly filter: Prefilter;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const EMPTY: Info = { exact: [[]], filter: ALL };
|
|
56
|
+
const UNKNOWN: Info = { exact: [[GAP]], filter: ALL };
|
|
57
|
+
|
|
58
|
+
interface Context {
|
|
59
|
+
readonly ignoreCase: boolean;
|
|
60
|
+
readonly unicode: boolean;
|
|
61
|
+
readonly unicodeSets: boolean;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Characters whose original bytes may differ from the LF view: LF stands for CRLF,
|
|
66
|
+
* U+FFFD for malformed bytes, and a lone surrogate for half of a UTF-8 character.
|
|
67
|
+
* Files containing NUL are never searched.
|
|
68
|
+
*/
|
|
69
|
+
function isUnstable(point: number): boolean {
|
|
70
|
+
return point === 0 || point === 0x0a || point === 0xfffd || (point >= 0xd800 && point <= 0xdfff);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function charUnit(point: number, ctx: Context): Unit {
|
|
74
|
+
if (isUnstable(point)) return GAP;
|
|
75
|
+
const char = String.fromCodePoint(point);
|
|
76
|
+
return ctx.ignoreCase ? caseVariants(char, ctx.unicode) : [char];
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function unionUnits(units: readonly Unit[]): Unit {
|
|
80
|
+
const chars = new Set<string>();
|
|
81
|
+
for (const unit of units) {
|
|
82
|
+
if (unit === GAP) return GAP;
|
|
83
|
+
for (const char of unit) chars.add(char);
|
|
84
|
+
}
|
|
85
|
+
return chars.size > MAX_CLASS_CHARS ? GAP : [...chars].sort();
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const key = (value: unknown) => JSON.stringify(value);
|
|
89
|
+
|
|
90
|
+
function distinct<T>(values: readonly T[]): T[] {
|
|
91
|
+
return [...new Map(values.map((value) => [key(value), value])).values()];
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function literalFilter(values: readonly Literal[]): Prefilter {
|
|
95
|
+
let literals = distinct(values);
|
|
96
|
+
if (!literals.length || literals.some((literal) => !literal.length)) return ALL;
|
|
97
|
+
if (literals.length <= MAX_LITERALS) return { kind: "literals", literals };
|
|
98
|
+
// Keep every branch while shortening its necessary prefix or suffix.
|
|
99
|
+
for (let length = MAX_SEQUENCE_LENGTH; length >= 1; length = Math.floor(length / 2)) {
|
|
100
|
+
const prefix = distinct(literals.map((literal) => literal.slice(0, length)));
|
|
101
|
+
const suffix = distinct(literals.map((literal) => literal.slice(-length)));
|
|
102
|
+
const shorter = prefix.length <= suffix.length ? prefix : suffix;
|
|
103
|
+
if (shorter.length <= MAX_LITERALS) return { kind: "literals", literals: shorter };
|
|
104
|
+
}
|
|
105
|
+
const first = unionUnits(literals.map((literal) => literal[0]));
|
|
106
|
+
return first === GAP ? ALL : { kind: "literals", literals: [[first]] };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function implies(left: LiteralFilter, right: LiteralFilter): boolean {
|
|
110
|
+
return left.literals.every((long) =>
|
|
111
|
+
right.literals.some((short) => {
|
|
112
|
+
for (let offset = 0; offset <= long.length - short.length; offset++)
|
|
113
|
+
if (
|
|
114
|
+
short.every((chars, index) => long[offset + index].every((char) => chars.includes(char)))
|
|
115
|
+
)
|
|
116
|
+
return true;
|
|
117
|
+
return false;
|
|
118
|
+
}),
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function andFilters(filters: readonly Prefilter[]): Prefilter {
|
|
123
|
+
const clauses = distinct(
|
|
124
|
+
filters.flatMap((filter) =>
|
|
125
|
+
filter.kind === "all" ? [] : filter.kind === "and" ? filter.filters : [filter],
|
|
126
|
+
),
|
|
127
|
+
);
|
|
128
|
+
const kept = clauses.filter(
|
|
129
|
+
(clause, index) =>
|
|
130
|
+
!clauses.some(
|
|
131
|
+
(other, at) =>
|
|
132
|
+
at !== index && implies(other, clause) && (!implies(clause, other) || at < index),
|
|
133
|
+
),
|
|
134
|
+
);
|
|
135
|
+
kept.sort(
|
|
136
|
+
(a, b) =>
|
|
137
|
+
Math.min(...b.literals.map((literal) => literal.length)) -
|
|
138
|
+
Math.min(...a.literals.map((literal) => literal.length)) ||
|
|
139
|
+
a.literals.length - b.literals.length,
|
|
140
|
+
);
|
|
141
|
+
const bounded = kept.slice(0, MAX_PREFILTER_CLAUSES);
|
|
142
|
+
return bounded.length === 0
|
|
143
|
+
? ALL
|
|
144
|
+
: bounded.length === 1
|
|
145
|
+
? bounded[0]
|
|
146
|
+
: { kind: "and", filters: bounded };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function orFilters(filters: readonly Prefilter[]): Prefilter {
|
|
150
|
+
if (!filters.length || filters.some((filter) => filter.kind === "all")) return ALL;
|
|
151
|
+
let result = filters[0];
|
|
152
|
+
for (const filter of filters.slice(1)) {
|
|
153
|
+
if (result.kind === "all" || filter.kind === "all") return ALL;
|
|
154
|
+
const left = result.kind === "and" ? result.filters : [result];
|
|
155
|
+
const right = filter.kind === "and" ? filter.filters : [filter];
|
|
156
|
+
// CNF distribution creates AND clauses; keeping only bounded clauses is a widening.
|
|
157
|
+
result = andFilters(
|
|
158
|
+
left.flatMap((a) => right.map((b) => literalFilter([...a.literals, ...b.literals]))),
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
return result;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function sequenceFilter(sequences: readonly Sequence[]): Prefilter {
|
|
165
|
+
return orFilters(
|
|
166
|
+
sequences.map((sequence) => {
|
|
167
|
+
const filters: Prefilter[] = [];
|
|
168
|
+
let run: LiteralChar[] = [];
|
|
169
|
+
for (const unit of [...sequence, GAP]) {
|
|
170
|
+
if (unit !== GAP) run.push(unit);
|
|
171
|
+
else if (run.length) {
|
|
172
|
+
filters.push(literalFilter([run]));
|
|
173
|
+
run = [];
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return andFilters(filters);
|
|
177
|
+
}),
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const filterOf = (info: Info): Prefilter =>
|
|
182
|
+
info.exact ? andFilters([info.filter, sequenceFilter(info.exact)]) : info.filter;
|
|
183
|
+
|
|
184
|
+
function cross(left: readonly Sequence[], right: readonly Sequence[]): Sequence[] | undefined {
|
|
185
|
+
if (left.length * right.length > MAX_SEQUENCES) return undefined;
|
|
186
|
+
const result: Sequence[] = [];
|
|
187
|
+
for (const a of left)
|
|
188
|
+
for (const b of right) {
|
|
189
|
+
if (a.length + b.length > MAX_SEQUENCE_LENGTH) return undefined;
|
|
190
|
+
result.push([...a, ...b]);
|
|
191
|
+
}
|
|
192
|
+
return distinct(result);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function concatenate(infos: readonly Info[]): Info {
|
|
196
|
+
let run: readonly Sequence[] = [[]];
|
|
197
|
+
let whole = true;
|
|
198
|
+
const filters = infos.map((info) => info.filter);
|
|
199
|
+
for (const info of infos) {
|
|
200
|
+
const joined = info.exact && cross(run, info.exact);
|
|
201
|
+
if (joined) {
|
|
202
|
+
run = joined;
|
|
203
|
+
continue;
|
|
204
|
+
}
|
|
205
|
+
whole = false;
|
|
206
|
+
filters.push(sequenceFilter(run));
|
|
207
|
+
run = info.exact ?? [[]];
|
|
208
|
+
}
|
|
209
|
+
return whole
|
|
210
|
+
? { exact: run, filter: andFilters(filters) }
|
|
211
|
+
: { filter: andFilters([...filters, sequenceFilter(run)]) };
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function alternate(infos: readonly Info[]): Info {
|
|
215
|
+
if (infos.every((info) => info.exact)) {
|
|
216
|
+
const exact = distinct(infos.flatMap((info) => info.exact!));
|
|
217
|
+
if (exact.length <= MAX_SEQUENCES)
|
|
218
|
+
return { exact, filter: orFilters(infos.map((info) => info.filter)) };
|
|
219
|
+
}
|
|
220
|
+
return { filter: orFilters(infos.map(filterOf)) };
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function repeat(exact: readonly Sequence[], count: number): readonly Sequence[] | undefined {
|
|
224
|
+
if (exact.every((sequence) => !sequence.length)) return [[]];
|
|
225
|
+
if (count > MAX_SEQUENCE_LENGTH) return undefined;
|
|
226
|
+
let result: readonly Sequence[] | undefined = [[]];
|
|
227
|
+
for (let index = 0; index < count && result; index++) result = cross(result, exact);
|
|
228
|
+
return result;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function quantified(node: AST.Quantifier, ctx: Context): Info {
|
|
232
|
+
if (node.max === 0) return EMPTY;
|
|
233
|
+
const inner = analyzeElement(node.element, ctx);
|
|
234
|
+
if (inner.exact) {
|
|
235
|
+
const head = repeat(inner.exact, node.min);
|
|
236
|
+
if (node.min === node.max && head) return { exact: head, filter: inner.filter };
|
|
237
|
+
if (node.min === 0 && node.max === 1) {
|
|
238
|
+
const exact = distinct([[], ...inner.exact]);
|
|
239
|
+
if (exact.length <= MAX_SEQUENCES) return { exact, filter: ALL };
|
|
240
|
+
}
|
|
241
|
+
// The repetitions beyond the minimum are text of unknown length.
|
|
242
|
+
const exact = head && cross(head, UNKNOWN.exact!);
|
|
243
|
+
if (exact) return { exact, filter: node.min ? inner.filter : ALL };
|
|
244
|
+
}
|
|
245
|
+
return node.min === 0 ? UNKNOWN : { filter: filterOf(inner) };
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function classInfo(node: CharacterNode, ctx: Context): Info {
|
|
249
|
+
if (node.type === "CharacterSet" && node.kind === "any") return UNKNOWN;
|
|
250
|
+
const strings = classStrings(node);
|
|
251
|
+
if (!strings) return UNKNOWN;
|
|
252
|
+
const flags = `${ctx.ignoreCase ? "i" : ""}${ctx.unicodeSets ? "v" : ctx.unicode ? "u" : ""}`;
|
|
253
|
+
const ranges = nativeCharacterRanges(node.raw, flags);
|
|
254
|
+
if (total(ranges) > MAX_CLASS_CHARS) return UNKNOWN;
|
|
255
|
+
const units: Unit[] = [];
|
|
256
|
+
for (const [low, high] of ranges)
|
|
257
|
+
for (let point = low; point <= high; point++)
|
|
258
|
+
units.push(charUnit(point, { ...ctx, ignoreCase: false }));
|
|
259
|
+
const infos: Info[] = units.length ? [{ exact: [[unionUnits(units)]], filter: ALL }] : [];
|
|
260
|
+
const accepts = membership(node.raw, flags);
|
|
261
|
+
for (const value of strings) {
|
|
262
|
+
if (!accepts.test(value)) continue;
|
|
263
|
+
const sequence = [...value].map((char) => charUnit(char.codePointAt(0)!, ctx));
|
|
264
|
+
infos.push(
|
|
265
|
+
sequence.length <= MAX_SEQUENCE_LENGTH
|
|
266
|
+
? { exact: [sequence], filter: ALL }
|
|
267
|
+
: { filter: sequenceFilter([sequence]) },
|
|
268
|
+
);
|
|
269
|
+
}
|
|
270
|
+
return alternate(infos);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function analyzeElement(node: AST.Element, ctx: Context): Info {
|
|
274
|
+
switch (node.type) {
|
|
275
|
+
case "Character":
|
|
276
|
+
return { exact: [[charUnit(node.value, ctx)]], filter: ALL };
|
|
277
|
+
case "CharacterClass":
|
|
278
|
+
case "CharacterSet":
|
|
279
|
+
case "ExpressionCharacterClass":
|
|
280
|
+
return classInfo(node, ctx);
|
|
281
|
+
// Assertions and lookarounds consume nothing; the match text is the rest.
|
|
282
|
+
case "Assertion":
|
|
283
|
+
return (node.kind === "lookahead" || node.kind === "lookbehind") && !node.negate
|
|
284
|
+
? { exact: [[]], filter: filterOf(analyzeAlternatives(node.alternatives, ctx)) }
|
|
285
|
+
: EMPTY;
|
|
286
|
+
case "Backreference":
|
|
287
|
+
return UNKNOWN;
|
|
288
|
+
case "Group": {
|
|
289
|
+
const ignoreCase = node.modifiers?.add.ignoreCase
|
|
290
|
+
? true
|
|
291
|
+
: node.modifiers?.remove?.ignoreCase
|
|
292
|
+
? false
|
|
293
|
+
: ctx.ignoreCase;
|
|
294
|
+
return analyzeAlternatives(node.alternatives, { ...ctx, ignoreCase });
|
|
295
|
+
}
|
|
296
|
+
case "CapturingGroup":
|
|
297
|
+
return analyzeAlternatives(node.alternatives, ctx);
|
|
298
|
+
case "Quantifier":
|
|
299
|
+
return quantified(node, ctx);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function analyzeAlternatives(alternatives: readonly AST.Alternative[], ctx: Context): Info {
|
|
304
|
+
return alternate(
|
|
305
|
+
alternatives.map(({ elements }) => {
|
|
306
|
+
const infos: Info[] = [];
|
|
307
|
+
for (let index = 0; index < elements.length; index++) {
|
|
308
|
+
const pair = ctx.unicode ? undefined : surrogatePair(elements[index], elements[index + 1]);
|
|
309
|
+
if (pair === undefined) infos.push(analyzeElement(elements[index], ctx));
|
|
310
|
+
else {
|
|
311
|
+
infos.push({ exact: [[charUnit(pair, ctx)]], filter: ALL });
|
|
312
|
+
index++;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
return concatenate(infos);
|
|
316
|
+
}),
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Parse a pattern V8 already accepted; undefined when regexpp lacks its syntax or
|
|
322
|
+
* exceeds its own limits, which only makes an analysis less precise.
|
|
323
|
+
*/
|
|
324
|
+
export function parseQueryPattern(
|
|
325
|
+
pattern: string,
|
|
326
|
+
literal: boolean,
|
|
327
|
+
flags: string,
|
|
328
|
+
): AST.Pattern | undefined {
|
|
329
|
+
const source = regexSource(pattern, !literal);
|
|
330
|
+
try {
|
|
331
|
+
return new RegExpParser({ ecmaVersion: 2025 }).parsePattern(source, 0, source.length, {
|
|
332
|
+
unicode: flags.includes("u"),
|
|
333
|
+
unicodeSets: flags.includes("v"),
|
|
334
|
+
});
|
|
335
|
+
} catch (error) {
|
|
336
|
+
if (error instanceof SyntaxError || error instanceof RangeError) return undefined;
|
|
337
|
+
throw error;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** Smart case over decoded characters; case-sensitive when a pattern cannot be analyzed. */
|
|
342
|
+
export function smartIgnoreCase(
|
|
343
|
+
patterns: readonly string[],
|
|
344
|
+
literal: boolean,
|
|
345
|
+
flags = "",
|
|
346
|
+
): boolean {
|
|
347
|
+
return !patterns.some((pattern) => {
|
|
348
|
+
const parsed = parseQueryPattern(pattern, literal, flags);
|
|
349
|
+
if (!parsed) return true;
|
|
350
|
+
let uppercase = false;
|
|
351
|
+
visitRegExpAST(parsed, {
|
|
352
|
+
onCharacterEnter({ value }) {
|
|
353
|
+
const text = String.fromCodePoint(value);
|
|
354
|
+
uppercase ||= text !== text.toLowerCase();
|
|
355
|
+
},
|
|
356
|
+
});
|
|
357
|
+
return uppercase;
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/** Necessary file conditions in bounded conjunctive normal form; every OR retains all alternatives. */
|
|
362
|
+
export function extractPrefilter(query: GrepQuery): Prefilter {
|
|
363
|
+
const unicode = query.flags.includes("u") || query.flags.includes("v");
|
|
364
|
+
const ctx: Context = {
|
|
365
|
+
ignoreCase: query.flags.includes("i"),
|
|
366
|
+
unicode,
|
|
367
|
+
unicodeSets: query.flags.includes("v"),
|
|
368
|
+
};
|
|
369
|
+
return orFilters(
|
|
370
|
+
query.patterns.map((pattern) => {
|
|
371
|
+
const parsed = parseQueryPattern(pattern, query.literal, query.flags);
|
|
372
|
+
return parsed ? filterOf(analyzeAlternatives(parsed.alternatives, ctx)) : ALL;
|
|
373
|
+
}),
|
|
374
|
+
);
|
|
375
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { test } from "node:test";
|
|
3
|
+
import { extractPrefilter } from "./search-analysis.ts";
|
|
4
|
+
import { searchText } from "./search.ts";
|
|
5
|
+
import {
|
|
6
|
+
acceptsNative,
|
|
7
|
+
hasCandidateBytes,
|
|
8
|
+
matrixCases,
|
|
9
|
+
MATRIX_INPUTS,
|
|
10
|
+
} from "./search-matrix.testing.ts";
|
|
11
|
+
|
|
12
|
+
test("Cartesian JS syntax × quantifiers × contexts × flags × line modes × bytes → prefilter never drops a native match", (t) => {
|
|
13
|
+
let accepted = 0;
|
|
14
|
+
let rejected = 0;
|
|
15
|
+
let evaluations = 0;
|
|
16
|
+
let hits = 0;
|
|
17
|
+
let filteredHits = 0;
|
|
18
|
+
let misses = 0;
|
|
19
|
+
const examples: string[] = [];
|
|
20
|
+
const candidateCache = new Map<string, readonly boolean[]>();
|
|
21
|
+
for (const scenario of matrixCases()) {
|
|
22
|
+
if (!acceptsNative(scenario.query)) {
|
|
23
|
+
rejected++;
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
accepted++;
|
|
27
|
+
const prefilter = extractPrefilter(scenario.query);
|
|
28
|
+
const key = JSON.stringify(prefilter);
|
|
29
|
+
let candidates = candidateCache.get(key);
|
|
30
|
+
if (!candidates) {
|
|
31
|
+
candidates = MATRIX_INPUTS.map(([, bytes]) => hasCandidateBytes(bytes, prefilter));
|
|
32
|
+
candidateCache.set(key, candidates);
|
|
33
|
+
}
|
|
34
|
+
for (const [index, [input, bytes]] of MATRIX_INPUTS.entries()) {
|
|
35
|
+
evaluations++;
|
|
36
|
+
if (
|
|
37
|
+
!searchText({ source: bytes.toString("utf8"), query: scenario.query, limit: 1 }).lines
|
|
38
|
+
.length
|
|
39
|
+
)
|
|
40
|
+
continue;
|
|
41
|
+
hits++;
|
|
42
|
+
if (prefilter.kind !== "all") filteredHits++;
|
|
43
|
+
if (candidates[index]) continue;
|
|
44
|
+
misses++;
|
|
45
|
+
if (examples.length < 10)
|
|
46
|
+
examples.push(
|
|
47
|
+
JSON.stringify({ ...scenario, input, bytes: bytes.toString("hex"), prefilter }),
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
t.diagnostic(
|
|
52
|
+
JSON.stringify({
|
|
53
|
+
accepted,
|
|
54
|
+
rejected,
|
|
55
|
+
evaluations,
|
|
56
|
+
hits,
|
|
57
|
+
filteredHits,
|
|
58
|
+
prefilters: candidateCache.size,
|
|
59
|
+
misses,
|
|
60
|
+
}),
|
|
61
|
+
);
|
|
62
|
+
assert.ok(accepted > 0 && rejected > 0 && filteredHits > 0);
|
|
63
|
+
assert.equal(misses, 0, examples.join("\n"));
|
|
64
|
+
});
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/** Deterministic Cartesian inputs shared by the pure prefilter and real-rg boundary tests. */
|
|
2
|
+
import type { GrepQuery } from "./search.ts";
|
|
3
|
+
import type { Prefilter } from "./search-analysis.ts";
|
|
4
|
+
|
|
5
|
+
export const MATRIX_SYNTAX = [
|
|
6
|
+
["ASCII literal", "a"],
|
|
7
|
+
["non-ASCII literal", "é"],
|
|
8
|
+
["Kelvin folding", "k"],
|
|
9
|
+
["long-s folding", "s"],
|
|
10
|
+
["sigma folding", "Σ"],
|
|
11
|
+
["supplementary literal", "😀"],
|
|
12
|
+
["high surrogate", "\\uD83D"],
|
|
13
|
+
["low surrogate", "\\uDE00"],
|
|
14
|
+
["escaped surrogate pair", "\\uD83D\\uDE00"],
|
|
15
|
+
["identity escape", "\\K"],
|
|
16
|
+
["escaped punctuation", "\\."],
|
|
17
|
+
["control escape", "\\cA"],
|
|
18
|
+
["hex escape", "\\x61"],
|
|
19
|
+
["Unicode escape", "\\u0061"],
|
|
20
|
+
["code-point escape", "\\u{1F600}"],
|
|
21
|
+
["legacy octal", "\\141"],
|
|
22
|
+
["legacy decimal escape", "\\8"],
|
|
23
|
+
["NUL", "\\0"],
|
|
24
|
+
["LF", "\\n"],
|
|
25
|
+
["CR", "\\r"],
|
|
26
|
+
["line separator", "\\u2028"],
|
|
27
|
+
["paragraph separator", "\\u2029"],
|
|
28
|
+
["replacement character", "\\uFFFD"],
|
|
29
|
+
["dot", "."],
|
|
30
|
+
["positive class", "[a-c]"],
|
|
31
|
+
["negative class", "[^a]"],
|
|
32
|
+
["digit", "\\d"],
|
|
33
|
+
["non-digit", "\\D"],
|
|
34
|
+
["word", "\\w"],
|
|
35
|
+
["non-word", "\\W"],
|
|
36
|
+
["space", "\\s"],
|
|
37
|
+
["non-space", "\\S"],
|
|
38
|
+
["start", "^"],
|
|
39
|
+
["end", "$"],
|
|
40
|
+
["word boundary", "\\b"],
|
|
41
|
+
["non-word boundary", "\\B"],
|
|
42
|
+
["positive lookahead", "(?=a)"],
|
|
43
|
+
["negative lookahead", "(?!a)"],
|
|
44
|
+
["positive lookbehind", "(?<=a)"],
|
|
45
|
+
["negative lookbehind", "(?<!a)"],
|
|
46
|
+
["unbounded lookbehind", "(?<=a+)b"],
|
|
47
|
+
["lookbehind capture", "(?<=(a))\\1"],
|
|
48
|
+
["numeric backreference", "(a)\\1"],
|
|
49
|
+
["forward backreference", "\\1(a)"],
|
|
50
|
+
["named backreference", "(?<word>a)\\k<word>"],
|
|
51
|
+
["unset capture", "(?:(a)|b)\\1"],
|
|
52
|
+
["alternation", "(?:a|b)"],
|
|
53
|
+
["empty group", "(?:)"],
|
|
54
|
+
["add i", "(?i:a)"],
|
|
55
|
+
["remove i", "(?-i:a)"],
|
|
56
|
+
["add s", "(?s:.)"],
|
|
57
|
+
["remove s", "(?-s:.)"],
|
|
58
|
+
["add m", "(?m:^a$)"],
|
|
59
|
+
["remove m", "(?-m:^a$)"],
|
|
60
|
+
["Unicode property", "\\p{Letter}"],
|
|
61
|
+
["negated Unicode property", "\\P{ASCII}"],
|
|
62
|
+
["v intersection", "[\\p{ASCII}&&\\p{Letter}]"],
|
|
63
|
+
["v subtraction", "[\\p{Letter}--[a]]"],
|
|
64
|
+
["v string alternatives", "[\\q{ab|cd}]"],
|
|
65
|
+
["v string property", "\\p{RGI_Emoji}"],
|
|
66
|
+
] as const;
|
|
67
|
+
|
|
68
|
+
export const MATRIX_QUANTIFIERS = ["", "?", "*", "+", "*?", "+?", "{0}", "{2}", "{1,3}?"] as const;
|
|
69
|
+
export const MATRIX_CONTEXTS = ["bare", "sequence", "alternative", "capture", "OR query"] as const;
|
|
70
|
+
|
|
71
|
+
/** All combinations of matching flags; d and caller-supplied g are covered at tool entry. */
|
|
72
|
+
export const MATRIX_FLAGS = ["", "u", "v"].flatMap((unicode) =>
|
|
73
|
+
Array.from(
|
|
74
|
+
{ length: 16 },
|
|
75
|
+
(_, mask) => [..."imsy"].filter((_, bit) => mask & (1 << bit)).join("") + unicode,
|
|
76
|
+
),
|
|
77
|
+
);
|
|
78
|
+
|
|
79
|
+
export const MATRIX_INPUTS = [
|
|
80
|
+
["empty", Buffer.alloc(0)],
|
|
81
|
+
["LF", Buffer.from("a\nb\nab\naa\nxay\nZ\n1\n8\n_\nk\ns\nA\nB\nK\nS\n.\n")],
|
|
82
|
+
["CRLF", Buffer.from("a\r\nb\r\nab\r\naa\r\nxay\r\nZ\r\n")],
|
|
83
|
+
["empty lines", Buffer.from("\n\r\n\n")],
|
|
84
|
+
["Unicode", Buffer.from("é\nÉ\nΣ\nσ\nς\nK\nſ\n😀\n😀😀\nx😀y\n")],
|
|
85
|
+
["standalone CR", Buffer.from("a\rb\r\r\nZ\r")],
|
|
86
|
+
["BOM and separators", Buffer.from("\uFEFFa\u2028b\u2029Z\n")],
|
|
87
|
+
["controls", Buffer.from("\t\f\v\x01 \n")],
|
|
88
|
+
[
|
|
89
|
+
"malformed bytes",
|
|
90
|
+
Buffer.from([0x61, 0xff, 0x62, 0x0d, 0x0a, 0xc3, 0x28, 0x0a, 0xed, 0xa0, 0x80]),
|
|
91
|
+
],
|
|
92
|
+
["literal U+FFFD", Buffer.from("a\uFFFDb\n\uFFFD\n")],
|
|
93
|
+
["unterminated", Buffer.from("ab")],
|
|
94
|
+
["mixed boundaries", Buffer.from("aa\r\nab\nxay\rZ\n\u2028\u2029😀")],
|
|
95
|
+
] as const;
|
|
96
|
+
|
|
97
|
+
export interface MatrixCase {
|
|
98
|
+
readonly syntax: string;
|
|
99
|
+
readonly quantifier: string;
|
|
100
|
+
readonly context: (typeof MATRIX_CONTEXTS)[number];
|
|
101
|
+
readonly query: GrepQuery;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function* matrixCases(): Generator<MatrixCase> {
|
|
105
|
+
for (const [syntax, atom] of MATRIX_SYNTAX) {
|
|
106
|
+
for (const quantifier of MATRIX_QUANTIFIERS) {
|
|
107
|
+
const part = `(?:${atom})${quantifier}`;
|
|
108
|
+
for (const context of MATRIX_CONTEXTS) {
|
|
109
|
+
const patterns =
|
|
110
|
+
context === "bare"
|
|
111
|
+
? [part]
|
|
112
|
+
: context === "sequence"
|
|
113
|
+
? [`x${part}y`]
|
|
114
|
+
: context === "alternative"
|
|
115
|
+
? [`(?:${part}|Z)`]
|
|
116
|
+
: context === "capture"
|
|
117
|
+
? [`(${part})\\1`]
|
|
118
|
+
: [part, "Z"];
|
|
119
|
+
for (const flags of MATRIX_FLAGS) {
|
|
120
|
+
for (const multiline of [false, true])
|
|
121
|
+
yield {
|
|
122
|
+
syntax,
|
|
123
|
+
quantifier,
|
|
124
|
+
context,
|
|
125
|
+
query: { patterns, flags, multiline, literal: false },
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function acceptsNative(query: GrepQuery): boolean {
|
|
134
|
+
try {
|
|
135
|
+
for (const pattern of query.patterns) new RegExp(pattern, query.flags);
|
|
136
|
+
return true;
|
|
137
|
+
} catch (error) {
|
|
138
|
+
if (error instanceof SyntaxError) return false;
|
|
139
|
+
throw error;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Match literal bytes directly, without relying on the candidate regex formatter or expanding products. */
|
|
144
|
+
export function hasCandidateBytes(bytes: Buffer, prefilter: Prefilter): boolean {
|
|
145
|
+
if (prefilter.kind === "all") return true;
|
|
146
|
+
if (prefilter.kind === "and")
|
|
147
|
+
return prefilter.filters.every((filter) => hasCandidateBytes(bytes, filter));
|
|
148
|
+
return prefilter.literals.some((literal) => {
|
|
149
|
+
const positions = literal.map((chars) => chars.map((char) => Buffer.from(char)));
|
|
150
|
+
for (let start = 0; start < bytes.length; start++) {
|
|
151
|
+
let ends = new Set([start]);
|
|
152
|
+
for (const variants of positions) {
|
|
153
|
+
const next = new Set<number>();
|
|
154
|
+
for (const end of ends)
|
|
155
|
+
for (const variant of variants)
|
|
156
|
+
if (bytes.subarray(end, end + variant.length).equals(variant))
|
|
157
|
+
next.add(end + variant.length);
|
|
158
|
+
ends = next;
|
|
159
|
+
if (!ends.size) break;
|
|
160
|
+
}
|
|
161
|
+
if (ends.size) return true;
|
|
162
|
+
}
|
|
163
|
+
return false;
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Pair every syntax fragment with every other fragment, including independent OR-array entries. */
|
|
168
|
+
export function* pairedMatrixCases(): Generator<{ readonly query: GrepQuery }> {
|
|
169
|
+
for (const [, left] of MATRIX_SYNTAX) {
|
|
170
|
+
for (const [, right] of MATRIX_SYNTAX) {
|
|
171
|
+
for (const patterns of [
|
|
172
|
+
[`(?:${left})(?:${right})`],
|
|
173
|
+
[`(?:${left}|${right})`],
|
|
174
|
+
[left, right],
|
|
175
|
+
]) {
|
|
176
|
+
for (const flags of MATRIX_FLAGS) {
|
|
177
|
+
for (const multiline of [false, true])
|
|
178
|
+
yield { query: { patterns, flags, multiline, literal: false } };
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { Type, type Static } from "typebox";
|
|
2
|
+
|
|
3
|
+
export const SEARCH_RESULT_SCHEMA = Type.Object(
|
|
4
|
+
{
|
|
5
|
+
lines: Type.Array(
|
|
6
|
+
Type.Object(
|
|
7
|
+
{
|
|
8
|
+
lineNumber: Type.Integer({ minimum: 1 }),
|
|
9
|
+
column: Type.Integer({ minimum: 0 }),
|
|
10
|
+
},
|
|
11
|
+
{ additionalProperties: false },
|
|
12
|
+
),
|
|
13
|
+
),
|
|
14
|
+
totalLines: Type.Integer({ minimum: 0 }),
|
|
15
|
+
},
|
|
16
|
+
{ additionalProperties: false },
|
|
17
|
+
);
|
|
18
|
+
export type SearchResult = Static<typeof SEARCH_RESULT_SCHEMA>;
|