@openrewrite/rewrite 8.107.1 → 8.107.3

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.
@@ -0,0 +1,776 @@
1
+ /*
2
+ * Copyright 2026 the original author or authors.
3
+ * <p>
4
+ * Licensed under the Moderne Source Available License (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ * <p>
8
+ * https://docs.moderne.io/licensing/moderne-source-available-license
9
+ * <p>
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import {Cursor} from "../tree";
17
+ import {getValue, isAttribute, isCharData, isDocument, isTag, isXml, Xml} from "./tree";
18
+ import {localName} from "./namespaces";
19
+ import {ComparisonOp, CompiledExpr, CompiledFilterExpr, CompiledStep, CompiledXPath, compileXPath} from "./xpath-compiler";
20
+
21
+ type Value = string | number | boolean | undefined;
22
+
23
+ export class XPathMatcher {
24
+ private compiled?: CompiledXPath;
25
+
26
+ constructor(readonly expression: string) {
27
+ }
28
+
29
+ matches(cursor: Cursor): boolean {
30
+ const compiled = this.compiled ??= compileXPath(this.expression);
31
+ switch (compiled.type) {
32
+ case "path":
33
+ return compiled.steps.length > 0 && new PathMatch(compiled.steps, compiled.absolute).matches(cursor);
34
+ case "boolean":
35
+ return matchBooleanExpr(compiled.expr, cursor);
36
+ case "filter":
37
+ return matchFilterExpr(compiled.filter, cursor);
38
+ }
39
+ }
40
+ }
41
+
42
+ function isTagCursor(cursor: Cursor | undefined): cursor is Cursor & { value: Xml.Tag } {
43
+ return cursor !== undefined && isXml(cursor.value) && isTag(cursor.value);
44
+ }
45
+
46
+ function parentTagCursor(cursor: Cursor | undefined): Cursor | undefined {
47
+ let parent = cursor?.parent;
48
+ while (parent && !isTagCursor(parent)) {
49
+ if (isXml(parent.value) && isDocument(parent.value)) {
50
+ return undefined;
51
+ }
52
+ parent = parent.parent;
53
+ }
54
+ return parent;
55
+ }
56
+
57
+ function matchesElementName(step: CompiledStep, name: string): boolean {
58
+ return step.nodeType === "node" || step.nodeType === "unknown" && matchesName(step.name, name);
59
+ }
60
+
61
+ function matchesName(pattern: string | undefined, name: string): boolean {
62
+ return pattern === undefined || pattern === "*" || name === pattern;
63
+ }
64
+
65
+ class PathMatch {
66
+ constructor(private readonly steps: CompiledStep[], private readonly absolute: boolean) {
67
+ }
68
+
69
+ matches(cursor: Cursor): boolean {
70
+ const steps = this.steps;
71
+ const value = isXml(cursor.value) ? cursor.value : undefined;
72
+ const last = steps[steps.length - 1];
73
+
74
+ if (last.type === "attribute") {
75
+ if (!value || !isAttribute(value) || !matchesName(last.name, value.key.name)) {
76
+ return false;
77
+ }
78
+ if (!last.predicates.every(p => evaluateExpr(p, undefined, value, cursor, 1, 1))) {
79
+ return false;
80
+ }
81
+ const parent = cursor.parent;
82
+ return isTagCursor(parent) && this.matchRemaining(parent, steps.length - 2);
83
+ }
84
+
85
+ if (last.type === "nodeType") {
86
+ return this.matchNodeTypeTest(last, cursor, steps.length - 2);
87
+ }
88
+
89
+ if (last.type === "dotdot" || (last.type === "axis" && last.axis === "parent")) {
90
+ return this.matchParentStepAsLast(last, cursor, steps.length - 2);
91
+ }
92
+
93
+ if (last.type === "dot" || (last.type === "axis" && last.axis === "self")) {
94
+ if (!value || !isTag(value) || (last.type === "axis" && !matchesElementName(last, value.name))) {
95
+ return false;
96
+ }
97
+ return this.matchRemaining(cursor, steps.length - 2);
98
+ }
99
+
100
+ if (!value || !isTag(value) || !matchStepAgainstTag(last, value, cursor)) {
101
+ return false;
102
+ }
103
+ return this.matchRemaining(parentTagCursor(cursor), steps.length - 2);
104
+ }
105
+
106
+ private matchParentStepAsLast(step: CompiledStep, cursor: Cursor, previous: number): boolean {
107
+ if (!isTagCursor(cursor)) {
108
+ return false;
109
+ }
110
+ const tag = cursor.value;
111
+ if (step.type === "axis" && !matchesElementName(step, tag.name)) {
112
+ return false;
113
+ }
114
+ if (previous < 0) {
115
+ return true;
116
+ }
117
+ const previousStep = this.steps[previous];
118
+ if (previousStep.type === "nodeTest" && previousStep.name !== undefined &&
119
+ !findChildTag(tag, previousStep.name)) {
120
+ return false;
121
+ }
122
+ return this.matchRemaining(cursor, previous - 1);
123
+ }
124
+
125
+ private matchParentStepInMiddle(cursor: Cursor | undefined, previous: number): boolean {
126
+ if (!isTagCursor(cursor)) {
127
+ return false;
128
+ }
129
+ if (previous < 0) {
130
+ if (this.absolute && !this.steps[0].isDescendant) {
131
+ return !isTagCursor(parentTagCursor(cursor));
132
+ }
133
+ return true;
134
+ }
135
+ const previousStep = this.steps[previous];
136
+ if (previousStep.type === "nodeTest" && previousStep.name !== undefined &&
137
+ !findChildTag(cursor.value, previousStep.name)) {
138
+ return false;
139
+ }
140
+ return this.matchRemaining(cursor, previous - 1);
141
+ }
142
+
143
+ private matchNodeTypeTest(step: CompiledStep, cursor: Cursor, next: number): boolean {
144
+ const value = cursor.value;
145
+ switch (step.nodeType) {
146
+ case "text":
147
+ if (isXml(value) && value.kind === Xml.Kind.CharData) {
148
+ return this.matchRemaining(parentTagCursor(cursor), next);
149
+ }
150
+ if (isXml(value) && isTag(value) && getValue(value) !== undefined) {
151
+ return this.matchRemaining(cursor, next);
152
+ }
153
+ return false;
154
+ case "comment":
155
+ return isXml(value) && value.kind === Xml.Kind.Comment &&
156
+ this.matchRemaining(parentTagCursor(cursor), next);
157
+ case "node":
158
+ return this.matchRemaining(parentTagCursor(cursor), next);
159
+ case "processing-instruction":
160
+ return isXml(value) && value.kind === Xml.Kind.ProcessingInstruction &&
161
+ this.matchRemaining(parentTagCursor(cursor), next);
162
+ default:
163
+ return false;
164
+ }
165
+ }
166
+
167
+ private matchRemaining(cursor: Cursor | undefined, index: number): boolean {
168
+ if (index < 0) {
169
+ return !this.absolute || !isTagCursor(cursor);
170
+ }
171
+
172
+ const step = this.steps[index];
173
+ switch (step.type) {
174
+ case "dot":
175
+ return this.matchRemaining(cursor, index - 1);
176
+ case "dotdot":
177
+ return this.matchParentStepInMiddle(cursor, index - 1);
178
+ case "axis":
179
+ return this.matchAxisStep(step, cursor, index);
180
+ case "nodeType":
181
+ return step.nodeType === "node" && this.matchRemaining(cursor, index - 1);
182
+ }
183
+
184
+ if (this.steps[index + 1].isDescendant) {
185
+ for (let pos = cursor; isTagCursor(pos); pos = parentTagCursor(pos)) {
186
+ if (matchStepAgainstTag(step, pos.value, pos) && this.matchRemaining(parentTagCursor(pos), index - 1)) {
187
+ return true;
188
+ }
189
+ }
190
+ return false;
191
+ }
192
+ return isTagCursor(cursor) && matchStepAgainstTag(step, cursor.value, cursor) &&
193
+ this.matchRemaining(parentTagCursor(cursor), index - 1);
194
+ }
195
+
196
+ private matchAxisStep(step: CompiledStep, cursor: Cursor | undefined, index: number): boolean {
197
+ switch (step.axis) {
198
+ case "parent":
199
+ if (isTagCursor(cursor) && !matchesElementName(step, cursor.value.name)) {
200
+ return false;
201
+ }
202
+ return this.matchParentStepInMiddle(cursor, index - 1);
203
+ case "self":
204
+ if (isTagCursor(cursor) && !matchesElementName(step, cursor.value.name)) {
205
+ return false;
206
+ }
207
+ return this.matchRemaining(cursor, index - 1);
208
+ case "child":
209
+ return isTagCursor(cursor) && matchStepAgainstTag(step, cursor.value, cursor) &&
210
+ this.matchRemaining(parentTagCursor(cursor), index - 1);
211
+ default:
212
+ return false;
213
+ }
214
+ }
215
+ }
216
+
217
+ function matchStepAgainstTag(step: CompiledStep, tag: Xml.Tag, cursor: Cursor): boolean {
218
+ switch (step.type) {
219
+ case "nodeTest":
220
+ return matchesName(step.name, tag.name) &&
221
+ (step.predicates.length === 0 || evaluatePredicates(step, tag, cursor));
222
+ case "dot":
223
+ return true;
224
+ case "nodeType":
225
+ return step.nodeType === "node";
226
+ default:
227
+ return false;
228
+ }
229
+ }
230
+
231
+ function needsPosition(expr: CompiledExpr): boolean {
232
+ switch (expr.type) {
233
+ case "numeric":
234
+ return true;
235
+ case "function":
236
+ return expr.functionType === "position" || expr.functionType === "last" || expr.args.some(needsPosition);
237
+ case "comparison":
238
+ case "and":
239
+ case "or":
240
+ return needsPosition(expr.left) || needsPosition(expr.right);
241
+ default:
242
+ return false;
243
+ }
244
+ }
245
+
246
+ function evaluatePredicates(step: CompiledStep, tag: Xml.Tag, cursor: Cursor): boolean {
247
+ if (!step.predicates.some(needsPosition)) {
248
+ return step.predicates.every(p => evaluateExpr(p, tag, undefined, cursor, 1, 1));
249
+ }
250
+ const parent = cursor.parent;
251
+ const candidates = isTagCursor(parent) ? (parent.value.content ?? [])
252
+ .filter((c: Xml.Content): c is Xml.Tag => isTag(c) && matchesName(step.name, c.name))
253
+ .map((c: Xml.Tag) => new Cursor(c, parent)) : [cursor];
254
+ return filterCandidates(candidates, step.predicates).some(c => c.value === tag);
255
+ }
256
+
257
+ function evaluateExpr(expr: CompiledExpr, tag: Xml.Tag | undefined, attr: Xml.Attribute | undefined,
258
+ cursor: Cursor, position: number, size: number): boolean {
259
+ switch (expr.type) {
260
+ case "numeric":
261
+ return position === expr.value;
262
+ case "and":
263
+ return evaluateExpr(expr.left, tag, attr, cursor, position, size) &&
264
+ evaluateExpr(expr.right, tag, attr, cursor, position, size);
265
+ case "or":
266
+ return evaluateExpr(expr.left, tag, attr, cursor, position, size) ||
267
+ evaluateExpr(expr.right, tag, attr, cursor, position, size);
268
+ case "comparison": {
269
+ const left = resolveValue(expr.left, tag, attr, cursor, position, size);
270
+ const right = resolveValue(expr.right, tag, attr, cursor, position, size);
271
+ return left !== undefined && right !== undefined && compareValues(left, right, expr.op);
272
+ }
273
+ case "function":
274
+ return evaluateFunction(expr, tag, attr, cursor, position, size);
275
+ case "child":
276
+ return tag !== undefined && findChildTag(tag, expr.name) !== undefined;
277
+ case "path":
278
+ return tag !== undefined && (expr.pathSteps ? selectSteps([cursor], expr.pathSteps).length > 0 : pathExists(tag, expr.steps));
279
+ case "attribute":
280
+ return tag !== undefined && tag.attributes.some(a => matchesName(expr.name, a.key.name));
281
+ default:
282
+ return false;
283
+ }
284
+ }
285
+
286
+ function resolveValue(expr: CompiledExpr, tag: Xml.Tag | undefined, attr: Xml.Attribute | undefined,
287
+ cursor: Cursor, position: number, size: number): Value {
288
+ switch (expr.type) {
289
+ case "string":
290
+ case "numeric":
291
+ return expr.value;
292
+ case "child": {
293
+ const child = tag && findChildTag(tag, expr.name);
294
+ return child && (getValue(child) ?? "");
295
+ }
296
+ case "attribute":
297
+ if (tag) {
298
+ return attributeValue(tag, expr.name);
299
+ }
300
+ if (attr) {
301
+ if (expr.name === "*") {
302
+ return attr.value.value;
303
+ }
304
+ const parent = cursor.parent;
305
+ if (isTagCursor(parent)) {
306
+ return attributeValue(parent.value, expr.name);
307
+ }
308
+ }
309
+ return undefined;
310
+ case "self":
311
+ return tag ? stringValue(tag) : attr?.value.value;
312
+ case "path": {
313
+ if (expr.pathSteps) {
314
+ const first = selectSteps([cursor], expr.pathSteps)[0];
315
+ return first && stringValue(first.value);
316
+ }
317
+ return tag && resolvePathValue(expr.steps, tag);
318
+ }
319
+ case "absolutePath": {
320
+ const root = rootTag(cursor);
321
+ const first = root && [...findTagsByPath(root, expr.path).values()][0];
322
+ return first ? getValue(first) ?? "" : "";
323
+ }
324
+ case "function":
325
+ return resolveFunctionValue(expr, tag, attr, cursor, position, size);
326
+ default:
327
+ return undefined;
328
+ }
329
+ }
330
+
331
+ function evaluateFunction(expr: CompiledExpr & { type: "function" }, tag: Xml.Tag | undefined,
332
+ attr: Xml.Attribute | undefined, cursor: Cursor, position: number, size: number): boolean {
333
+ switch (expr.functionType) {
334
+ case "position":
335
+ return position > 0;
336
+ case "last":
337
+ return position === size;
338
+ case "not":
339
+ return expr.args.length > 0 && !evaluateExpr(expr.args[0], tag, attr, cursor, position, size);
340
+ case "contains":
341
+ case "starts-with":
342
+ case "ends-with":
343
+ return resolveFunctionValue(expr, tag, attr, cursor, position, size) === true;
344
+ case "string-length":
345
+ case "count": {
346
+ const result = resolveFunctionValue(expr, tag, attr, cursor, position, size);
347
+ return typeof result === "number" && result > 0;
348
+ }
349
+ case "text": {
350
+ const value = tag && getValue(tag);
351
+ return value !== undefined && javaTrim(value) !== "";
352
+ }
353
+ case "local-name":
354
+ case "namespace-uri":
355
+ return true;
356
+ default:
357
+ return false;
358
+ }
359
+ }
360
+
361
+ function resolveFunctionValue(expr: CompiledExpr & { type: "function" }, tag: Xml.Tag | undefined,
362
+ attr: Xml.Attribute | undefined, cursor: Cursor, position: number, size: number): Value {
363
+ const args = expr.args;
364
+ const stringArg = (i: number): string | undefined => {
365
+ const value = resolveValue(args[i], tag, attr, cursor, position, size);
366
+ return value === undefined ? undefined : functionStringValue(value);
367
+ };
368
+ switch (expr.functionType) {
369
+ case "position":
370
+ return position;
371
+ case "last":
372
+ return size;
373
+ case "local-name": {
374
+ const target = args.length > 0 && args[0].type === "parent" ? parentTagCursor(cursor)?.value as Xml.Tag | undefined : tag;
375
+ if (target) {
376
+ return localName(target.name);
377
+ }
378
+ return attr && args.length === 0 ? localName(attr.key.name) : undefined;
379
+ }
380
+ case "namespace-uri": {
381
+ let target = tag;
382
+ let targetCursor = cursor;
383
+ if (args.length > 0 && args[0].type === "parent") {
384
+ const parent = parentTagCursor(cursor);
385
+ if (!isTagCursor(parent)) {
386
+ return undefined;
387
+ }
388
+ target = parent.value;
389
+ targetCursor = parent;
390
+ }
391
+ if (target) {
392
+ return findNamespaceUri(namespacePrefixOf(target.name), targetCursor);
393
+ }
394
+ if (attr && args.length === 0) {
395
+ const name = attr.key.name;
396
+ return name.includes(":") ? findNamespaceUri(namespacePrefixOf(name), cursor) : "";
397
+ }
398
+ return undefined;
399
+ }
400
+ case "text":
401
+ return tag && (getValue(tag) ?? "");
402
+ case "string-length":
403
+ return args.length > 0 ? stringArg(0)?.length ?? 0 : 0;
404
+ case "substring-before":
405
+ case "substring-after": {
406
+ if (args.length < 2) {
407
+ return "";
408
+ }
409
+ const str = stringArg(0);
410
+ const delimiter = stringArg(1);
411
+ if (str === undefined || delimiter === undefined) {
412
+ return "";
413
+ }
414
+ const index = str.indexOf(delimiter);
415
+ if (index < 0) {
416
+ return "";
417
+ }
418
+ return expr.functionType === "substring-before" ? str.substring(0, index) : str.substring(index + delimiter.length);
419
+ }
420
+ case "count": {
421
+ const path = args[0];
422
+ if (path?.type === "absolutePath") {
423
+ const root = rootTag(cursor);
424
+ if (root) {
425
+ return findTagsByPath(root, path.path).size;
426
+ }
427
+ }
428
+ return 0;
429
+ }
430
+ case "contains":
431
+ case "starts-with":
432
+ case "ends-with": {
433
+ if (args.length < 2) {
434
+ return false;
435
+ }
436
+ const str = stringArg(0);
437
+ const other = stringArg(1);
438
+ if (str === undefined || other === undefined) {
439
+ return false;
440
+ }
441
+ return expr.functionType === "contains" ? str.includes(other) :
442
+ expr.functionType === "starts-with" ? str.startsWith(other) : str.endsWith(other);
443
+ }
444
+ default:
445
+ return undefined;
446
+ }
447
+ }
448
+
449
+ function namespacePrefixOf(name: string): string {
450
+ const colon = name.indexOf(":");
451
+ return colon >= 0 ? name.substring(0, colon) : "";
452
+ }
453
+
454
+ function findNamespaceUri(prefix: string, cursor: Cursor): string | undefined {
455
+ const declaration = prefix === "" ? "xmlns" : `xmlns:${prefix}`;
456
+ for (let c: Cursor | undefined = cursor; c; c = c.parent) {
457
+ if (isTagCursor(c)) {
458
+ const attribute = c.value.attributes.find((a: Xml.Attribute) => a.key.name === declaration);
459
+ if (attribute) {
460
+ return attribute.value.value;
461
+ }
462
+ }
463
+ }
464
+ return prefix === "" ? "" : undefined;
465
+ }
466
+
467
+ function attributeValue(tag: Xml.Tag, name: string): string | undefined {
468
+ return tag.attributes.find(a => matchesName(name, a.key.name))?.value.value;
469
+ }
470
+
471
+ function findChildTag(parent: Xml.Tag, name: string): Xml.Tag | undefined {
472
+ return parent.content?.find((c): c is Xml.Tag => isTag(c) && matchesName(name, c.name));
473
+ }
474
+
475
+ function pathExists(tag: Xml.Tag, steps: CompiledExpr[]): boolean {
476
+ let current: Xml.Tag | undefined = tag;
477
+ for (const step of steps) {
478
+ current = step.type === "child" ? findChildTag(current, step.name) : undefined;
479
+ if (!current) {
480
+ return false;
481
+ }
482
+ }
483
+ return true;
484
+ }
485
+
486
+ function resolvePathValue(steps: CompiledExpr[], tag: Xml.Tag): string | undefined {
487
+ if (steps.length === 0) {
488
+ return undefined;
489
+ }
490
+ let current: Xml.Tag | undefined = tag;
491
+ for (const step of steps) {
492
+ current = step.type === "child" ? findChildTag(current, step.name) : undefined;
493
+ if (!current) {
494
+ return undefined;
495
+ }
496
+ }
497
+ return getValue(current) ?? "";
498
+ }
499
+
500
+ function compareValues(left: string | number | boolean, right: string | number | boolean, op: ComparisonOp): boolean {
501
+ if (typeof left === "number" || typeof right === "number" || op !== "=" && op !== "!=") {
502
+ return compareOrdered(numberValue(left), numberValue(right), op);
503
+ }
504
+ return op === "=" ? String(left) === String(right) : String(left) !== String(right);
505
+ }
506
+
507
+ function numberValue(value: string | number | boolean): number {
508
+ if (typeof value === "number") {
509
+ return value;
510
+ }
511
+ const text = javaTrim(String(value));
512
+ return /^-?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)$/.test(text) ? Number(text) : NaN;
513
+ }
514
+
515
+ function functionStringValue(value: string | number | boolean): string {
516
+ const text = String(value);
517
+ if (typeof value !== "number" || !Number.isFinite(value) || !text.includes("e")) {
518
+ return text;
519
+ }
520
+ const [coefficient, exponent] = text.split("e");
521
+ const sign = coefficient.startsWith("-") ? "-" : "";
522
+ const unsigned = coefficient.substring(sign.length);
523
+ const digits = unsigned.replace(".", "");
524
+ const point = (unsigned.includes(".") ? unsigned.indexOf(".") : unsigned.length) + Number(exponent);
525
+ if (point <= 0) {
526
+ return `${sign}0.${"0".repeat(-point)}${digits}`;
527
+ }
528
+ if (point >= digits.length) {
529
+ return sign + digits + "0".repeat(point - digits.length);
530
+ }
531
+ return `${sign}${digits.substring(0, point)}.${digits.substring(point)}`;
532
+ }
533
+
534
+ function compareOrdered(left: number, right: number, op: ComparisonOp): boolean {
535
+ switch (op) {
536
+ case "=":
537
+ return left === right;
538
+ case "!=":
539
+ return left !== right;
540
+ case "<":
541
+ return left < right;
542
+ case "<=":
543
+ return left <= right;
544
+ case ">":
545
+ return left > right;
546
+ case ">=":
547
+ return left >= right;
548
+ }
549
+ }
550
+
551
+ function javaTrim(s: string): string {
552
+ let start = 0;
553
+ let end = s.length;
554
+ while (start < end && s.charCodeAt(start) <= 0x20) {
555
+ start++;
556
+ }
557
+ while (end > start && s.charCodeAt(end - 1) <= 0x20) {
558
+ end--;
559
+ }
560
+ return s.substring(start, end);
561
+ }
562
+
563
+ function matchBooleanExpr(expr: CompiledExpr, cursor: Cursor): boolean {
564
+ if (!isTagCursor(cursor)) {
565
+ return false;
566
+ }
567
+ if (hasRelativePath(expr) || !hasPureAbsolutePath(expr)) {
568
+ return evaluateExpr(expr, cursor.value, undefined, cursor, 1, 1);
569
+ }
570
+ let parent = cursor.parent;
571
+ while (parent && !isTagCursor(parent) && !(isXml(parent.value) && isDocument(parent.value))) {
572
+ parent = parent.parent;
573
+ }
574
+ if (!parent || !isXml(parent.value) || !isDocument(parent.value)) {
575
+ return false;
576
+ }
577
+ return evaluateExpr(expr, cursor.value, undefined, cursor, 1, 1);
578
+ }
579
+
580
+ function hasRelativePath(expr: CompiledExpr): boolean {
581
+ switch (expr.type) {
582
+ case "child":
583
+ case "path":
584
+ return true;
585
+ case "comparison":
586
+ case "and":
587
+ case "or":
588
+ return hasRelativePath(expr.left) || hasRelativePath(expr.right);
589
+ case "function":
590
+ return expr.args.some(hasRelativePath);
591
+ default:
592
+ return false;
593
+ }
594
+ }
595
+
596
+ function hasPureAbsolutePath(expr: CompiledExpr): boolean {
597
+ switch (expr.type) {
598
+ case "absolutePath":
599
+ return expr.path.startsWith("/") && !expr.path.startsWith("//");
600
+ case "comparison":
601
+ case "and":
602
+ case "or": {
603
+ const leftPure = !hasAnyAbsolutePath(expr.left) || hasPureAbsolutePath(expr.left);
604
+ const rightPure = !hasAnyAbsolutePath(expr.right) || hasPureAbsolutePath(expr.right);
605
+ return (hasAnyAbsolutePath(expr.left) || hasAnyAbsolutePath(expr.right)) && leftPure && rightPure;
606
+ }
607
+ case "function": {
608
+ const absolute = expr.args.filter(hasAnyAbsolutePath);
609
+ return absolute.length > 0 && absolute.every(hasPureAbsolutePath);
610
+ }
611
+ default:
612
+ return false;
613
+ }
614
+ }
615
+
616
+ function hasAnyAbsolutePath(expr: CompiledExpr): boolean {
617
+ switch (expr.type) {
618
+ case "absolutePath":
619
+ return true;
620
+ case "comparison":
621
+ case "and":
622
+ case "or":
623
+ return hasAnyAbsolutePath(expr.left) || hasAnyAbsolutePath(expr.right);
624
+ case "function":
625
+ return expr.args.some(hasAnyAbsolutePath);
626
+ default:
627
+ return false;
628
+ }
629
+ }
630
+
631
+ function matchFilterExpr(filter: CompiledFilterExpr, cursor: Cursor): boolean {
632
+ const root = rootTag(cursor);
633
+ if (!root) {
634
+ return false;
635
+ }
636
+ let nodes = filterCandidates(findNodesByPath(root, filter.path), filter.predicates);
637
+ if (filter.trailingPath) {
638
+ if (filter.trailingIsDescendant) {
639
+ nodes = nodes.flatMap(c => collectDescendants(c));
640
+ }
641
+ nodes = selectSteps(nodes, filter.trailingPath);
642
+ }
643
+ return nodes.some(c => c.value === cursor.value);
644
+ }
645
+
646
+ function rootTag(cursor: Cursor): Xml.Tag | undefined {
647
+ let c = cursor;
648
+ while (c.parent && !(isXml(c.parent.value) && isDocument(c.parent.value))) {
649
+ c = c.parent;
650
+ }
651
+ return isTagCursor(c) ? c.value : undefined;
652
+ }
653
+
654
+ type Tags = Map<string, Xml.Tag>;
655
+
656
+ function findTagsByPath(root: Xml.Tag, path: string): Tags {
657
+ return new Map(findNodesByPath(root, path).filter(isTagCursor).map(c => [c.value.id, c.value]));
658
+ }
659
+
660
+ function findNodesByPath(root: Xml.Tag, path: string): Cursor[] {
661
+ if (compileXPath(path).type !== "path") {
662
+ throw new Error(`Unsupported XPath expression: parenthesized expression must be a location path: ${path}`);
663
+ }
664
+ const matcher = new XPathMatcher(path);
665
+ const matches: Cursor[] = [];
666
+ for (const candidate of collectDescendants(new Cursor(root))) {
667
+ if (matcher.matches(candidate)) {
668
+ matches.push(candidate);
669
+ }
670
+ if (isTagCursor(candidate)) {
671
+ for (const attr of candidate.value.attributes) {
672
+ const attrCursor = new Cursor(attr, candidate);
673
+ if (matcher.matches(attrCursor)) {
674
+ matches.push(attrCursor);
675
+ }
676
+ }
677
+ }
678
+ }
679
+ return matches;
680
+ }
681
+
682
+ function collectDescendants(cursor: Cursor, result: Cursor[] = []): Cursor[] {
683
+ result.push(cursor);
684
+ if (isTagCursor(cursor)) {
685
+ for (const child of cursor.value.content ?? []) {
686
+ if (isTag(child)) {
687
+ collectDescendants(new Cursor(child, cursor), result);
688
+ }
689
+ }
690
+ }
691
+ return result;
692
+ }
693
+
694
+ function selectSteps(contexts: Cursor[], steps: CompiledStep[]): Cursor[] {
695
+ for (const step of steps) {
696
+ const next: Cursor[] = [];
697
+ for (const context of contexts) {
698
+ const origins = step.isDescendant ? collectDescendants(context) : [context];
699
+ for (const origin of origins) {
700
+ const candidates: Cursor[] = [];
701
+ const value = origin.value;
702
+ if (step.type === "dot" || step.type === "axis" && step.axis === "self") {
703
+ if (step.type === "dot" || matchesNodeTest(step, value)) {
704
+ candidates.push(origin);
705
+ }
706
+ } else if (step.type === "dotdot" || step.type === "axis" && step.axis === "parent") {
707
+ const parent = parentTagCursor(origin);
708
+ if (isTagCursor(parent) && (step.type === "dotdot" || matchesElementName(step, parent.value.name))) {
709
+ candidates.push(parent);
710
+ }
711
+ } else if (isTagCursor(origin)) {
712
+ if (step.type === "attribute") {
713
+ for (const attr of origin.value.attributes) {
714
+ if (matchesName(step.name, attr.key.name)) {
715
+ candidates.push(new Cursor(attr, origin));
716
+ }
717
+ }
718
+ } else if (step.type === "nodeType") {
719
+ for (const content of origin.value.content ?? []) {
720
+ if (matchesNodeTest(step, content)) {
721
+ candidates.push(new Cursor(content, origin));
722
+ }
723
+ }
724
+ } else {
725
+ for (const child of origin.value.content ?? []) {
726
+ if (isTag(child) && (step.type === "axis" ? matchesElementName(step, child.name) :
727
+ matchesName(step.name, child.name))) {
728
+ candidates.push(new Cursor(child, origin));
729
+ }
730
+ }
731
+ }
732
+ }
733
+ next.push(...filterCandidates(candidates, step.predicates));
734
+ }
735
+ }
736
+ contexts = next;
737
+ }
738
+ return contexts;
739
+ }
740
+
741
+ function filterCandidates(candidates: Cursor[], predicates: CompiledExpr[]): Cursor[] {
742
+ for (const predicate of predicates) {
743
+ candidates = candidates.filter((candidate, i) => {
744
+ const value = candidate.value;
745
+ return evaluateExpr(predicate, isTagCursor(candidate) ? value : undefined,
746
+ isXml(value) && isAttribute(value) ? value : undefined, candidate, i + 1, candidates.length);
747
+ });
748
+ }
749
+ return candidates;
750
+ }
751
+
752
+ function stringValue(node: Xml): string {
753
+ if (isAttribute(node)) {
754
+ return node.value.value;
755
+ }
756
+ if (isCharData(node)) {
757
+ return node.text;
758
+ }
759
+ return isTag(node) ? (node.content ?? []).filter(c => isTag(c) || c.kind === Xml.Kind.CharData)
760
+ .map(stringValue).join("") : "";
761
+ }
762
+
763
+ function matchesNodeTest(step: CompiledStep, value: Xml): boolean {
764
+ switch (step.nodeType) {
765
+ case "node":
766
+ return true;
767
+ case "text":
768
+ return value.kind === Xml.Kind.CharData;
769
+ case "comment":
770
+ return value.kind === Xml.Kind.Comment;
771
+ case "processing-instruction":
772
+ return value.kind === Xml.Kind.ProcessingInstruction;
773
+ default:
774
+ return isTag(value) && matchesName(step.name, value.name);
775
+ }
776
+ }