@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.
Files changed (88) hide show
  1. package/LICENSE +1 -0
  2. package/README.md +59 -16
  3. package/README.zh-CN.md +59 -16
  4. package/package.json +2 -2
  5. package/src/core/AGENTS.md +2 -2
  6. package/src/core/apply.test.ts +13 -0
  7. package/src/core/apply.ts +5 -9
  8. package/src/core/case-fold.test.ts +16 -25
  9. package/src/core/case-fold.ts +4 -4
  10. package/src/core/character-set.test.ts +1 -6
  11. package/src/core/character-set.ts +7 -61
  12. package/src/core/regex.ts +2 -36
  13. package/src/core/search-analysis.test.ts +66 -61
  14. package/src/core/search-analysis.ts +24 -39
  15. package/src/core/search-matrix.test.ts +2 -2
  16. package/src/core/search-matrix.testing.ts +6 -16
  17. package/src/core/search-schema.ts +0 -1
  18. package/src/core/search.test.ts +6 -19
  19. package/src/core/search.ts +10 -8
  20. package/src/index.ts +27 -2
  21. package/src/integration/config-registration.test.ts +77 -4
  22. package/src/integration/fusion-dispatch.test.ts +47 -2
  23. package/src/integration/grep-errors.test.ts +31 -0
  24. package/src/integration/grep-flags.test.ts +13 -196
  25. package/src/integration/grep-js-completeness.test.ts +41 -8
  26. package/src/integration/grep-line-candidates.test.ts +3 -33
  27. package/src/integration/grep-matrix.test.ts +1 -1
  28. package/src/integration/grep-path-matrix.test.ts +59 -65
  29. package/src/integration/grep-prefilter-coverage.test.ts +15 -8
  30. package/src/integration/grep-process-limits.test.ts +46 -0
  31. package/src/integration/grep-regex.test.ts +7 -2
  32. package/src/integration/grep-rg.test.ts +63 -12
  33. package/src/integration/grep-translation.test.ts +14 -7
  34. package/src/integration/model-budget-lifecycle.test.ts +41 -2
  35. package/src/integration/npm-package.testing.ts +2 -3
  36. package/src/integration/replace-package.testing.ts +2 -2
  37. package/src/pi/AGENTS.md +21 -13
  38. package/src/pi/action-fusion.test.ts +38 -4
  39. package/src/pi/action-fusion.ts +23 -19
  40. package/src/pi/argument-diagnostics.ts +28 -48
  41. package/src/pi/argument-validation.test.ts +61 -27
  42. package/src/pi/argument-validation.ts +34 -0
  43. package/src/pi/budgets.ts +19 -10
  44. package/src/pi/config.test.ts +1 -1
  45. package/src/pi/diagnostic-buffer.test.ts +1 -0
  46. package/src/pi/edit-tool.ts +1 -1
  47. package/src/pi/failure-context.test.ts +23 -2
  48. package/src/pi/failure-context.ts +36 -42
  49. package/src/pi/failure-path.test.ts +8 -3
  50. package/src/pi/file-commit.test.ts +109 -52
  51. package/src/pi/file-commit.ts +62 -56
  52. package/src/pi/fusion-card.ts +3 -2
  53. package/src/pi/grep-candidates.test.ts +5 -5
  54. package/src/pi/grep-candidates.ts +81 -50
  55. package/src/pi/grep-matrix.test.ts +14 -29
  56. package/src/pi/grep-order.test.ts +132 -9
  57. package/src/pi/grep-output.ts +169 -51
  58. package/src/pi/grep-render.ts +40 -34
  59. package/src/pi/grep-rg.testing.ts +9 -6
  60. package/src/pi/grep-scope.ts +51 -29
  61. package/src/pi/grep-search.ts +96 -71
  62. package/src/pi/grep-tool.ts +13 -22
  63. package/src/pi/grep.test.ts +310 -84
  64. package/src/pi/model-budgets.test.ts +56 -6
  65. package/src/pi/model-budgets.ts +7 -4
  66. package/src/pi/mutation-result.test.ts +25 -1
  67. package/src/pi/mutation-result.ts +7 -2
  68. package/src/pi/mutation-runner.ts +3 -4
  69. package/src/pi/output-budgets.test.ts +3 -1
  70. package/src/pi/path.ts +18 -4
  71. package/src/pi/pi.test.ts +22 -0
  72. package/src/pi/read-delegation.test.ts +119 -0
  73. package/src/pi/read-tool.ts +109 -61
  74. package/src/pi/read.test.ts +306 -17
  75. package/src/pi/regex-worker.test.ts +42 -0
  76. package/src/pi/regex-worker.ts +17 -11
  77. package/src/pi/registration.test.ts +157 -102
  78. package/src/pi/render.test.ts +54 -0
  79. package/src/pi/render.ts +9 -9
  80. package/src/pi/replace-tool.ts +5 -2
  81. package/src/pi/report-schema.ts +52 -31
  82. package/src/pi/report.test.ts +60 -10
  83. package/src/pi/rg-process.ts +41 -5
  84. package/src/pi/rg-regex.test.ts +12 -52
  85. package/src/pi/rg-regex.ts +29 -77
  86. package/src/pi/text-stream.test.ts +3 -0
  87. package/src/pi/text-stream.ts +1 -1
  88. 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 exact single-character part of a validated expression; flags contain only i, s, u or v. */
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 <= max; 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, max]);
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, unicode: boolean): 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, unicode ? "iu" : "i");
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 prepareArguments
13
- * validate flags and compile regexes through checkRegexArguments before any file is read.
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,36 +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, fix?: 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(
48
- field,
49
- errorMessage(error),
50
- "For an exact-text match, set literal to true; otherwise correct the regex syntax.",
51
- );
52
- }
53
- }
54
- }
@@ -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, flags = "m", literal = false): GrepQuery => ({
7
+ const query = (pattern: string, ignoreCase = false, literal = false): GrepQuery => ({
8
8
  patterns: [pattern],
9
- flags,
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, flags, expected] of [
16
- ["colou?r", "m", [literal("color"), literal("colour")]],
17
- ["a*", "m", undefined],
18
- ["(?:word|)", "m", undefined],
19
- ["[^a]+", "m", undefined],
20
- ["(?=word)", "m", [literal("word")]],
21
- ["(?i:a)(?-i:b)", "m", [[["A", "a"], ["b"]]]],
22
- ["(?-i:a)(?i:b)", "mi", [[["a"], ["B", "b"]]]],
23
- ["k", "mi", [[["K", "k"]]]],
24
- ["s", "mi", [[["S", "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
- "miu",
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
- ["é", "miu", [[["É", "é"]]]],
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")]],
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)} /${flags} → conservative candidate literals`, () => {
44
+ test(`${pattern.slice(0, 80)} ignoreCase=${ignoreCase} → conservative candidate literals`, () => {
47
45
  assert.deepEqual(
48
- extractPrefilter(query(pattern, flags)),
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`, "m", true));
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, "m", true)), { kind: "all" });
60
+ assert.deepEqual(extractPrefilter(query(boundary, false, true)), { kind: "all" });
63
61
  });
