@criogaid/pi-hashline-edit 0.8.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 +13 -10
- package/README.zh-CN.md +12 -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 +118 -293
- package/src/core/apply.ts +63 -165
- 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/ranges.test.ts +16 -8
- package/src/core/ranges.ts +10 -6
- 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/config-registration.test.ts +2 -2
- 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 +123 -25
- 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 +13 -3
- package/src/integration/mutation-file-types.testing.ts +1 -1
- package/src/integration/npm-package.testing.ts +1 -1
- package/src/integration/publication-read-changes.test.ts +125 -47
- package/src/integration/replace-worker-boundary.test.ts +21 -11
- package/src/integration/report-replay.test.ts +21 -23
- package/src/integration/utf8-errors.test.ts +1 -1
- package/src/pi/AGENTS.md +16 -16
- package/src/pi/action-fusion.test.ts +168 -300
- 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 +52 -207
- package/src/pi/argument-error.ts +2 -1
- package/src/pi/argument-format.test.ts +20 -22
- package/src/pi/argument-validation.test.ts +382 -418
- 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 +173 -226
- package/src/pi/error-text.ts +4 -8
- package/src/pi/execute.test.ts +165 -266
- package/src/pi/failure-context.test.ts +144 -126
- package/src/pi/failure-context.ts +45 -94
- 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 +81 -46
- 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 +38 -16
- package/src/pi/path.ts +1 -1
- package/src/pi/pi.test.ts +3 -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 +82 -20
- package/src/pi/render.test.ts +79 -42
- package/src/pi/render.ts +69 -63
- package/src/pi/replace-regex.ts +14 -2
- package/src/pi/replace-tool.ts +22 -83
- 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 +65 -81
- package/src/pi/report.test.ts +171 -25
- package/src/pi/report.ts +33 -87
- package/src/pi/result-safety.test.ts +177 -189
- 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/core/hash.ts
CHANGED
|
@@ -28,8 +28,8 @@ export const HASH_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
|
28
28
|
* distributed, non-cryptographic. Uses `Math.imul` for correct 32-bit integer
|
|
29
29
|
* multiplication under JS.
|
|
30
30
|
*/
|
|
31
|
-
function fnv1a32(str: string
|
|
32
|
-
let h =
|
|
31
|
+
function fnv1a32(str: string): number {
|
|
32
|
+
let h = 0x811c9dc5;
|
|
33
33
|
for (let i = 0; i < str.length; i++) {
|
|
34
34
|
h ^= str.charCodeAt(i);
|
|
35
35
|
h = Math.imul(h, 0x01000193);
|
|
@@ -37,26 +37,6 @@ function fnv1a32(str: string, seed = 0x811c9dc5): number {
|
|
|
37
37
|
return h >>> 0;
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
-
/**
|
|
41
|
-
* Compute the FNV-1a 32-bit hash of `${line}\n${content}` without allocating
|
|
42
|
-
* the intermediate template string.
|
|
43
|
-
*/
|
|
44
|
-
function fnv1a32Line(line: number, content: string): number {
|
|
45
|
-
let h = 0x811c9dc5;
|
|
46
|
-
// Feed digit characters of the line number without String(line) allocation.
|
|
47
|
-
let n = line;
|
|
48
|
-
let divisor = 1;
|
|
49
|
-
while (divisor * 10 <= n) divisor *= 10;
|
|
50
|
-
while (divisor >= 1) {
|
|
51
|
-
h ^= (((n / divisor) | 0) % 10) + 48;
|
|
52
|
-
h = Math.imul(h, 0x01000193);
|
|
53
|
-
divisor = (divisor / 10) | 0;
|
|
54
|
-
}
|
|
55
|
-
h ^= 10;
|
|
56
|
-
h = Math.imul(h, 0x01000193);
|
|
57
|
-
return fnv1a32(content, h);
|
|
58
|
-
}
|
|
59
|
-
|
|
60
40
|
/**
|
|
61
41
|
* Encode a 32-bit integer into a base32 string of the given length.
|
|
62
42
|
*
|
|
@@ -84,5 +64,5 @@ export const HASH_LEN_MAX = 8;
|
|
|
84
64
|
* @param len caller-selected hash length
|
|
85
65
|
*/
|
|
86
66
|
export function computeLineHash(line: number, content: string, len: number): string {
|
|
87
|
-
return toBase32(
|
|
67
|
+
return toBase32(fnv1a32(`${line}\n${content}`), len);
|
|
88
68
|
}
|
package/src/core/lines.ts
CHANGED
|
@@ -16,8 +16,6 @@
|
|
|
16
16
|
* @module pi-hashline-edit/core
|
|
17
17
|
*/
|
|
18
18
|
|
|
19
|
-
import type { LineEnding } from "./types.ts";
|
|
20
|
-
|
|
21
19
|
/** Normalize CRLF boundaries to LF; standalone CR remains content. */
|
|
22
20
|
export function normalizeLineEndings(text: string): string {
|
|
23
21
|
return text.replace(/\r\n/g, "\n");
|
|
@@ -69,7 +67,7 @@ export function restoreLineEndings(logical: string, original: string, fallback:
|
|
|
69
67
|
/** Build an LF matching view with UTF-16 boundary offsets back into the original text. */
|
|
70
68
|
export function createLfTextView(source: string) {
|
|
71
69
|
const removed: number[] = [];
|
|
72
|
-
for (const match of source.matchAll(/\r\n/g)) removed.push(match.index
|
|
70
|
+
for (const match of source.matchAll(/\r\n/g)) removed.push(match.index - removed.length);
|
|
73
71
|
return {
|
|
74
72
|
text: normalizeLineEndings(source),
|
|
75
73
|
sourceOffset(offset: number): number {
|
|
@@ -103,7 +101,7 @@ export function splitLines(text: string): string[] {
|
|
|
103
101
|
}
|
|
104
102
|
|
|
105
103
|
/** Whether the text uses CRLF at all (any `\r\n` counts; mixed files report "crlf"). */
|
|
106
|
-
export function detectLineEnding(text: string):
|
|
104
|
+
export function detectLineEnding(text: string): "lf" | "crlf" {
|
|
107
105
|
return text.includes("\r\n") ? "crlf" : "lf";
|
|
108
106
|
}
|
|
109
107
|
|
package/src/core/ranges.test.ts
CHANGED
|
@@ -2,7 +2,7 @@ import assert from "node:assert/strict";
|
|
|
2
2
|
import { test } from "node:test";
|
|
3
3
|
import { findSortedRangeConflict, mergeRanges, type HalfOpenRange } from "./ranges.ts";
|
|
4
4
|
|
|
5
|
-
test("sorted ranges
|
|
5
|
+
test("sorted ranges sharing or crossing boundaries → report conflicts according to insertion policy", () => {
|
|
6
6
|
const cases: [HalfOpenRange[], number | undefined, number | undefined][] = [
|
|
7
7
|
[[], undefined, undefined],
|
|
8
8
|
[
|
|
@@ -27,7 +27,7 @@ test("sorted ranges → ordered starts allow only empty ranges before a shared s
|
|
|
27
27
|
[0, 0],
|
|
28
28
|
],
|
|
29
29
|
1,
|
|
30
|
-
|
|
30
|
+
1,
|
|
31
31
|
],
|
|
32
32
|
[
|
|
33
33
|
[
|
|
@@ -44,7 +44,7 @@ test("sorted ranges → ordered starts allow only empty ranges before a shared s
|
|
|
44
44
|
[0, 2],
|
|
45
45
|
],
|
|
46
46
|
1,
|
|
47
|
-
|
|
47
|
+
1,
|
|
48
48
|
],
|
|
49
49
|
[
|
|
50
50
|
[
|
|
@@ -70,6 +70,14 @@ test("sorted ranges → ordered starts allow only empty ranges before a shared s
|
|
|
70
70
|
1,
|
|
71
71
|
1,
|
|
72
72
|
],
|
|
73
|
+
[
|
|
74
|
+
[
|
|
75
|
+
[0, 2],
|
|
76
|
+
[0, 2],
|
|
77
|
+
],
|
|
78
|
+
1,
|
|
79
|
+
1,
|
|
80
|
+
],
|
|
73
81
|
[
|
|
74
82
|
[
|
|
75
83
|
[0, 1],
|
|
@@ -80,17 +88,17 @@ test("sorted ranges → ordered starts allow only empty ranges before a shared s
|
|
|
80
88
|
2,
|
|
81
89
|
],
|
|
82
90
|
];
|
|
83
|
-
for (const [ranges, strictConflict,
|
|
84
|
-
for (const
|
|
85
|
-
const expected =
|
|
91
|
+
for (const [ranges, strictConflict, insertionBeforeRangeConflict] of cases) {
|
|
92
|
+
for (const insertBeforeRange of [false, true]) {
|
|
93
|
+
const expected = insertBeforeRange ? insertionBeforeRangeConflict : strictConflict;
|
|
86
94
|
for (const shift of [0, 10]) {
|
|
87
95
|
assert.equal(
|
|
88
96
|
findSortedRangeConflict(
|
|
89
97
|
ranges.map(([start, end]) => [start + shift, end + shift]),
|
|
90
|
-
|
|
98
|
+
insertBeforeRange,
|
|
91
99
|
),
|
|
92
100
|
expected,
|
|
93
|
-
JSON.stringify({ ranges,
|
|
101
|
+
JSON.stringify({ ranges, insertBeforeRange, shift }),
|
|
94
102
|
);
|
|
95
103
|
}
|
|
96
104
|
}
|
package/src/core/ranges.ts
CHANGED
|
@@ -2,19 +2,23 @@
|
|
|
2
2
|
export type HalfOpenRange = readonly [start: number, end: number];
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
|
-
* Find the first conflicting pair's second index. Input must be sorted by start, then end
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* is set; then it applies
|
|
5
|
+
* Find the first conflicting pair's second index. Input must be sorted by start, then end.
|
|
6
|
+
* A range starting inside an earlier non-empty range conflicts, and so do two insertions
|
|
7
|
+
* (empty ranges) at one position. An insertion at the start of a non-empty range also
|
|
8
|
+
* conflicts unless `insertBeforeRange` is set; then it applies before that range.
|
|
9
9
|
*/
|
|
10
10
|
export function findSortedRangeConflict(
|
|
11
11
|
ranges: readonly HalfOpenRange[],
|
|
12
|
-
|
|
12
|
+
insertBeforeRange = false,
|
|
13
13
|
): number | undefined {
|
|
14
14
|
for (let i = 1; i < ranges.length; i++) {
|
|
15
15
|
const previous = ranges[i - 1];
|
|
16
16
|
const current = ranges[i];
|
|
17
|
-
if (
|
|
17
|
+
if (
|
|
18
|
+
current[0] < previous[1] ||
|
|
19
|
+
(current[0] === previous[0] && (!insertBeforeRange || current[1] === previous[1]))
|
|
20
|
+
)
|
|
21
|
+
return i;
|
|
18
22
|
}
|
|
19
23
|
return undefined;
|
|
20
24
|
}
|
package/src/core/regex.ts
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
/** JavaScript regex construction on the shared LF view, used by both grep and replace. */
|
|
2
2
|
import { errorMessage } from "./errors.ts";
|
|
3
3
|
import { normalizeLineEndings } from "./lines.ts";
|
|
4
|
-
import { escapeRegex } from "./text.ts";
|
|
5
4
|
|
|
6
5
|
/** JavaScript regex source on the shared LF view; literal text matches exactly. */
|
|
7
6
|
export function regexSource(find: string, literal: boolean): string {
|
|
8
7
|
const logical = normalizeLineEndings(find);
|
|
9
|
-
return literal ?
|
|
8
|
+
return literal ? logical.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") : logical;
|
|
10
9
|
}
|
|
11
10
|
|
|
12
11
|
/**
|
|
@@ -24,7 +23,7 @@ export function buildRegex(find: string, literal: boolean, flagsRaw: string | un
|
|
|
24
23
|
/**
|
|
25
24
|
* Report V8's diagnostics for a rule's flags and, in regex mode, for each pattern that
|
|
26
25
|
* buildRegex would reject. Invalid flags stop the check, since every pattern compiles with
|
|
27
|
-
* them; values that are not
|
|
26
|
+
* them; values that are not strings are left to schema validation.
|
|
28
27
|
*/
|
|
29
28
|
export function checkRegexArguments(
|
|
30
29
|
flagsField: string,
|
|
@@ -41,7 +40,7 @@ export function checkRegexArguments(
|
|
|
41
40
|
}
|
|
42
41
|
if (literal) return;
|
|
43
42
|
for (const [field, value] of patterns) {
|
|
44
|
-
if (typeof value !== "string"
|
|
43
|
+
if (typeof value !== "string") continue;
|
|
45
44
|
try {
|
|
46
45
|
buildRegex(value, false, flags);
|
|
47
46
|
} catch (error) {
|
package/src/core/replace.test.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { test } from "node:test";
|
|
2
2
|
import assert from "node:assert/strict";
|
|
3
|
-
import { applyReplacements
|
|
3
|
+
import { applyReplacements } from "./replace.ts";
|
|
4
|
+
import type { Replacement } from "./replace-schema.ts";
|
|
5
|
+
import { HashlineError } from "./errors.ts";
|
|
4
6
|
|
|
5
7
|
test("replacement joins beside LF → preserve standalone CR content", async (t) => {
|
|
6
8
|
const literal = (find: string, replace: string): Replacement => ({
|
|
@@ -88,3 +90,47 @@ test("replacement joins beside LF → preserve standalone CR content", async (t)
|
|
|
88
90
|
});
|
|
89
91
|
}
|
|
90
92
|
});
|
|
93
|
+
|
|
94
|
+
test("replacement rejection → reports all unmatched rules or the conflicting rule pair and line", async (t) => {
|
|
95
|
+
const literal = (find: string): Replacement => ({ find, replace: "x", literal: true });
|
|
96
|
+
const cases = [
|
|
97
|
+
{
|
|
98
|
+
name: "multiple unmatched rules",
|
|
99
|
+
source: "present",
|
|
100
|
+
rules: [literal("missing"), literal("present"), literal("absent")],
|
|
101
|
+
code: "NO_MATCH",
|
|
102
|
+
message: "Rules match nothing in the file.",
|
|
103
|
+
facts: { unmatched: ["replacements[0]", "replacements[2]"] },
|
|
104
|
+
},
|
|
105
|
+
...["\n", "\r\n"].map((eol) => ({
|
|
106
|
+
name: `overlap in reversed input order with ${JSON.stringify(eol)}`,
|
|
107
|
+
source: `head${eol}abcd${eol}tail`,
|
|
108
|
+
rules: [literal("cd"), literal("bc")],
|
|
109
|
+
code: "OVERLAPPING_MATCHES",
|
|
110
|
+
message: "Matches of two rules overlap.",
|
|
111
|
+
facts: { conflict: ["replacements[0]", "replacements[1]"], line: 2 },
|
|
112
|
+
})),
|
|
113
|
+
{
|
|
114
|
+
name: "overlap on first line",
|
|
115
|
+
source: "abcd",
|
|
116
|
+
rules: [literal("ab"), literal("bc")],
|
|
117
|
+
code: "OVERLAPPING_MATCHES",
|
|
118
|
+
message: "Matches of two rules overlap.",
|
|
119
|
+
facts: { conflict: ["replacements[0]", "replacements[1]"], line: 1 },
|
|
120
|
+
},
|
|
121
|
+
];
|
|
122
|
+
for (const { name, source, rules, code, message, facts } of cases) {
|
|
123
|
+
await t.test(name, () => {
|
|
124
|
+
assert.throws(
|
|
125
|
+
() => applyReplacements(source, rules),
|
|
126
|
+
(error: unknown) => {
|
|
127
|
+
assert.ok(error instanceof HashlineError);
|
|
128
|
+
assert.equal(error.errorCode, code);
|
|
129
|
+
assert.equal(error.message, message);
|
|
130
|
+
assert.deepEqual(error.facts, facts);
|
|
131
|
+
return true;
|
|
132
|
+
},
|
|
133
|
+
);
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
});
|
package/src/core/replace.ts
CHANGED
|
@@ -19,10 +19,9 @@ import { findSortedRangeConflict } from "./ranges.ts";
|
|
|
19
19
|
import { HashlineError } from "./errors.ts";
|
|
20
20
|
|
|
21
21
|
import type { Replacement, ReplacementResult } from "./replace-schema.ts";
|
|
22
|
-
export type { Replacement } from "./replace-schema.ts";
|
|
23
22
|
|
|
24
23
|
/** Expand JS replacement tokens against the original match, including prefix/suffix context. */
|
|
25
|
-
function expandReplacement(template: string, match:
|
|
24
|
+
function expandReplacement(template: string, match: RegExpExecArray, source: string): string {
|
|
26
25
|
// Without named captures, $<...> is ordinary text and may contain other $ tokens.
|
|
27
26
|
const tokens =
|
|
28
27
|
match.groups === undefined ? /\$(\$|&|`|'|\d{1,2})/g : /\$(\$|&|`|'|<[^>]*>|\d{1,2})/g;
|
|
@@ -30,9 +29,8 @@ function expandReplacement(template: string, match: RegExpMatchArray, source: st
|
|
|
30
29
|
if (key === "$") return "$";
|
|
31
30
|
if (key === "&") return match[0];
|
|
32
31
|
if (key === "`") return source.slice(0, match.index);
|
|
33
|
-
if (key === "'") return source.slice(match.index
|
|
34
|
-
if (key.startsWith("<"))
|
|
35
|
-
return match.groups === undefined ? token : (match.groups[key.slice(1, -1)] ?? "");
|
|
32
|
+
if (key === "'") return source.slice(match.index + match[0].length);
|
|
33
|
+
if (key.startsWith("<")) return match.groups![key.slice(1, -1)] ?? "";
|
|
36
34
|
const index = Number(key);
|
|
37
35
|
if (index > 0 && index < match.length) return match[index] ?? "";
|
|
38
36
|
// $12 falls back to capture 1 plus literal 2 when capture 12 does not exist.
|
|
@@ -42,6 +40,9 @@ function expandReplacement(template: string, match: RegExpMatchArray, source: st
|
|
|
42
40
|
});
|
|
43
41
|
}
|
|
44
42
|
|
|
43
|
+
/** A rule's field in the tool's arguments, as argument issues name it. */
|
|
44
|
+
const ruleField = (index: number): string => `replacements[${index}]`;
|
|
45
|
+
|
|
45
46
|
export function applyReplacements(
|
|
46
47
|
source: string,
|
|
47
48
|
rules: readonly Replacement[],
|
|
@@ -49,14 +50,15 @@ export function applyReplacements(
|
|
|
49
50
|
const changes: { start: number; end: number; text: string; rule: number }[] = [];
|
|
50
51
|
const view = createLfTextView(source);
|
|
51
52
|
const fallbackEnding = detectLineEnding(source) === "crlf" ? "\r\n" : "\n";
|
|
53
|
+
const unmatched: string[] = [];
|
|
52
54
|
for (const [index, rule] of rules.entries()) {
|
|
53
55
|
const regex = buildRegex(rule.find, rule.literal, rule.flags);
|
|
54
56
|
let count = 0;
|
|
55
57
|
const replacement = normalizeLineEndings(rule.replace);
|
|
56
58
|
for (const match of view.text.matchAll(regex)) {
|
|
57
59
|
count++;
|
|
58
|
-
const start = view.sourceOffset(match.index
|
|
59
|
-
const end = view.sourceOffset(match.index
|
|
60
|
+
const start = view.sourceOffset(match.index);
|
|
61
|
+
const end = view.sourceOffset(match.index + match[0].length);
|
|
60
62
|
changes.push({
|
|
61
63
|
start,
|
|
62
64
|
end,
|
|
@@ -68,18 +70,22 @@ export function applyReplacements(
|
|
|
68
70
|
),
|
|
69
71
|
});
|
|
70
72
|
}
|
|
71
|
-
if (count === 0)
|
|
72
|
-
throw new HashlineError("NO_MATCH", "The rule matches nothing in the file.", {
|
|
73
|
-
facts: { rule: index },
|
|
74
|
-
});
|
|
73
|
+
if (count === 0) unmatched.push(ruleField(index));
|
|
75
74
|
}
|
|
75
|
+
if (unmatched.length)
|
|
76
|
+
throw new HashlineError("NO_MATCH", "Rules match nothing in the file.", {
|
|
77
|
+
facts: { unmatched },
|
|
78
|
+
});
|
|
76
79
|
changes.sort((a, b) => a.start - b.start || a.end - b.end);
|
|
77
80
|
const conflict = findSortedRangeConflict(changes.map((change) => [change.start, change.end]));
|
|
78
81
|
if (conflict !== undefined) {
|
|
79
82
|
const previous = changes[conflict - 1];
|
|
80
83
|
const current = changes[conflict];
|
|
81
|
-
throw new HashlineError("OVERLAPPING_MATCHES", "Matches of
|
|
82
|
-
facts: {
|
|
84
|
+
throw new HashlineError("OVERLAPPING_MATCHES", "Matches of two rules overlap.", {
|
|
85
|
+
facts: {
|
|
86
|
+
conflict: [previous.rule, current.rule].sort((a, b) => a - b).map(ruleField),
|
|
87
|
+
line: source.slice(0, current.start).split("\n").length,
|
|
88
|
+
},
|
|
83
89
|
});
|
|
84
90
|
}
|
|
85
91
|
const parts: string[] = [];
|
|
@@ -38,6 +38,10 @@ for (const [pattern, flags, expected] of [
|
|
|
38
38
|
],
|
|
39
39
|
["é", "miu", [[["É", "é"]]]],
|
|
40
40
|
["[\\u0100-\\u0200]", "m", undefined],
|
|
41
|
+
["foo.*bar", "m", [literal("foo")]],
|
|
42
|
+
["(?:abcdef.*xy|zz.*ghijkl)", "m", [literal("abcdef"), literal("ghijkl")]],
|
|
43
|
+
["foo|bar.*baz", "m", [literal("foo"), literal("bar")]],
|
|
44
|
+
["(?=foo|bar).*baz", "m", [literal("baz")]],
|
|
41
45
|
] as const) {
|
|
42
46
|
test(`${pattern.slice(0, 80)} /${flags} → conservative candidate literals`, () => {
|
|
43
47
|
assert.deepEqual(
|
|
@@ -49,29 +53,30 @@ for (const [pattern, flags, expected] of [
|
|
|
49
53
|
|
|
50
54
|
for (const boundary of ["\n", "\r\n", "\uFFFD", "\uD800", "\uDC00", "\0"]) {
|
|
51
55
|
test(`literal ${JSON.stringify(boundary)} boundary → no candidate spans changed bytes`, () => {
|
|
52
|
-
const prefilter = extractPrefilter(query(`left${boundary}
|
|
53
|
-
assert.
|
|
54
|
-
assert.ok(hasCandidateBytes(Buffer.from(
|
|
56
|
+
const prefilter = extractPrefilter(query(`left${boundary}right`, "m", true));
|
|
57
|
+
assert.deepEqual(prefilter, { kind: "literals", literals: [literal("right")] });
|
|
58
|
+
assert.ok(hasCandidateBytes(Buffer.from(`left${boundary}right`), prefilter));
|
|
59
|
+
assert.ok(hasCandidateBytes(Buffer.from("left\nright"), prefilter));
|
|
55
60
|
assert.equal(hasCandidateBytes(Buffer.from("left"), prefilter), false);
|
|
56
|
-
assert.
|
|
61
|
+
assert.ok(hasCandidateBytes(Buffer.from("right"), prefilter));
|
|
57
62
|
assert.deepEqual(extractPrefilter(query(boundary, "m", true)), { kind: "all" });
|
|
58
63
|
});
|
|
59
64
|
}
|
|
60
65
|
|
|
61
66
|
for (const [patterns, isLiteral, expected, flags] of [
|
|
62
|
-
[["foo", "bar"], false, true],
|
|
63
|
-
[["foo", "Bar"], false, false],
|
|
64
|
-
[["foo\\S*", "\\D", "\\W"], false, true],
|
|
65
|
-
[["\\u0041"], false, false],
|
|
66
|
-
[["\\x41"], false, false],
|
|
67
|
-
[["\\u0061"], false, true],
|
|
68
|
-
[["[A-Z]"], false, false],
|
|
69
|
-
[["(?<UPPER>foo)"], false, true],
|
|
70
|
-
[["ς", "σ"], false, true],
|
|
71
|
-
[["σ", "Σ"], false, false],
|
|
72
|
-
[["foo\\S*"], true, false],
|
|
73
|
-
[["\\u0041"], true, true],
|
|
74
|
-
[["foo", "BAR"], true, false],
|
|
67
|
+
[["foo", "bar"], false, true, ""],
|
|
68
|
+
[["foo", "Bar"], false, false, ""],
|
|
69
|
+
[["foo\\S*", "\\D", "\\W"], false, true, ""],
|
|
70
|
+
[["\\u0041"], false, false, ""],
|
|
71
|
+
[["\\x41"], false, false, ""],
|
|
72
|
+
[["\\u0061"], false, true, ""],
|
|
73
|
+
[["[A-Z]"], false, false, ""],
|
|
74
|
+
[["(?<UPPER>foo)"], false, true, ""],
|
|
75
|
+
[["ς", "σ"], false, true, ""],
|
|
76
|
+
[["σ", "Σ"], false, false, ""],
|
|
77
|
+
[["foo\\S*"], true, false, ""],
|
|
78
|
+
[["\\u0041"], true, true, ""],
|
|
79
|
+
[["foo", "BAR"], true, false, ""],
|
|
75
80
|
[["\\u{41}"], false, false, "u"],
|
|
76
81
|
[["\\u{41}"], false, false, "v"],
|
|
77
82
|
[["\\u{61}"], false, true, "u"],
|
|
@@ -81,7 +86,7 @@ for (const [patterns, isLiteral, expected, flags] of [
|
|
|
81
86
|
[["𐐨"], false, true, "u"],
|
|
82
87
|
[["𐐨"], false, true, "v"],
|
|
83
88
|
] as const) {
|
|
84
|
-
test(`${JSON.stringify(patterns)} literal=${isLiteral} flags=${flags
|
|
89
|
+
test(`${JSON.stringify(patterns)} literal=${isLiteral} flags=${flags} → smart case follows decoded letters`, () => {
|
|
85
90
|
assert.equal(smartIgnoreCase(patterns, isLiteral, flags), expected);
|
|
86
91
|
});
|
|
87
92
|
}
|
|
@@ -180,14 +185,6 @@ test("oversized literal alternation → retains necessary prefixes without dropp
|
|
|
180
185
|
assert.equal(hasCandidateBytes(Buffer.from("unrelated"), prefilter), false);
|
|
181
186
|
});
|
|
182
187
|
|
|
183
|
-
test("AND and OR file conditions → retain each alternative and require each conjunction", () => {
|
|
184
|
-
const prefilter = extractPrefilter(query("(?:foo.*bar|baz.*qux)"));
|
|
185
|
-
for (const value of ["foo\nbar", "baz\nqux"])
|
|
186
|
-
assert.ok(hasCandidateBytes(Buffer.from(value), prefilter));
|
|
187
|
-
for (const value of ["foo", "bar", "baz", "qux", "foo\nqux", "baz\nbar"])
|
|
188
|
-
assert.equal(hasCandidateBytes(Buffer.from(value), prefilter), false, value);
|
|
189
|
-
});
|
|
190
|
-
|
|
191
188
|
test("empty expression with a huge repeat → completes without iterating the repeat count", () => {
|
|
192
189
|
assert.deepEqual(extractPrefilter(query("(?:){1000000000}")), { kind: "all" });
|
|
193
190
|
});
|
|
@@ -202,7 +199,7 @@ test("deeply nested uppercase pattern → smart case stays sensitive and prefilt
|
|
|
202
199
|
for (const depth of [50, 200, 500, 1_000, 2_000, 4_000]) {
|
|
203
200
|
const pattern = `${"(?:".repeat(depth)}A${")".repeat(depth)}`;
|
|
204
201
|
assert.equal(new RegExp(pattern).test("A"), true);
|
|
205
|
-
assert.equal(smartIgnoreCase([pattern], false), false);
|
|
202
|
+
assert.equal(smartIgnoreCase([pattern], false, ""), false);
|
|
206
203
|
assert.equal(hasCandidateBytes(Buffer.from("A"), extractPrefilter(query(pattern))), true);
|
|
207
204
|
}
|
|
208
205
|
});
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Static analysis of grep queries: smart case, and the necessary literals of grep's
|
|
3
3
|
* candidate-file prefilter. Every JavaScript match of the query, on the LF view of a
|
|
4
|
-
* file without NUL,
|
|
4
|
+
* file without NUL, contains one of the returned literals; that text
|
|
5
5
|
* appears unchanged in the file's original bytes. Native RegExp still decides every
|
|
6
6
|
* match; an unknown construct only widens the candidate set, down to every file.
|
|
7
7
|
*
|
|
@@ -27,25 +27,20 @@ interface LiteralFilter {
|
|
|
27
27
|
readonly kind: "literals";
|
|
28
28
|
readonly literals: readonly Literal[];
|
|
29
29
|
}
|
|
30
|
-
export type Prefilter =
|
|
31
|
-
| { readonly kind: "all" }
|
|
32
|
-
| LiteralFilter
|
|
33
|
-
| { readonly kind: "and"; readonly filters: readonly LiteralFilter[] };
|
|
30
|
+
export type Prefilter = { readonly kind: "all" } | LiteralFilter;
|
|
34
31
|
|
|
35
32
|
const ALL: Prefilter = { kind: "all" };
|
|
36
33
|
const MAX_SEQUENCES = 16;
|
|
37
34
|
const MAX_SEQUENCE_LENGTH = 64;
|
|
38
35
|
const MAX_CLASS_CHARS = 64;
|
|
39
36
|
const MAX_LITERALS = 64;
|
|
40
|
-
/** Dropping an AND clause widens safely; no OR alternative may be discarded. */
|
|
41
|
-
const MAX_PREFILTER_CLAUSES = 8;
|
|
42
37
|
|
|
43
38
|
/** Text of unknown length and content: a literal never spans it. */
|
|
44
39
|
const GAP = null;
|
|
45
40
|
type Unit = LiteralChar | typeof GAP;
|
|
46
41
|
type Sequence = readonly Unit[];
|
|
47
42
|
|
|
48
|
-
/** A node's bounded exact texts and necessary
|
|
43
|
+
/** A node's bounded exact texts and necessary condition on original bytes. */
|
|
49
44
|
interface Info {
|
|
50
45
|
readonly exact?: readonly Sequence[];
|
|
51
46
|
readonly filter: Prefilter;
|
|
@@ -105,61 +100,35 @@ function literalFilter(values: readonly Literal[]): Prefilter {
|
|
|
105
100
|
return first === GAP ? ALL : { kind: "literals", literals: [[first]] };
|
|
106
101
|
}
|
|
107
102
|
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
const kept = clauses.filter(
|
|
128
|
-
(clause, index) =>
|
|
129
|
-
!clauses.some(
|
|
130
|
-
(other, at) =>
|
|
131
|
-
at !== index && implies(other, clause) && (!implies(clause, other) || at < index),
|
|
132
|
-
),
|
|
133
|
-
);
|
|
134
|
-
kept.sort(
|
|
135
|
-
(a, b) =>
|
|
136
|
-
Math.min(...b.literals.map((literal) => literal.length)) -
|
|
137
|
-
Math.min(...a.literals.map((literal) => literal.length)) ||
|
|
138
|
-
a.literals.length - b.literals.length,
|
|
139
|
-
);
|
|
140
|
-
const bounded = kept.slice(0, MAX_PREFILTER_CLAUSES);
|
|
141
|
-
return bounded.length === 0
|
|
142
|
-
? ALL
|
|
143
|
-
: bounded.length === 1
|
|
144
|
-
? bounded[0]
|
|
145
|
-
: { kind: "and", filters: bounded };
|
|
103
|
+
/**
|
|
104
|
+
* Of conditions that all hold, the most selective: the longest shortest literal, then the
|
|
105
|
+
* fewest literals. One rg pass per condition costs more than it saves, and dropping a
|
|
106
|
+
* necessary condition only widens the candidates.
|
|
107
|
+
*/
|
|
108
|
+
function strongestFilter(filters: readonly Prefilter[]): Prefilter {
|
|
109
|
+
const shortest = (filter: LiteralFilter) =>
|
|
110
|
+
Math.min(...filter.literals.map((literal) => literal.length));
|
|
111
|
+
let best: Prefilter = ALL;
|
|
112
|
+
for (const filter of filters) {
|
|
113
|
+
if (filter.kind === "all") continue;
|
|
114
|
+
if (
|
|
115
|
+
best.kind === "all" ||
|
|
116
|
+
shortest(filter) > shortest(best) ||
|
|
117
|
+
(shortest(filter) === shortest(best) && filter.literals.length < best.literals.length)
|
|
118
|
+
)
|
|
119
|
+
best = filter;
|
|
120
|
+
}
|
|
121
|
+
return best;
|
|
146
122
|
}
|
|
147
123
|
|
|
124
|
+
/** Any of these conditions may hold, so the result keeps every alternative. */
|
|
148
125
|
function orFilters(filters: readonly Prefilter[]): Prefilter {
|
|
149
|
-
const
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
// Distribution can drop every bounded clause, leaving no condition.
|
|
154
|
-
if (result.kind === "all") return ALL;
|
|
155
|
-
const left = result.kind === "and" ? result.filters : [result];
|
|
156
|
-
const right = filter.kind === "and" ? filter.filters : [filter];
|
|
157
|
-
// CNF distribution creates AND clauses; keeping only bounded clauses is a widening.
|
|
158
|
-
result = andFilters(
|
|
159
|
-
left.flatMap((a) => right.map((b) => literalFilter([...a.literals, ...b.literals]))),
|
|
160
|
-
);
|
|
126
|
+
const literals: Literal[] = [];
|
|
127
|
+
for (const filter of filters) {
|
|
128
|
+
if (filter.kind === "all") return ALL;
|
|
129
|
+
literals.push(...filter.literals);
|
|
161
130
|
}
|
|
162
|
-
return
|
|
131
|
+
return literalFilter(literals);
|
|
163
132
|
}
|
|
164
133
|
|
|
165
134
|
function sequenceFilter(sequences: readonly Sequence[]): Prefilter {
|
|
@@ -174,13 +143,13 @@ function sequenceFilter(sequences: readonly Sequence[]): Prefilter {
|
|
|
174
143
|
run = [];
|
|
175
144
|
}
|
|
176
145
|
}
|
|
177
|
-
return
|
|
146
|
+
return strongestFilter(filters);
|
|
178
147
|
}),
|
|
179
148
|
);
|
|
180
149
|
}
|
|
181
150
|
|
|
182
151
|
const filterOf = (info: Info): Prefilter =>
|
|
183
|
-
info.exact ?
|
|
152
|
+
info.exact ? strongestFilter([info.filter, sequenceFilter(info.exact)]) : info.filter;
|
|
184
153
|
|
|
185
154
|
function cross(left: readonly Sequence[], right: readonly Sequence[]): Sequence[] | undefined {
|
|
186
155
|
if (left.length * right.length > MAX_SEQUENCES) return undefined;
|
|
@@ -208,8 +177,8 @@ function concatenate(infos: readonly Info[]): Info {
|
|
|
208
177
|
run = info.exact ?? [[]];
|
|
209
178
|
}
|
|
210
179
|
return whole
|
|
211
|
-
? { exact: run, filter:
|
|
212
|
-
: { filter:
|
|
180
|
+
? { exact: run, filter: strongestFilter(filters) }
|
|
181
|
+
: { filter: strongestFilter([...filters, sequenceFilter(run)]) };
|
|
213
182
|
}
|
|
214
183
|
|
|
215
184
|
function alternate(infos: readonly Info[]): Info {
|
|
@@ -343,7 +312,7 @@ export function analyzeQueryPattern<T>(
|
|
|
343
312
|
export function smartIgnoreCase(
|
|
344
313
|
patterns: readonly string[],
|
|
345
314
|
literal: boolean,
|
|
346
|
-
flags
|
|
315
|
+
flags: string,
|
|
347
316
|
): boolean {
|
|
348
317
|
return !patterns.some((pattern) => {
|
|
349
318
|
const uppercase = analyzeQueryPattern(pattern, literal, flags, (parsed) => {
|
|
@@ -360,7 +329,7 @@ export function smartIgnoreCase(
|
|
|
360
329
|
});
|
|
361
330
|
}
|
|
362
331
|
|
|
363
|
-
/**
|
|
332
|
+
/** One necessary file condition, its literals bounded; every OR retains all alternatives. */
|
|
364
333
|
export function extractPrefilter(query: GrepQuery): Prefilter {
|
|
365
334
|
const unicode = query.flags.includes("u") || query.flags.includes("v");
|
|
366
335
|
const ctx: Context = {
|
|
@@ -143,8 +143,6 @@ export function acceptsNative(query: GrepQuery): boolean {
|
|
|
143
143
|
/** Match literal bytes directly, without relying on the candidate regex formatter or expanding products. */
|
|
144
144
|
export function hasCandidateBytes(bytes: Buffer, prefilter: Prefilter): boolean {
|
|
145
145
|
if (prefilter.kind === "all") return true;
|
|
146
|
-
if (prefilter.kind === "and")
|
|
147
|
-
return prefilter.filters.every((filter) => hasCandidateBytes(bytes, filter));
|
|
148
146
|
return prefilter.literals.some((literal) => {
|
|
149
147
|
const positions = literal.map((chars) => chars.map((char) => Buffer.from(char)));
|
|
150
148
|
for (let start = 0; start < bytes.length; start++) {
|
package/src/core/search.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { countLines, normalizeLineEndings } from "./lines.ts";
|
|
|
3
3
|
import { buildRegex } from "./regex.ts";
|
|
4
4
|
import type { SearchResult } from "./search-schema.ts";
|
|
5
5
|
|
|
6
|
-
/**
|
|
6
|
+
/** Explicit flags replace this default. */
|
|
7
7
|
export const DEFAULT_GREP_FLAGS = "m";
|
|
8
8
|
|
|
9
9
|
export interface GrepQuery {
|
package/src/core/text.test.ts
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
import { test } from "node:test";
|
|
2
2
|
import assert from "node:assert/strict";
|
|
3
|
-
import { createUtf8Decoder, decodeEditableText,
|
|
3
|
+
import { createUtf8Decoder, decodeEditableText, Utf8DecodingError } from "./text.ts";
|
|
4
4
|
import { HashlineError, TEXT_ERROR_MESSAGES } from "./errors.ts";
|
|
5
5
|
|
|
6
|
-
test("
|
|
6
|
+
test("decodeEditableText rejects malformed input instead of replacing bytes", () => {
|
|
7
7
|
assert.throws(
|
|
8
|
-
() =>
|
|
8
|
+
() => decodeEditableText(Uint8Array.from([0xc3, 0x28])),
|
|
9
9
|
(error: unknown) =>
|
|
10
10
|
error instanceof HashlineError && error.errorCode === "UNSUPPORTED_ENCODING",
|
|
11
11
|
);
|
|
12
12
|
});
|
|
13
13
|
|
|
14
|
-
test("
|
|
15
|
-
assert.equal(
|
|
14
|
+
test("decodeEditableText preserves a leading BOM", () => {
|
|
15
|
+
assert.equal(decodeEditableText(Uint8Array.from([0xef, 0xbb, 0xbf, 0x61])), "\ufeffa");
|
|
16
16
|
});
|
|
17
17
|
|
|
18
18
|
test("decodeEditableText rejects NUL bytes", () => {
|