@criogaid/pi-hashline-edit 0.9.0 → 0.10.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 +9 -10
- package/README.zh-CN.md +8 -9
- package/THIRD_PARTY_NOTICES.md +0 -6
- package/package.json +1 -1
- package/src/core/AGENTS.md +4 -5
- package/src/core/apply.test.ts +96 -271
- package/src/core/apply.ts +62 -169
- package/src/core/case-fold.ts +8 -67
- package/src/core/character-set.ts +4 -4
- package/src/core/errors.test.ts +23 -7
- package/src/core/errors.ts +32 -5
- package/src/core/hash.test.ts +8 -16
- package/src/core/hash.ts +3 -23
- package/src/core/lines.ts +2 -4
- package/src/core/regex.ts +3 -4
- package/src/core/replace.test.ts +47 -1
- package/src/core/replace.ts +19 -13
- package/src/core/search-analysis.test.ts +24 -27
- package/src/core/search-analysis.ts +34 -65
- package/src/core/search-matrix.testing.ts +0 -2
- package/src/core/search.ts +1 -1
- package/src/core/text.test.ts +5 -5
- package/src/core/text.ts +5 -12
- package/src/core/types.ts +7 -43
- package/src/integration/fusion-dispatch.test.ts +2 -5
- package/src/integration/grep-flags.test.ts +0 -14
- package/src/integration/grep-js-completeness.test.ts +34 -8
- package/src/integration/grep-line-candidates.test.ts +4 -8
- package/src/integration/grep-matrix.test.ts +3 -7
- package/src/integration/grep-path-matrix.test.ts +5 -5
- package/src/integration/grep-prefilter-coverage.test.ts +3 -7
- package/src/integration/grep-process-limits.test.ts +78 -0
- package/src/integration/grep-rg.test.ts +118 -20
- package/src/integration/grep-scan-budget.test.ts +2 -2
- package/src/integration/grep-translation.test.ts +12 -27
- package/src/integration/large-text.test.ts +1 -47
- package/src/integration/model-budget-lifecycle.test.ts +2 -1
- package/src/integration/publication-read-changes.test.ts +123 -45
- package/src/integration/replace-worker-boundary.test.ts +21 -11
- package/src/integration/report-replay.test.ts +20 -22
- package/src/pi/AGENTS.md +15 -15
- package/src/pi/action-fusion.test.ts +164 -296
- package/src/pi/action-fusion.ts +148 -111
- package/src/pi/anchor-format.test.ts +9 -9
- package/src/pi/anchor-format.ts +6 -8
- package/src/pi/argument-diagnostics.ts +21 -25
- package/src/pi/argument-error.ts +2 -1
- package/src/pi/argument-validation.test.ts +129 -157
- package/src/pi/argument-validation.ts +5 -8
- package/src/pi/budgets.ts +5 -4
- package/src/pi/config.test.ts +5 -2
- package/src/pi/config.ts +4 -6
- package/src/pi/diagnostic-buffer.test.ts +12 -1
- package/src/pi/diagnostic-buffer.ts +1 -2
- package/src/pi/directory-sync.test.ts +0 -1
- package/src/pi/edit-tool.ts +46 -156
- package/src/pi/error-text.ts +4 -8
- package/src/pi/execute.test.ts +83 -196
- package/src/pi/failure-context.test.ts +144 -126
- package/src/pi/failure-context.ts +44 -93
- package/src/pi/failure-path.test.ts +168 -141
- package/src/pi/file-commit.test.ts +110 -53
- package/src/pi/file-commit.ts +90 -137
- package/src/pi/file-snapshot.test.ts +3 -5
- package/src/pi/fusion-card.test.ts +4 -1
- package/src/pi/fusion-card.ts +16 -24
- package/src/pi/grep-candidates.test.ts +2 -101
- package/src/pi/grep-candidates.ts +23 -69
- package/src/pi/grep-matrix.test.ts +2 -2
- package/src/pi/grep-order.test.ts +4 -4
- package/src/pi/grep-output.ts +62 -96
- package/src/pi/grep-render.ts +1 -1
- package/src/pi/grep-reread.ts +92 -0
- package/src/pi/grep-scope.ts +40 -42
- package/src/pi/grep-search.ts +22 -31
- package/src/pi/grep-tool.ts +55 -82
- package/src/pi/grep.test.ts +80 -45
- package/src/pi/model-budgets.test.ts +25 -23
- package/src/pi/model-budgets.ts +6 -38
- package/src/pi/mutation-result.test.ts +44 -35
- package/src/pi/mutation-result.ts +51 -20
- package/src/pi/mutation-runner.ts +126 -70
- package/src/pi/output-budgets.test.ts +36 -14
- package/src/pi/path.ts +1 -1
- package/src/pi/read-tool.ts +5 -5
- package/src/pi/regex-worker-contract.ts +3 -13
- package/src/pi/regex-worker.ts +1 -10
- package/src/pi/registration.test.ts +64 -36
- package/src/pi/render.test.ts +38 -28
- package/src/pi/render.ts +59 -63
- package/src/pi/replace-regex.ts +14 -2
- package/src/pi/replace-tool.ts +20 -82
- package/src/pi/replace-worker.ts +1 -1
- package/src/pi/replace.test.ts +9 -5
- package/src/pi/report-cause.ts +3 -8
- package/src/pi/report-failure.testing.ts +1 -2
- package/src/pi/report-schema.ts +62 -81
- package/src/pi/report.test.ts +171 -25
- package/src/pi/report.ts +33 -87
- package/src/pi/result-safety.test.ts +149 -176
- package/src/pi/rg-process.test.ts +77 -63
- package/src/pi/rg-process.ts +48 -64
- package/src/pi/rg-regex.ts +40 -400
- package/src/pi/schema.ts +12 -0
- package/src/pi/text-stream.test.ts +0 -21
- package/src/pi/text-stream.ts +14 -21
- package/src/pi/write-tool.ts +33 -62
- package/src/pi/write.test.ts +1 -3
- package/src/testing/regex-translation-corpus.ts +12 -12
- package/src/pi/replace-worker-contract.ts +0 -10
package/src/pi/rg-regex.ts
CHANGED
|
@@ -12,27 +12,23 @@
|
|
|
12
12
|
* @module pi-hashline-edit/pi
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
|
-
import {
|
|
15
|
+
import type { AST } from "@eslint-community/regexpp";
|
|
16
16
|
import {
|
|
17
|
-
MAX_UNIT,
|
|
18
17
|
MAX_SCALAR,
|
|
19
18
|
normalize,
|
|
20
|
-
complement,
|
|
21
19
|
subtract,
|
|
22
20
|
intersect,
|
|
23
|
-
total,
|
|
24
21
|
contains,
|
|
25
22
|
nativeCharacterRanges,
|
|
26
23
|
foldRanges,
|
|
27
24
|
type Ranges,
|
|
28
25
|
acceptedClassStrings,
|
|
29
|
-
classStrings,
|
|
30
26
|
type CharacterNode,
|
|
31
27
|
surrogatePair,
|
|
32
28
|
} from "../core/character-set.ts";
|
|
33
|
-
import { caseVariants } from "../core/case-fold.ts";
|
|
34
29
|
import { analyzeQueryPattern } from "../core/search-analysis.ts";
|
|
35
30
|
import type { GrepQuery } from "../core/search.ts";
|
|
31
|
+
import { MAX_RG_PATTERN_UNITS } from "./rg-process.ts";
|
|
36
32
|
|
|
37
33
|
const LF = 0x0a;
|
|
38
34
|
const REPLACEMENT = 0xfffd;
|
|
@@ -42,11 +38,6 @@ const SUPPLEMENTARY: Ranges = [[0x10000, MAX_SCALAR]];
|
|
|
42
38
|
const MAX_EXACT_REPEAT = 16;
|
|
43
39
|
/** Bound expanded class strings by total code points, counting an empty string as one. */
|
|
44
40
|
const MAX_EXPANDED_STRING_POINTS = 256;
|
|
45
|
-
/** Bound emitted string alternatives; oversized sets retain necessary prefixes. */
|
|
46
|
-
const MAX_STRING_PATTERN_UNITS = 8192;
|
|
47
|
-
const MAX_STRING_PREFIX_POINTS = 16;
|
|
48
|
-
/** Leave room for rg's arguments and paths on hosts with small command-line limits. */
|
|
49
|
-
const MAX_LINE_PATTERN_UNITS = 24 * 1024;
|
|
50
41
|
|
|
51
42
|
/** The bytes a lossy decoder shows as U+FFFD: every byte of a malformed sequence is 0x80–0xFF. */
|
|
52
43
|
const MALFORMED = "(?-u:[\\x80-\\xff])+";
|
|
@@ -67,7 +58,6 @@ interface Context {
|
|
|
67
58
|
readonly multilineAnchors: boolean;
|
|
68
59
|
/** Translating a group as the text a backreference repeats, away from where it matched. */
|
|
69
60
|
readonly repeated: boolean;
|
|
70
|
-
readonly bindings: ReadonlyMap<AST.CapturingGroup, string>;
|
|
71
61
|
}
|
|
72
62
|
|
|
73
63
|
/** Whether nothing consumed can precede or follow an element within its pattern's match. */
|
|
@@ -77,212 +67,20 @@ interface Position {
|
|
|
77
67
|
}
|
|
78
68
|
const INNER: Position = { first: false, last: false };
|
|
79
69
|
|
|
80
|
-
/** Bound assertion alternatives and correlated capture expansion. */
|
|
81
|
-
const MAX_ANALYSIS_BRANCHES = 16;
|
|
82
|
-
const MAX_FIXED_UNITS = 64;
|
|
83
|
-
interface FixedSequence {
|
|
84
|
-
readonly positions: readonly Ranges[];
|
|
85
|
-
readonly exact: boolean;
|
|
86
|
-
}
|
|
87
|
-
type Constraints = ReadonlyMap<AST.Element, readonly Ranges[]>;
|
|
88
|
-
|
|
89
|
-
function fixedAlternatives(
|
|
90
|
-
nodes: readonly AST.Alternative[],
|
|
91
|
-
ctx: Context,
|
|
92
|
-
): FixedSequence | undefined {
|
|
93
|
-
const branches: FixedSequence[] = [];
|
|
94
|
-
for (const node of nodes) {
|
|
95
|
-
const positions: Ranges[] = [];
|
|
96
|
-
let exact = true;
|
|
97
|
-
for (const child of node.elements) {
|
|
98
|
-
const fixed = fixedSequence(child, ctx);
|
|
99
|
-
if (!fixed) return undefined;
|
|
100
|
-
positions.push(...fixed.positions);
|
|
101
|
-
exact &&= fixed.exact;
|
|
102
|
-
if (positions.length > MAX_FIXED_UNITS) return undefined;
|
|
103
|
-
}
|
|
104
|
-
branches.push({ positions, exact });
|
|
105
|
-
}
|
|
106
|
-
if (!branches.every((branch) => branch.positions.length === branches[0].positions.length))
|
|
107
|
-
return undefined;
|
|
108
|
-
return {
|
|
109
|
-
positions: branches[0].positions.map((_, index) =>
|
|
110
|
-
normalize(branches.flatMap((branch) => branch.positions[index])),
|
|
111
|
-
),
|
|
112
|
-
exact:
|
|
113
|
-
branches.every((branch) => branch.exact) &&
|
|
114
|
-
(branches.length === 1 || branches[0].positions.length <= 1),
|
|
115
|
-
};
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
function fixedSequence(node: AST.Element, ctx: Context): FixedSequence | undefined {
|
|
119
|
-
switch (node.type) {
|
|
120
|
-
case "Character":
|
|
121
|
-
case "CharacterClass":
|
|
122
|
-
case "ExpressionCharacterClass":
|
|
123
|
-
case "CharacterSet":
|
|
124
|
-
if (classStrings(node)?.length !== 0) return undefined;
|
|
125
|
-
return { positions: [scalarRanges(node, ctx)], exact: true };
|
|
126
|
-
case "Assertion":
|
|
127
|
-
return { positions: [], exact: false };
|
|
128
|
-
case "Backreference":
|
|
129
|
-
return undefined;
|
|
130
|
-
case "Group":
|
|
131
|
-
return fixedAlternatives(node.alternatives, modified(node, ctx));
|
|
132
|
-
case "CapturingGroup": {
|
|
133
|
-
const bound = ctx.bindings.get(node);
|
|
134
|
-
if (bound !== undefined)
|
|
135
|
-
return {
|
|
136
|
-
positions: [...(ctx.unicode ? [...bound] : bound.split(""))].map((char) => [
|
|
137
|
-
[char.codePointAt(0)!, char.codePointAt(0)!],
|
|
138
|
-
]),
|
|
139
|
-
exact: true,
|
|
140
|
-
};
|
|
141
|
-
return fixedAlternatives(node.alternatives, ctx);
|
|
142
|
-
}
|
|
143
|
-
case "Quantifier": {
|
|
144
|
-
if (node.max === 0) return { positions: [], exact: true };
|
|
145
|
-
if (node.min !== node.max || node.max > MAX_FIXED_UNITS) return undefined;
|
|
146
|
-
const inner = fixedSequence(node.element, ctx);
|
|
147
|
-
if (!inner || inner.positions.length * node.max > MAX_FIXED_UNITS) return undefined;
|
|
148
|
-
return {
|
|
149
|
-
positions: Array.from({ length: node.max }, () => inner.positions).flat(),
|
|
150
|
-
exact: inner.exact,
|
|
151
|
-
};
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
interface Neighbour {
|
|
157
|
-
readonly node: AST.Element;
|
|
158
|
-
readonly index: number;
|
|
159
|
-
readonly ranges: Ranges;
|
|
160
|
-
}
|
|
161
|
-
function neighbours(
|
|
162
|
-
elements: readonly AST.Element[],
|
|
163
|
-
from: number,
|
|
164
|
-
direction: number,
|
|
165
|
-
count: number,
|
|
166
|
-
ctx: Context,
|
|
167
|
-
plan: Constraints,
|
|
168
|
-
): Neighbour[] {
|
|
169
|
-
const result: Neighbour[] = [];
|
|
170
|
-
for (
|
|
171
|
-
let index = from + direction;
|
|
172
|
-
index >= 0 && index < elements.length && result.length < count;
|
|
173
|
-
index += direction
|
|
174
|
-
) {
|
|
175
|
-
const node = elements[index];
|
|
176
|
-
const fixed = fixedSequence(node, ctx);
|
|
177
|
-
if (!fixed) break;
|
|
178
|
-
const positions = plan.get(node) ?? fixed.positions;
|
|
179
|
-
for (
|
|
180
|
-
let at = direction > 0 ? 0 : positions.length - 1;
|
|
181
|
-
at >= 0 && at < positions.length && result.length < count;
|
|
182
|
-
at += direction
|
|
183
|
-
)
|
|
184
|
-
result.push({ node, index: at, ranges: positions[at] });
|
|
185
|
-
}
|
|
186
|
-
return result;
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
function restrict(
|
|
190
|
-
plan: Constraints,
|
|
191
|
-
neighbour: Neighbour,
|
|
192
|
-
allowed: Ranges,
|
|
193
|
-
ctx: Context,
|
|
194
|
-
): Constraints {
|
|
195
|
-
const result = new Map(plan);
|
|
196
|
-
const positions = [
|
|
197
|
-
...(result.get(neighbour.node) ?? fixedSequence(neighbour.node, ctx)!.positions),
|
|
198
|
-
];
|
|
199
|
-
positions[neighbour.index] = intersect(positions[neighbour.index], allowed);
|
|
200
|
-
result.set(neighbour.node, positions);
|
|
201
|
-
return result;
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
/** Apply only proved constraints; a negative test needs an exact forbidden set. */
|
|
205
|
-
function assertionPlans(elements: readonly AST.Element[], ctx: Context): readonly Constraints[] {
|
|
206
|
-
let plans: readonly Constraints[] = [new Map()];
|
|
207
|
-
if (ctx.repeated) return plans;
|
|
208
|
-
for (const [index, node] of elements.entries()) {
|
|
209
|
-
if (node.type !== "Assertion") continue;
|
|
210
|
-
if (node.kind === "lookahead" || node.kind === "lookbehind") {
|
|
211
|
-
const fixed = fixedAlternatives(node.alternatives, ctx);
|
|
212
|
-
if (!fixed) continue;
|
|
213
|
-
const direction = node.kind === "lookahead" ? 1 : -1;
|
|
214
|
-
const asserted = direction > 0 ? fixed.positions : [...fixed.positions].reverse();
|
|
215
|
-
if (node.negate && (!fixed.exact || plans.length * asserted.length > MAX_ANALYSIS_BRANCHES))
|
|
216
|
-
continue;
|
|
217
|
-
plans = plans.flatMap((plan) => {
|
|
218
|
-
const adjacent = neighbours(elements, index, direction, asserted.length, ctx, plan);
|
|
219
|
-
if (node.negate) {
|
|
220
|
-
if (adjacent.length !== asserted.length) return [plan];
|
|
221
|
-
return adjacent.map((item, at) =>
|
|
222
|
-
restrict(plan, item, complement(asserted[at], maxElement(ctx)), ctx),
|
|
223
|
-
);
|
|
224
|
-
}
|
|
225
|
-
let constrained = plan;
|
|
226
|
-
for (const [at, item] of adjacent.entries())
|
|
227
|
-
constrained = restrict(constrained, item, asserted[at], ctx);
|
|
228
|
-
return [constrained];
|
|
229
|
-
});
|
|
230
|
-
} else if (node.kind === "word") {
|
|
231
|
-
const word = nativeCharacterRanges("\\w", nativeFlags(node, ctx));
|
|
232
|
-
plans = plans.map((plan) => {
|
|
233
|
-
const left = neighbours(elements, index, -1, 1, ctx, plan)[0];
|
|
234
|
-
const right = neighbours(elements, index, 1, 1, ctx, plan)[0];
|
|
235
|
-
if (!left || !right) return plan;
|
|
236
|
-
for (const [known, other] of [
|
|
237
|
-
[left, right],
|
|
238
|
-
[right, left],
|
|
239
|
-
]) {
|
|
240
|
-
const isWord = subtract(known.ranges, word).length === 0;
|
|
241
|
-
const isNonWord = intersect(known.ranges, word).length === 0;
|
|
242
|
-
if (isWord || isNonWord)
|
|
243
|
-
plan = restrict(
|
|
244
|
-
plan,
|
|
245
|
-
other,
|
|
246
|
-
isWord === node.negate ? word : complement(word, maxElement(ctx)),
|
|
247
|
-
ctx,
|
|
248
|
-
);
|
|
249
|
-
}
|
|
250
|
-
return plan;
|
|
251
|
-
});
|
|
252
|
-
} else {
|
|
253
|
-
const direction = node.kind === "start" ? -1 : 1;
|
|
254
|
-
plans = plans.map((plan) => {
|
|
255
|
-
const neighbour = neighbours(elements, index, direction, 1, ctx, plan)[0];
|
|
256
|
-
if (!neighbour) return plan;
|
|
257
|
-
const terminators = nativeCharacterRanges("[\\n\\r\\u2028\\u2029]", ctx.unicode ? "u" : "");
|
|
258
|
-
return restrict(
|
|
259
|
-
plan,
|
|
260
|
-
neighbour,
|
|
261
|
-
node.kind === "start" && !ctx.multilineAnchors ? [] : terminators,
|
|
262
|
-
ctx,
|
|
263
|
-
);
|
|
264
|
-
});
|
|
265
|
-
}
|
|
266
|
-
}
|
|
267
|
-
return plans;
|
|
268
|
-
}
|
|
269
|
-
|
|
270
70
|
const intersects = (ranges: Ranges, other: Ranges) => intersect(ranges, other).length !== 0;
|
|
271
71
|
|
|
272
|
-
/** The largest value one element can consume: a code point with u, a UTF-16 unit without. */
|
|
273
|
-
const maxElement = (ctx: Context): number => (ctx.unicode ? MAX_SCALAR : MAX_UNIT);
|
|
274
|
-
|
|
275
72
|
const folded = (ranges: Ranges, ctx: Context): Ranges =>
|
|
276
73
|
ctx.ignoreCase ? foldRanges(ranges, ctx.unicode) : ranges;
|
|
277
74
|
|
|
278
|
-
|
|
75
|
+
/** One code point in an rg pattern; every non-word character is a code point escape. */
|
|
76
|
+
export const rgCodePoint = (point: number) =>
|
|
279
77
|
/^[0-9A-Za-z_]$/.test(String.fromCodePoint(point))
|
|
280
78
|
? String.fromCodePoint(point)
|
|
281
79
|
: `\\x{${point.toString(16)}}`;
|
|
282
80
|
|
|
283
81
|
function classPattern(ranges: Ranges): string {
|
|
284
|
-
if (ranges.length === 1 && ranges[0][0] === ranges[0][1]) return
|
|
285
|
-
return `[${ranges.map(([low, high]) => (low === high ?
|
|
82
|
+
if (ranges.length === 1 && ranges[0][0] === ranges[0][1]) return rgCodePoint(ranges[0][0]);
|
|
83
|
+
return `[${ranges.map(([low, high]) => (low === high ? rgCodePoint(low) : `${rgCodePoint(low)}-${rgCodePoint(high)}`)).join("")}]`;
|
|
286
84
|
}
|
|
287
85
|
|
|
288
86
|
/**
|
|
@@ -303,19 +101,21 @@ function unit(ranges: Ranges, ctx: Context): string {
|
|
|
303
101
|
return halves ? `(?:${body})?` : body;
|
|
304
102
|
}
|
|
305
103
|
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
for (let parent = node.parent; parent; parent = parent.parent)
|
|
309
|
-
if (parent.type
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
break;
|
|
313
|
-
}
|
|
314
|
-
if (parent.modifiers.remove?.dotAll) {
|
|
315
|
-
dotAll = false;
|
|
316
|
-
break;
|
|
104
|
+
/** A flag where a node appears: the innermost modifier group that sets it decides. */
|
|
105
|
+
function flagAt(node: AST.Node, flag: "ignoreCase" | "dotAll", patternFlag: boolean): boolean {
|
|
106
|
+
for (let parent = node.parent; parent; parent = parent.parent)
|
|
107
|
+
if (parent.type === "Group" && parent.modifiers) {
|
|
108
|
+
if (parent.modifiers.add[flag]) return true;
|
|
109
|
+
if (parent.modifiers.remove?.[flag]) return false;
|
|
317
110
|
}
|
|
318
|
-
|
|
111
|
+
return patternFlag;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const ignoreCaseAt = (node: AST.Node, ctx: Context) =>
|
|
115
|
+
flagAt(node, "ignoreCase", ctx.flagIgnoreCase);
|
|
116
|
+
|
|
117
|
+
function nativeFlags(node: AST.Node, ctx: Context): string {
|
|
118
|
+
const dotAll = flagAt(node, "dotAll", ctx.flagDotAll);
|
|
319
119
|
return `${ignoreCaseAt(node, ctx) ? "i" : ""}${dotAll ? "s" : ""}${ctx.unicodeSets ? "v" : ctx.unicode ? "u" : ""}`;
|
|
320
120
|
}
|
|
321
121
|
|
|
@@ -351,30 +151,7 @@ function wordTree(words: readonly (readonly number[])[], ctx: Context): string {
|
|
|
351
151
|
function stringPattern(strings: readonly string[], ctx: Context): string {
|
|
352
152
|
const words = [...new Set(strings)].map((text) => [...text].map((char) => char.codePointAt(0)!));
|
|
353
153
|
const size = words.reduce((sum, word) => sum + Math.max(1, word.length), 0);
|
|
354
|
-
|
|
355
|
-
const shortest = words.reduce((length, word) => Math.min(length, word.length), Infinity);
|
|
356
|
-
if (!shortest) return ANY_TEXT;
|
|
357
|
-
// A suffix survives only where it cannot overlap the retained prefix.
|
|
358
|
-
const suffix: number[] = [];
|
|
359
|
-
for (
|
|
360
|
-
let index = 1;
|
|
361
|
-
index <= Math.min(MAX_STRING_PREFIX_POINTS, Math.floor(shortest / 2));
|
|
362
|
-
index++
|
|
363
|
-
) {
|
|
364
|
-
const point = words[0].at(-index)!;
|
|
365
|
-
if (!words.every((word) => word.at(-index) === point)) break;
|
|
366
|
-
suffix.unshift(point);
|
|
367
|
-
}
|
|
368
|
-
for (
|
|
369
|
-
let length = Math.min(MAX_STRING_PREFIX_POINTS, shortest - suffix.length);
|
|
370
|
-
length >= 1;
|
|
371
|
-
length = Math.floor(length / 2)
|
|
372
|
-
) {
|
|
373
|
-
const prefixes = words.map((word) => word.slice(0, length));
|
|
374
|
-
const pattern = wordTree(prefixes, ctx) + ANY_TEXT + wordTree([suffix], ctx);
|
|
375
|
-
if (pattern.length <= MAX_STRING_PATTERN_UNITS) return pattern;
|
|
376
|
-
}
|
|
377
|
-
return ANY_TEXT;
|
|
154
|
+
return size <= MAX_EXPANDED_STRING_POINTS ? wordTree(words, ctx) : ANY_TEXT;
|
|
378
155
|
}
|
|
379
156
|
|
|
380
157
|
function characterPattern(node: CharacterNode, ctx: Context): string {
|
|
@@ -432,7 +209,7 @@ function quantifier(node: AST.Quantifier, ctx: Context): string {
|
|
|
432
209
|
return node.min === 0 ? `${group}*` : `${group}+`;
|
|
433
210
|
}
|
|
434
211
|
|
|
435
|
-
/** A modifier group's i and m; its s
|
|
212
|
+
/** A modifier group's i and m; `nativeFlags` reads its s from the node's ancestors. */
|
|
436
213
|
function modified(node: AST.Group, ctx: Context): Context {
|
|
437
214
|
const { add, remove } = node.modifiers ?? {};
|
|
438
215
|
if (!add) return ctx;
|
|
@@ -444,16 +221,6 @@ function modified(node: AST.Group, ctx: Context): Context {
|
|
|
444
221
|
};
|
|
445
222
|
}
|
|
446
223
|
|
|
447
|
-
/** ignoreCase where a node appears: the innermost modifier group that sets it decides. */
|
|
448
|
-
function ignoreCaseAt(node: AST.Node, ctx: Context): boolean {
|
|
449
|
-
for (let parent = node.parent; parent; parent = parent.parent)
|
|
450
|
-
if (parent.type === "Group" && parent.modifiers) {
|
|
451
|
-
if (parent.modifiers.add.ignoreCase) return true;
|
|
452
|
-
if (parent.modifiers.remove?.ignoreCase) return false;
|
|
453
|
-
}
|
|
454
|
-
return ctx.flagIgnoreCase;
|
|
455
|
-
}
|
|
456
|
-
|
|
457
224
|
/**
|
|
458
225
|
* Whether a group has always matched when its backreference is reached: the group executes
|
|
459
226
|
* before the reference in one alternative, and nothing between the group and that alternative
|
|
@@ -498,10 +265,6 @@ function participates(group: AST.CapturingGroup, reference: AST.Backreference):
|
|
|
498
265
|
* not have matched leaves the reference empty.
|
|
499
266
|
*/
|
|
500
267
|
function backreference(node: AST.Backreference, ctx: Context): string {
|
|
501
|
-
if (!node.ambiguous) {
|
|
502
|
-
const bound = ctx.bindings.get(node.resolved);
|
|
503
|
-
if (bound !== undefined) return literalWord(bound, ctx);
|
|
504
|
-
}
|
|
505
268
|
// A reference inside repeated text could repeat itself.
|
|
506
269
|
if (ctx.repeated) return ANY_TEXT;
|
|
507
270
|
const groups = node.ambiguous ? node.resolved : [node.resolved];
|
|
@@ -533,9 +296,7 @@ function element(node: AST.Element, ctx: Context, position: Position): string {
|
|
|
533
296
|
case "Group":
|
|
534
297
|
return alternatives(node.alternatives, modified(node, ctx), position);
|
|
535
298
|
case "CapturingGroup":
|
|
536
|
-
return
|
|
537
|
-
? literalWord(ctx.bindings.get(node)!, { ...ctx, ignoreCase: false })
|
|
538
|
-
: alternatives(node.alternatives, ctx, position);
|
|
299
|
+
return alternatives(node.alternatives, ctx, position);
|
|
539
300
|
case "Quantifier":
|
|
540
301
|
return quantifier(node, ctx);
|
|
541
302
|
}
|
|
@@ -543,139 +304,23 @@ function element(node: AST.Element, ctx: Context, position: Position): string {
|
|
|
543
304
|
|
|
544
305
|
function alternatives(nodes: readonly AST.Alternative[], ctx: Context, position: Position): string {
|
|
545
306
|
return choice(
|
|
546
|
-
nodes.
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
}
|
|
555
|
-
const pair =
|
|
556
|
-
ctx.unicode || plan.has(elements[index + 1])
|
|
557
|
-
? undefined
|
|
558
|
-
: surrogatePair(elements[index], elements[index + 1]);
|
|
559
|
-
if (pair !== undefined) {
|
|
560
|
-
pattern += classPattern([[pair, pair]]);
|
|
561
|
-
index++;
|
|
562
|
-
continue;
|
|
563
|
-
}
|
|
564
|
-
pattern += element(elements[index], ctx, {
|
|
565
|
-
first: position.first && index === 0,
|
|
566
|
-
last: position.last && index === elements.length - 1,
|
|
567
|
-
});
|
|
307
|
+
nodes.map(({ elements }) => {
|
|
308
|
+
let pattern = "";
|
|
309
|
+
for (let index = 0; index < elements.length; index++) {
|
|
310
|
+
const pair = ctx.unicode ? undefined : surrogatePair(elements[index], elements[index + 1]);
|
|
311
|
+
if (pair !== undefined) {
|
|
312
|
+
pattern += classPattern([[pair, pair]]);
|
|
313
|
+
index++;
|
|
314
|
+
continue;
|
|
568
315
|
}
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
}
|
|
574
|
-
|
|
575
|
-
function literalWord(text: string, ctx: Context): string {
|
|
576
|
-
return [...text]
|
|
577
|
-
.map((char) => {
|
|
578
|
-
const point = char.codePointAt(0)!;
|
|
579
|
-
return !ctx.unicode && point > MAX_UNIT
|
|
580
|
-
? classPattern([[point, point]])
|
|
581
|
-
: unit(folded([[point, point]], ctx), ctx);
|
|
582
|
-
})
|
|
583
|
-
.join("");
|
|
584
|
-
}
|
|
585
|
-
|
|
586
|
-
function joinWords(
|
|
587
|
-
left: readonly string[],
|
|
588
|
-
right: readonly string[],
|
|
589
|
-
): readonly string[] | undefined {
|
|
590
|
-
if (left.length * right.length > MAX_ANALYSIS_BRANCHES) return undefined;
|
|
591
|
-
const words = [...new Set(left.flatMap((a) => right.map((b) => a + b)))];
|
|
592
|
-
return words.some((word) => word.length > MAX_FIXED_UNITS) ? undefined : words;
|
|
593
|
-
}
|
|
594
|
-
|
|
595
|
-
function finiteWords(node: AST.Element, ctx: Context): readonly string[] | undefined {
|
|
596
|
-
if (node.type === "Assertion" || node.type === "Backreference") return undefined;
|
|
597
|
-
if (node.type === "Group" || node.type === "CapturingGroup") {
|
|
598
|
-
const result: string[] = [];
|
|
599
|
-
for (const branch of node.alternatives) {
|
|
600
|
-
let words: readonly string[] = [""];
|
|
601
|
-
for (const child of branch.elements) {
|
|
602
|
-
const part = finiteWords(child, ctx);
|
|
603
|
-
const joined = part && joinWords(words, part);
|
|
604
|
-
if (!joined) return undefined;
|
|
605
|
-
words = joined;
|
|
316
|
+
pattern += element(elements[index], ctx, {
|
|
317
|
+
first: position.first && index === 0,
|
|
318
|
+
last: position.last && index === elements.length - 1,
|
|
319
|
+
});
|
|
606
320
|
}
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
return [...new Set(result)];
|
|
611
|
-
}
|
|
612
|
-
if (node.type === "Quantifier") {
|
|
613
|
-
if (node.max > MAX_ANALYSIS_BRANCHES) return undefined;
|
|
614
|
-
if (!node.max) return [""];
|
|
615
|
-
const inner = finiteWords(node.element, ctx);
|
|
616
|
-
if (!inner) return undefined;
|
|
617
|
-
let words: readonly string[] = [""];
|
|
618
|
-
const result: string[] = node.min === 0 ? [""] : [];
|
|
619
|
-
for (let count = 1; count <= node.max; count++) {
|
|
620
|
-
const joined = joinWords(words, inner);
|
|
621
|
-
if (!joined) return undefined;
|
|
622
|
-
words = joined;
|
|
623
|
-
if (count >= node.min) result.push(...words);
|
|
624
|
-
if (result.length > MAX_ANALYSIS_BRANCHES) return undefined;
|
|
625
|
-
}
|
|
626
|
-
return [...new Set(result)];
|
|
627
|
-
}
|
|
628
|
-
const ranges = scalarRanges(node, ctx);
|
|
629
|
-
if (total(ranges) > MAX_ANALYSIS_BRANCHES) return undefined;
|
|
630
|
-
const result: string[] = [];
|
|
631
|
-
for (const [low, high] of ranges)
|
|
632
|
-
for (let point = low; point <= high; point++) result.push(String.fromCodePoint(point));
|
|
633
|
-
const strings = acceptedClassStrings(node, nativeFlags(node, ctx));
|
|
634
|
-
if (!strings) return undefined;
|
|
635
|
-
for (const value of strings) {
|
|
636
|
-
let words: readonly string[] = [""];
|
|
637
|
-
for (const char of value) {
|
|
638
|
-
const variants = ignoreCaseAt(node, ctx) ? caseVariants(char, ctx.unicode) : [char];
|
|
639
|
-
const joined = joinWords(words, variants);
|
|
640
|
-
if (!joined) return undefined;
|
|
641
|
-
words = joined;
|
|
642
|
-
}
|
|
643
|
-
result.push(...words);
|
|
644
|
-
if (result.length > MAX_ANALYSIS_BRANCHES) return undefined;
|
|
645
|
-
}
|
|
646
|
-
return [...new Set(result)];
|
|
647
|
-
}
|
|
648
|
-
|
|
649
|
-
/** Enumerate only captures whose value is stable at every reference. */
|
|
650
|
-
function bindingContexts(parsed: AST.Pattern, ctx: Context): readonly Context[] {
|
|
651
|
-
let contexts = [ctx];
|
|
652
|
-
visitRegExpAST(parsed, {
|
|
653
|
-
onCapturingGroupEnter(group) {
|
|
654
|
-
if (
|
|
655
|
-
!group.references.length ||
|
|
656
|
-
group.references.some((ref) => ref.ambiguous || !participates(group, ref))
|
|
657
|
-
)
|
|
658
|
-
return;
|
|
659
|
-
for (let parent: AST.Node | null = group.parent; parent; parent = parent.parent)
|
|
660
|
-
if (parent.type === "Assertion" || parent.type === "Quantifier") return;
|
|
661
|
-
let nested = false;
|
|
662
|
-
visitRegExpAST(group, {
|
|
663
|
-
onCapturingGroupEnter(node) {
|
|
664
|
-
if (node !== group) nested = true;
|
|
665
|
-
},
|
|
666
|
-
});
|
|
667
|
-
if (nested) return;
|
|
668
|
-
const words = finiteWords(group, ctx);
|
|
669
|
-
if (!words?.length || words.length * contexts.length > MAX_ANALYSIS_BRANCHES) return;
|
|
670
|
-
contexts = contexts.flatMap((context) =>
|
|
671
|
-
words.map((word) => ({
|
|
672
|
-
...context,
|
|
673
|
-
bindings: new Map([...context.bindings, [group, word]]),
|
|
674
|
-
})),
|
|
675
|
-
);
|
|
676
|
-
},
|
|
677
|
-
});
|
|
678
|
-
return contexts;
|
|
321
|
+
return pattern;
|
|
322
|
+
}),
|
|
323
|
+
);
|
|
679
324
|
}
|
|
680
325
|
|
|
681
326
|
/**
|
|
@@ -691,21 +336,16 @@ export function lineCandidatePatterns(query: GrepQuery): string[] | undefined {
|
|
|
691
336
|
unicodeSets: query.flags.includes("v"),
|
|
692
337
|
multilineAnchors: query.flags.includes("m"),
|
|
693
338
|
repeated: false,
|
|
694
|
-
bindings: new Map(),
|
|
695
339
|
};
|
|
696
340
|
const patterns: string[] = [];
|
|
697
341
|
for (const pattern of query.patterns) {
|
|
698
342
|
const translated = analyzeQueryPattern(pattern, query.literal, query.flags, (parsed) =>
|
|
699
|
-
|
|
700
|
-
bindingContexts(parsed, ctx).map((context) =>
|
|
701
|
-
alternatives(parsed.alternatives, context, { first: true, last: true }),
|
|
702
|
-
),
|
|
703
|
-
),
|
|
343
|
+
alternatives(parsed.alternatives, ctx, { first: true, last: true }),
|
|
704
344
|
);
|
|
705
345
|
if (translated === undefined) return undefined;
|
|
706
346
|
if (
|
|
707
347
|
translated.length + patterns.reduce((sum, value) => sum + value.length, 0) >
|
|
708
|
-
|
|
348
|
+
MAX_RG_PATTERN_UNITS
|
|
709
349
|
)
|
|
710
350
|
return undefined;
|
|
711
351
|
// A sticky match starts where the line starts.
|
package/src/pi/schema.ts
CHANGED
|
@@ -7,6 +7,18 @@
|
|
|
7
7
|
* @module pi-hashline-edit/pi
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
|
+
import type { ConstrainedSamplingConfig } from "@earendil-works/pi-ai";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Every tool's sampling request: providers that support it enforce the parameter schema while
|
|
14
|
+
* sampling, and the rest sample as usual. Pi's strict converter rejects object and array
|
|
15
|
+
* unions, so no tool schema uses them.
|
|
16
|
+
*/
|
|
17
|
+
export const STRICT_SAMPLING = {
|
|
18
|
+
type: "json_schema",
|
|
19
|
+
strict: "prefer",
|
|
20
|
+
} as const satisfies ConstrainedSamplingConfig;
|
|
21
|
+
|
|
10
22
|
/** JSON Schema keywords for an integer in [minimum, maximum]; fractions are rejected, not rounded. */
|
|
11
23
|
export function integerRange(minimum: number, maximum: number) {
|
|
12
24
|
return { minimum, multipleOf: 1, maximum };
|
|
@@ -47,7 +47,6 @@ test("streamed lines preserve BOM, standalone CR, and boundaries split across ch
|
|
|
47
47
|
assert.deepEqual(lines, splitLines(text));
|
|
48
48
|
assert.equal(stats.totalLines, lines.length);
|
|
49
49
|
assert.equal(stats.finalNewline, text === "" || text.endsWith("\n"));
|
|
50
|
-
assert.equal(stats.byteLength, Buffer.byteLength(text));
|
|
51
50
|
}
|
|
52
51
|
}));
|
|
53
52
|
|
|
@@ -71,7 +70,6 @@ test("streamed scans → return the revision of every original byte and byte-bas
|
|
|
71
70
|
});
|
|
72
71
|
assert.equal(chunks.join(""), source.toString("utf8"));
|
|
73
72
|
assert.equal(stats.revision, byteRevision(source));
|
|
74
|
-
assert.equal(stats.byteLength, source.length);
|
|
75
73
|
assert.equal(progress.at(-1) ?? 0, source.length);
|
|
76
74
|
if (source.length > chunkBytes) assert.equal(progress[0], chunkBytes);
|
|
77
75
|
const selected = await scanTextLines(
|
|
@@ -198,25 +196,6 @@ test("lossy scans flush a multibyte sequence split across chunks and incomplete
|
|
|
198
196
|
assert.equal(emitted.at(-1), "�");
|
|
199
197
|
assert.equal(stats.validUtf8, false);
|
|
200
198
|
assert.equal(stats.hasNul, false);
|
|
201
|
-
assert.equal(stats.byteLength, source.length);
|
|
202
|
-
}));
|
|
203
|
-
|
|
204
|
-
test("lossy scans without a text consumer report validity and retain all raw bytes", async () =>
|
|
205
|
-
withFile(async (path) => {
|
|
206
|
-
const source = Buffer.concat([
|
|
207
|
-
Buffer.from("\ufeffbefore\r\n"),
|
|
208
|
-
Buffer.from([0xff, 0xf0, 0x9f]),
|
|
209
|
-
]);
|
|
210
|
-
await writeFile(path, source);
|
|
211
|
-
const stats = await scanTextFile(path, {
|
|
212
|
-
decoding: "lossy",
|
|
213
|
-
});
|
|
214
|
-
assert.equal(stats.revision, byteRevision(source));
|
|
215
|
-
assert.equal(stats.validUtf8, false);
|
|
216
|
-
assert.equal(stats.hasNul, false);
|
|
217
|
-
assert.equal(stats.totalLines, 2);
|
|
218
|
-
assert.equal(stats.finalNewline, false);
|
|
219
|
-
assert.equal(stats.byteLength, source.length);
|
|
220
199
|
}));
|
|
221
200
|
|
|
222
201
|
test("NUL suppresses its chunk and all later text without flushing a pending sequence", async () =>
|
package/src/pi/text-stream.ts
CHANGED
|
@@ -35,6 +35,17 @@ export async function scanTextFile(
|
|
|
35
35
|
let lastByte = -1;
|
|
36
36
|
let hasNul = false;
|
|
37
37
|
let decodingError: unknown;
|
|
38
|
+
/** Strict text of a chunk, or of the final flush without bytes; undefined once malformed. */
|
|
39
|
+
const decodeStrict = (bytes?: Buffer): string | undefined => {
|
|
40
|
+
if (decodingError) return undefined;
|
|
41
|
+
try {
|
|
42
|
+
return decode(bytes, bytes !== undefined);
|
|
43
|
+
} catch (error) {
|
|
44
|
+
if (!(error instanceof Utf8DecodingError)) throw error;
|
|
45
|
+
decodingError = error;
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
};
|
|
38
49
|
const stream = createReadStream(path, {
|
|
39
50
|
fd: handle,
|
|
40
51
|
autoClose: false,
|
|
@@ -55,15 +66,7 @@ export async function scanTextFile(
|
|
|
55
66
|
}
|
|
56
67
|
// NUL takes precedence even when an earlier chunk contained malformed UTF-8.
|
|
57
68
|
if (hasNul) continue;
|
|
58
|
-
let text
|
|
59
|
-
if (!decodingError) {
|
|
60
|
-
try {
|
|
61
|
-
text = decode(bytes, true);
|
|
62
|
-
} catch (error) {
|
|
63
|
-
if (!(error instanceof Utf8DecodingError)) throw error;
|
|
64
|
-
decodingError = error;
|
|
65
|
-
}
|
|
66
|
-
}
|
|
69
|
+
let text = decodeStrict(bytes);
|
|
67
70
|
if (lossy) text = lossy(bytes, true);
|
|
68
71
|
if (text !== undefined) await onChunk?.(text, byteLength);
|
|
69
72
|
}
|
|
@@ -74,22 +77,13 @@ export async function scanTextFile(
|
|
|
74
77
|
}
|
|
75
78
|
throwIfCancelled(signal);
|
|
76
79
|
if (!hasNul) {
|
|
77
|
-
let tail
|
|
78
|
-
if (!decodingError) {
|
|
79
|
-
try {
|
|
80
|
-
tail = decode();
|
|
81
|
-
} catch (error) {
|
|
82
|
-
if (!(error instanceof Utf8DecodingError)) throw error;
|
|
83
|
-
decodingError = error;
|
|
84
|
-
}
|
|
85
|
-
}
|
|
80
|
+
let tail = decodeStrict();
|
|
86
81
|
if (lossy) tail = lossy();
|
|
87
82
|
else if (decodingError && decoding === "strict") throw decodingError;
|
|
88
83
|
if (tail) await onChunk?.(tail, byteLength);
|
|
89
84
|
}
|
|
90
85
|
return {
|
|
91
86
|
revision: revision.digest(),
|
|
92
|
-
byteLength,
|
|
93
87
|
totalLines: lineFeeds + (lastByte !== -1 && lastByte !== 10 ? 1 : 0),
|
|
94
88
|
finalNewline: lastByte === -1 || lastByte === 10,
|
|
95
89
|
hasNul,
|
|
@@ -117,7 +111,7 @@ export async function scanTextLines(
|
|
|
117
111
|
readonly decoding?: Utf8Decoding;
|
|
118
112
|
} = {},
|
|
119
113
|
) {
|
|
120
|
-
const maxBytes =
|
|
114
|
+
const { signal, decoding, maxLineBytes: maxBytes = Infinity } = options;
|
|
121
115
|
let number = 1;
|
|
122
116
|
let byteLength = 0;
|
|
123
117
|
let carriageReturns = 0;
|
|
@@ -144,7 +138,6 @@ export async function scanTextLines(
|
|
|
144
138
|
number++;
|
|
145
139
|
selected = select(number);
|
|
146
140
|
};
|
|
147
|
-
const { signal, decoding } = options;
|
|
148
141
|
const stats = await scanTextFile(path, {
|
|
149
142
|
signal,
|
|
150
143
|
decoding,
|