64
62
  }
65
63
 
66
- for (const [patterns, isLiteral, expected, flags] of [
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} flags=${flags} → smart case follows decoded letters`, () => {
90
- assert.equal(smartIgnoreCase(patterns, isLiteral, flags), expected);
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 flags of ["m", "mi", "miu", "miv"]) {
151
- // Some generated legacy patterns are invalid in Unicode mode; the real boundary rejects them.
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, flags), multiline };
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({ pattern, flags, multiline, bytes: bytes.toString("hex"), prefilter }),
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, ""), 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, ctx.unicode) : [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 flags = `${ctx.ignoreCase ? "i" : ""}${ctx.unicodeSets ? "v" : ctx.unicode ? "u" : ""}`;
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, { ...ctx, ignoreCase: false }));
229
- const infos: Info[] = units.length ? [{ exact: [[unionUnits(units)]], filter: ALL }] : [];
230
- for (const value of strings) {
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 = ctx.unicode ? undefined : surrogatePair(elements[index], elements[index + 1]);
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: flags.includes("u"),
302
- unicodeSets: flags.includes("v"),
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
- /** Smart case over decoded characters; case-sensitive when a pattern cannot be analyzed. */
312
- export function smartIgnoreCase(
313
- patterns: readonly string[],
314
- literal: boolean,
315
- flags: string,
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, flags, (parsed) => {
302
+ const uppercase = analyzeQueryPattern(pattern, literal, (parsed) => {
319
303
  let found = false;
320
304
  visitRegExpAST(parsed, {
321
- onCharacterEnter({ value }) {
322
- const text = String.fromCodePoint(value);
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 unicode = query.flags.includes("u") || query.flags.includes("v");
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, query.flags, (parsed) =>
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 × flags × line modes × bytes → prefilter never drops a native match", (t) => {
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 && rejected > 0 && filteredHits > 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
- /** All combinations of matching flags; d and caller-supplied g are covered at tool entry. */
72
- export const MATRIX_FLAGS = ["", "u", "v"].flatMap((unicode) =>
73
- Array.from(
74
- { length: 16 },
75
- (_, mask) => [..."imsy"].filter((_, bit) => mask & (1 << bit)).join("") + unicode,
76
- ),
77
- );
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 flags of MATRIX_FLAGS) {
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, flags, multiline, literal: false },
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.flags);
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 flags of MATRIX_FLAGS) {
164
+ for (const ignoreCase of MATRIX_IGNORE_CASE) {
175
165
  for (const multiline of [false, true])
176
- yield { query: { patterns, flags, multiline, literal: false } };
166
+ yield { query: { patterns, ignoreCase, multiline, literal: false } };
177
167
  }
178
168
  }
179
169
  }
@@ -11,7 +11,6 @@ export const SEARCH_RESULT_SCHEMA = Type.Object(
11
11
  { additionalProperties: false },
12
12
  ),
13
13
  ),
14
- totalLines: Type.Integer({ minimum: 0 }),
15
14
  },
16
15
  { additionalProperties: false },
17
16
  );
@@ -76,7 +76,7 @@ for (const scenario of cases) {
76
76
  query: {
77
77
  patterns: [scenario.pattern],
78
78
  literal: false,
79
- flags: scenario.ignoreCase ? "mi" : "m",
79
+ ignoreCase: scenario.ignoreCase ?? false,
80
80
  multiline: scenario.multiline ?? false,
81
81
  },
82
82
  limit: 100,
@@ -94,7 +94,7 @@ test("JS search: alternatives merge before the physical row limit", () => {
94
94
  query: {
95
95
  patterns: ["c", "a\\nb", "(?=b)"],
96
96
  literal: false,
97
- flags: "m",
97
+ ignoreCase: false,
98
98
  multiline: true,
99
99
  },
100
100
  limit: 2,
@@ -103,43 +103,30 @@ test("JS search: alternatives merge before the physical row limit", () => {
103
103
  { lineNumber: 2, column: 0 },
104
104
  { lineNumber: 3, column: 0 },
105
105
  ]);
106
- assert.equal(result.totalLines, 4);
107
106
  });
108
107
 
109
108
  test("JS search: columns retain UTF-16 positions inside supplementary characters", () => {
110
109
  const result = searchText({
111
110
  source: "😀x\n",
112
- query: { patterns: ["\\uDE00"], literal: false, flags: "m", multiline: false },
111
+ query: { patterns: ["\\uDE00"], literal: false, ignoreCase: false, multiline: false },
113
112
  limit: 1,
114
113
  });
115
114
  assert.deepEqual(result.lines, [{ lineNumber: 1, column: 1 }]);
116
115
  });
117
116
 
118
117
  test("selected lines ending in CR → matching preserves the CR and uses 1-based positions", () => {
119
- const query = { patterns: ["\\r$"], literal: false, flags: "", multiline: false };
118
+ const query = { patterns: ["\\r$"], literal: false, ignoreCase: false, multiline: false };
120
119
  assert.deepEqual(searchLines({ lines: "skip\na\r\nb\r\n", query, limit: 10 }), {
121
120
  lines: [
122
121
  { lineNumber: 2, column: 1 },
123
122
  { lineNumber: 3, column: 1 },
124
123
  ],
125
- totalLines: 3,
126
124
  });
127
125
  });
128
126
 
129
- test("selected lines exceed limit → rows truncate while totalLines counts all lines", () => {
130
- const query = { patterns: ["a", "b"], literal: true, flags: "", multiline: false };
127
+ test("selected lines exceed limit → matching rows truncate at the limit", () => {
128
+ const query = { patterns: ["a", "b"], literal: true, ignoreCase: false, multiline: false };
131
129
  assert.deepEqual(searchLines({ lines: "skip\nxa\nb\na\n", query, limit: 1 }), {
132
130
  lines: [{ lineNumber: 2, column: 1 }],
133
- totalLines: 4,
134
131
  });
135
132
  });
136
-
137
- test("empty selected input or one empty line → physical totals are zero or one", () => {
138
- const query = { patterns: ["^$"], literal: false, flags: "", multiline: false };
139
- for (const [lines, expected] of [
140
- ["", { lines: [], totalLines: 0 }],
141
- ["\n", { lines: [{ lineNumber: 1, column: 0 }], totalLines: 1 }],
142
- ] as const) {
143
- assert.deepEqual(searchLines({ lines, query, limit: 1 }), expected);
144
- }
145
- });