@criogaid/pi-hashline-edit 0.11.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 +73 -17
- package/README.zh-CN.md +74 -18
- package/package.json +8 -7
- package/src/core/AGENTS.md +2 -2
- package/src/core/apply.test.ts +15 -2
- package/src/core/apply.ts +6 -10
- 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 -32
- package/src/core/replace.test.ts +51 -0
- package/src/core/replace.ts +10 -4
- 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 +28 -3
- 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 +4 -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 +26 -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 +106 -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.test.ts +12 -10
- package/src/integration/npm-package.testing.ts +147 -1
- package/src/integration/replace-package.testing.ts +2 -2
- package/src/integration/report-replay.test.ts +4 -0
- package/src/pi/AGENTS.md +23 -15
- 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 +103 -6
- package/src/pi/argument-validation.ts +55 -31
- 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 +3 -3
- package/src/pi/execute.test.ts +4 -0
- package/src/pi/failure-context.test.ts +24 -3
- 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 +12 -7
- package/src/pi/grep-candidates.test.ts +5 -5
- package/src/pi/grep-candidates.ts +80 -48
- package/src/pi/grep-matrix.test.ts +14 -29
- package/src/pi/grep-order.test.ts +132 -9
- package/src/pi/grep-output.ts +173 -48
- 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 +28 -34
- package/src/pi/grep.test.ts +348 -83
- 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 +4 -5
- 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 +351 -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 +97 -0
- package/src/pi/render.ts +9 -9
- package/src/pi/replace-tool.ts +5 -2
- package/src/pi/report-schema.ts +75 -37
- package/src/pi/report.test.ts +73 -31
- package/src/pi/report.ts +12 -5
- package/src/pi/rg-process.ts +41 -5
- package/src/pi/rg-regex.test.ts +12 -39
- package/src/pi/rg-regex.ts +31 -79
- 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
|
@@ -5,11 +5,6 @@ export type CharacterNode =
|
|
|
5
5
|
| AST.CharacterClass
|
|
6
6
|
| AST.ExpressionCharacterClass
|
|
7
7
|
| AST.CharacterSet;
|
|
8
|
-
type ClassNode =
|
|
9
|
-
| CharacterNode
|
|
10
|
-
| AST.CharacterClassElement
|
|
11
|
-
| AST.ClassIntersection
|
|
12
|
-
| AST.ClassSubtraction;
|
|
13
8
|
/** Sorted, disjoint, inclusive code point intervals. */
|
|
14
9
|
export type Ranges = readonly (readonly [number, number])[];
|
|
15
10
|
export const MAX_UNIT = 0xffff;
|
|
@@ -28,10 +23,7 @@ let cachedRanges = 0;
|
|
|
28
23
|
const nativeSets = new Map<string, Ranges>();
|
|
29
24
|
|
|
30
25
|
/** Without u, two adjacent Character nodes can encode one supplementary code point. */
|
|
31
|
-
export function surrogatePair(
|
|
32
|
-
element: AST.Element,
|
|
33
|
-
next: AST.Element | undefined,
|
|
34
|
-
): number | undefined {
|
|
26
|
+
export function surrogatePair(element: AST.Node, next: AST.Node | undefined): number | undefined {
|
|
35
27
|
if (element.type !== "Character" || next?.type !== "Character") return undefined;
|
|
36
28
|
const [high, low] = [element.value, next.value];
|
|
37
29
|
if (
|
|
@@ -97,7 +89,7 @@ export const contains = (ranges: Ranges, point: number): boolean =>
|
|
|
97
89
|
const membership = (source: string, flags: string): RegExp =>
|
|
98
90
|
new RegExp(`^(?:${source})(?![\\s\\S])`, flags);
|
|
99
91
|
|
|
100
|
-
/** The
|
|
92
|
+
/** The UTF-16 units a validated expression matches; flags contain only i or s. */
|
|
101
93
|
export function nativeCharacterRanges(source: string, flags: string): Ranges {
|
|
102
94
|
const key = `${flags}:${source}`;
|
|
103
95
|
const cached = nativeSets.get(key);
|
|
@@ -107,17 +99,16 @@ export function nativeCharacterRanges(source: string, flags: string): Ranges {
|
|
|
107
99
|
return cached;
|
|
108
100
|
}
|
|
109
101
|
const native = membership(source, flags);
|
|
110
|
-
const max = flags.includes("u") || flags.includes("v") ? MAX_SCALAR : MAX_UNIT;
|
|
111
102
|
const ranges: [number, number][] = [];
|
|
112
103
|
let start: number | undefined;
|
|
113
|
-
for (let point = 0; point <=
|
|
104
|
+
for (let point = 0; point <= MAX_UNIT; point++) {
|
|
114
105
|
if (native.test(String.fromCodePoint(point))) start ??= point;
|
|
115
106
|
else if (start !== undefined) {
|
|
116
107
|
ranges.push([start, point - 1]);
|
|
117
108
|
start = undefined;
|
|
118
109
|
}
|
|
119
110
|
}
|
|
120
|
-
if (start !== undefined) ranges.push([start,
|
|
111
|
+
if (start !== undefined) ranges.push([start, MAX_UNIT]);
|
|
121
112
|
if (ranges.length <= MAX_CACHED_RANGES && source.length <= MAX_CACHED_SOURCE_UNITS) {
|
|
122
113
|
while (nativeSets.size >= MAX_CACHED_SETS || cachedRanges + ranges.length > MAX_CACHED_RANGES) {
|
|
123
114
|
const oldest = nativeSets.keys().next().value!;
|
|
@@ -131,54 +122,9 @@ export function nativeCharacterRanges(source: string, flags: string): Ranges {
|
|
|
131
122
|
}
|
|
132
123
|
|
|
133
124
|
/** Close intervals under V8 case equivalence without shipping a second Unicode version. */
|
|
134
|
-
export function foldRanges(ranges: Ranges
|
|
125
|
+
export function foldRanges(ranges: Ranges): Ranges {
|
|
135
126
|
if (!ranges.length) return ranges;
|
|
136
|
-
const escape = (point: number) =>
|
|
137
|
-
unicode ? `\\u{${point.toString(16)}}` : `\\u${point.toString(16).padStart(4, "0")}`;
|
|
127
|
+
const escape = (point: number) => `\\u${point.toString(16).padStart(4, "0")}`;
|
|
138
128
|
const source = `[${ranges.map(([low, high]) => (low === high ? escape(low) : `${escape(low)}-${escape(high)}`)).join("")}]`;
|
|
139
|
-
return nativeCharacterRanges(source,
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
/**
|
|
143
|
-
* The multi-character strings a class node matches under `flags`; undefined when a string
|
|
144
|
-
* property cannot be enumerated here.
|
|
145
|
-
*/
|
|
146
|
-
export function acceptedClassStrings(
|
|
147
|
-
node: CharacterNode,
|
|
148
|
-
flags: string,
|
|
149
|
-
): readonly string[] | undefined {
|
|
150
|
-
const strings = classStrings(node);
|
|
151
|
-
if (!strings?.length) return strings;
|
|
152
|
-
const accepts = membership(node.raw, flags);
|
|
153
|
-
return strings.filter((value) => accepts.test(value));
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
/** String representatives of a class; undefined means a string property is not enumerable here. */
|
|
157
|
-
function classStrings(node: ClassNode): readonly string[] | undefined {
|
|
158
|
-
switch (node.type) {
|
|
159
|
-
case "ExpressionCharacterClass":
|
|
160
|
-
return node.negate ? [] : classStrings(node.expression);
|
|
161
|
-
case "ClassIntersection":
|
|
162
|
-
return classStrings(node.left) ?? classStrings(node.right);
|
|
163
|
-
case "ClassSubtraction":
|
|
164
|
-
return classStrings(node.left);
|
|
165
|
-
case "CharacterClass": {
|
|
166
|
-
if (node.negate) return [];
|
|
167
|
-
const result: string[] = [];
|
|
168
|
-
for (const child of node.elements) {
|
|
169
|
-
const strings = classStrings(child);
|
|
170
|
-
if (!strings) return undefined;
|
|
171
|
-
result.push(...strings);
|
|
172
|
-
}
|
|
173
|
-
return result;
|
|
174
|
-
}
|
|
175
|
-
case "ClassStringDisjunction":
|
|
176
|
-
return node.alternatives
|
|
177
|
-
.filter(({ elements }) => elements.length !== 1)
|
|
178
|
-
.map(({ elements }) => elements.map(({ value }) => String.fromCodePoint(value)).join(""));
|
|
179
|
-
case "CharacterSet":
|
|
180
|
-
return node.kind === "property" && node.strings ? undefined : [];
|
|
181
|
-
default:
|
|
182
|
-
return [];
|
|
183
|
-
}
|
|
129
|
+
return nativeCharacterRanges(source, "i");
|
|
184
130
|
}
|
package/src/core/regex.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
/** JavaScript regex construction on the shared LF view, used by both grep and replace. */
|
|
2
|
-
import { errorMessage } from "./errors.ts";
|
|
3
2
|
import { normalizeLineEndings } from "./lines.ts";
|
|
4
3
|
|
|
5
4
|
/** JavaScript regex source on the shared LF view; literal text matches exactly. */
|
|
@@ -9,8 +8,8 @@ export function regexSource(find: string, literal: boolean): string {
|
|
|
9
8
|
}
|
|
10
9
|
|
|
11
10
|
/**
|
|
12
|
-
* Both matcher modes operate on the shared LF view. Replace's and grep's
|
|
13
|
-
*
|
|
11
|
+
* Both matcher modes operate on the shared LF view. Replace's and grep's argument checks
|
|
12
|
+
* compile their regexes with it before any file is read.
|
|
14
13
|
*/
|
|
15
14
|
export function buildRegex(find: string, literal: boolean, flagsRaw: string | undefined): RegExp {
|
|
16
15
|
const set = new Set((flagsRaw ?? "").split(""));
|
|
@@ -19,32 +18,3 @@ export function buildRegex(find: string, literal: boolean, flagsRaw: string | un
|
|
|
19
18
|
// The engine's SyntaxError already names the pattern and flags it compiled.
|
|
20
19
|
return new RegExp(regexSource(find, literal), flagStr);
|
|
21
20
|
}
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* Report V8's diagnostics for a rule's flags and, in regex mode, for each pattern that
|
|
25
|
-
* buildRegex would reject. Invalid flags stop the check, since every pattern compiles with
|
|
26
|
-
* them; values that are not strings are left to schema validation.
|
|
27
|
-
*/
|
|
28
|
-
export function checkRegexArguments(
|
|
29
|
-
flagsField: string,
|
|
30
|
-
flags: string | undefined,
|
|
31
|
-
literal: boolean,
|
|
32
|
-
patterns: readonly (readonly [field: string, value: unknown])[],
|
|
33
|
-
report: (field: string, reason: string) => void,
|
|
34
|
-
): void {
|
|
35
|
-
try {
|
|
36
|
-
buildRegex("", true, flags);
|
|
37
|
-
} catch (error) {
|
|
38
|
-
report(flagsField, errorMessage(error));
|
|
39
|
-
return;
|
|
40
|
-
}
|
|
41
|
-
if (literal) return;
|
|
42
|
-
for (const [field, value] of patterns) {
|
|
43
|
-
if (typeof value !== "string") continue;
|
|
44
|
-
try {
|
|
45
|
-
buildRegex(value, false, flags);
|
|
46
|
-
} catch (error) {
|
|
47
|
-
report(field, errorMessage(error));
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
}
|
package/src/core/replace.test.ts
CHANGED
|
@@ -4,6 +4,57 @@ import { applyReplacements } from "./replace.ts";
|
|
|
4
4
|
import type { Replacement } from "./replace-schema.ts";
|
|
5
5
|
import { HashlineError } from "./errors.ts";
|
|
6
6
|
|
|
7
|
+
test("replacement at the file start → retains the original BOM at byte zero", async (t) => {
|
|
8
|
+
const cases = [
|
|
9
|
+
{
|
|
10
|
+
name: "zero-width insertion",
|
|
11
|
+
source: "\uFEFFfoo\r\nbar\n",
|
|
12
|
+
find: "^",
|
|
13
|
+
replace: "X",
|
|
14
|
+
expected: "\uFEFFXfoo\r\nbar\n",
|
|
15
|
+
},
|
|
16
|
+
{
|
|
17
|
+
name: "whole-file replacement",
|
|
18
|
+
source: "\uFEFFfoo",
|
|
19
|
+
find: "^[\\s\\S]*$",
|
|
20
|
+
replace: "X",
|
|
21
|
+
expected: "\uFEFFX",
|
|
22
|
+
},
|
|
23
|
+
{ name: "copied BOM", source: "\uFEFFfoo", find: "^.", replace: "$&X", expected: "\uFEFFXfoo" },
|
|
24
|
+
{ name: "consumed BOM", source: "\uFEFFfoo", find: "^.", replace: "", expected: "\uFEFFfoo" },
|
|
25
|
+
{
|
|
26
|
+
name: "inserted body BOM",
|
|
27
|
+
source: "\uFEFFfoo",
|
|
28
|
+
find: "^",
|
|
29
|
+
replace: "\uFEFF",
|
|
30
|
+
expected: "\uFEFF\uFEFFfoo",
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
name: "capture copied into body",
|
|
34
|
+
source: "\uFEFFfoo",
|
|
35
|
+
find: "^(.*)",
|
|
36
|
+
replace: "X$1",
|
|
37
|
+
expected: "\uFEFFX\uFEFFfoo",
|
|
38
|
+
},
|
|
39
|
+
{ name: "BOM-only file", source: "\uFEFF", find: "^", replace: "X", expected: "\uFEFFX" },
|
|
40
|
+
{
|
|
41
|
+
name: "body BOM",
|
|
42
|
+
source: "foo\uFEFFbar",
|
|
43
|
+
find: "^",
|
|
44
|
+
replace: "X",
|
|
45
|
+
expected: "Xfoo\uFEFFbar",
|
|
46
|
+
},
|
|
47
|
+
];
|
|
48
|
+
for (const { name, source, find, replace, expected } of cases) {
|
|
49
|
+
await t.test(name, () => {
|
|
50
|
+
assert.deepEqual(applyReplacements(source, [{ literal: false, find, replace }]), {
|
|
51
|
+
text: expected,
|
|
52
|
+
count: 1,
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
|
|
7
58
|
test("replacement joins beside LF → preserve standalone CR content", async (t) => {
|
|
8
59
|
const literal = (find: string, replace: string): Replacement => ({
|
|
9
60
|
find,
|
package/src/core/replace.ts
CHANGED
|
@@ -88,11 +88,17 @@ export function applyReplacements(
|
|
|
88
88
|
},
|
|
89
89
|
});
|
|
90
90
|
}
|
|
91
|
-
const
|
|
92
|
-
|
|
91
|
+
const bom = source.startsWith("\uFEFF") ? "\uFEFF" : "";
|
|
92
|
+
const parts: string[] = [bom];
|
|
93
|
+
let cursor = bom.length;
|
|
93
94
|
for (const change of changes) {
|
|
94
|
-
|
|
95
|
-
|
|
95
|
+
// Keep the original header at byte zero; a copied leading BOM denotes that same header.
|
|
96
|
+
const text =
|
|
97
|
+
bom && change.start === 0 && change.end > 0 && change.text.startsWith(bom)
|
|
98
|
+
? change.text.slice(1)
|
|
99
|
+
: change.text;
|
|
100
|
+
parts.push(source.slice(cursor, Math.max(bom.length, change.start)), text);
|
|
101
|
+
cursor = Math.max(bom.length, change.end);
|
|
96
102
|
}
|
|
97
103
|
parts.push(source.slice(cursor));
|
|
98
104
|
return { text: joinTextFragments(parts), count: changes.length };
|
|
@@ -2,31 +2,29 @@ import assert from "node:assert/strict";
|
|
|
2
2
|
import { test } from "node:test";
|
|
3
3
|
import { extractPrefilter, smartIgnoreCase, type Literal } from "./search-analysis.ts";
|
|
4
4
|
import { searchText, type GrepQuery } from "./search.ts";
|
|
5
|
-
import { hasCandidateBytes } from "./search-matrix.testing.ts";
|
|
5
|
+
import { acceptsNative, hasCandidateBytes } from "./search-matrix.testing.ts";
|
|
6
6
|
|
|
7
|
-
const query = (pattern: string,
|
|
7
|
+
const query = (pattern: string, ignoreCase = false, literal = false): GrepQuery => ({
|
|
8
8
|
patterns: [pattern],
|
|
9
|
-
|
|
9
|
+
ignoreCase,
|
|
10
10
|
literal,
|
|
11
11
|
multiline: true,
|
|
12
12
|
});
|
|
13
13
|
const literal = (text: string): Literal => [...text].map((char) => [char]);
|
|
14
14
|
|
|
15
|
-
for (const [pattern,
|
|
16
|
-
["colou?r",
|
|
17
|
-
["a*",
|
|
18
|
-
["(?:word|)",
|
|
19
|
-
["[^a]+",
|
|
20
|
-
["(?=word)",
|
|
21
|
-
["(?i:a)(?-i:b)",
|
|
22
|
-
["(?-i:a)(?i:b)",
|
|
23
|
-
["k",
|
|
24
|
-
["s",
|
|
25
|
-
["k", "miu", [[["K", "k", "K"]]]],
|
|
26
|
-
["s", "miv", [[["S", "s", "ſ"]]]],
|
|
15
|
+
for (const [pattern, ignoreCase, expected] of [
|
|
16
|
+
["colou?r", false, [literal("color"), literal("colour")]],
|
|
17
|
+
["a*", false, undefined],
|
|
18
|
+
["(?:word|)", false, undefined],
|
|
19
|
+
["[^a]+", false, undefined],
|
|
20
|
+
["(?=word)", false, [literal("word")]],
|
|
21
|
+
["(?i:a)(?-i:b)", false, [[["A", "a"], ["b"]]]],
|
|
22
|
+
["(?-i:a)(?i:b)", true, [[["a"], ["B", "b"]]]],
|
|
23
|
+
["k", true, [[["K", "k"]]]],
|
|
24
|
+
["s", true, [[["S", "s"]]]],
|
|
27
25
|
[
|
|
28
26
|
"abéz",
|
|
29
|
-
|
|
27
|
+
true,
|
|
30
28
|
[
|
|
31
29
|
[
|
|
32
30
|
["A", "a"],
|
|
@@ -36,16 +34,16 @@ for (const [pattern, flags, expected] of [
|
|
|
36
34
|
],
|
|
37
35
|
],
|
|
38
36
|
],
|
|
39
|
-
["é",
|
|
40
|
-
["[\\u0100-\\u0200]",
|
|
41
|
-
["foo.*bar",
|
|
42
|
-
["(?:abcdef.*xy|zz.*ghijkl)",
|
|
43
|
-
["foo|bar.*baz",
|
|
44
|
-
["(?=foo|bar).*baz",
|
|
37
|
+
["é", true, [[["É", "é"]]]],
|
|
38
|
+
["[\\u0100-\\u0200]", false, undefined],
|
|
39
|
+
["foo.*bar", false, [literal("foo")]],
|
|
40
|
+
["(?:abcdef.*xy|zz.*ghijkl)", false, [literal("abcdef"), literal("ghijkl")]],
|
|
41
|
+
["foo|bar.*baz", false, [literal("foo"), literal("bar")]],
|
|
42
|
+
["(?=foo|bar).*baz", false, [literal("baz")]],
|
|
45
43
|
] as const) {
|
|
46
|
-
test(`${pattern.slice(0, 80)}
|
|
44
|
+
test(`${pattern.slice(0, 80)} ignoreCase=${ignoreCase} → conservative candidate literals`, () => {
|
|
47
45
|
assert.deepEqual(
|
|
48
|
-
extractPrefilter(query(pattern,
|
|
46
|
+
extractPrefilter(query(pattern, ignoreCase)),
|
|
49
47
|
expected ? { kind: "literals", literals: expected } : { kind: "all" },
|
|
50
48
|
);
|
|
51
49
|
});
|
|
@@ -53,44 +51,51 @@ for (const [pattern, flags, expected] of [
|
|
|
53
51
|
|
|
54
52
|
for (const boundary of ["\n", "\r\n", "\uFFFD", "\uD800", "\uDC00", "\0"]) {
|
|
55
53
|
test(`literal ${JSON.stringify(boundary)} boundary → no candidate spans changed bytes`, () => {
|
|
56
|
-
const prefilter = extractPrefilter(query(`left${boundary}right`,
|
|
54
|
+
const prefilter = extractPrefilter(query(`left${boundary}right`, false, true));
|
|
57
55
|
assert.deepEqual(prefilter, { kind: "literals", literals: [literal("right")] });
|
|
58
56
|
assert.ok(hasCandidateBytes(Buffer.from(`left${boundary}right`), prefilter));
|
|
59
57
|
assert.ok(hasCandidateBytes(Buffer.from("left\nright"), prefilter));
|
|
60
58
|
assert.equal(hasCandidateBytes(Buffer.from("left"), prefilter), false);
|
|
61
59
|
assert.ok(hasCandidateBytes(Buffer.from("right"), prefilter));
|
|
62
|
-
assert.deepEqual(extractPrefilter(query(boundary,
|
|
60
|
+
assert.deepEqual(extractPrefilter(query(boundary, false, true)), { kind: "all" });
|
|
63
61
|
});
|
|
64
62
|
}
|
|
65
63
|
|
|
66
|
-
for (const [patterns, isLiteral, expected
|
|
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
|
|
80
|
-
[["\\u{41}"], false, false, "u"],
|
|
81
|
-
[["\\u{41}"], false, false, "v"],
|
|
82
|
-
[["\\u{61}"], false, true, "u"],
|
|
83
|
-
[["\\u{61}"], false, true, "v"],
|
|
84
|
-
[["𐐀"], false, false, "u"],
|
|
85
|
-
[["𐐀"], false, false, "v"],
|
|
86
|
-
[["𐐨"], false, true, "u"],
|
|
87
|
-
[["𐐨"], false, true, "v"],
|
|
64
|
+
for (const [patterns, isLiteral, expected] of [
|
|
65
|
+
[["foo", "bar"], false, true],
|
|
66
|
+
[["foo", "Bar"], false, false],
|
|
67
|
+
[["foo\\S*", "\\D", "\\W"], false, true],
|
|
68
|
+
[["\\u0041"], false, false],
|
|
69
|
+
[["\\x41"], false, false],
|
|
70
|
+
[["\\u0061"], false, true],
|
|
71
|
+
[["[A-Z]"], false, false],
|
|
72
|
+
[["(?<UPPER>foo)"], false, true],
|
|
73
|
+
[["ς", "σ"], false, true],
|
|
74
|
+
[["σ", "Σ"], false, false],
|
|
75
|
+
[["foo\\S*"], true, false],
|
|
76
|
+
[["\\u0041"], true, true],
|
|
77
|
+
[["foo", "BAR"], true, false],
|
|
88
78
|
] as const) {
|
|
89
|
-
test(`${JSON.stringify(patterns)} literal=${isLiteral}
|
|
90
|
-
assert.equal(smartIgnoreCase(patterns, isLiteral
|
|
79
|
+
test(`${JSON.stringify(patterns)} literal=${isLiteral} → smart case follows decoded letters`, () => {
|
|
80
|
+
assert.equal(smartIgnoreCase(patterns, isLiteral), expected);
|
|
91
81
|
});
|
|
92
82
|
}
|
|
93
83
|
|
|
84
|
+
test("smart case: a supplementary uppercase letter → case-sensitive", () => {
|
|
85
|
+
for (const [pattern, isLiteral] of [
|
|
86
|
+
["𐐀é", true],
|
|
87
|
+
["𐐀é", false],
|
|
88
|
+
["\\uD801\\uDC00", false],
|
|
89
|
+
["[𐐀]", false],
|
|
90
|
+
] as const) {
|
|
91
|
+
assert.equal(
|
|
92
|
+
smartIgnoreCase([pattern], isLiteral),
|
|
93
|
+
false,
|
|
94
|
+
`${JSON.stringify(pattern)} literal=${isLiteral}`,
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
|
|
94
99
|
test("seeded random patterns × raw bytes → a JS hit always retains a candidate byte literal", () => {
|
|
95
100
|
let seed = 0x5eed1234;
|
|
96
101
|
const next = (bound: number) => {
|
|
@@ -147,16 +152,10 @@ test("seeded random patterns × raw bytes → a JS hit always retains a candidat
|
|
|
147
152
|
let checkedHits = 0;
|
|
148
153
|
let filteredHits = 0;
|
|
149
154
|
for (const pattern of patterns) {
|
|
150
|
-
for (const
|
|
151
|
-
|
|
152
|
-
try {
|
|
153
|
-
new RegExp(pattern, flags);
|
|
154
|
-
} catch (error) {
|
|
155
|
-
if (error instanceof SyntaxError) continue;
|
|
156
|
-
throw error;
|
|
157
|
-
}
|
|
155
|
+
for (const ignoreCase of [false, true]) {
|
|
156
|
+
if (!acceptsNative(query(pattern, ignoreCase))) continue;
|
|
158
157
|
for (const multiline of [false, true]) {
|
|
159
|
-
const request = { ...query(pattern,
|
|
158
|
+
const request = { ...query(pattern, ignoreCase), multiline };
|
|
160
159
|
const prefilter = extractPrefilter(request);
|
|
161
160
|
for (const bytes of sources) {
|
|
162
161
|
if (
|
|
@@ -168,7 +167,13 @@ test("seeded random patterns × raw bytes → a JS hit always retains a candidat
|
|
|
168
167
|
filteredHits++;
|
|
169
168
|
assert.ok(
|
|
170
169
|
hasCandidateBytes(bytes, prefilter),
|
|
171
|
-
JSON.stringify({
|
|
170
|
+
JSON.stringify({
|
|
171
|
+
pattern,
|
|
172
|
+
ignoreCase,
|
|
173
|
+
multiline,
|
|
174
|
+
bytes: bytes.toString("hex"),
|
|
175
|
+
prefilter,
|
|
176
|
+
}),
|
|
172
177
|
);
|
|
173
178
|
}
|
|
174
179
|
}
|
|
@@ -199,7 +204,7 @@ test("deeply nested uppercase pattern → smart case stays sensitive and prefilt
|
|
|
199
204
|
for (const depth of [50, 200, 500, 1_000, 2_000, 4_000]) {
|
|
200
205
|
const pattern = `${"(?:".repeat(depth)}A${")".repeat(depth)}`;
|
|
201
206
|
assert.equal(new RegExp(pattern).test("A"), true);
|
|
202
|
-
assert.equal(smartIgnoreCase([pattern], false
|
|
207
|
+
assert.equal(smartIgnoreCase([pattern], false), false);
|
|
203
208
|
assert.equal(hasCandidateBytes(Buffer.from("A"), extractPrefilter(query(pattern))), true);
|
|
204
209
|
}
|
|
205
210
|
});
|
|
@@ -11,7 +11,6 @@
|
|
|
11
11
|
import { RegExpParser, visitRegExpAST, type AST } from "@eslint-community/regexpp";
|
|
12
12
|
import { caseVariants } from "./case-fold.ts";
|
|
13
13
|
import {
|
|
14
|
-
acceptedClassStrings,
|
|
15
14
|
nativeCharacterRanges,
|
|
16
15
|
total,
|
|
17
16
|
type CharacterNode,
|
|
@@ -51,8 +50,6 @@ const UNKNOWN: Info = { exact: [[GAP]], filter: ALL };
|
|
|
51
50
|
|
|
52
51
|
interface Context {
|
|
53
52
|
readonly ignoreCase: boolean;
|
|
54
|
-
readonly unicode: boolean;
|
|
55
|
-
readonly unicodeSets: boolean;
|
|
56
53
|
}
|
|
57
54
|
|
|
58
55
|
/**
|
|
@@ -67,7 +64,7 @@ function isUnstable(point: number): boolean {
|
|
|
67
64
|
function charUnit(point: number, ctx: Context): Unit {
|
|
68
65
|
if (isUnstable(point)) return GAP;
|
|
69
66
|
const char = String.fromCodePoint(point);
|
|
70
|
-
return ctx.ignoreCase ? caseVariants(char
|
|
67
|
+
return ctx.ignoreCase ? caseVariants(char) : [char];
|
|
71
68
|
}
|
|
72
69
|
|
|
73
70
|
function unionUnits(units: readonly Unit[]): Unit {
|
|
@@ -217,25 +214,14 @@ function quantified(node: AST.Quantifier, ctx: Context): Info {
|
|
|
217
214
|
|
|
218
215
|
function classInfo(node: CharacterNode, ctx: Context): Info {
|
|
219
216
|
if (node.type === "CharacterSet" && node.kind === "any") return UNKNOWN;
|
|
220
|
-
const
|
|
221
|
-
const strings = acceptedClassStrings(node, flags);
|
|
222
|
-
if (!strings) return UNKNOWN;
|
|
223
|
-
const ranges = nativeCharacterRanges(node.raw, flags);
|
|
217
|
+
const ranges = nativeCharacterRanges(node.raw, ctx.ignoreCase ? "i" : "");
|
|
224
218
|
if (total(ranges) > MAX_CLASS_CHARS) return UNKNOWN;
|
|
225
219
|
const units: Unit[] = [];
|
|
226
220
|
for (const [low, high] of ranges)
|
|
227
221
|
for (let point = low; point <= high; point++)
|
|
228
|
-
units.push(charUnit(point, {
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
const sequence = [...value].map((char) => charUnit(char.codePointAt(0)!, ctx));
|
|
232
|
-
infos.push(
|
|
233
|
-
sequence.length <= MAX_SEQUENCE_LENGTH
|
|
234
|
-
? { exact: [sequence], filter: ALL }
|
|
235
|
-
: { filter: sequenceFilter([sequence]) },
|
|
236
|
-
);
|
|
237
|
-
}
|
|
238
|
-
return alternate(infos);
|
|
222
|
+
units.push(charUnit(point, { ignoreCase: false }));
|
|
223
|
+
// A class that matches nothing has no exact text.
|
|
224
|
+
return alternate(units.length ? [{ exact: [[unionUnits(units)]], filter: ALL }] : []);
|
|
239
225
|
}
|
|
240
226
|
|
|
241
227
|
function analyzeElement(node: AST.Element, ctx: Context): Info {
|
|
@@ -273,7 +259,7 @@ function analyzeAlternatives(alternatives: readonly AST.Alternative[], ctx: Cont
|
|
|
273
259
|
alternatives.map(({ elements }) => {
|
|
274
260
|
const infos: Info[] = [];
|
|
275
261
|
for (let index = 0; index < elements.length; index++) {
|
|
276
|
-
const pair =
|
|
262
|
+
const pair = surrogatePair(elements[index], elements[index + 1]);
|
|
277
263
|
if (pair === undefined) infos.push(analyzeElement(elements[index], ctx));
|
|
278
264
|
else {
|
|
279
265
|
infos.push({ exact: [[charUnit(pair, ctx)]], filter: ALL });
|
|
@@ -292,14 +278,13 @@ function analyzeAlternatives(alternatives: readonly AST.Alternative[], ctx: Cont
|
|
|
292
278
|
export function analyzeQueryPattern<T>(
|
|
293
279
|
pattern: string,
|
|
294
280
|
literal: boolean,
|
|
295
|
-
flags: string,
|
|
296
281
|
analyze: (parsed: AST.Pattern) => T,
|
|
297
282
|
): T | undefined {
|
|
298
283
|
const source = regexSource(pattern, literal);
|
|
299
284
|
try {
|
|
300
285
|
const parsed = new RegExpParser({ ecmaVersion: 2025 }).parsePattern(source, 0, source.length, {
|
|
301
|
-
unicode:
|
|
302
|
-
unicodeSets:
|
|
286
|
+
unicode: false,
|
|
287
|
+
unicodeSets: false,
|
|
303
288
|
});
|
|
304
289
|
return analyze(parsed);
|
|
305
290
|
} catch (error) {
|
|
@@ -308,18 +293,23 @@ export function analyzeQueryPattern<T>(
|
|
|
308
293
|
}
|
|
309
294
|
}
|
|
310
295
|
|
|
311
|
-
/**
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
): boolean {
|
|
296
|
+
/**
|
|
297
|
+
* Smart case over decoded characters, a surrogate pair counting as its supplementary
|
|
298
|
+
* character; case-sensitive when a pattern cannot be analyzed.
|
|
299
|
+
*/
|
|
300
|
+
export function smartIgnoreCase(patterns: readonly string[], literal: boolean): boolean {
|
|
317
301
|
return !patterns.some((pattern) => {
|
|
318
|
-
const uppercase = analyzeQueryPattern(pattern, literal,
|
|
302
|
+
const uppercase = analyzeQueryPattern(pattern, literal, (parsed) => {
|
|
319
303
|
let found = false;
|
|
320
304
|
visitRegExpAST(parsed, {
|
|
321
|
-
onCharacterEnter(
|
|
322
|
-
const
|
|
305
|
+
onCharacterEnter(node) {
|
|
306
|
+
const { parent } = node;
|
|
307
|
+
const siblings: readonly AST.Node[] =
|
|
308
|
+
parent.type === "Alternative" || parent.type === "CharacterClass"
|
|
309
|
+
? parent.elements
|
|
310
|
+
: [];
|
|
311
|
+
const point = surrogatePair(node, siblings[siblings.indexOf(node) + 1]) ?? node.value;
|
|
312
|
+
const text = String.fromCodePoint(point);
|
|
323
313
|
found ||= text !== text.toLowerCase();
|
|
324
314
|
},
|
|
325
315
|
});
|
|
@@ -331,16 +321,11 @@ export function smartIgnoreCase(
|
|
|
331
321
|
|
|
332
322
|
/** One necessary file condition, its literals bounded; every OR retains all alternatives. */
|
|
333
323
|
export function extractPrefilter(query: GrepQuery): Prefilter {
|
|
334
|
-
const
|
|
335
|
-
const ctx: Context = {
|
|
336
|
-
ignoreCase: query.flags.includes("i"),
|
|
337
|
-
unicode,
|
|
338
|
-
unicodeSets: query.flags.includes("v"),
|
|
339
|
-
};
|
|
324
|
+
const ctx: Context = { ignoreCase: query.ignoreCase };
|
|
340
325
|
return orFilters(
|
|
341
326
|
query.patterns.map(
|
|
342
327
|
(pattern) =>
|
|
343
|
-
analyzeQueryPattern(pattern, query.literal,
|
|
328
|
+
analyzeQueryPattern(pattern, query.literal, (parsed) =>
|
|
344
329
|
filterOf(analyzeAlternatives(parsed.alternatives, ctx)),
|
|
345
330
|
) ?? ALL,
|
|
346
331
|
),
|
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
MATRIX_INPUTS,
|
|
10
10
|
} from "./search-matrix.testing.ts";
|
|
11
11
|
|
|
12
|
-
test("Cartesian JS syntax × quantifiers × contexts ×
|
|
12
|
+
test("Cartesian JS syntax × quantifiers × contexts × case modes × line modes × bytes → prefilter never drops a native match", (t) => {
|
|
13
13
|
let accepted = 0;
|
|
14
14
|
let rejected = 0;
|
|
15
15
|
let evaluations = 0;
|
|
@@ -59,6 +59,6 @@ test("Cartesian JS syntax × quantifiers × contexts × flags × line modes × b
|
|
|
59
59
|
misses,
|
|
60
60
|
}),
|
|
61
61
|
);
|
|
62
|
-
assert.ok(accepted > 0 &&
|
|
62
|
+
assert.ok(accepted > 0 && filteredHits > 0);
|
|
63
63
|
assert.equal(misses, 0, examples.join("\n"));
|
|
64
64
|
});
|
|
@@ -59,22 +59,12 @@ export const MATRIX_SYNTAX = [
|
|
|
59
59
|
["remove m", "(?-m:^a$)"],
|
|
60
60
|
["Unicode property", "\\p{Letter}"],
|
|
61
61
|
["negated Unicode property", "\\P{ASCII}"],
|
|
62
|
-
["v intersection", "[\\p{ASCII}&&\\p{Letter}]"],
|
|
63
|
-
["v subtraction", "[\\p{Letter}--[a]]"],
|
|
64
|
-
["v string alternatives", "[\\q{ab|cd}]"],
|
|
65
|
-
["v string property", "\\p{RGI_Emoji}"],
|
|
66
62
|
] as const;
|
|
67
63
|
|
|
68
64
|
export const MATRIX_QUANTIFIERS = ["", "?", "*", "+", "*?", "+?", "{0}", "{2}", "{1,3}?"] as const;
|
|
69
65
|
export const MATRIX_CONTEXTS = ["bare", "sequence", "alternative", "capture", "OR query"] as const;
|
|
70
66
|
|
|
71
|
-
|
|
72
|
-
export const MATRIX_FLAGS = ["", "u", "v"].flatMap((unicode) =>
|
|
73
|
-
Array.from(
|
|
74
|
-
{ length: 16 },
|
|
75
|
-
(_, mask) => [..."imsy"].filter((_, bit) => mask & (1 << bit)).join("") + unicode,
|
|
76
|
-
),
|
|
77
|
-
);
|
|
67
|
+
export const MATRIX_IGNORE_CASE = [false, true] as const;
|
|
78
68
|
|
|
79
69
|
export const MATRIX_INPUTS = [
|
|
80
70
|
["empty", Buffer.alloc(0)],
|
|
@@ -116,13 +106,13 @@ export function* matrixCases(): Generator<MatrixCase> {
|
|
|
116
106
|
: context === "capture"
|
|
117
107
|
? [`(${part})\\1`]
|
|
118
108
|
: [part, "Z"];
|
|
119
|
-
for (const
|
|
109
|
+
for (const ignoreCase of MATRIX_IGNORE_CASE) {
|
|
120
110
|
for (const multiline of [false, true])
|
|
121
111
|
yield {
|
|
122
112
|
syntax,
|
|
123
113
|
quantifier,
|
|
124
114
|
context,
|
|
125
|
-
query: { patterns,
|
|
115
|
+
query: { patterns, ignoreCase, multiline, literal: false },
|
|
126
116
|
};
|
|
127
117
|
}
|
|
128
118
|
}
|
|
@@ -132,7 +122,7 @@ export function* matrixCases(): Generator<MatrixCase> {
|
|
|
132
122
|
|
|
133
123
|
export function acceptsNative(query: GrepQuery): boolean {
|
|
134
124
|
try {
|
|
135
|
-
for (const pattern of query.patterns) new RegExp(pattern, query.
|
|
125
|
+
for (const pattern of query.patterns) new RegExp(pattern, query.ignoreCase ? "mi" : "m");
|
|
136
126
|
return true;
|
|
137
127
|
} catch (error) {
|
|
138
128
|
if (error instanceof SyntaxError) return false;
|
|
@@ -171,9 +161,9 @@ export function* pairedMatrixCases(): Generator<{ readonly query: GrepQuery }> {
|
|
|
171
161
|
[`(?:${left}|${right})`],
|
|
172
162
|
[left, right],
|
|
173
163
|
]) {
|
|
174
|
-
for (const
|
|
164
|
+
for (const ignoreCase of MATRIX_IGNORE_CASE) {
|
|
175
165
|
for (const multiline of [false, true])
|
|
176
|
-
yield { query: { patterns,
|
|
166
|
+
yield { query: { patterns, ignoreCase, multiline, literal: false } };
|
|
177
167
|
}
|
|
178
168
|
}
|
|
179
169
|
}
|