@criogaid/pi-hashline-edit 0.12.0 → 0.13.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/LICENSE +1 -0
- package/README.md +59 -16
- package/README.zh-CN.md +59 -16
- package/package.json +2 -2
- package/src/core/AGENTS.md +2 -2
- package/src/core/apply.test.ts +13 -0
- package/src/core/apply.ts +5 -9
- package/src/core/case-fold.test.ts +16 -25
- package/src/core/case-fold.ts +4 -4
- package/src/core/character-set.test.ts +1 -6
- package/src/core/character-set.ts +7 -61
- package/src/core/regex.ts +2 -36
- package/src/core/search-analysis.test.ts +66 -61
- package/src/core/search-analysis.ts +24 -39
- package/src/core/search-matrix.test.ts +2 -2
- package/src/core/search-matrix.testing.ts +6 -16
- package/src/core/search-schema.ts +0 -1
- package/src/core/search.test.ts +6 -19
- package/src/core/search.ts +10 -8
- package/src/index.ts +27 -2
- package/src/integration/config-registration.test.ts +77 -4
- package/src/integration/fusion-dispatch.test.ts +47 -2
- package/src/integration/grep-errors.test.ts +31 -0
- package/src/integration/grep-flags.test.ts +13 -196
- package/src/integration/grep-js-completeness.test.ts +41 -8
- package/src/integration/grep-line-candidates.test.ts +3 -33
- package/src/integration/grep-matrix.test.ts +1 -1
- package/src/integration/grep-path-matrix.test.ts +59 -65
- package/src/integration/grep-prefilter-coverage.test.ts +15 -8
- package/src/integration/grep-process-limits.test.ts +46 -0
- package/src/integration/grep-regex.test.ts +7 -2
- package/src/integration/grep-rg.test.ts +63 -12
- package/src/integration/grep-translation.test.ts +14 -7
- package/src/integration/model-budget-lifecycle.test.ts +41 -2
- package/src/integration/npm-package.testing.ts +2 -3
- package/src/integration/replace-package.testing.ts +2 -2
- package/src/pi/AGENTS.md +21 -13
- package/src/pi/action-fusion.test.ts +38 -4
- package/src/pi/action-fusion.ts +23 -19
- package/src/pi/argument-diagnostics.ts +28 -48
- package/src/pi/argument-validation.test.ts +61 -27
- package/src/pi/argument-validation.ts +34 -0
- package/src/pi/budgets.ts +19 -10
- package/src/pi/config.test.ts +1 -1
- package/src/pi/diagnostic-buffer.test.ts +1 -0
- package/src/pi/edit-tool.ts +1 -1
- package/src/pi/failure-context.test.ts +23 -2
- package/src/pi/failure-context.ts +36 -42
- package/src/pi/failure-path.test.ts +8 -3
- package/src/pi/file-commit.test.ts +109 -52
- package/src/pi/file-commit.ts +62 -56
- package/src/pi/fusion-card.ts +3 -2
- package/src/pi/grep-candidates.test.ts +5 -5
- package/src/pi/grep-candidates.ts +81 -50
- package/src/pi/grep-matrix.test.ts +14 -29
- package/src/pi/grep-order.test.ts +132 -9
- package/src/pi/grep-output.ts +169 -51
- package/src/pi/grep-render.ts +40 -34
- package/src/pi/grep-rg.testing.ts +9 -6
- package/src/pi/grep-scope.ts +51 -29
- package/src/pi/grep-search.ts +96 -71
- package/src/pi/grep-tool.ts +13 -22
- package/src/pi/grep.test.ts +310 -84
- package/src/pi/model-budgets.test.ts +56 -6
- package/src/pi/model-budgets.ts +7 -4
- package/src/pi/mutation-result.test.ts +25 -1
- package/src/pi/mutation-result.ts +7 -2
- package/src/pi/mutation-runner.ts +3 -4
- package/src/pi/output-budgets.test.ts +3 -1
- package/src/pi/path.ts +18 -4
- package/src/pi/pi.test.ts +22 -0
- package/src/pi/read-delegation.test.ts +119 -0
- package/src/pi/read-tool.ts +109 -61
- package/src/pi/read.test.ts +306 -17
- package/src/pi/regex-worker.test.ts +42 -0
- package/src/pi/regex-worker.ts +17 -11
- package/src/pi/registration.test.ts +157 -102
- package/src/pi/render.test.ts +54 -0
- package/src/pi/render.ts +9 -9
- package/src/pi/replace-tool.ts +5 -2
- package/src/pi/report-schema.ts +52 -31
- package/src/pi/report.test.ts +60 -10
- package/src/pi/rg-process.ts +41 -5
- package/src/pi/rg-regex.test.ts +12 -52
- package/src/pi/rg-regex.ts +29 -77
- package/src/pi/text-stream.test.ts +3 -0
- package/src/pi/text-stream.ts +1 -1
- package/src/testing/regex-translation-corpus.ts +39 -96
package/src/pi/report.test.ts
CHANGED
|
@@ -368,16 +368,21 @@ test("grep preview from invalid UTF-8 → recovery selects bash for the listed p
|
|
|
368
368
|
assert.match(next, /invalidUtf8.*bash/);
|
|
369
369
|
});
|
|
370
370
|
|
|
371
|
-
test("
|
|
372
|
-
const
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
371
|
+
test("grep limits coincide → recovery prioritizes output, then match, then scan", () => {
|
|
372
|
+
for (const key of ["matchLimit", "outputLimit"] as const) {
|
|
373
|
+
const next = OUTCOME_NEXT.find(([fact]) => fact === key)?.[1];
|
|
374
|
+
assert.ok(next);
|
|
375
|
+
const result = reportResult({
|
|
376
|
+
tool: "grep",
|
|
377
|
+
matches: 1,
|
|
378
|
+
matchLimit: 1,
|
|
379
|
+
scanLimit: formatByteSize(MAX_UNNARROWED_SCAN_BYTES),
|
|
380
|
+
...(key === "outputLimit" && {
|
|
381
|
+
outputLimit: formatByteSize(DEFAULT_OUTPUT_BUDGETS.grepBytes),
|
|
382
|
+
}),
|
|
383
|
+
});
|
|
384
|
+
assert.equal(reportOf(result, "grep")?.next, typeof next === "string" ? next : next.default);
|
|
385
|
+
}
|
|
381
386
|
});
|
|
382
387
|
|
|
383
388
|
test("output limit with read next offset → recovery prioritizes the next offset", () => {
|
|
@@ -481,3 +486,48 @@ test("mutation freshness → retains the fact and requests reread only for an ex
|
|
|
481
486
|
assert.equal(Object.hasOwn(JSON.parse(block.text), "next"), freshness !== "missing");
|
|
482
487
|
}
|
|
483
488
|
});
|
|
489
|
+
|
|
490
|
+
test("text-only error resembles a success report → keeps the original diagnostic visible", () => {
|
|
491
|
+
const diagnostic = '{"matches":1}';
|
|
492
|
+
assert.equal(displayed({ content: [text(diagnostic)] }, "grep").trimEnd(), diagnostic);
|
|
493
|
+
});
|
|
494
|
+
|
|
495
|
+
test("read and grep failures cannot carry mutation state → reject invalid replay facts", () => {
|
|
496
|
+
for (const tool of ["read", "grep"] as const) {
|
|
497
|
+
const raw = {
|
|
498
|
+
error: "FILESYSTEM_ERROR",
|
|
499
|
+
message: "disk read failed",
|
|
500
|
+
publication: "PUBLISHED",
|
|
501
|
+
};
|
|
502
|
+
const content = [text(JSON.stringify(raw))];
|
|
503
|
+
assert.equal(reportOf({ content }, tool), undefined);
|
|
504
|
+
assert.equal(
|
|
505
|
+
splitReport({ details: { report: { tool, ...raw } }, content }, tool).report,
|
|
506
|
+
undefined,
|
|
507
|
+
);
|
|
508
|
+
}
|
|
509
|
+
});
|
|
510
|
+
|
|
511
|
+
test("mutation failure carries a freshness fact → rejects the invalid replay report", () => {
|
|
512
|
+
const tool = "edit";
|
|
513
|
+
const failure = {
|
|
514
|
+
error: "PUBLISH_FAILED",
|
|
515
|
+
message: "Publication failed.",
|
|
516
|
+
publication: "NOT_PUBLISHED",
|
|
517
|
+
};
|
|
518
|
+
const valid = {
|
|
519
|
+
content: [text(JSON.stringify(failure))],
|
|
520
|
+
details: { report: { tool, ...failure } },
|
|
521
|
+
};
|
|
522
|
+
assert.deepEqual(reportOf(valid, tool), valid.details.report);
|
|
523
|
+
for (const facts of [
|
|
524
|
+
{ freshness: "changed" },
|
|
525
|
+
{ freshnessError: { message: "Could not inspect target." } },
|
|
526
|
+
]) {
|
|
527
|
+
const raw = { ...failure, ...facts };
|
|
528
|
+
const content = [text(JSON.stringify(raw))];
|
|
529
|
+
const details = { report: { tool, ...raw } };
|
|
530
|
+
assert.equal(splitReport({ content, details }, tool).report, undefined);
|
|
531
|
+
assert.equal(reportOf({ content }, tool), undefined);
|
|
532
|
+
}
|
|
533
|
+
});
|
package/src/pi/rg-process.ts
CHANGED
|
@@ -11,7 +11,7 @@ import { rgPath } from "@vscode/ripgrep";
|
|
|
11
11
|
import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
|
|
12
12
|
import { spawn, type ChildProcessByStdio } from "node:child_process";
|
|
13
13
|
import type { Readable } from "node:stream";
|
|
14
|
-
import { HashlineError } from "../core/errors.ts";
|
|
14
|
+
import { errnoCode, HashlineError } from "../core/errors.ts";
|
|
15
15
|
import { throwIfCancelled, type SearchWarning } from "./error-text.ts";
|
|
16
16
|
import { formatByteSize } from "./budgets.ts";
|
|
17
17
|
|
|
@@ -23,6 +23,14 @@ import { formatByteSize } from "./budgets.ts";
|
|
|
23
23
|
export const COMMON_RG_ARGS = ["--no-config", "--color=never", "--sort=path"];
|
|
24
24
|
/** Leave room for rg's arguments and paths on hosts with small command-line limits. */
|
|
25
25
|
export const MAX_RG_PATTERN_UNITS = 24 * 1024;
|
|
26
|
+
export const RG_PATTERN_FLAG = "-e";
|
|
27
|
+
|
|
28
|
+
/** Command-line cost of a translated pattern and its flag, including separators. */
|
|
29
|
+
export function rgPatternArgUnits(pattern: string): number {
|
|
30
|
+
// Translations use ASCII without whitespace or quotes; Windows quotes an empty argument.
|
|
31
|
+
return RG_PATTERN_FLAG.length + 2 + (pattern.length || 2);
|
|
32
|
+
}
|
|
33
|
+
|
|
26
34
|
const MAX_RG_RECORD_BYTES = 16 * 1024 * 1024;
|
|
27
35
|
const RG_RECORD_LIMIT_MESSAGE = `ripgrep output record exceeds ${formatByteSize(MAX_RG_RECORD_BYTES)}.`;
|
|
28
36
|
|
|
@@ -58,8 +66,17 @@ export function searchDiagnostic(result: RgRunResult): SearchWarning | undefined
|
|
|
58
66
|
}
|
|
59
67
|
|
|
60
68
|
/** spawn reports a failure to start by throwing or by an error event, depending on the errno. */
|
|
61
|
-
|
|
62
|
-
|
|
69
|
+
class RgStartError extends HashlineError<"RIPGREP_FAILED"> {
|
|
70
|
+
constructor(cause: unknown) {
|
|
71
|
+
super("RIPGREP_FAILED", "Failed to run ripgrep.", { cause });
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Whether rg could not start because the OS rejected its command line length. */
|
|
76
|
+
export function isRgArgumentLimit(error: unknown): boolean {
|
|
77
|
+
if (!(error instanceof RgStartError)) return false;
|
|
78
|
+
const code = errnoCode(error.cause);
|
|
79
|
+
return code === "ENAMETOOLONG" || code === "E2BIG";
|
|
63
80
|
}
|
|
64
81
|
|
|
65
82
|
function startRg(args: readonly string[], signal?: AbortSignal): RunningProcess {
|
|
@@ -71,7 +88,7 @@ function startRg(args: readonly string[], signal?: AbortSignal): RunningProcess
|
|
|
71
88
|
shell: false,
|
|
72
89
|
});
|
|
73
90
|
} catch (cause) {
|
|
74
|
-
throw
|
|
91
|
+
throw new RgStartError(cause);
|
|
75
92
|
}
|
|
76
93
|
const stderr = new DiagnosticBuffer(MAX_RG_STDERR_BYTES);
|
|
77
94
|
const stderrDecoder = new StringDecoder("utf8");
|
|
@@ -139,7 +156,7 @@ async function runRg(
|
|
|
139
156
|
if (stopped) rg.kill();
|
|
140
157
|
const result = await rg.done;
|
|
141
158
|
throwIfCancelled(signal);
|
|
142
|
-
if (result.error) throw
|
|
159
|
+
if (result.error) throw new RgStartError(result.error);
|
|
143
160
|
return { code: result.code, stderr: result.stderr, stopped };
|
|
144
161
|
} finally {
|
|
145
162
|
rg.kill();
|
|
@@ -162,6 +179,25 @@ export function runRgPaths(
|
|
|
162
179
|
});
|
|
163
180
|
}
|
|
164
181
|
|
|
182
|
+
/**
|
|
183
|
+
* Whether rg rejects pattern arguments. Exit code 2 also covers paths rg could not read, so the
|
|
184
|
+
* patterns run alone against empty standard input, where only a pattern error fails.
|
|
185
|
+
*/
|
|
186
|
+
export async function rgRejectsPatterns(
|
|
187
|
+
patternArgs: readonly string[],
|
|
188
|
+
signal: AbortSignal | undefined,
|
|
189
|
+
): Promise<boolean> {
|
|
190
|
+
const result = await runRg(
|
|
191
|
+
[...COMMON_RG_ARGS, ...patternArgs, "--", "-"],
|
|
192
|
+
signal,
|
|
193
|
+
async (stdout) => {
|
|
194
|
+
for await (const _ of stdout);
|
|
195
|
+
return true;
|
|
196
|
+
},
|
|
197
|
+
);
|
|
198
|
+
return result.code === 2;
|
|
199
|
+
}
|
|
200
|
+
|
|
165
201
|
/** A path rg reported; one that is not valid UTF-8 cannot be addressed by tools. */
|
|
166
202
|
function decodePath(record: Buffer): string {
|
|
167
203
|
const path = record.toString("utf8");
|
package/src/pi/rg-regex.test.ts
CHANGED
|
@@ -3,65 +3,25 @@ import { test } from "node:test";
|
|
|
3
3
|
import { lineCandidatePatterns } from "./rg-regex.ts";
|
|
4
4
|
|
|
5
5
|
// These expressions are the byte-level boundary contract, including deliberate widening.
|
|
6
|
-
for (const [pattern, flags, expected] of [
|
|
7
|
-
["a$", "", "a\\r?$"],
|
|
8
|
-
["[A-Z]{10,}", "m", "(?:[A-Z]){10,}"],
|
|
9
|
-
["(?m:^)b", "", "(?:^|[\\r\\x{2028}\\x{2029}])b"],
|
|
10
|
-
["(\\w)\\1{4}", "m", "[0-9A-Z_a-z](?:[0-9A-Z_a-z]){4,4}"],
|
|
11
|
-
] as const) {
|
|
12
|
-
test(`line candidates ${pattern} /${flags} → preserve required byte positions`, () => {
|
|
13
|
-
assert.deepEqual(
|
|
14
|
-
lineCandidatePatterns({ patterns: [pattern], literal: false, flags, multiline: false }),
|
|
15
|
-
[expected],
|
|
16
|
-
);
|
|
17
|
-
});
|
|
18
|
-
}
|
|
19
|
-
|
|
20
6
|
for (const [pattern, expected] of [
|
|
21
|
-
["
|
|
22
|
-
["[
|
|
23
|
-
["[\\
|
|
24
|
-
["
|
|
25
|
-
["[[a-c]--\\p{Uppercase_Letter}]", "[a-c]"],
|
|
26
|
-
["[a[bc]\\q{de|fg}]", "(?:[a-c]|(?:de|fg))"],
|
|
27
|
-
["[\\q{ab|cd}&&\\q{cd|ef}]", "cd"],
|
|
28
|
-
["[\\q{ab|cd}--\\q{cd}]", "ab"],
|
|
29
|
-
["[\\q{ab|}]", "(?:ab|)"],
|
|
30
|
-
["[[a]--[a]]", "[^\\x{0}-\\x{10ffff}]"],
|
|
7
|
+
["a$", "a(?:[\\r\\x{2028}\\x{2029}]|\\r?$)"],
|
|
8
|
+
["[A-Z]{10,}", "(?:[A-Z]){10,}"],
|
|
9
|
+
["(?m:^)b", "(?:^|[\\r\\x{2028}\\x{2029}])b"],
|
|
10
|
+
["(\\w)\\1{4}", "[0-9A-Z_a-z](?:[0-9A-Z_a-z]){4,4}"],
|
|
31
11
|
] as const) {
|
|
32
|
-
test(`
|
|
12
|
+
test(`line candidates ${pattern} → preserve required byte positions`, () => {
|
|
33
13
|
assert.deepEqual(
|
|
34
|
-
lineCandidatePatterns({
|
|
14
|
+
lineCandidatePatterns({
|
|
15
|
+
patterns: [pattern],
|
|
16
|
+
literal: false,
|
|
17
|
+
ignoreCase: false,
|
|
18
|
+
multiline: false,
|
|
19
|
+
}),
|
|
35
20
|
[expected],
|
|
36
21
|
);
|
|
37
22
|
});
|
|
38
23
|
}
|
|
39
24
|
|
|
40
|
-
test("capture disables i inside a caseless reference → retain the reference's case variants", () => {
|
|
41
|
-
assert.deepEqual(
|
|
42
|
-
lineCandidatePatterns({
|
|
43
|
-
patterns: ["((?-i:[[a]--[A]]))(?i:\\1)"],
|
|
44
|
-
literal: false,
|
|
45
|
-
flags: "v",
|
|
46
|
-
multiline: false,
|
|
47
|
-
}),
|
|
48
|
-
["a[Aa]"],
|
|
49
|
-
);
|
|
50
|
-
});
|
|
51
|
-
|
|
52
|
-
test("caseless backreference repeats a v string-class capture → retains native case variants", () => {
|
|
53
|
-
const pattern = "([\\q{a}])\\1";
|
|
54
|
-
assert.equal(new RegExp(pattern, "iv").test("aA"), true);
|
|
55
|
-
const candidates = lineCandidatePatterns({
|
|
56
|
-
patterns: [pattern],
|
|
57
|
-
literal: false,
|
|
58
|
-
flags: "iv",
|
|
59
|
-
multiline: false,
|
|
60
|
-
});
|
|
61
|
-
// This ASCII-only translation uses syntax shared by rg and JavaScript.
|
|
62
|
-
assert.ok(candidates?.some((candidate) => new RegExp(candidate).test("aA")));
|
|
63
|
-
});
|
|
64
|
-
|
|
65
25
|
test("deeply nested pattern → line candidates retain the native match", () => {
|
|
66
26
|
for (const depth of [50, 200, 500, 1_000, 2_000, 4_000]) {
|
|
67
27
|
const pattern = `${"(?:".repeat(depth)}A${")".repeat(depth)}`;
|
|
@@ -69,7 +29,7 @@ test("deeply nested pattern → line candidates retain the native match", () =>
|
|
|
69
29
|
const candidates = lineCandidatePatterns({
|
|
70
30
|
patterns: [pattern],
|
|
71
31
|
literal: false,
|
|
72
|
-
|
|
32
|
+
ignoreCase: false,
|
|
73
33
|
multiline: false,
|
|
74
34
|
});
|
|
75
35
|
// An unavailable line analysis delegates candidate discovery to the file prefilter.
|
package/src/pi/rg-regex.ts
CHANGED
|
@@ -6,8 +6,8 @@
|
|
|
6
6
|
* may be dropped and an element may match more text, but nothing a match needs is removed.
|
|
7
7
|
*
|
|
8
8
|
* Original line bytes differ from the LF view in three ways, each widened here: a CRLF line
|
|
9
|
-
* keeps its CR before the line feed, malformed UTF-8 is U+FFFD in the view, and
|
|
10
|
-
*
|
|
9
|
+
* keeps its CR before the line feed, malformed UTF-8 is U+FFFD in the view, and a consuming
|
|
10
|
+
* element can match half of a supplementary character, since grep regexes have no u flag.
|
|
11
11
|
*
|
|
12
12
|
* @module pi-hashline-edit/pi
|
|
13
13
|
*/
|
|
@@ -22,13 +22,12 @@ import {
|
|
|
22
22
|
nativeCharacterRanges,
|
|
23
23
|
foldRanges,
|
|
24
24
|
type Ranges,
|
|
25
|
-
acceptedClassStrings,
|
|
26
25
|
type CharacterNode,
|
|
27
26
|
surrogatePair,
|
|
28
27
|
} from "../core/character-set.ts";
|
|
29
28
|
import { analyzeQueryPattern } from "../core/search-analysis.ts";
|
|
30
|
-
import type
|
|
31
|
-
import { MAX_RG_PATTERN_UNITS } from "./rg-process.ts";
|
|
29
|
+
import { GREP_FLAGS, type GrepQuery } from "../core/search.ts";
|
|
30
|
+
import { MAX_RG_PATTERN_UNITS, rgPatternArgUnits } from "./rg-process.ts";
|
|
32
31
|
|
|
33
32
|
const LF = 0x0a;
|
|
34
33
|
const REPLACEMENT = 0xfffd;
|
|
@@ -36,8 +35,6 @@ const SURROGATES: Ranges = [[0xd800, 0xdfff]];
|
|
|
36
35
|
const SUPPLEMENTARY: Ranges = [[0x10000, MAX_SCALAR]];
|
|
37
36
|
/** Repetition counts above this become unbounded, keeping rg's compiled size small. */
|
|
38
37
|
const MAX_EXACT_REPEAT = 16;
|
|
39
|
-
/** Bound expanded class strings by total code points, counting an empty string as one. */
|
|
40
|
-
const MAX_EXPANDED_STRING_POINTS = 256;
|
|
41
38
|
|
|
42
39
|
/** The bytes a lossy decoder shows as U+FFFD: every byte of a malformed sequence is 0x80–0xFF. */
|
|
43
40
|
const MALFORMED = "(?-u:[\\x80-\\xff])+";
|
|
@@ -51,10 +48,6 @@ interface Context {
|
|
|
51
48
|
readonly ignoreCase: boolean;
|
|
52
49
|
/** The i flag, which modifier groups override. */
|
|
53
50
|
readonly flagIgnoreCase: boolean;
|
|
54
|
-
readonly flagDotAll: boolean;
|
|
55
|
-
/** u or v: elements consume code points, not UTF-16 units. */
|
|
56
|
-
readonly unicode: boolean;
|
|
57
|
-
readonly unicodeSets: boolean;
|
|
58
51
|
readonly multilineAnchors: boolean;
|
|
59
52
|
/** Translating a group as the text a backreference repeats, away from where it matched. */
|
|
60
53
|
readonly repeated: boolean;
|
|
@@ -70,7 +63,7 @@ const INNER: Position = { first: false, last: false };
|
|
|
70
63
|
const intersects = (ranges: Ranges, other: Ranges) => intersect(ranges, other).length !== 0;
|
|
71
64
|
|
|
72
65
|
const folded = (ranges: Ranges, ctx: Context): Ranges =>
|
|
73
|
-
ctx.ignoreCase ? foldRanges(ranges
|
|
66
|
+
ctx.ignoreCase ? foldRanges(ranges) : ranges;
|
|
74
67
|
|
|
75
68
|
/** One code point in an rg pattern; every non-word character is a code point escape. */
|
|
76
69
|
export const rgCodePoint = (point: number) =>
|
|
@@ -84,12 +77,12 @@ function classPattern(ranges: Ranges): string {
|
|
|
84
77
|
}
|
|
85
78
|
|
|
86
79
|
/**
|
|
87
|
-
* One consuming element over the units
|
|
88
|
-
*
|
|
89
|
-
*
|
|
80
|
+
* One consuming element over the UTF-16 units it can match. U+FFFD may be malformed bytes.
|
|
81
|
+
* A surrogate may be half of a supplementary character: the element then consumes the whole
|
|
82
|
+
* character or nothing, and its neighbour consumes the other half.
|
|
90
83
|
*/
|
|
91
|
-
function unit(ranges: Ranges
|
|
92
|
-
const halves =
|
|
84
|
+
function unit(ranges: Ranges): string {
|
|
85
|
+
const halves = intersects(ranges, SURROGATES);
|
|
93
86
|
let scalars = subtract(ranges, [[LF, LF], ...SURROGATES]);
|
|
94
87
|
if (halves) scalars = normalize([...scalars, ...SUPPLEMENTARY]);
|
|
95
88
|
const alternatives = [
|
|
@@ -114,9 +107,9 @@ function flagAt(node: AST.Node, flag: "ignoreCase" | "dotAll", patternFlag: bool
|
|
|
114
107
|
const ignoreCaseAt = (node: AST.Node, ctx: Context) =>
|
|
115
108
|
flagAt(node, "ignoreCase", ctx.flagIgnoreCase);
|
|
116
109
|
|
|
110
|
+
/** Grep regexes have no s flag; only a modifier group sets dotAll. */
|
|
117
111
|
function nativeFlags(node: AST.Node, ctx: Context): string {
|
|
118
|
-
|
|
119
|
-
return `${ignoreCaseAt(node, ctx) ? "i" : ""}${dotAll ? "s" : ""}${ctx.unicodeSets ? "v" : ctx.unicode ? "u" : ""}`;
|
|
112
|
+
return `${ignoreCaseAt(node, ctx) ? "i" : ""}${flagAt(node, "dotAll", false) ? "s" : ""}`;
|
|
120
113
|
}
|
|
121
114
|
|
|
122
115
|
function scalarRanges(node: CharacterNode, ctx: Context): Ranges {
|
|
@@ -128,42 +121,9 @@ function scalarRanges(node: CharacterNode, ctx: Context): Ranges {
|
|
|
128
121
|
const choice = (patterns: readonly string[]): string =>
|
|
129
122
|
patterns.length === 0 ? NEVER : patterns.length === 1 ? patterns[0] : `(?:${patterns.join("|")})`;
|
|
130
123
|
|
|
131
|
-
/** Factor common prefixes without dropping an alternative or cutting a code point escape. */
|
|
132
|
-
function wordTree(words: readonly (readonly number[])[], ctx: Context): string {
|
|
133
|
-
const branches = new Map<number, number[][]>();
|
|
134
|
-
let empty = false;
|
|
135
|
-
for (const word of words) {
|
|
136
|
-
if (!word.length) {
|
|
137
|
-
empty = true;
|
|
138
|
-
continue;
|
|
139
|
-
}
|
|
140
|
-
const branch = branches.get(word[0]) ?? [];
|
|
141
|
-
branch.push(word.slice(1));
|
|
142
|
-
branches.set(word[0], branch);
|
|
143
|
-
}
|
|
144
|
-
const patterns = [...branches].map(
|
|
145
|
-
([point, tails]) => unit(folded([[point, point]], ctx), ctx) + wordTree(tails, ctx),
|
|
146
|
-
);
|
|
147
|
-
if (empty) patterns.push("");
|
|
148
|
-
return choice(patterns);
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
function stringPattern(strings: readonly string[], ctx: Context): string {
|
|
152
|
-
const words = [...new Set(strings)].map((text) => [...text].map((char) => char.codePointAt(0)!));
|
|
153
|
-
const size = words.reduce((sum, word) => sum + Math.max(1, word.length), 0);
|
|
154
|
-
return size <= MAX_EXPANDED_STRING_POINTS ? wordTree(words, ctx) : ANY_TEXT;
|
|
155
|
-
}
|
|
156
|
-
|
|
157
124
|
function characterPattern(node: CharacterNode, ctx: Context): string {
|
|
158
|
-
const accepted = acceptedClassStrings(node, nativeFlags(node, ctx));
|
|
159
|
-
if (!accepted) return ANY_TEXT;
|
|
160
125
|
const ranges = scalarRanges(node, ctx);
|
|
161
|
-
return
|
|
162
|
-
...(ranges.length ? [unit(ranges, ctx)] : []),
|
|
163
|
-
...(accepted.length
|
|
164
|
-
? [stringPattern(accepted, { ...ctx, ignoreCase: ctx.ignoreCase || ignoreCaseAt(node, ctx) })]
|
|
165
|
-
: []),
|
|
166
|
-
]);
|
|
126
|
+
return ranges.length ? unit(ranges) : NEVER;
|
|
167
127
|
}
|
|
168
128
|
|
|
169
129
|
function assertion(node: AST.Assertion, ctx: Context, position: Position): string {
|
|
@@ -181,12 +141,10 @@ function assertion(node: AST.Assertion, ctx: Context, position: Position): strin
|
|
|
181
141
|
if (!position.last) return "";
|
|
182
142
|
return ctx.multilineAnchors ? `(?:${TERMINATORS}|\\r?$)` : "\\r?$";
|
|
183
143
|
case "word":
|
|
184
|
-
// JavaScript and rg agree on ASCII word boundaries over valid text and malformed bytes
|
|
185
|
-
//
|
|
186
|
-
//
|
|
187
|
-
|
|
188
|
-
if (node.negate) return ctx.unicode ? "(?-u:\\B)" : "";
|
|
189
|
-
return "(?-u:\\b)";
|
|
144
|
+
// JavaScript and rg agree on ASCII word boundaries over valid text and malformed bytes;
|
|
145
|
+
// \B also holds between the two halves of a supplementary character, which rg consumes
|
|
146
|
+
// as one.
|
|
147
|
+
return node.negate ? "" : "(?-u:\\b)";
|
|
190
148
|
default:
|
|
191
149
|
if (!node.negate && position.first && position.last)
|
|
192
150
|
return alternatives(node.alternatives, ctx, INNER);
|
|
@@ -231,11 +189,11 @@ function participates(group: AST.CapturingGroup, reference: AST.Backreference):
|
|
|
231
189
|
for (let node: AST.Node | null = group; node; node = node.parent) ancestors.add(node);
|
|
232
190
|
let referenceChild: AST.Node = reference;
|
|
233
191
|
let common: AST.Node | null = reference.parent;
|
|
234
|
-
while (
|
|
192
|
+
while (!ancestors.has(common)) {
|
|
235
193
|
referenceChild = common;
|
|
236
194
|
common = common.parent;
|
|
237
195
|
}
|
|
238
|
-
if (common
|
|
196
|
+
if (common.type !== "Alternative") return false;
|
|
239
197
|
let groupChild: AST.Node = group;
|
|
240
198
|
for (let node: AST.Node = group.parent; node !== common; node = node.parent!) {
|
|
241
199
|
const kept =
|
|
@@ -284,7 +242,7 @@ function element(node: AST.Element, ctx: Context, position: Position): string {
|
|
|
284
242
|
switch (node.type) {
|
|
285
243
|
case "Character":
|
|
286
244
|
if (node.value === LF) return NEVER;
|
|
287
|
-
return unit(folded([[node.value, node.value]], ctx)
|
|
245
|
+
return unit(folded([[node.value, node.value]], ctx));
|
|
288
246
|
case "CharacterClass":
|
|
289
247
|
case "ExpressionCharacterClass":
|
|
290
248
|
case "CharacterSet":
|
|
@@ -307,7 +265,7 @@ function alternatives(nodes: readonly AST.Alternative[], ctx: Context, position:
|
|
|
307
265
|
nodes.map(({ elements }) => {
|
|
308
266
|
let pattern = "";
|
|
309
267
|
for (let index = 0; index < elements.length; index++) {
|
|
310
|
-
const pair =
|
|
268
|
+
const pair = surrogatePair(elements[index], elements[index + 1]);
|
|
311
269
|
if (pair !== undefined) {
|
|
312
270
|
pattern += classPattern([[pair, pair]]);
|
|
313
271
|
index++;
|
|
@@ -329,27 +287,21 @@ function alternatives(nodes: readonly AST.Alternative[], ctx: Context, position:
|
|
|
329
287
|
*/
|
|
330
288
|
export function lineCandidatePatterns(query: GrepQuery): string[] | undefined {
|
|
331
289
|
const ctx: Context = {
|
|
332
|
-
ignoreCase: query.
|
|
333
|
-
flagIgnoreCase: query.
|
|
334
|
-
|
|
335
|
-
unicode: query.flags.includes("u") || query.flags.includes("v"),
|
|
336
|
-
unicodeSets: query.flags.includes("v"),
|
|
337
|
-
multilineAnchors: query.flags.includes("m"),
|
|
290
|
+
ignoreCase: query.ignoreCase,
|
|
291
|
+
flagIgnoreCase: query.ignoreCase,
|
|
292
|
+
multilineAnchors: GREP_FLAGS.includes("m"),
|
|
338
293
|
repeated: false,
|
|
339
294
|
};
|
|
340
295
|
const patterns: string[] = [];
|
|
296
|
+
let argumentUnits = 0;
|
|
341
297
|
for (const pattern of query.patterns) {
|
|
342
|
-
const translated = analyzeQueryPattern(pattern, query.literal,
|
|
298
|
+
const translated = analyzeQueryPattern(pattern, query.literal, (parsed) =>
|
|
343
299
|
alternatives(parsed.alternatives, ctx, { first: true, last: true }),
|
|
344
300
|
);
|
|
345
301
|
if (translated === undefined) return undefined;
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
)
|
|
350
|
-
return undefined;
|
|
351
|
-
// A sticky match starts where the line starts.
|
|
352
|
-
patterns.push(query.flags.includes("y") ? `^(?:${translated})` : translated);
|
|
302
|
+
argumentUnits += rgPatternArgUnits(translated);
|
|
303
|
+
if (argumentUnits > MAX_RG_PATTERN_UNITS) return undefined;
|
|
304
|
+
patterns.push(translated);
|
|
353
305
|
}
|
|
354
306
|
return patterns;
|
|
355
307
|
}
|
|
@@ -43,6 +43,7 @@ test("streamed lines preserve BOM, standalone CR, and boundaries split across ch
|
|
|
43
43
|
assert.equal(line.byteLength, Buffer.byteLength(line.text!));
|
|
44
44
|
lines.push(line.text!);
|
|
45
45
|
},
|
|
46
|
+
{},
|
|
46
47
|
);
|
|
47
48
|
assert.deepEqual(lines, splitLines(text));
|
|
48
49
|
assert.equal(stats.totalLines, lines.length);
|
|
@@ -76,6 +77,7 @@ test("streamed scans → return the revision of every original byte and byte-bas
|
|
|
76
77
|
path,
|
|
77
78
|
(number) => number === 1,
|
|
78
79
|
() => {},
|
|
80
|
+
{},
|
|
79
81
|
);
|
|
80
82
|
assert.equal(selected.revision, stats.revision);
|
|
81
83
|
}
|
|
@@ -110,6 +112,7 @@ test("streamed validation checks the entire file and gives NUL precedence over m
|
|
|
110
112
|
path,
|
|
111
113
|
(number) => number === 1,
|
|
112
114
|
() => {},
|
|
115
|
+
{},
|
|
113
116
|
),
|
|
114
117
|
(error: unknown) => error instanceof Utf8DecodingError,
|
|
115
118
|
);
|
package/src/pi/text-stream.ts
CHANGED
|
@@ -109,7 +109,7 @@ export async function scanTextLines(
|
|
|
109
109
|
readonly signal?: AbortSignal;
|
|
110
110
|
readonly maxLineBytes?: number;
|
|
111
111
|
readonly decoding?: Utf8Decoding;
|
|
112
|
-
}
|
|
112
|
+
},
|
|
113
113
|
) {
|
|
114
114
|
const { signal, decoding, maxLineBytes: maxBytes = Infinity } = options;
|
|
115
115
|
let number = 1;
|