@libreflare/worker-runtime 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +235 -13
- package/dist/rule-evaluator/accept-encoding.d.ts +2 -2
- package/dist/rule-evaluator/accept-encoding.d.ts.map +1 -1
- package/dist/rule-evaluator/accept-encoding.js +62 -15
- package/dist/rule-evaluator/accept-encoding.js.map +1 -1
- package/dist/rule-evaluator/access-values.d.ts +77 -14
- package/dist/rule-evaluator/access-values.d.ts.map +1 -1
- package/dist/rule-evaluator/access-values.js +149 -17
- package/dist/rule-evaluator/access-values.js.map +1 -1
- package/dist/rule-evaluator/analysis.d.ts +43 -8
- package/dist/rule-evaluator/analysis.d.ts.map +1 -1
- package/dist/rule-evaluator/analysis.js +72 -29
- package/dist/rule-evaluator/analysis.js.map +1 -1
- package/dist/rule-evaluator/ast.d.ts +145 -11
- package/dist/rule-evaluator/ast.d.ts.map +1 -1
- package/dist/rule-evaluator/ast.js +102 -4
- package/dist/rule-evaluator/ast.js.map +1 -1
- package/dist/rule-evaluator/byte-strings.d.ts +23 -0
- package/dist/rule-evaluator/byte-strings.d.ts.map +1 -0
- package/dist/rule-evaluator/byte-strings.js +150 -0
- package/dist/rule-evaluator/byte-strings.js.map +1 -0
- package/dist/rule-evaluator/constants.d.ts +1 -1
- package/dist/rule-evaluator/constants.d.ts.map +1 -1
- package/dist/rule-evaluator/constants.js +1 -0
- package/dist/rule-evaluator/constants.js.map +1 -1
- package/dist/rule-evaluator/country-codes.generated.js +1 -1
- package/dist/rule-evaluator/custom-lists.d.ts +9 -0
- package/dist/rule-evaluator/custom-lists.d.ts.map +1 -1
- package/dist/rule-evaluator/custom-lists.js +43 -0
- package/dist/rule-evaluator/custom-lists.js.map +1 -1
- package/dist/rule-evaluator/diagnostics.d.ts +1 -3
- package/dist/rule-evaluator/diagnostics.d.ts.map +1 -1
- package/dist/rule-evaluator/diagnostics.js +10 -53
- package/dist/rule-evaluator/diagnostics.js.map +1 -1
- package/dist/rule-evaluator/engine-observations.d.ts +37 -0
- package/dist/rule-evaluator/engine-observations.d.ts.map +1 -0
- package/dist/rule-evaluator/engine-observations.generated.d.ts +991 -0
- package/dist/rule-evaluator/engine-observations.generated.d.ts.map +1 -0
- package/dist/rule-evaluator/engine-observations.generated.js +292 -0
- package/dist/rule-evaluator/engine-observations.generated.js.map +1 -0
- package/dist/rule-evaluator/engine-observations.js +13 -0
- package/dist/rule-evaluator/engine-observations.js.map +1 -0
- package/dist/rule-evaluator/evaluator.d.ts +1 -1
- package/dist/rule-evaluator/evaluator.d.ts.map +1 -1
- package/dist/rule-evaluator/evaluator.js +16 -15
- package/dist/rule-evaluator/evaluator.js.map +1 -1
- package/dist/rule-evaluator/explain.d.ts.map +1 -1
- package/dist/rule-evaluator/explain.js +35 -20
- package/dist/rule-evaluator/explain.js.map +1 -1
- package/dist/rule-evaluator/field-availability.d.ts +11 -10
- package/dist/rule-evaluator/field-availability.d.ts.map +1 -1
- package/dist/rule-evaluator/field-availability.js +136 -97
- package/dist/rule-evaluator/field-availability.js.map +1 -1
- package/dist/rule-evaluator/field-descriptions.generated.d.ts +1 -1
- package/dist/rule-evaluator/field-descriptions.generated.js +1 -1
- package/dist/rule-evaluator/field-descriptions.generated.js.map +1 -1
- package/dist/rule-evaluator/field-value-domains.d.ts.map +1 -1
- package/dist/rule-evaluator/field-value-domains.js +2 -4
- package/dist/rule-evaluator/field-value-domains.js.map +1 -1
- package/dist/rule-evaluator/fields.d.ts +25 -2
- package/dist/rule-evaluator/fields.d.ts.map +1 -1
- package/dist/rule-evaluator/fields.js +276 -119
- package/dist/rule-evaluator/fields.js.map +1 -1
- package/dist/rule-evaluator/function-availability.d.ts +16 -0
- package/dist/rule-evaluator/function-availability.d.ts.map +1 -0
- package/dist/rule-evaluator/function-availability.js +28 -0
- package/dist/rule-evaluator/function-availability.js.map +1 -0
- package/dist/rule-evaluator/function-descriptions.d.ts +15 -1
- package/dist/rule-evaluator/function-descriptions.d.ts.map +1 -1
- package/dist/rule-evaluator/function-descriptions.generated.d.ts +50 -7
- package/dist/rule-evaluator/function-descriptions.generated.d.ts.map +1 -1
- package/dist/rule-evaluator/function-descriptions.generated.js +98 -12
- package/dist/rule-evaluator/function-descriptions.generated.js.map +1 -1
- package/dist/rule-evaluator/function-descriptions.js +11 -2
- package/dist/rule-evaluator/function-descriptions.js.map +1 -1
- package/dist/rule-evaluator/function-signature-validation.d.ts +26 -2
- package/dist/rule-evaluator/function-signature-validation.d.ts.map +1 -1
- package/dist/rule-evaluator/function-signature-validation.js +311 -181
- package/dist/rule-evaluator/function-signature-validation.js.map +1 -1
- package/dist/rule-evaluator/functions.d.ts +24 -5
- package/dist/rule-evaluator/functions.d.ts.map +1 -1
- package/dist/rule-evaluator/functions.js +353 -190
- package/dist/rule-evaluator/functions.js.map +1 -1
- package/dist/rule-evaluator/hash-in-range.d.ts +33 -0
- package/dist/rule-evaluator/hash-in-range.d.ts.map +1 -0
- package/dist/rule-evaluator/hash-in-range.js +72 -0
- package/dist/rule-evaluator/hash-in-range.js.map +1 -0
- package/dist/rule-evaluator/log-sample.d.ts.map +1 -1
- package/dist/rule-evaluator/log-sample.js +14 -6
- package/dist/rule-evaluator/log-sample.js.map +1 -1
- package/dist/rule-evaluator/match-chain.d.ts +3 -3
- package/dist/rule-evaluator/match-chain.d.ts.map +1 -1
- package/dist/rule-evaluator/match-chain.js +19 -13
- package/dist/rule-evaluator/match-chain.js.map +1 -1
- package/dist/rule-evaluator/minifier.d.ts.map +1 -1
- package/dist/rule-evaluator/minifier.js +16 -20
- package/dist/rule-evaluator/minifier.js.map +1 -1
- package/dist/rule-evaluator/normalizer.d.ts.map +1 -1
- package/dist/rule-evaluator/normalizer.js +6 -6
- package/dist/rule-evaluator/normalizer.js.map +1 -1
- package/dist/rule-evaluator/operators.d.ts +11 -4
- package/dist/rule-evaluator/operators.d.ts.map +1 -1
- package/dist/rule-evaluator/operators.js +62 -35
- package/dist/rule-evaluator/operators.js.map +1 -1
- package/dist/rule-evaluator/outcome.d.ts +2 -0
- package/dist/rule-evaluator/outcome.d.ts.map +1 -1
- package/dist/rule-evaluator/outcome.js +4 -0
- package/dist/rule-evaluator/outcome.js.map +1 -1
- package/dist/rule-evaluator/parse-cache.d.ts +3 -3
- package/dist/rule-evaluator/parse-cache.d.ts.map +1 -1
- package/dist/rule-evaluator/parse-cache.js +5 -13
- package/dist/rule-evaluator/parse-cache.js.map +1 -1
- package/dist/rule-evaluator/parser.d.ts +318 -11
- package/dist/rule-evaluator/parser.d.ts.map +1 -1
- package/dist/rule-evaluator/parser.js +1314 -333
- package/dist/rule-evaluator/parser.js.map +1 -1
- package/dist/rule-evaluator/quantifier.d.ts +1 -1
- package/dist/rule-evaluator/quantifier.d.ts.map +1 -1
- package/dist/rule-evaluator/quantifier.js +1 -16
- package/dist/rule-evaluator/quantifier.js.map +1 -1
- package/dist/rule-evaluator/request-headers.d.ts +101 -0
- package/dist/rule-evaluator/request-headers.d.ts.map +1 -0
- package/dist/rule-evaluator/request-headers.js +344 -0
- package/dist/rule-evaluator/request-headers.js.map +1 -0
- package/dist/rule-evaluator/rule-language-types.d.ts +80 -21
- package/dist/rule-evaluator/rule-language-types.d.ts.map +1 -1
- package/dist/rule-evaluator/rule-language-types.js +228 -67
- package/dist/rule-evaluator/rule-language-types.js.map +1 -1
- package/dist/rule-evaluator/tokenizer.d.ts +14 -4
- package/dist/rule-evaluator/tokenizer.d.ts.map +1 -1
- package/dist/rule-evaluator/tokenizer.js +24 -11
- package/dist/rule-evaluator/tokenizer.js.map +1 -1
- package/dist/rule-evaluator/transformation.d.ts.map +1 -1
- package/dist/rule-evaluator/transformation.js +10 -6
- package/dist/rule-evaluator/transformation.js.map +1 -1
- package/dist/rule-evaluator/url-decode.d.ts +8 -0
- package/dist/rule-evaluator/url-decode.d.ts.map +1 -0
- package/dist/rule-evaluator/url-decode.js +126 -0
- package/dist/rule-evaluator/url-decode.js.map +1 -0
- package/dist/rule-evaluator/validation.d.ts.map +1 -1
- package/dist/rule-evaluator/validation.js +405 -235
- package/dist/rule-evaluator/validation.js.map +1 -1
- package/dist/rule-evaluator.d.ts +2 -2
- package/dist/rule-evaluator.d.ts.map +1 -1
- package/dist/rule-evaluator.js.map +1 -1
- package/package.json +5 -2
- package/dist/rule-evaluator/comparison.d.ts +0 -16
- package/dist/rule-evaluator/comparison.d.ts.map +0 -1
- package/dist/rule-evaluator/comparison.js +0 -43
- package/dist/rule-evaluator/comparison.js.map +0 -1
- package/dist/rule-evaluator/custom-security-rule-analysis.d.ts +0 -36
- package/dist/rule-evaluator/custom-security-rule-analysis.d.ts.map +0 -1
- package/dist/rule-evaluator/custom-security-rule-analysis.js +0 -382
- package/dist/rule-evaluator/custom-security-rule-analysis.js.map +0 -1
- package/dist/rule-evaluator/values.d.ts +0 -26
- package/dist/rule-evaluator/values.d.ts.map +0 -1
- package/dist/rule-evaluator/values.js +0 -55
- package/dist/rule-evaluator/values.js.map +0 -1
- package/dist/rule-evaluator/warnings.d.ts +0 -2
- package/dist/rule-evaluator/warnings.d.ts.map +0 -1
- package/dist/rule-evaluator/warnings.js +0 -5
- package/dist/rule-evaluator/warnings.js.map +0 -1
|
@@ -1,193 +1,703 @@
|
|
|
1
1
|
import { RULE_EXPRESSION_FUNCTIONS } from './constants.js';
|
|
2
2
|
import { isRuleExpressionIpAddress, isRuleExpressionIpLiteral } from './custom-lists.js';
|
|
3
3
|
import { KNOWN_AVAILABLE_FIELDS, KNOWN_UNAVAILABLE_FIELDS } from './fields.js';
|
|
4
|
-
import { unquotedSetElementType } from './rule-language-types.js';
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
4
|
+
import { acceptsComparisonArgument, canReturnBoolean, integerLiteralValue, isComparableValue, unquotedSetElementType } from './rule-language-types.js';
|
|
5
|
+
import { unhandledNode, } from './ast.js';
|
|
6
|
+
import { tokenLength } from './tokenizer.js';
|
|
7
7
|
const VALUE_CONTEXT_LOCATIONS = {
|
|
8
8
|
operator: 'on right side of operator',
|
|
9
9
|
function: 'as function argument',
|
|
10
10
|
set: 'in inline list',
|
|
11
11
|
};
|
|
12
|
+
/**
|
|
13
|
+
* The arguments of any() or all(). They take no comma, so none may be
|
|
14
|
+
* another call's or come after a missing comma, and they return a Boolean,
|
|
15
|
+
* which recovery never cuts short.
|
|
16
|
+
*/
|
|
17
|
+
function quantifierArguments(args, uncertainFrom, moreArguments) {
|
|
18
|
+
return { args, uncertainFrom, moreArguments, openInCall: false, strayArgument: false, cutShort: false };
|
|
19
|
+
}
|
|
20
|
+
const NO_CONSTRUCTS = { closed: -1, call: -1, logical: -1, access: -1 };
|
|
21
|
+
/** The closer of each opener, and the opener of each closer. */
|
|
22
|
+
const CLOSER_OF = { LParen: 'RParen', LBracket: 'RBracket', LBrace: 'RBrace' };
|
|
23
|
+
const OPENER_OF = { RParen: 'LParen', RBracket: 'LBracket', RBrace: 'LBrace' };
|
|
24
|
+
// Compared directly rather than read from OPENER_OF: it runs for most tokens, where the lookup cost about a
|
|
25
|
+
// tenth of parsing.
|
|
26
|
+
function isCloser(token) {
|
|
27
|
+
return token.kind === 'RParen' || token.kind === 'RBracket' || token.kind === 'RBrace';
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Pairs each opener with its closer, by token index, or -1 when it has none.
|
|
31
|
+
* A closer that matches the innermost open opener closes it. One that does
|
|
32
|
+
* not is stray when both that opener's own closer and another closer of its
|
|
33
|
+
* kind still come later, unclaimed by an opener after it, so that the
|
|
34
|
+
* innermost opener and an opener of its kind still have one. With more
|
|
35
|
+
* openers of its kind open than come later, the outer ones go without; see
|
|
36
|
+
* docs/parser-error-recovery.md. Otherwise it closes the nearest open opener
|
|
37
|
+
* of its kind, leaving the openers inside that one without closers.
|
|
38
|
+
*
|
|
39
|
+
* Inside a call, when too few `)` follow for every open `(`, a token that
|
|
40
|
+
* what is open cannot take ends it without its `)`: a comma after a complete
|
|
41
|
+
* operand ends the groups, any(), and all() inside the call, and a comparison
|
|
42
|
+
* the call cannot take ends the call; see readsComparison(). An access takes
|
|
43
|
+
* no comparison either, so when too few `]` follow, it ends at one first.
|
|
44
|
+
*/
|
|
45
|
+
function pairDelimiters(tokens) {
|
|
46
|
+
const partners = new Int32Array(tokens.length).fill(-1);
|
|
47
|
+
// Most input nests, with each closer closing the innermost opener and every opener closed, and needs
|
|
48
|
+
// only one stack.
|
|
49
|
+
const open = [];
|
|
50
|
+
for (let index = 0; index < tokens.length; index++) {
|
|
51
|
+
switch (tokens[index].kind) {
|
|
52
|
+
case 'LParen':
|
|
53
|
+
case 'LBracket':
|
|
54
|
+
case 'LBrace':
|
|
55
|
+
open.push(index);
|
|
56
|
+
break;
|
|
57
|
+
case 'RParen':
|
|
58
|
+
case 'RBracket':
|
|
59
|
+
case 'RBrace': {
|
|
60
|
+
const opener = open.pop();
|
|
61
|
+
if (opener === undefined || CLOSER_OF[tokens[opener].kind] !== tokens[index].kind)
|
|
62
|
+
return pairMisnested(tokens);
|
|
63
|
+
partners[opener] = index;
|
|
64
|
+
partners[index] = opener;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return open.length === 0 ? partners : pairMisnested(tokens);
|
|
69
|
+
}
|
|
70
|
+
/** pairDelimiters() for input that does not nest, or leaves an opener without its closer. */
|
|
71
|
+
function pairMisnested(tokens) {
|
|
72
|
+
// Only a closer that does not match the innermost opener, a comma, or a comparison needs these.
|
|
73
|
+
let unclaimed;
|
|
74
|
+
const partners = new Int32Array(tokens.length).fill(-1);
|
|
75
|
+
// The open openers, innermost last, and for each kind, their depths in `open`.
|
|
76
|
+
const open = [];
|
|
77
|
+
const depthsByKind = new Map(Object.keys(CLOSER_OF).map(kind => [kind, []]));
|
|
78
|
+
// For each open opener, the depth of the call that takes commas at or below it with only groups and
|
|
79
|
+
// quantifiers between them, or -1.
|
|
80
|
+
const callDepths = [];
|
|
81
|
+
// For each open opener, whether it is a call whose current argument is a condition: one with a group, a
|
|
82
|
+
// quantifier, `not`, or a logical operator in it, as the parser reads one; see parseFunctionArg().
|
|
83
|
+
const conditions = [];
|
|
84
|
+
// For each open opener that starts a call that takes commas, its function's name and the index of the
|
|
85
|
+
// argument it reads.
|
|
86
|
+
const names = [];
|
|
87
|
+
const argumentIndexes = [];
|
|
88
|
+
const leave = (depth) => {
|
|
89
|
+
while (open.length > depth) {
|
|
90
|
+
depthsByKind.get(tokens[open.pop()].kind).pop();
|
|
91
|
+
callDepths.pop();
|
|
92
|
+
conditions.pop();
|
|
93
|
+
names.pop();
|
|
94
|
+
argumentIndexes.pop();
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
// The depth of the innermost open opener when it is a call that takes commas, or -1.
|
|
98
|
+
const innermostCall = () => {
|
|
99
|
+
const call = callDepths.at(-1) ?? -1;
|
|
100
|
+
return call === open.length - 1 ? call : -1;
|
|
101
|
+
};
|
|
102
|
+
const markCondition = () => {
|
|
103
|
+
const call = innermostCall();
|
|
104
|
+
if (call >= 0)
|
|
105
|
+
conditions[call] = true;
|
|
106
|
+
};
|
|
107
|
+
const tooFewClosersAfter = (index, opener) => {
|
|
108
|
+
unclaimed ??= unclaimedClosers(tokens);
|
|
109
|
+
return unclaimed.get(CLOSER_OF[opener])[index + 1] < depthsByKind.get(opener).length;
|
|
110
|
+
};
|
|
111
|
+
tokens.forEach((token, index) => {
|
|
112
|
+
const depths = depthsByKind.get(token.kind);
|
|
113
|
+
if (depths) {
|
|
114
|
+
const name = token.kind === 'LParen' ? callName(tokens, partners, index) : undefined;
|
|
115
|
+
const startsCall = name !== undefined;
|
|
116
|
+
if (token.kind === 'LParen' && !startsCall)
|
|
117
|
+
markCondition();
|
|
118
|
+
names.push(name);
|
|
119
|
+
argumentIndexes.push(0);
|
|
120
|
+
callDepths.push(token.kind !== 'LParen' ? -1 : startsCall ? open.length : callDepths.at(-1) ?? -1);
|
|
121
|
+
conditions.push(false);
|
|
122
|
+
depths.push(open.length);
|
|
123
|
+
open.push(index);
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
if (token.kind === 'Comma') {
|
|
127
|
+
const call = callDepths.at(-1) ?? -1;
|
|
128
|
+
if (call < 0)
|
|
129
|
+
return;
|
|
130
|
+
if (call < open.length - 1) {
|
|
131
|
+
// A group or a quantifier takes no comma, so after a complete operand in one inside a call, when
|
|
132
|
+
// too few `)` follow, it ends at the comma without its `)`, and the call takes the comma.
|
|
133
|
+
if (!endsOperand(tokens[index - 1]) || !tooFewClosersAfter(index, 'LParen'))
|
|
134
|
+
return;
|
|
135
|
+
leave(call + 1);
|
|
136
|
+
}
|
|
137
|
+
conditions[call] = false;
|
|
138
|
+
argumentIndexes[call]++;
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
if (isLogicalOperator(token) || (token.kind === 'Operator' && token.value === 'not')) {
|
|
142
|
+
markCondition();
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
if (isComparisonStart(tokens, index)) {
|
|
146
|
+
// The parser ends an access without its `]` at a comparison; see endsAtComparison().
|
|
147
|
+
while (startsAccess(tokens, open.at(-1) ?? -1) && tooFewClosersAfter(index, 'LBracket'))
|
|
148
|
+
leave(open.length - 1);
|
|
149
|
+
const call = innermostCall();
|
|
150
|
+
if (call >= 0 && !conditions[call] && tooFewClosersAfter(index, 'LParen') &&
|
|
151
|
+
!readsComparison(tokens, partners, open[call], index, names[call], argumentIndexes[call])) {
|
|
152
|
+
leave(call);
|
|
153
|
+
}
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
const opener = OPENER_OF[token.kind];
|
|
157
|
+
const innermost = open.at(-1);
|
|
158
|
+
if (!opener || innermost === undefined)
|
|
159
|
+
return;
|
|
160
|
+
const innermostCloser = CLOSER_OF[tokens[innermost].kind];
|
|
161
|
+
if (innermostCloser !== token.kind) {
|
|
162
|
+
unclaimed ??= unclaimedClosers(tokens);
|
|
163
|
+
if (unclaimed.get(innermostCloser)[index + 1] > 0 && unclaimed.get(token.kind)[index + 1] > 0)
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
const depth = depthsByKind.get(opener).at(-1);
|
|
167
|
+
if (depth === undefined)
|
|
168
|
+
return;
|
|
169
|
+
partners[open[depth]] = index;
|
|
170
|
+
partners[index] = open[depth];
|
|
171
|
+
// Each opener is left once, so pairing stays linear.
|
|
172
|
+
leave(depth);
|
|
173
|
+
});
|
|
174
|
+
return partners;
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* The index of the token before an index, past the closers that pair with no
|
|
178
|
+
* opener, as the parser reads them; see skipStrayClosers(). Pairing has
|
|
179
|
+
* decided each closer before an index already.
|
|
180
|
+
*/
|
|
181
|
+
function indexBefore(tokens, partners, index) {
|
|
182
|
+
let before = index - 1;
|
|
183
|
+
while (before >= 0 && isCloser(tokens[before]) && partners[before] === -1)
|
|
184
|
+
before--;
|
|
185
|
+
return before;
|
|
186
|
+
}
|
|
187
|
+
/** The function's name when the `(` at an index starts a call that takes commas, not a group, any(), or all(). */
|
|
188
|
+
function callName(tokens, partners, index) {
|
|
189
|
+
const name = tokens[indexBefore(tokens, partners, index)];
|
|
190
|
+
const takesCommas = name?.kind === 'Identifier' && name.value !== 'any' && name.value !== 'all' && isFunctionName(name.value);
|
|
191
|
+
return takesCommas ? name.value : undefined;
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Whether the call whose `(` is at `opener` can take the comparison at an
|
|
195
|
+
* index in the value argument it reads, as far as the tokens tell: not one
|
|
196
|
+
* right after a literal argument, which Cloudflare never compares, and one
|
|
197
|
+
* that callTakesComparison() allows. The parser decides the rest from types;
|
|
198
|
+
* see takesComparison().
|
|
199
|
+
*/
|
|
200
|
+
function readsComparison(tokens, partners, opener, index, name, argumentIndex) {
|
|
201
|
+
const end = indexBefore(tokens, partners, index);
|
|
202
|
+
// A set literal ends at its `}`.
|
|
203
|
+
const start = tokens[end].kind === 'RBrace' && partners[end] >= 0 ? partners[end] : end;
|
|
204
|
+
const literal = isLiteral(tokens[end]) || start !== end;
|
|
205
|
+
const before = indexBefore(tokens, partners, start);
|
|
206
|
+
if (literal && (before === opener || tokens[before].kind === 'Comma'))
|
|
207
|
+
return false;
|
|
208
|
+
return callTakesComparison(name, argumentIndex, []);
|
|
209
|
+
}
|
|
210
|
+
/** Whether the token at an index is a `[` that starts an access: one after a name, or after what ends one. */
|
|
211
|
+
function startsAccess(tokens, index) {
|
|
212
|
+
const before = tokens[index - 1]?.kind;
|
|
213
|
+
return tokens[index]?.kind === 'LBracket' && (before === 'Identifier' || before === 'RBracket' || before === 'RParen');
|
|
214
|
+
}
|
|
215
|
+
/** For each closer kind, how many closers at or after each index no opener at or after it claims. */
|
|
216
|
+
function unclaimedClosers(tokens) {
|
|
217
|
+
const unclaimed = new Map();
|
|
218
|
+
for (const kind of Object.values(CLOSER_OF))
|
|
219
|
+
unclaimed.set(kind, new Int32Array(tokens.length + 1));
|
|
220
|
+
for (let index = tokens.length - 1; index >= 0; index--) {
|
|
221
|
+
const { kind } = tokens[index];
|
|
222
|
+
for (const [closer, counts] of unclaimed) {
|
|
223
|
+
counts[index] = counts[index + 1] + (kind === closer ? 1 : 0);
|
|
224
|
+
if (CLOSER_OF[kind] === closer && counts[index] > 0)
|
|
225
|
+
counts[index]--;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
return unclaimed;
|
|
229
|
+
}
|
|
230
|
+
const FUNCTION_NAMES = new Set(RULE_EXPRESSION_FUNCTIONS);
|
|
231
|
+
function isFunctionName(name) {
|
|
232
|
+
return FUNCTION_NAMES.has(name);
|
|
233
|
+
}
|
|
234
|
+
/** Whether a token can start a value: a field, a function call, or a literal. */
|
|
235
|
+
function startsValue(token) {
|
|
236
|
+
switch (token.kind) {
|
|
237
|
+
case 'Identifier':
|
|
238
|
+
case 'String':
|
|
239
|
+
case 'Number':
|
|
240
|
+
case 'Boolean':
|
|
241
|
+
case 'LBrace':
|
|
242
|
+
return true;
|
|
243
|
+
default:
|
|
244
|
+
return false;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
/** Whether a token can start a function argument: a value, or a condition. */
|
|
248
|
+
function startsArgument(token) {
|
|
249
|
+
return startsValue(token) || token.kind === 'LParen' || (token.kind === 'Operator' && token.value === 'not');
|
|
250
|
+
}
|
|
251
|
+
/** Whether a token can start a condition. */
|
|
252
|
+
function startsCondition(token) {
|
|
253
|
+
switch (token.kind) {
|
|
254
|
+
case 'LParen':
|
|
255
|
+
case 'Identifier':
|
|
256
|
+
case 'Boolean':
|
|
257
|
+
return true;
|
|
258
|
+
case 'Operator':
|
|
259
|
+
return token.value === 'not';
|
|
260
|
+
default:
|
|
261
|
+
return false;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
/** Whether a comparison operator starts at a token: `strict` is one only before `wildcard`. */
|
|
265
|
+
function isComparisonStart(tokens, index) {
|
|
266
|
+
const token = tokens[index];
|
|
267
|
+
if (token?.kind === 'Equals' || token?.kind === 'NotEquals')
|
|
268
|
+
return true;
|
|
269
|
+
if (token?.kind !== 'Operator')
|
|
270
|
+
return false;
|
|
271
|
+
if (token.value !== 'strict')
|
|
272
|
+
return Object.hasOwn(WORD_COMPARISON_OPERATORS, token.value);
|
|
273
|
+
const next = tokens[index + 1];
|
|
274
|
+
return next?.kind === 'Operator' && next.value === 'wildcard';
|
|
275
|
+
}
|
|
276
|
+
function isLogicalOperator(token) {
|
|
277
|
+
return token.kind === 'Operator' && (token.value === 'and' || token.value === 'or' || token.value === 'xor');
|
|
278
|
+
}
|
|
279
|
+
function isLiteral(token) {
|
|
280
|
+
return token?.kind === 'String' || token?.kind === 'Number' || token?.kind === 'Boolean';
|
|
281
|
+
}
|
|
282
|
+
/** Whether a token can end an operand: a name or a literal, or the closer of what holds one. */
|
|
283
|
+
function endsOperand(token) {
|
|
284
|
+
return token.kind === 'Identifier' || token.kind === 'Number' || token.kind === 'String' || token.kind === 'Boolean' || isCloser(token);
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* Whether the value argument a call without its `)` reads can be a
|
|
288
|
+
* comparison, as Cloudflare would accept the call with its `)` after it: the
|
|
289
|
+
* value can be compared, as neither a literal nor a Boolean can, and the call
|
|
290
|
+
* can take one; see callTakesComparison(). Otherwise the comparison compares
|
|
291
|
+
* the call's result.
|
|
292
|
+
*/
|
|
293
|
+
function takesComparison(call) {
|
|
294
|
+
const value = call.argumentValue;
|
|
295
|
+
if (value === 'literal' || (value !== null && !isComparableValue(value)))
|
|
296
|
+
return false;
|
|
297
|
+
return callTakesComparison(call.functionName, call.argumentIndex, call.args ?? []);
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Whether a call without its `)` can take a comparison as its argument at an
|
|
301
|
+
* index: the parameter accepts one, with T fixed by the arguments before it
|
|
302
|
+
* (see acceptsComparisonArgument()), and the call's result can be a Boolean.
|
|
303
|
+
* A call that returns no Boolean, as to_string() does, could stand only where
|
|
304
|
+
* a value does, and is compared far more often than given a comparison.
|
|
305
|
+
*/
|
|
306
|
+
function callTakesComparison(name, index, before) {
|
|
307
|
+
return canReturnBoolean(name) && acceptsComparisonArgument(name, index, before);
|
|
308
|
+
}
|
|
309
|
+
const NO_OPERATOR_CHARACTERS = new Set();
|
|
310
|
+
/**
|
|
311
|
+
* The tokens the parser reads: all but the unknown characters it reads past
|
|
312
|
+
* as if they were not there. A run of them counts as one. One between two
|
|
313
|
+
* operands may stand for an operator, as `=` does in `http.host = "x"` and
|
|
314
|
+
* `:=` in `http.host := "x"`, and reading past it would leave the operands
|
|
315
|
+
* side by side, so recovery starts there. Elsewhere, a name, number, or
|
|
316
|
+
* string right after one, with nothing between, may belong to it, as `x` may
|
|
317
|
+
* in `http.host eq @x`, so recovery starts there too, but a function name
|
|
318
|
+
* with its `(` does not, since nothing joins a call. The parser reads past
|
|
319
|
+
* any other. The tokenizer reported each already.
|
|
320
|
+
*/
|
|
321
|
+
function readTokens(tokens) {
|
|
322
|
+
if (!tokens.some(token => token.kind === 'Invalid'))
|
|
323
|
+
return { tokens, operatorCharacters: NO_OPERATOR_CHARACTERS };
|
|
324
|
+
const kept = [];
|
|
325
|
+
const operatorCharacters = new Set();
|
|
326
|
+
for (let index = 0; index < tokens.length;) {
|
|
327
|
+
if (!isUnknownCharacter(tokens[index])) {
|
|
328
|
+
kept.push(tokens[index++]);
|
|
329
|
+
continue;
|
|
330
|
+
}
|
|
331
|
+
let end = index;
|
|
332
|
+
while (isUnknownCharacter(tokens[end]))
|
|
333
|
+
end++;
|
|
334
|
+
const operator = standsBetweenOperands(tokens[index - 1], tokens[end]);
|
|
335
|
+
for (; index < end; index++) {
|
|
336
|
+
if (operator)
|
|
337
|
+
operatorCharacters.add(kept.length);
|
|
338
|
+
if (operator || isTouchedByValue(tokens, index))
|
|
339
|
+
kept.push(tokens[index]);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
return { tokens: kept, operatorCharacters };
|
|
343
|
+
}
|
|
344
|
+
/** Whether what comes between two tokens stands between two operands, other than a function name and its `(`. */
|
|
345
|
+
function standsBetweenOperands(previous, next) {
|
|
346
|
+
if (!previous || !next || !endsOperand(previous) || !startsArgument(next))
|
|
347
|
+
return false;
|
|
348
|
+
return !(next.kind === 'LParen' && previous.kind === 'Identifier' && isFunctionName(previous.value));
|
|
349
|
+
}
|
|
350
|
+
/** Whether a name, number, or string touches a token after it, with nothing between, other than a function name and its `(`. */
|
|
351
|
+
function isTouchedByValue(tokens, index) {
|
|
352
|
+
const token = tokens[index];
|
|
353
|
+
const next = tokens[index + 1];
|
|
354
|
+
if (next === undefined || next.pos !== token.pos + tokenLength(token))
|
|
355
|
+
return false;
|
|
356
|
+
if (next.kind === 'Identifier')
|
|
357
|
+
return !(isFunctionName(next.value) && tokens[index + 2]?.kind === 'LParen');
|
|
358
|
+
return next.kind === 'Number' || next.kind === 'String' || next.kind === 'Boolean';
|
|
359
|
+
}
|
|
360
|
+
function isUnknownCharacter(token) {
|
|
361
|
+
return token?.kind === 'Invalid' && token.closed !== false;
|
|
362
|
+
}
|
|
363
|
+
/** Whether a token is malformed: the tokenizer reported it already. */
|
|
364
|
+
function isMalformed(token) {
|
|
365
|
+
return token.kind === 'Invalid' || token.closed === false;
|
|
366
|
+
}
|
|
367
|
+
const CLOSER_TEXT = { group: ')', call: ')', quantifier: ')', access: ']', list: '}' };
|
|
368
|
+
function readHiddenClosers(text) {
|
|
369
|
+
const counts = { ')': 0, ']': 0, '}': 0 };
|
|
370
|
+
for (const char of text) {
|
|
371
|
+
if (char in counts)
|
|
372
|
+
counts[char]++;
|
|
373
|
+
}
|
|
374
|
+
return counts;
|
|
375
|
+
}
|
|
376
|
+
/** The comparison operators that are one word, each spelled as its CompOp. The type keeps the list complete. */
|
|
377
|
+
const WORD_COMPARISON_OPERATORS = {
|
|
378
|
+
eq: true, ne: true, lt: true, le: true, gt: true, ge: true, contains: true, matches: true, wildcard: true, in: true,
|
|
379
|
+
};
|
|
12
380
|
const MAX_ARRAY_INDEX = 0xffff_ffff;
|
|
381
|
+
/** Cloudflare stores integers as signed 64-bit values. */
|
|
382
|
+
const MIN_INTEGER = -(2n ** 63n);
|
|
383
|
+
const MAX_INTEGER = 2n ** 63n - 1n;
|
|
13
384
|
export class Parser {
|
|
14
|
-
tokens;
|
|
15
385
|
source;
|
|
16
|
-
warnings;
|
|
17
386
|
diagnostics;
|
|
18
387
|
pos = 0;
|
|
19
|
-
|
|
20
|
-
|
|
388
|
+
/** Each delimiter's partner; see pairDelimiters(). */
|
|
389
|
+
partners;
|
|
390
|
+
/** The constructs that enclose the current token, innermost last. */
|
|
391
|
+
constructs = [];
|
|
392
|
+
/** The depth of each construct in `constructs` that has a closer, by its closer's token index. */
|
|
393
|
+
closerDepths = new Map();
|
|
394
|
+
/** The index of the last token the parser read, where a node's span ends. Recovery skips tokens without reading them. */
|
|
395
|
+
lastRead = -1;
|
|
396
|
+
/** The closers the last token may hide that no construct has taken; see takeHiddenCloser(). */
|
|
397
|
+
hiddenClosers;
|
|
398
|
+
tokens;
|
|
399
|
+
/** The unknown characters that may stand for an operator; see readTokens(). */
|
|
400
|
+
operatorCharacters;
|
|
401
|
+
/**
|
|
402
|
+
* The access paths where recovery in an access without its `]` skipped
|
|
403
|
+
* past the token with the error. What it skipped may hold the `]` and a
|
|
404
|
+
* comparison operator, which would make the field or call before the path
|
|
405
|
+
* a comparison's left side; see InvalidNode.operand. fieldCondition() and
|
|
406
|
+
* functionCondition() look up the path of the node they get, so the mark
|
|
407
|
+
* reaches them however the node does, as a function argument too.
|
|
408
|
+
*/
|
|
409
|
+
cutShortAccessPaths = new WeakSet();
|
|
410
|
+
constructor(tokens, source, diagnostics) {
|
|
21
411
|
this.source = source;
|
|
22
|
-
this.warnings = warnings;
|
|
23
412
|
this.diagnostics = diagnostics;
|
|
413
|
+
const read = readTokens(tokens);
|
|
414
|
+
this.tokens = read.tokens;
|
|
415
|
+
this.operatorCharacters = read.operatorCharacters;
|
|
416
|
+
this.partners = pairDelimiters(this.tokens);
|
|
417
|
+
this.hiddenClosers = readHiddenClosers(this.hiddenText(tokens));
|
|
24
418
|
}
|
|
25
419
|
parse() {
|
|
26
420
|
const node = this.parseOr();
|
|
27
421
|
if (this.peek().kind !== 'EOF') {
|
|
28
|
-
//
|
|
29
|
-
this.
|
|
422
|
+
// Recovery at the top level runs to the end, so this is only a safety net.
|
|
423
|
+
this.reportAtCurrent('unexpected tokens after expression end', { id: 'syntax.unexpected_tokens_after_expression_end' });
|
|
30
424
|
}
|
|
31
425
|
return node;
|
|
32
426
|
}
|
|
33
427
|
peek(offset = 0) {
|
|
34
|
-
|
|
35
|
-
|
|
428
|
+
return this.tokenAt(this.pos + offset);
|
|
429
|
+
}
|
|
430
|
+
tokenAt(index) {
|
|
431
|
+
return index < this.tokens.length ? this.tokens[index] : { kind: 'EOF', value: '', pos: this.source.length };
|
|
432
|
+
}
|
|
433
|
+
/** The token at an offset, not counting closers that pair with no opener; see skipStrayClosers(). */
|
|
434
|
+
peekPastStrayClosers(offset) {
|
|
435
|
+
return this.tokenAt(this.indexPastStrayClosers(offset));
|
|
436
|
+
}
|
|
437
|
+
/** The index of the token at an offset, not counting closers that pair with no opener. */
|
|
438
|
+
indexPastStrayClosers(offset) {
|
|
439
|
+
let index = this.pos + offset;
|
|
440
|
+
while (this.isStrayCloser(index))
|
|
441
|
+
index++;
|
|
442
|
+
return index;
|
|
36
443
|
}
|
|
37
444
|
consume() {
|
|
38
|
-
|
|
445
|
+
const token = this.tokens[this.pos] ?? { kind: 'EOF', value: '', pos: this.source.length };
|
|
446
|
+
if (this.pos < this.tokens.length)
|
|
447
|
+
this.lastRead = this.pos;
|
|
448
|
+
this.pos++;
|
|
449
|
+
return token;
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* The text of the token that ends the input when it lacks its closing
|
|
453
|
+
* delimiter, or '' for any other. What was meant to follow such a token
|
|
454
|
+
* may be in it, but only where its text holds it: in
|
|
455
|
+
* `coalesce(http.host eq "x, ssl)` the string holds the `)`, and in
|
|
456
|
+
* `lower(http.host eq "ab` it holds nothing. A string without its `"` ends
|
|
457
|
+
* at the end of its line, and the tokens after it are read as usual. It
|
|
458
|
+
* reads the tokenizer's tokens, since an unknown character that the
|
|
459
|
+
* parser reads past still follows the string, on a later line.
|
|
460
|
+
*/
|
|
461
|
+
hiddenText(tokens) {
|
|
462
|
+
const token = tokens.at(-2);
|
|
463
|
+
if (token?.closed !== false || tokens.at(-1)?.kind !== 'EOF')
|
|
464
|
+
return '';
|
|
465
|
+
return this.source.slice(token.pos, token.pos + tokenLength(token));
|
|
39
466
|
}
|
|
40
467
|
rawSpan(startPos) {
|
|
41
|
-
const lastToken = this.tokens[this.
|
|
468
|
+
const lastToken = this.tokens[this.lastRead];
|
|
42
469
|
if (!lastToken)
|
|
43
470
|
return this.source.slice(startPos).trim();
|
|
44
471
|
return this.source.slice(startPos, lastToken.pos + tokenLength(lastToken)).trim();
|
|
45
472
|
}
|
|
46
473
|
// or_expr = and_expr ("or" and_expr)*
|
|
47
|
-
parseOr() {
|
|
48
|
-
const startPos = this.
|
|
49
|
-
|
|
474
|
+
parseOr(first) {
|
|
475
|
+
const startPos = first?.pos ?? this.conditionStart();
|
|
476
|
+
const operands = [this.parseXor(first)];
|
|
50
477
|
while (this.peek().kind === 'Operator' && this.peek().value === 'or') {
|
|
51
478
|
this.consume(); // 'or'
|
|
52
|
-
|
|
53
|
-
const raw = this.rawSpan(startPos);
|
|
54
|
-
left = this.makeLogicalNode('Or', left, right, raw);
|
|
479
|
+
operands.push(this.parseXor());
|
|
55
480
|
}
|
|
56
|
-
return
|
|
481
|
+
return this.logicalNode('Or', operands, startPos);
|
|
57
482
|
}
|
|
58
483
|
// xor_expr = and_expr ("xor" and_expr)*
|
|
59
|
-
parseXor() {
|
|
60
|
-
const startPos = this.
|
|
61
|
-
|
|
484
|
+
parseXor(first) {
|
|
485
|
+
const startPos = first?.pos ?? this.conditionStart();
|
|
486
|
+
const operands = [this.parseAnd(first)];
|
|
62
487
|
while (this.peek().kind === 'Operator' && this.peek().value === 'xor') {
|
|
63
488
|
this.consume(); // 'xor'
|
|
64
|
-
|
|
65
|
-
const raw = this.rawSpan(startPos);
|
|
66
|
-
left = this.makeLogicalNode('Xor', left, right, raw);
|
|
489
|
+
operands.push(this.parseAnd());
|
|
67
490
|
}
|
|
68
|
-
return
|
|
491
|
+
return this.logicalNode('Xor', operands, startPos);
|
|
69
492
|
}
|
|
70
493
|
// and_expr = not_expr ("and" not_expr)*
|
|
71
|
-
parseAnd() {
|
|
72
|
-
const startPos = this.
|
|
73
|
-
|
|
494
|
+
parseAnd(first) {
|
|
495
|
+
const startPos = first?.pos ?? this.conditionStart();
|
|
496
|
+
const operands = [first?.node ?? this.parseNot()];
|
|
497
|
+
this.finishOperand();
|
|
74
498
|
while (this.peek().kind === 'Operator' && this.peek().value === 'and') {
|
|
75
499
|
this.consume(); // 'and'
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
left = this.makeLogicalNode('And', left, right, raw);
|
|
500
|
+
operands.push(this.parseNot());
|
|
501
|
+
this.finishOperand();
|
|
79
502
|
}
|
|
80
|
-
return
|
|
503
|
+
return this.logicalNode('And', operands, startPos);
|
|
81
504
|
}
|
|
82
|
-
|
|
505
|
+
/**
|
|
506
|
+
* Combines the operands of one operator, or returns the only one. An
|
|
507
|
+
* operand that combines with the same operator, such as a group, is
|
|
508
|
+
* flattened into it. The node is built once, so a long chain stays linear.
|
|
509
|
+
*/
|
|
510
|
+
logicalNode(kind, operands, pos) {
|
|
511
|
+
if (operands.length === 1)
|
|
512
|
+
return operands[0];
|
|
513
|
+
const raw = this.rawSpan(pos);
|
|
83
514
|
return {
|
|
84
515
|
kind,
|
|
85
516
|
raw,
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
],
|
|
517
|
+
pos,
|
|
518
|
+
length: raw.length,
|
|
519
|
+
operands: operands.flatMap(operand => (operand.kind === kind ? operand.operands : [operand])),
|
|
90
520
|
};
|
|
91
521
|
}
|
|
92
522
|
// not_expr = "not" not_expr | primary
|
|
93
523
|
parseNot() {
|
|
524
|
+
this.skipBeforeCondition();
|
|
94
525
|
const startPos = this.peek().pos;
|
|
95
526
|
if (this.peek().kind === 'Operator' && this.peek().value === 'not') {
|
|
96
527
|
this.consume(); // 'not'
|
|
97
528
|
const operand = this.parseNot();
|
|
98
529
|
const raw = this.rawSpan(startPos);
|
|
99
|
-
return { kind: 'Not', operand, raw };
|
|
530
|
+
return { kind: 'Not', operand, raw, pos: startPos, length: raw.length };
|
|
100
531
|
}
|
|
101
532
|
return this.parsePrimary();
|
|
102
533
|
}
|
|
103
|
-
|
|
104
|
-
|
|
534
|
+
/**
|
|
535
|
+
* Reports and skips each closer that pairs with no opener before a
|
|
536
|
+
* condition. In place of a condition, with none after it, one is the
|
|
537
|
+
* condition, invalid; see invalidCondition().
|
|
538
|
+
*/
|
|
539
|
+
skipBeforeCondition() {
|
|
540
|
+
if (startsCondition(this.peekPastStrayClosers(0)))
|
|
541
|
+
this.skipStrayClosers();
|
|
542
|
+
}
|
|
543
|
+
/** Where the condition at the current token starts, past the closers skipBeforeCondition() skips. */
|
|
544
|
+
conditionStart() {
|
|
545
|
+
const next = this.peekPastStrayClosers(0);
|
|
546
|
+
return startsCondition(next) ? next.pos : this.peek().pos;
|
|
105
547
|
}
|
|
106
548
|
// primary = "(" expr ")" | func_call | comparison | bool_field
|
|
107
549
|
parsePrimary() {
|
|
108
550
|
const startPos = this.peek().pos;
|
|
109
551
|
// Parenthesised expression
|
|
110
552
|
if (this.peek().kind === 'LParen') {
|
|
111
|
-
this.
|
|
553
|
+
const group = this.open('group');
|
|
112
554
|
const node = this.parseOr();
|
|
113
|
-
|
|
114
|
-
this.consume(); // ')'
|
|
115
|
-
}
|
|
116
|
-
else {
|
|
117
|
-
this.pushWarningAtCurrent('missing closing parenthesis', { id: 'syntax.missing_closing_parenthesis' });
|
|
118
|
-
}
|
|
555
|
+
this.close(group, () => this.reportAtCurrent('missing closing parenthesis', { id: 'syntax.missing_closing_parenthesis' }));
|
|
119
556
|
return node;
|
|
120
557
|
}
|
|
121
558
|
// Function call (starts with known function name)
|
|
122
|
-
if (this.peek().kind === 'Identifier' &&
|
|
559
|
+
if (this.peek().kind === 'Identifier' && isFunctionName(this.peek().value)) {
|
|
123
560
|
return this.parseFuncCall(startPos);
|
|
124
561
|
}
|
|
125
|
-
// Field reference (Identifier or known CF field)
|
|
562
|
+
// Field reference (Identifier or known CF field), or a Boolean literal used directly (e.g., `true`)
|
|
126
563
|
if (this.peek().kind === 'Identifier' || this.peek().kind === 'Boolean') {
|
|
127
564
|
return this.parseFieldOrComparison(startPos);
|
|
128
565
|
}
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
566
|
+
return this.invalidCondition();
|
|
567
|
+
}
|
|
568
|
+
/**
|
|
569
|
+
* Reports a token that cannot start a condition, and puts an InvalidNode
|
|
570
|
+
* in place of the condition. A token that an enclosing construct resumes
|
|
571
|
+
* at stays for it to read, and leaves the condition empty; any other is
|
|
572
|
+
* the condition, invalid, and recovery starts there.
|
|
573
|
+
*/
|
|
574
|
+
invalidCondition() {
|
|
575
|
+
const token = this.peek();
|
|
576
|
+
if (this.handlerOf(this.pos) !== null) {
|
|
577
|
+
this.reportUnexpectedToken(token);
|
|
578
|
+
return this.emptyInvalid(token);
|
|
579
|
+
}
|
|
580
|
+
// See finishOperand().
|
|
581
|
+
if (token.kind !== 'Invalid')
|
|
582
|
+
this.reportUnexpectedToken(token);
|
|
583
|
+
const invalid = this.readInvalid();
|
|
584
|
+
this.recover();
|
|
585
|
+
return invalid;
|
|
586
|
+
}
|
|
587
|
+
/**
|
|
588
|
+
* Reports a token that cannot start an argument, and puts an InvalidNode
|
|
589
|
+
* in place of the argument. A token that an enclosing construct resumes at
|
|
590
|
+
* leaves the argument empty; any other is the argument, invalid, and so is
|
|
591
|
+
* a logical operator, which has nothing to combine. A comparison operator
|
|
592
|
+
* that the call ends at gets the call's missing `)` instead, and what is
|
|
593
|
+
* around the call reads it; see endsAtComparison(). An unknown character
|
|
594
|
+
* starts recovery, since the name, number, or string touching it may
|
|
595
|
+
* belong to it, and that value takes the slot. So does a `[` with an
|
|
596
|
+
* argument in it, a value, a group, or `not`, which may be the argument in
|
|
597
|
+
* brackets. After a comma, a `[` with anything in it, as `[*]`, may
|
|
598
|
+
* instead be an access that a stray comma split off from the argument
|
|
599
|
+
* before it, and no argument at all, as a token after a missing comma may
|
|
600
|
+
* be, so that argument and the ones after it are uncertain. Any other
|
|
601
|
+
* token, and an unterminated comment, holds no value there, and may be
|
|
602
|
+
* what a stray comma left; see InvalidNode.empty.
|
|
603
|
+
*/
|
|
604
|
+
invalidArgument() {
|
|
605
|
+
const token = this.peek();
|
|
606
|
+
let invalid;
|
|
607
|
+
if (token.kind === 'Invalid') {
|
|
608
|
+
invalid = this.readInvalid();
|
|
609
|
+
this.recover();
|
|
610
|
+
// Where an argument starts, the parser keeps an unknown character only when a value touches it.
|
|
611
|
+
if (isUnknownCharacter(token))
|
|
612
|
+
return invalid;
|
|
133
613
|
}
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
614
|
+
else {
|
|
615
|
+
if (!isComparisonStart(this.tokens, this.pos) || !this.endsAtComparison())
|
|
616
|
+
this.reportUnexpectedToken(token);
|
|
617
|
+
if (this.handlerOf(this.pos) !== null && !isLogicalOperator(token)) {
|
|
618
|
+
invalid = this.emptyInvalid(token);
|
|
619
|
+
}
|
|
620
|
+
else {
|
|
621
|
+
const pos = token.pos >= 0 ? token.pos : undefined;
|
|
622
|
+
const partner = token.kind === 'LBracket' ? this.partners[this.pos] : -1;
|
|
623
|
+
const bracketed = partner > this.pos + 1;
|
|
624
|
+
const holdsArgument = bracketed && this.tokens.slice(this.pos + 1, partner).some(startsArgument);
|
|
625
|
+
this.skipInvalidValue();
|
|
626
|
+
invalid = this.invalidNode(pos, this.fieldLength(token.pos));
|
|
627
|
+
const call = this.constructs.at(-1);
|
|
628
|
+
if (bracketed && call.argumentIndex > 0) {
|
|
629
|
+
call.uncertainFrom ??= call.argumentIndex - 1;
|
|
630
|
+
call.strayArgument = true;
|
|
631
|
+
}
|
|
632
|
+
if (holdsArgument)
|
|
633
|
+
return invalid;
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
invalid.empty = true;
|
|
637
|
+
return invalid;
|
|
638
|
+
}
|
|
639
|
+
/**
|
|
640
|
+
* An InvalidNode for the tokens with the error, from the current one (see
|
|
641
|
+
* errorTokenCount()), or an opener with everything up to its closer, as
|
|
642
|
+
* skipInvalidValue() consumes it, which the parser reads as invalid
|
|
643
|
+
* without moving past them, so that the nodes around it span them before
|
|
644
|
+
* recovery skips them.
|
|
645
|
+
*/
|
|
646
|
+
readInvalid() {
|
|
647
|
+
const token = this.peek();
|
|
648
|
+
if (this.pos >= this.tokens.length)
|
|
649
|
+
return this.invalidNode(token.pos >= 0 ? token.pos : undefined, tokenLength(token));
|
|
650
|
+
const partner = this.partners[this.pos];
|
|
651
|
+
this.lastRead = partner > this.pos ? partner : this.pos + this.errorTokenCount(this.pos) - 1;
|
|
652
|
+
const last = this.tokens[this.lastRead];
|
|
653
|
+
return this.invalidNode(token.pos >= 0 ? token.pos : undefined, last.pos + tokenLength(last) - token.pos);
|
|
654
|
+
}
|
|
655
|
+
/** An InvalidNode with nothing in it, right after the last token read, before a token that belongs to something else. */
|
|
656
|
+
emptyInvalid(token) {
|
|
657
|
+
return this.invalidNode(this.previousTokenEnd() ?? token.pos, 0);
|
|
658
|
+
}
|
|
659
|
+
/** Reports a call's `)` missing, at the current token, or over a span. */
|
|
660
|
+
reportMissingCallCloser(name, span) {
|
|
661
|
+
const message = `missing closing parenthesis for function '${name}'`;
|
|
662
|
+
const metadata = { id: 'syntax.missing_function_closing_parenthesis', params: { functionName: name } };
|
|
663
|
+
if (span)
|
|
664
|
+
this.reportAtSpan(message, span.pos, span.length, metadata);
|
|
665
|
+
else
|
|
666
|
+
this.reportAtCurrent(message, metadata);
|
|
667
|
+
}
|
|
668
|
+
/** Reports a token that cannot appear where it is. */
|
|
669
|
+
reportUnexpectedToken(token) {
|
|
670
|
+
this.reportAtToken(`unexpected token: ${token.kind} "${token.value}"`, token, { id: 'syntax.unexpected_token', params: { tokenKind: token.kind, tokenValue: token.value } });
|
|
671
|
+
}
|
|
672
|
+
/** Stands in for invalid syntax after its error is reported, over the source text it spans; see InvalidNode. */
|
|
673
|
+
invalidNode(pos, length, operand) {
|
|
674
|
+
const raw = pos === undefined ? '' : this.source.slice(pos, pos + length);
|
|
675
|
+
return { kind: 'Invalid', raw, pos, length, ...(operand ? { operand } : {}) };
|
|
146
676
|
}
|
|
147
677
|
parseFieldOrComparison(startPos) {
|
|
148
678
|
const fieldNode = this.parseFieldRef();
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
679
|
+
return this.parseComparisonRest(fieldNode, startPos) ?? this.fieldCondition(fieldNode, this.cutsShort());
|
|
680
|
+
}
|
|
681
|
+
/**
|
|
682
|
+
* A field without a comparison: a Boolean field, or an InvalidNode that
|
|
683
|
+
* keeps it when it has an access path. One that recovery cuts short, after
|
|
684
|
+
* it or in an access without its `]`, may be a comparison's left side
|
|
685
|
+
* instead, so it is kept the same way, and its access path gets no error,
|
|
686
|
+
* unless it is a Boolean, which Cloudflare never compares; see
|
|
687
|
+
* InvalidNode.operand.
|
|
688
|
+
*/
|
|
689
|
+
fieldCondition(field, recoveryCutsShort) {
|
|
690
|
+
const cutShort = (recoveryCutsShort || this.cutShortAccessPaths.has(field.accessPath)) && isComparableValue(field);
|
|
691
|
+
if (field.accessPath.length === 0 && !cutShort) {
|
|
692
|
+
return { kind: 'BoolField', name: field.name, raw: this.source.slice(field.pos, field.pos + field.length), pos: field.pos, length: field.length };
|
|
162
693
|
}
|
|
163
|
-
if (
|
|
164
|
-
this.
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
694
|
+
if (!cutShort) {
|
|
695
|
+
this.reportAtSpan('unexpected field access without comparison operator', field.pos, field.length, {
|
|
696
|
+
id: 'syntax.field_access_without_comparison',
|
|
697
|
+
params: { fieldName: field.name },
|
|
698
|
+
});
|
|
168
699
|
}
|
|
169
|
-
|
|
170
|
-
const raw = this.rawSpan(startPos);
|
|
171
|
-
if (fieldNode.accessPath.length === 0) {
|
|
172
|
-
return {
|
|
173
|
-
kind: 'BoolField',
|
|
174
|
-
name: fieldNode.name,
|
|
175
|
-
raw,
|
|
176
|
-
pos: fieldNode.pos,
|
|
177
|
-
length: fieldNode.length,
|
|
178
|
-
};
|
|
179
|
-
}
|
|
180
|
-
this.pushWarningAtSpan('unexpected field access without comparison operator', fieldNode.pos, fieldNode.length, {
|
|
181
|
-
id: 'syntax.field_access_without_comparison',
|
|
182
|
-
params: { fieldName: fieldNode.name },
|
|
183
|
-
});
|
|
184
|
-
return {
|
|
185
|
-
kind: 'BoolField',
|
|
186
|
-
name: 'false',
|
|
187
|
-
raw,
|
|
188
|
-
pos: fieldNode.pos,
|
|
189
|
-
length: fieldNode.length,
|
|
190
|
-
};
|
|
700
|
+
return this.invalidNode(field.pos, field.length, field);
|
|
191
701
|
}
|
|
192
702
|
parseFieldRef() {
|
|
193
703
|
const start = this.peek();
|
|
@@ -197,63 +707,88 @@ export class Parser {
|
|
|
197
707
|
}
|
|
198
708
|
parseAccessPath() {
|
|
199
709
|
const accessPath = [];
|
|
200
|
-
|
|
201
|
-
const start = this.
|
|
202
|
-
const
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
710
|
+
for (this.skipStrayClosers(); this.peek().kind === 'LBracket'; this.skipStrayClosers()) {
|
|
711
|
+
const start = this.peek();
|
|
712
|
+
const access = this.open('access');
|
|
713
|
+
const value = this.parseAccessValue(start);
|
|
714
|
+
this.finishOperand();
|
|
715
|
+
this.close(access, () => this.reportAtSpan('missing closing bracket for access expression', this.previousTokenEnd(), 0, { id: 'syntax.missing_closing_bracket' }));
|
|
716
|
+
// A valid value stays even when the `]` is missing, and the token after it is the stray one, as after
|
|
717
|
+
// a list member or an argument. An invalid one stays as an invalid segment.
|
|
718
|
+
const length = this.fieldLength(start.pos);
|
|
719
|
+
accessPath.push(value ? { ...value, length } : this.invalidNode(start.pos, length));
|
|
720
|
+
if (access.closer === null && access.recoveredIn !== null)
|
|
721
|
+
this.cutShortAccessPaths.add(accessPath);
|
|
722
|
+
}
|
|
723
|
+
return accessPath;
|
|
724
|
+
}
|
|
725
|
+
/**
|
|
726
|
+
* The value of an access, or null when it is not a valid one, after
|
|
727
|
+
* reporting it. A number or string touching an unknown character is the
|
|
728
|
+
* value, as a list keeps its member; see readTokens().
|
|
729
|
+
*/
|
|
730
|
+
parseAccessValue(start) {
|
|
731
|
+
const next = this.peek(1).kind;
|
|
732
|
+
if (isUnknownCharacter(this.peek()) && (next === 'Number' || next === 'String'))
|
|
733
|
+
this.consume();
|
|
734
|
+
const value = this.peek();
|
|
735
|
+
if (value.kind === 'Star') {
|
|
736
|
+
this.consume();
|
|
737
|
+
return { kind: 'ArrayWildcardAccess', pos: start.pos };
|
|
738
|
+
}
|
|
739
|
+
if (value.kind === 'Number') {
|
|
740
|
+
this.consume();
|
|
741
|
+
// Cloudflare reads an index as any integer literal, so a leading 0 makes it octal.
|
|
742
|
+
const index = this.readInteger(value, value.value);
|
|
743
|
+
if (index !== null && index >= 0 && index <= MAX_ARRAY_INDEX) {
|
|
744
|
+
return { kind: 'ArrayIndexAccess', index: Number(index), pos: start.pos };
|
|
224
745
|
}
|
|
225
|
-
|
|
226
|
-
this.
|
|
227
|
-
id: 'syntax.
|
|
228
|
-
params: {
|
|
746
|
+
if (index !== null) {
|
|
747
|
+
this.reportAtToken(`array index must be a non-negative integer no greater than ${MAX_ARRAY_INDEX}; received '${value.value}'`, value, {
|
|
748
|
+
id: 'syntax.invalid_array_index',
|
|
749
|
+
params: { value: value.value, min: 0, max: MAX_ARRAY_INDEX },
|
|
229
750
|
});
|
|
230
|
-
if (value.kind !== 'RBracket' &&
|
|
231
|
-
value.kind !== 'EOF' &&
|
|
232
|
-
value.kind !== 'RParen' &&
|
|
233
|
-
value.kind !== 'Comma' &&
|
|
234
|
-
value.kind !== 'Operator' &&
|
|
235
|
-
value.kind !== 'Equals' &&
|
|
236
|
-
value.kind !== 'NotEquals')
|
|
237
|
-
this.consume();
|
|
238
751
|
}
|
|
239
|
-
|
|
240
|
-
if (closed) {
|
|
241
|
-
this.consume();
|
|
242
|
-
}
|
|
243
|
-
else {
|
|
244
|
-
this.pushWarningAtSpan('missing closing bracket for access expression', this.previousTokenEnd(), 0, { id: 'syntax.missing_closing_bracket' });
|
|
245
|
-
}
|
|
246
|
-
const length = this.fieldLength(start.pos);
|
|
247
|
-
if (access && closed)
|
|
248
|
-
accessPath.push({ ...access, length });
|
|
752
|
+
return null;
|
|
249
753
|
}
|
|
250
|
-
|
|
754
|
+
if (value.kind === 'String') {
|
|
755
|
+
this.consume();
|
|
756
|
+
return { kind: 'MapKeyAccess', key: value.value, pos: start.pos };
|
|
757
|
+
}
|
|
758
|
+
if (value.kind === 'Invalid') {
|
|
759
|
+
// The segment spans the tokens with the error, as an invalid value does; see readInvalid().
|
|
760
|
+
this.readInvalid();
|
|
761
|
+
this.recover();
|
|
762
|
+
return null;
|
|
763
|
+
}
|
|
764
|
+
this.reportAtToken('access expression must contain *, a quoted map key, or a non-negative integer index', value, {
|
|
765
|
+
id: 'syntax.invalid_access_value',
|
|
766
|
+
params: { tokenKind: value.kind, tokenValue: value.value },
|
|
767
|
+
});
|
|
768
|
+
// A token that an enclosing construct resumes at leaves the access empty.
|
|
769
|
+
if (this.handlerOf(this.pos) === null)
|
|
770
|
+
this.skipInvalidValue();
|
|
771
|
+
return null;
|
|
251
772
|
}
|
|
252
773
|
// comparison_value = dynamic_value | literal
|
|
253
774
|
parseComparisonValue(op, insertionPos) {
|
|
775
|
+
this.skipNoise(this.isNoiseBeforeComparisonValue, startsValue);
|
|
254
776
|
const token = this.peek();
|
|
777
|
+
// An unknown character starts recovery, since what follows it may belong to it.
|
|
778
|
+
if (token.kind === 'Invalid') {
|
|
779
|
+
const invalid = this.readInvalid();
|
|
780
|
+
this.recover();
|
|
781
|
+
return invalid;
|
|
782
|
+
}
|
|
783
|
+
// With no value after it, a closer that pairs with no opener, or a comma no call takes, is this
|
|
784
|
+
// value, invalid, as any unexpected token is.
|
|
785
|
+
if ((isCloser(token) || token.kind === 'Comma') && this.handlerOf(this.pos) === null) {
|
|
786
|
+
this.reportUnexpectedToken(token);
|
|
787
|
+
this.consume();
|
|
788
|
+
return this.invalidNode(token.pos, tokenLength(token));
|
|
789
|
+
}
|
|
255
790
|
if (this.isMissingComparisonValueBoundary(token)) {
|
|
256
|
-
this.
|
|
791
|
+
this.reportAtSpan(`missing right-hand value for operator '${op}'`, insertionPos, 0, { id: 'syntax.missing_operator_value', params: { operator: op } });
|
|
257
792
|
return undefined;
|
|
258
793
|
}
|
|
259
794
|
return this.tryParseDynamicValue() ?? this.parseValue('operator');
|
|
@@ -264,7 +799,7 @@ export class Parser {
|
|
|
264
799
|
const token = this.peek();
|
|
265
800
|
if (token.kind !== 'Identifier')
|
|
266
801
|
return null;
|
|
267
|
-
if (
|
|
802
|
+
if (isFunctionName(token.value) && this.peekPastStrayClosers(1).kind === 'LParen') {
|
|
268
803
|
return this.parseFunctionValue(token.pos);
|
|
269
804
|
}
|
|
270
805
|
if (this.isKnownFieldName(token.value))
|
|
@@ -287,62 +822,33 @@ export class Parser {
|
|
|
287
822
|
}
|
|
288
823
|
}
|
|
289
824
|
previousTokenEnd() {
|
|
290
|
-
const token = this.tokens[this.
|
|
825
|
+
const token = this.tokens[this.lastRead];
|
|
291
826
|
if (!token || token.pos < 0)
|
|
292
827
|
return null;
|
|
293
828
|
return token.pos + tokenLength(token);
|
|
294
829
|
}
|
|
295
830
|
fieldLength(startPos) {
|
|
296
|
-
const lastToken = this.tokens[this.
|
|
831
|
+
const lastToken = this.tokens[this.lastRead];
|
|
297
832
|
if (!lastToken || startPos < 0)
|
|
298
833
|
return 0;
|
|
299
834
|
return Math.max(lastToken.pos + tokenLength(lastToken) - startPos, 0);
|
|
300
835
|
}
|
|
836
|
+
/** Reads the comparison operator at the current token, if one starts there; see isComparisonStart(). */
|
|
301
837
|
tryParseCompOp() {
|
|
302
|
-
|
|
303
|
-
if (t.kind !== 'Operator')
|
|
838
|
+
if (!isComparisonStart(this.tokens, this.pos))
|
|
304
839
|
return null;
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
case 'le':
|
|
316
|
-
this.consume();
|
|
317
|
-
return 'le';
|
|
318
|
-
case 'gt':
|
|
319
|
-
this.consume();
|
|
320
|
-
return 'gt';
|
|
321
|
-
case 'ge':
|
|
322
|
-
this.consume();
|
|
323
|
-
return 'ge';
|
|
324
|
-
case 'contains':
|
|
325
|
-
this.consume();
|
|
326
|
-
return 'contains';
|
|
327
|
-
case 'matches':
|
|
328
|
-
this.consume();
|
|
329
|
-
return 'matches';
|
|
330
|
-
case 'wildcard':
|
|
331
|
-
this.consume();
|
|
332
|
-
return 'wildcard';
|
|
333
|
-
case 'in':
|
|
334
|
-
this.consume();
|
|
335
|
-
return 'in';
|
|
336
|
-
case 'strict':
|
|
337
|
-
if (this.peek(1).kind === 'Operator' && this.peek(1).value === 'wildcard') {
|
|
338
|
-
this.consume();
|
|
339
|
-
this.consume();
|
|
340
|
-
return 'strict_wildcard';
|
|
341
|
-
}
|
|
342
|
-
return null;
|
|
343
|
-
default: return null;
|
|
344
|
-
}
|
|
840
|
+
const token = this.consume();
|
|
841
|
+
// `==` and `!=` are C-like spellings of `eq` and `ne`.
|
|
842
|
+
if (token.kind === 'Equals')
|
|
843
|
+
return 'eq';
|
|
844
|
+
if (token.kind === 'NotEquals')
|
|
845
|
+
return 'ne';
|
|
846
|
+
if (token.value !== 'strict')
|
|
847
|
+
return token.value;
|
|
848
|
+
this.consume(); // 'wildcard'
|
|
849
|
+
return 'strict_wildcard';
|
|
345
850
|
}
|
|
851
|
+
/** A literal value, or an InvalidNode for one that is not valid, such as an unquoted name, after reporting it. */
|
|
346
852
|
parseValue(context) {
|
|
347
853
|
const t = this.peek();
|
|
348
854
|
if (t.kind === 'String') {
|
|
@@ -352,10 +858,10 @@ export class Parser {
|
|
|
352
858
|
if (t.kind === 'Number') {
|
|
353
859
|
this.consume();
|
|
354
860
|
if (this.reportHexBytesLiteral(t))
|
|
355
|
-
return
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
861
|
+
return this.invalidNode(t.pos, tokenLength(t));
|
|
862
|
+
if (isRuleExpressionIpAddress(t.value))
|
|
863
|
+
return { kind: 'IpLiteral', value: t.value, pos: t.pos, length: tokenLength(t) };
|
|
864
|
+
return this.numberLiteral(t);
|
|
359
865
|
}
|
|
360
866
|
if (t.kind === 'Boolean') {
|
|
361
867
|
this.consume();
|
|
@@ -367,20 +873,46 @@ export class Parser {
|
|
|
367
873
|
this.consume();
|
|
368
874
|
return { kind: 'ListRef', name: t.value.slice(1), pos: t.pos, length: tokenLength(t) };
|
|
369
875
|
}
|
|
370
|
-
// Unquoted value - treat as string (may happen with some expressions)
|
|
371
876
|
if (t.kind === 'Identifier') {
|
|
372
877
|
this.consume();
|
|
373
|
-
this.
|
|
374
|
-
return
|
|
878
|
+
this.reportUnquotedName(t, context);
|
|
879
|
+
return this.invalidNode(t.pos, tokenLength(t));
|
|
375
880
|
}
|
|
376
|
-
this.
|
|
881
|
+
this.reportUnexpectedToken(t);
|
|
882
|
+
this.skipInvalidValue();
|
|
883
|
+
return this.invalidNode(t.pos >= 0 ? t.pos : undefined, this.fieldLength(t.pos));
|
|
884
|
+
}
|
|
885
|
+
/**
|
|
886
|
+
* Consumes an invalid value: one token, or an opener with everything up to
|
|
887
|
+
* its closer. An opener without its closer may hold everything after it,
|
|
888
|
+
* so recovery skips what it holds; see recoveryIndexAfter(). In a list,
|
|
889
|
+
* which holds only values, it holds nothing, and the members after it stay.
|
|
890
|
+
*/
|
|
891
|
+
skipInvalidValue() {
|
|
892
|
+
const inList = this.constructs.at(-1)?.kind === 'list';
|
|
893
|
+
if (!inList && CLOSER_OF[this.peek().kind] !== undefined && this.partners[this.pos] < 0) {
|
|
894
|
+
this.lastRead = this.pos;
|
|
895
|
+
this.recover();
|
|
896
|
+
return;
|
|
897
|
+
}
|
|
898
|
+
const partner = this.partners[this.pos] ?? -1;
|
|
899
|
+
if (partner > this.pos)
|
|
900
|
+
this.pos = partner;
|
|
377
901
|
this.consume();
|
|
378
|
-
|
|
902
|
+
}
|
|
903
|
+
/** A number literal, with its exact `integer` value, or an InvalidNode for one that is not a valid integer. */
|
|
904
|
+
numberLiteral(token) {
|
|
905
|
+
const integer = this.readInteger(token, token.value);
|
|
906
|
+
if (integer === null)
|
|
907
|
+
return this.invalidNode(token.pos, tokenLength(token));
|
|
908
|
+
return { kind: 'NumberLiteral', value: Number(integer), integer, raw: token.value, pos: token.pos, length: tokenLength(token) };
|
|
379
909
|
}
|
|
380
910
|
parseSetLiteral() {
|
|
381
|
-
const start = this.
|
|
911
|
+
const start = this.peek();
|
|
912
|
+
const list = this.open('list');
|
|
382
913
|
const elements = [];
|
|
383
|
-
|
|
914
|
+
// A list with its `}` owns every token up to it; one without ends where an enclosing construct resumes.
|
|
915
|
+
while (this.handlerOf(this.pos) === null) {
|
|
384
916
|
const t = this.peek();
|
|
385
917
|
const unquotedType = t.kind === 'Number' ? unquotedSetElementType(t.value) : null;
|
|
386
918
|
if (t.kind === 'String') {
|
|
@@ -388,157 +920,616 @@ export class Parser {
|
|
|
388
920
|
this.consume();
|
|
389
921
|
}
|
|
390
922
|
else if (unquotedType === 'integer') {
|
|
391
|
-
|
|
392
|
-
elements.push({ type: 'integer', value: /^-?\d+$/.test(t.value) ? Number(t.value) : t.value });
|
|
923
|
+
const [first, last = first] = t.value.split('..').map(bound => this.readInteger(t, bound));
|
|
393
924
|
this.consume();
|
|
925
|
+
// Ranges stay as written.
|
|
926
|
+
elements.push(first === null || last === null
|
|
927
|
+
? this.invalidMember(t)
|
|
928
|
+
: { type: 'integer', value: t.value.includes('..') ? t.value : Number(first), raw: t.value, bounds: [first, last] });
|
|
394
929
|
}
|
|
395
930
|
else if (unquotedType === 'ip') {
|
|
396
931
|
elements.push({ type: 'ip', value: t.value });
|
|
397
932
|
this.consume();
|
|
398
933
|
}
|
|
399
|
-
else if (t.kind === 'Identifier') {
|
|
400
|
-
this.pushIdentifierValueWarning(t, 'set');
|
|
401
|
-
this.consume();
|
|
402
|
-
}
|
|
403
|
-
else if (t.kind === 'Number' && this.reportHexBytesLiteral(t)) {
|
|
404
|
-
this.consume();
|
|
405
|
-
}
|
|
406
934
|
else {
|
|
407
|
-
|
|
408
|
-
|
|
935
|
+
if (t.kind === 'Identifier')
|
|
936
|
+
this.reportUnquotedName(t, 'set');
|
|
937
|
+
// A malformed token has its own error.
|
|
938
|
+
else if (!(t.kind === 'Number' && this.reportHexBytesLiteral(t)) && t.kind !== 'Invalid') {
|
|
939
|
+
this.reportAtToken(`unexpected token in set literal: ${t.kind} "${t.value}"`, t, { id: 'syntax.unexpected_token_in_set_literal', params: { tokenKind: t.kind, tokenValue: t.value } });
|
|
940
|
+
}
|
|
941
|
+
this.skipInvalidValue();
|
|
942
|
+
elements.push(this.invalidMember(t));
|
|
409
943
|
}
|
|
410
944
|
}
|
|
411
|
-
|
|
412
|
-
this.consume(); // '}'
|
|
413
|
-
}
|
|
414
|
-
else {
|
|
415
|
-
this.pushWarningAtCurrent('missing closing brace', { id: 'syntax.missing_closing_brace' });
|
|
416
|
-
}
|
|
945
|
+
this.close(list, () => this.reportAtCurrent('missing closing brace', { id: 'syntax.missing_closing_brace' }));
|
|
417
946
|
return { kind: 'SetLiteral', elements, pos: start.pos, length: this.fieldLength(start.pos) };
|
|
418
947
|
}
|
|
948
|
+
/** A list member that is not a valid element, from its token to the last token read. */
|
|
949
|
+
invalidMember(token) {
|
|
950
|
+
return { ...this.invalidNode(token.pos, this.fieldLength(token.pos)), type: 'invalid' };
|
|
951
|
+
}
|
|
419
952
|
// func_call = funcName "(" args ")"
|
|
420
953
|
parseFuncCall(startPos) {
|
|
421
|
-
const
|
|
954
|
+
const nameToken = this.consume();
|
|
955
|
+
const name = nameToken.value;
|
|
956
|
+
this.skipStrayClosers();
|
|
422
957
|
if (this.peek().kind !== 'LParen') {
|
|
423
|
-
//
|
|
424
|
-
|
|
958
|
+
// Like a missing closer, a missing opener leaves the parser without its place.
|
|
959
|
+
this.reportAtCurrent(`missing opening parenthesis for function '${name}'`, { id: 'syntax.missing_function_opening_parenthesis', params: { functionName: name } });
|
|
960
|
+
this.recover();
|
|
961
|
+
return this.invalidNode(startPos, tokenLength(nameToken));
|
|
425
962
|
}
|
|
426
|
-
this.consume(); // '('
|
|
427
963
|
if (name === 'any' || name === 'all') {
|
|
428
964
|
return this.parseAnyAll(name, startPos);
|
|
429
965
|
}
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
const accessPath = this.parseAccessPath();
|
|
433
|
-
const raw = this.rawSpan(startPos);
|
|
434
|
-
return { kind: 'Func', name, args, accessPath, raw, pos: startPos, length: raw.length };
|
|
435
|
-
}
|
|
436
|
-
const args = this.parseFunctionArgs(name);
|
|
437
|
-
return this.parseScalarFunctionComparison(name, args, startPos);
|
|
966
|
+
const parsed = this.parseArguments(name);
|
|
967
|
+
return this.parseScalarFunctionComparison(name, parsed, startPos);
|
|
438
968
|
}
|
|
969
|
+
/** A function call as a value; the caller has checked that `(` follows its name. */
|
|
439
970
|
parseFunctionValue(startPos) {
|
|
440
971
|
const name = this.consume().value;
|
|
441
|
-
|
|
442
|
-
this.pushWarningAtCurrent(`missing opening parenthesis for function '${name}'`, { id: 'syntax.missing_function_opening_parenthesis', params: { functionName: name } });
|
|
443
|
-
return { kind: 'Func', name, args: [], accessPath: [], raw: name, pos: startPos, length: name.length };
|
|
444
|
-
}
|
|
445
|
-
this.consume();
|
|
972
|
+
this.skipStrayClosers();
|
|
446
973
|
if (name === 'any' || name === 'all')
|
|
447
974
|
return this.parseAnyAll(name, startPos);
|
|
448
|
-
|
|
449
|
-
const
|
|
975
|
+
// One object, so that the frame each nested call adds stays small.
|
|
976
|
+
const parsed = this.parseArguments(name);
|
|
977
|
+
return this.funcNode(name, parsed, this.parseAccessPath(), startPos);
|
|
978
|
+
}
|
|
979
|
+
funcNode(name, parsed, accessPath, startPos) {
|
|
450
980
|
const raw = this.rawSpan(startPos);
|
|
451
|
-
return {
|
|
981
|
+
return {
|
|
982
|
+
kind: 'Func',
|
|
983
|
+
name,
|
|
984
|
+
args: parsed.args,
|
|
985
|
+
accessPath,
|
|
986
|
+
raw,
|
|
987
|
+
pos: startPos,
|
|
988
|
+
length: raw.length,
|
|
989
|
+
...(parsed.uncertainFrom === undefined ? {} : { uncertainFrom: parsed.uncertainFrom }),
|
|
990
|
+
...(parsed.moreArguments ? { moreArguments: true } : {}),
|
|
991
|
+
...(parsed.openInCall ? { openInCall: true } : {}),
|
|
992
|
+
...(parsed.strayArgument ? { strayArgument: true } : {}),
|
|
993
|
+
};
|
|
452
994
|
}
|
|
453
|
-
|
|
995
|
+
/**
|
|
996
|
+
* Parses a call's argument list, from its `(` through its `)`, with the
|
|
997
|
+
* index from which the arguments are uncertain, and whether some may be
|
|
998
|
+
* another call's or not arguments at all (see FuncNode). When recovery in
|
|
999
|
+
* an argument skipped a token after the one with the error, that argument
|
|
1000
|
+
* may have gone on, and the ones after it may have shifted. Without its
|
|
1001
|
+
* `)`, the call may have more. The written ones keep their positions,
|
|
1002
|
+
* unless a call around it takes commas and its `)` is missing, rather than
|
|
1003
|
+
* hidden in a token that runs to the end: it may then be missing before
|
|
1004
|
+
* any of them.
|
|
1005
|
+
*/
|
|
1006
|
+
parseArguments(name) {
|
|
1007
|
+
const call = this.open('call');
|
|
1008
|
+
call.functionName = name;
|
|
1009
|
+
const args = this.parseFunctionArgs(name, call);
|
|
1010
|
+
const closing = this.close(call, () => this.reportMissingCallCloser(name));
|
|
1011
|
+
return this.parsedArguments(call, args, closing);
|
|
1012
|
+
}
|
|
1013
|
+
/** What parseArguments() returns; its own method, so that the frame each nested call adds stays small. */
|
|
1014
|
+
parsedArguments(call, args, closing) {
|
|
1015
|
+
// A `)` that the token at the end may hide may also be text, and more arguments may follow it.
|
|
1016
|
+
const uncertainFrom = call.uncertainFrom ?? (closing === 'read' ? undefined : args.length);
|
|
1017
|
+
// The tokens recovery skips after the one with the error may hold more, after a missing comma.
|
|
1018
|
+
const moreArguments = call.recoveredIn !== null || closing !== 'read';
|
|
1019
|
+
// Without its `)`, the token with the error in its last argument may stand for one and a
|
|
1020
|
+
// comparison operator, as `=` may in `lower(http.host = "x"`.
|
|
1021
|
+
const cutShort = closing !== 'read' && call.recoveredIn === args.length - 1;
|
|
1022
|
+
// Without its `)`, the call may end before any of its commas, when a call around it takes them. A
|
|
1023
|
+
// hidden `)` comes after all of them.
|
|
1024
|
+
const outside = this.constructs.at(-1)?.nearest ?? NO_CONSTRUCTS;
|
|
1025
|
+
const strayArgument = call.strayArgument;
|
|
1026
|
+
if (closing !== 'missing' || outside.call < 0 || outside.call < outside.closed)
|
|
1027
|
+
return { args, uncertainFrom, moreArguments, openInCall: false, strayArgument, cutShort };
|
|
1028
|
+
return { args, uncertainFrom: Math.min(uncertainFrom ?? args.length, 1), moreArguments, openInCall: true, strayArgument, cutShort };
|
|
1029
|
+
}
|
|
1030
|
+
parseFunctionArgs(name, call) {
|
|
454
1031
|
const args = [];
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
}
|
|
459
|
-
while (this.peek().kind !== 'RParen' && this.peek().kind !== 'EOF') {
|
|
1032
|
+
call.args = args;
|
|
1033
|
+
while (this.pos !== call.closer && !this.resumesOutside(call.depth)) {
|
|
1034
|
+
call.argumentIndex = args.length;
|
|
460
1035
|
args.push(this.parseFunctionArg());
|
|
461
1036
|
if (this.peek().kind === 'Comma') {
|
|
462
1037
|
this.consume();
|
|
1038
|
+
// Cloudflare needs an argument after every comma, and rejects the `)` after a trailing one.
|
|
1039
|
+
if (this.pos === call.closer)
|
|
1040
|
+
this.reportUnexpectedToken(this.peek());
|
|
463
1041
|
continue;
|
|
464
1042
|
}
|
|
465
|
-
if (this.
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
if (this.
|
|
470
|
-
|
|
1043
|
+
if (this.pos === call.closer || this.resumesOutside(call.depth))
|
|
1044
|
+
break;
|
|
1045
|
+
// A call that ends at a comparison operator ends before it, and the comparison then compares its
|
|
1046
|
+
// result; see parseArgumentComparison().
|
|
1047
|
+
if (isComparisonStart(this.tokens, this.pos) && this.endsAtComparison())
|
|
1048
|
+
break;
|
|
1049
|
+
// What follows a complete argument starts the next one. It may be a stray token instead, which may
|
|
1050
|
+
// belong to the argument before it, so that argument and the ones after it are uncertain, and
|
|
1051
|
+
// the call may have fewer arguments than it reads.
|
|
1052
|
+
this.leaveArgumentUncertain();
|
|
1053
|
+
call.strayArgument = true;
|
|
1054
|
+
this.reportAtCurrent(`missing comma between arguments for function '${name}'`, { id: 'syntax.missing_function_argument_comma', params: { functionName: name } });
|
|
1055
|
+
}
|
|
1056
|
+
return args;
|
|
1057
|
+
}
|
|
1058
|
+
/**
|
|
1059
|
+
* Parses a function argument as Cloudflare does. One that starts with
|
|
1060
|
+
* `(`, `not`, any() or all() is a whole logical expression, so `and`, `or`
|
|
1061
|
+
* and `xor` can follow, and a lone function call there is a condition too.
|
|
1062
|
+
* Any other is a value, or a comparison of one, as in
|
|
1063
|
+
* `coalesce(has_value(...), http.host eq "x")`.
|
|
1064
|
+
*/
|
|
1065
|
+
parseFunctionArg() {
|
|
1066
|
+
// The flag stays set after a condition, where recovery leaves no comparison operator, and is
|
|
1067
|
+
// cleared here, so that the frame each nested call adds stays small; see endsAtComparison().
|
|
1068
|
+
this.constructs.at(-1).readingCondition = false;
|
|
1069
|
+
this.constructs.at(-1).argumentValue = null;
|
|
1070
|
+
this.skipNoiseBeforeArgument();
|
|
1071
|
+
if (this.startsLogicalArgument()) {
|
|
1072
|
+
this.constructs.at(-1).readingCondition = true;
|
|
1073
|
+
const condition = this.parseOr();
|
|
1074
|
+
if (condition.kind === 'Func')
|
|
1075
|
+
condition.condition = true;
|
|
1076
|
+
return condition;
|
|
1077
|
+
}
|
|
1078
|
+
const startPos = this.peek().pos;
|
|
1079
|
+
const argument = startsValue(this.peek()) ? this.parseValueArgument(startPos) : this.invalidArgument();
|
|
1080
|
+
const cutShort = this.finishOperand();
|
|
1081
|
+
if (!isLogicalOperator(this.peek()))
|
|
1082
|
+
return argument;
|
|
1083
|
+
// Cloudflare needs parentheses to combine conditions here; read the rest as if they were there.
|
|
1084
|
+
const condition = this.asCondition(argument, cutShort);
|
|
1085
|
+
const operator = this.peek().value;
|
|
1086
|
+
this.reportAtCurrent(`conditions combined with '${operator}' in a function argument need parentheses`, { id: 'syntax.unparenthesized_logical_argument', params: { operator } });
|
|
1087
|
+
this.constructs.at(-1).readingCondition = true;
|
|
1088
|
+
return this.parseOr({ node: condition, pos: startPos });
|
|
1089
|
+
}
|
|
1090
|
+
/**
|
|
1091
|
+
* Reports and skips each token that stands for nothing before what
|
|
1092
|
+
* `starts` accepts, when that follows them: before an argument, see
|
|
1093
|
+
* isNoiseBeforeArgument(), or a comparison value, see
|
|
1094
|
+
* isNoiseBeforeComparisonValue(). In its place, with nothing after them,
|
|
1095
|
+
* one is that argument or value, invalid; see invalidArgument() and
|
|
1096
|
+
* parseComparisonValue(). Its own method, so that the frame each nested
|
|
1097
|
+
* call adds stays small.
|
|
1098
|
+
*/
|
|
1099
|
+
skipNoise(isNoise, starts) {
|
|
1100
|
+
let start = this.pos;
|
|
1101
|
+
while (isNoise.call(this, start))
|
|
1102
|
+
start++;
|
|
1103
|
+
if (!starts(this.tokenAt(start)))
|
|
1104
|
+
return;
|
|
1105
|
+
for (; this.pos < start; this.pos++)
|
|
1106
|
+
this.reportUnexpectedToken(this.peek());
|
|
1107
|
+
}
|
|
1108
|
+
/**
|
|
1109
|
+
* Skips the tokens that stand for nothing before an argument; see
|
|
1110
|
+
* skipNoise(). A comparison operator among them may have lost its left
|
|
1111
|
+
* side, which would make the argument a comparison, so that argument and
|
|
1112
|
+
* the ones after it are uncertain.
|
|
1113
|
+
*/
|
|
1114
|
+
skipNoiseBeforeArgument() {
|
|
1115
|
+
const start = this.pos;
|
|
1116
|
+
this.skipNoise(this.isNoiseBeforeArgument, startsArgument);
|
|
1117
|
+
for (let index = start; index < this.pos; index++) {
|
|
1118
|
+
if (!isComparisonStart(this.tokens, index))
|
|
471
1119
|
continue;
|
|
472
|
-
|
|
1120
|
+
this.leaveArgumentUncertain();
|
|
1121
|
+
return;
|
|
473
1122
|
}
|
|
474
|
-
|
|
475
|
-
|
|
1123
|
+
}
|
|
1124
|
+
/** Leaves the argument the innermost call reads, and the ones after it, uncertain; see FuncNode.uncertainFrom. */
|
|
1125
|
+
leaveArgumentUncertain() {
|
|
1126
|
+
const call = this.constructs.at(-1);
|
|
1127
|
+
call.uncertainFrom ??= call.argumentIndex;
|
|
1128
|
+
}
|
|
1129
|
+
/**
|
|
1130
|
+
* Whether a token stands for nothing before an argument: a logical
|
|
1131
|
+
* operator, which has nothing to combine, or one that stands for nothing
|
|
1132
|
+
* before anything an argument can start with; see standsForNothing().
|
|
1133
|
+
*/
|
|
1134
|
+
isNoiseBeforeArgument(index) {
|
|
1135
|
+
return isLogicalOperator(this.tokenAt(index)) || this.standsForNothing(index, startsArgument);
|
|
1136
|
+
}
|
|
1137
|
+
/**
|
|
1138
|
+
* Whether a token stands for nothing before a comparison value; see
|
|
1139
|
+
* standsForNothing(). An operator does not: after the comparison operator,
|
|
1140
|
+
* it belongs to something else, as a second operator or one after a
|
|
1141
|
+
* missing value does, so the value is missing.
|
|
1142
|
+
*/
|
|
1143
|
+
isNoiseBeforeComparisonValue(index) {
|
|
1144
|
+
const token = this.tokenAt(index);
|
|
1145
|
+
if (token.kind === 'Operator' || token.kind === 'Equals' || token.kind === 'NotEquals')
|
|
1146
|
+
return false;
|
|
1147
|
+
return this.standsForNothing(index, startsValue);
|
|
1148
|
+
}
|
|
1149
|
+
/**
|
|
1150
|
+
* Whether a token stands for nothing before one that `starts` accepts:
|
|
1151
|
+
* it can start nothing there and no open construct resumes at it, as a
|
|
1152
|
+
* closer that pairs with no opener, or a `*`. An opener holds what is up
|
|
1153
|
+
* to its closer, and a malformed token has its own rule.
|
|
1154
|
+
*/
|
|
1155
|
+
standsForNothing(index, starts) {
|
|
1156
|
+
const token = this.tokenAt(index);
|
|
1157
|
+
return this.handlerOf(index) === null && !starts(token) && CLOSER_OF[token.kind] === undefined && !isMalformed(token);
|
|
1158
|
+
}
|
|
1159
|
+
/** An argument that is a value, or a comparison of one. */
|
|
1160
|
+
parseValueArgument(startPos) {
|
|
1161
|
+
const value = this.tryParseArgumentValue();
|
|
1162
|
+
// A name is a string only for want of a comparison after it; see tryParseArgumentValue().
|
|
1163
|
+
this.constructs.at(-1).argumentValue = value ?? (this.peek().kind === 'Identifier' ? null : 'literal');
|
|
1164
|
+
if (!value)
|
|
1165
|
+
return this.parseValue('function');
|
|
1166
|
+
return this.parseArgumentComparison(value, startPos) ?? value;
|
|
1167
|
+
}
|
|
1168
|
+
/**
|
|
1169
|
+
* The field or function value an argument starts with. An unknown name
|
|
1170
|
+
* that a comparison, an access, or a logical operator follows is a field,
|
|
1171
|
+
* as at the top level. One alone is more likely an unquoted string.
|
|
1172
|
+
*/
|
|
1173
|
+
tryParseArgumentValue() {
|
|
1174
|
+
const value = this.tryParseDynamicValue();
|
|
1175
|
+
if (value)
|
|
1176
|
+
return value;
|
|
1177
|
+
const token = this.peek();
|
|
1178
|
+
if (token.kind !== 'Identifier' || token.value.startsWith('$'))
|
|
1179
|
+
return null;
|
|
1180
|
+
const nextIndex = this.indexPastStrayClosers(1);
|
|
1181
|
+
const next = this.tokenAt(nextIndex);
|
|
1182
|
+
if (next.kind === 'LBracket' || isComparisonStart(this.tokens, nextIndex) || isLogicalOperator(next))
|
|
1183
|
+
return this.parseFieldRef();
|
|
1184
|
+
return null;
|
|
1185
|
+
}
|
|
1186
|
+
/**
|
|
1187
|
+
* An argument read as the first of several combined conditions. A literal
|
|
1188
|
+
* cannot be one, and the missing parentheses already make it invalid.
|
|
1189
|
+
* Invalid syntax stays invalid. `cutShort` marks a field or call that
|
|
1190
|
+
* recovery cut short; see InvalidNode.operand.
|
|
1191
|
+
*/
|
|
1192
|
+
asCondition(argument, cutShort) {
|
|
1193
|
+
switch (argument.kind) {
|
|
1194
|
+
case 'Field':
|
|
1195
|
+
return this.fieldCondition(argument, cutShort);
|
|
1196
|
+
case 'Func':
|
|
1197
|
+
return this.functionCondition(argument, cutShort);
|
|
1198
|
+
case 'Comparison':
|
|
1199
|
+
case 'Invalid':
|
|
1200
|
+
return argument;
|
|
1201
|
+
case 'StringLiteral':
|
|
1202
|
+
case 'NumberLiteral':
|
|
1203
|
+
case 'IpLiteral':
|
|
1204
|
+
case 'BoolLiteral':
|
|
1205
|
+
case 'SetLiteral':
|
|
1206
|
+
case 'ListRef':
|
|
1207
|
+
return this.invalidNode(argument.pos, argument.length ?? 0);
|
|
1208
|
+
default:
|
|
1209
|
+
return unhandledNode(argument);
|
|
476
1210
|
}
|
|
477
|
-
|
|
478
|
-
|
|
1211
|
+
}
|
|
1212
|
+
/** Enters the construct that the opener at the current token starts. */
|
|
1213
|
+
open(kind) {
|
|
1214
|
+
const partner = this.partners[this.pos] ?? -1;
|
|
1215
|
+
const closer = partner >= 0 ? partner : null;
|
|
1216
|
+
const depth = this.constructs.length;
|
|
1217
|
+
const outside = this.constructs.at(-1)?.nearest ?? NO_CONSTRUCTS;
|
|
1218
|
+
const construct = {
|
|
1219
|
+
kind,
|
|
1220
|
+
closer,
|
|
1221
|
+
argumentIndex: 0,
|
|
1222
|
+
functionName: null,
|
|
1223
|
+
uncertainFrom: null,
|
|
1224
|
+
strayArgument: false,
|
|
1225
|
+
recoveredIn: null,
|
|
1226
|
+
readingCondition: false,
|
|
1227
|
+
args: null,
|
|
1228
|
+
argumentValue: null,
|
|
1229
|
+
depth,
|
|
1230
|
+
nearest: {
|
|
1231
|
+
closed: closer !== null ? depth : outside.closed,
|
|
1232
|
+
call: kind === 'call' ? depth : outside.call,
|
|
1233
|
+
logical: kind === 'group' || kind === 'call' ? depth : outside.logical,
|
|
1234
|
+
access: closer === null && kind === 'access' ? depth : outside.access,
|
|
1235
|
+
},
|
|
1236
|
+
};
|
|
1237
|
+
this.consume();
|
|
1238
|
+
this.constructs.push(construct);
|
|
1239
|
+
if (closer !== null)
|
|
1240
|
+
this.closerDepths.set(closer, depth);
|
|
1241
|
+
return construct;
|
|
1242
|
+
}
|
|
1243
|
+
/**
|
|
1244
|
+
* Leaves the innermost construct, consuming its closer. A construct with
|
|
1245
|
+
* its closer ends only there, since it owns every token up to it. One
|
|
1246
|
+
* without ends where an enclosing construct resumes, and its closer is
|
|
1247
|
+
* reported missing, since pairing found none, unless the input ends in a
|
|
1248
|
+
* token that may hide it; see takeHiddenCloser(). Returns whether the closer
|
|
1249
|
+
* was read, hidden in that token, or missing.
|
|
1250
|
+
*/
|
|
1251
|
+
close(construct, reportMissing) {
|
|
1252
|
+
this.constructs.pop();
|
|
1253
|
+
if (construct.closer !== null)
|
|
1254
|
+
this.closerDepths.delete(construct.closer);
|
|
1255
|
+
if (this.pos === construct.closer) {
|
|
1256
|
+
this.consume();
|
|
1257
|
+
return 'read';
|
|
479
1258
|
}
|
|
480
|
-
|
|
1259
|
+
if (construct.closer === null && this.takeHiddenCloser(construct))
|
|
1260
|
+
return 'hidden';
|
|
1261
|
+
if (construct.closer === null)
|
|
1262
|
+
reportMissing();
|
|
1263
|
+
return 'missing';
|
|
481
1264
|
}
|
|
482
|
-
|
|
483
|
-
|
|
1265
|
+
/**
|
|
1266
|
+
* Takes a closer of a construct from the token the input ends in, when the
|
|
1267
|
+
* parser is at the end of the input and that token's text holds one that
|
|
1268
|
+
* no construct inside this one took. Returns whether it took one. The
|
|
1269
|
+
* innermost take them first, as the closers would if the token had ended
|
|
1270
|
+
* before them.
|
|
1271
|
+
*/
|
|
1272
|
+
takeHiddenCloser(construct) {
|
|
1273
|
+
const closer = CLOSER_TEXT[construct.kind];
|
|
1274
|
+
if (this.peek().kind !== 'EOF' || !this.hiddenClosers[closer])
|
|
1275
|
+
return false;
|
|
1276
|
+
this.hiddenClosers[closer]--;
|
|
1277
|
+
return true;
|
|
484
1278
|
}
|
|
485
|
-
|
|
486
|
-
|
|
1279
|
+
/**
|
|
1280
|
+
* The open construct that resumes at a token: its index in `constructs`,
|
|
1281
|
+
* -1 for the top level, or null when none does. A construct with its
|
|
1282
|
+
* closer owns every token up to it, so none outside it resumes there. With
|
|
1283
|
+
* `argumentStarts`, a call also takes a token that can start an argument,
|
|
1284
|
+
* as the next argument after a missing comma.
|
|
1285
|
+
*/
|
|
1286
|
+
handlerOf(index, argumentStarts = false) {
|
|
1287
|
+
const token = this.tokens[index];
|
|
1288
|
+
if (!token || token.kind === 'EOF')
|
|
1289
|
+
return -1;
|
|
1290
|
+
const nearest = this.constructs.at(-1)?.nearest ?? NO_CONSTRUCTS;
|
|
1291
|
+
let handler = this.closerDepths.get(index) ?? -1;
|
|
1292
|
+
if (token.kind === 'Comma')
|
|
1293
|
+
handler = Math.max(handler, nearest.call);
|
|
1294
|
+
if (isLogicalOperator(token))
|
|
1295
|
+
handler = Math.max(handler, nearest.logical);
|
|
1296
|
+
if (argumentStarts && startsArgument(token))
|
|
1297
|
+
handler = Math.max(handler, nearest.call);
|
|
1298
|
+
if (isComparisonStart(this.tokens, index) && this.endsAtComparison())
|
|
1299
|
+
handler = Math.max(handler, this.constructs.length - 1);
|
|
1300
|
+
if (token.kind === 'LBracket')
|
|
1301
|
+
handler = Math.max(handler, nearest.access);
|
|
1302
|
+
if (handler >= 0 && handler >= nearest.closed)
|
|
1303
|
+
return handler;
|
|
1304
|
+
if (nearest.closed >= 0)
|
|
1305
|
+
return null;
|
|
1306
|
+
return isLogicalOperator(token) ? -1 : null;
|
|
487
1307
|
}
|
|
488
|
-
|
|
489
|
-
|
|
1308
|
+
/**
|
|
1309
|
+
* Whether the innermost construct ends at a comparison operator: an access
|
|
1310
|
+
* without its `]`, or a call without its `)` that reads a value argument
|
|
1311
|
+
* the comparison cannot be; see takesComparison(). A construct outside it
|
|
1312
|
+
* does not: the comparison belongs to the innermost one, or to what that
|
|
1313
|
+
* one holds, such as a condition.
|
|
1314
|
+
*/
|
|
1315
|
+
endsAtComparison() {
|
|
1316
|
+
const construct = this.constructs.at(-1);
|
|
1317
|
+
if (construct === undefined || construct.closer !== null)
|
|
1318
|
+
return false;
|
|
1319
|
+
if (construct.kind === 'access')
|
|
490
1320
|
return true;
|
|
491
|
-
|
|
1321
|
+
return construct.kind === 'call' && !construct.readingCondition && !takesComparison(construct);
|
|
1322
|
+
}
|
|
1323
|
+
/** Whether a construct outside the one at `depth` resumes at the current token. */
|
|
1324
|
+
resumesOutside(depth) {
|
|
1325
|
+
const handler = this.handlerOf(this.pos);
|
|
1326
|
+
return handler !== null && handler < depth;
|
|
1327
|
+
}
|
|
1328
|
+
isStrayCloser(index) {
|
|
1329
|
+
const token = this.tokens[index];
|
|
1330
|
+
return token !== undefined && isCloser(token) && this.partners[index] === -1;
|
|
1331
|
+
}
|
|
1332
|
+
/** Reports each closer at the current token that pairs with no opener, and skips it alone. */
|
|
1333
|
+
skipStrayClosers() {
|
|
1334
|
+
while (this.isStrayCloser(this.pos)) {
|
|
1335
|
+
this.reportUnexpectedToken(this.peek());
|
|
1336
|
+
this.pos++;
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
/**
|
|
1340
|
+
* Checks the token after a complete operand, argument, or access value. A
|
|
1341
|
+
* closer that pairs with no opener is skipped alone. A token that no open
|
|
1342
|
+
* construct takes starts recovery, and gets an error unless it is an
|
|
1343
|
+
* unknown character or an unterminated comment, which has its own. Returns
|
|
1344
|
+
* whether recovery skipped a token after the one with the error, which
|
|
1345
|
+
* may then stand for a comparison operator; see InvalidNode.operand.
|
|
1346
|
+
*/
|
|
1347
|
+
finishOperand() {
|
|
1348
|
+
this.skipStrayClosers();
|
|
1349
|
+
if (this.handlerOf(this.pos, true) !== null)
|
|
492
1350
|
return false;
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
1351
|
+
const token = this.peek();
|
|
1352
|
+
const recovery = this.recoveryEnd();
|
|
1353
|
+
// An unterminated string's own error says nothing about where it is.
|
|
1354
|
+
if (token.kind !== 'Invalid') {
|
|
1355
|
+
const end = this.tokens[recovery.end];
|
|
1356
|
+
if (this.constructs.length === 0 && (!end || end.kind === 'EOF')) {
|
|
1357
|
+
this.reportAtCurrent('unexpected tokens after expression end', { id: 'syntax.unexpected_tokens_after_expression_end' });
|
|
1358
|
+
}
|
|
1359
|
+
else {
|
|
1360
|
+
this.reportUnexpectedToken(token);
|
|
1361
|
+
}
|
|
1362
|
+
}
|
|
1363
|
+
this.recover(recovery);
|
|
1364
|
+
return recovery.skipsPastError;
|
|
1365
|
+
}
|
|
1366
|
+
/**
|
|
1367
|
+
* Skips tokens, each opener with everything up to its closer (see
|
|
1368
|
+
* recoveryIndexAfter()), until one that an open construct resumes at (see
|
|
1369
|
+
* handlerOf()). When recovery skips a token after the one with the error,
|
|
1370
|
+
* it marks the argument it is in as uncertain, in the construct it resumes
|
|
1371
|
+
* in and in each it leaves.
|
|
1372
|
+
*/
|
|
1373
|
+
recover(recovery = this.recoveryEnd()) {
|
|
1374
|
+
this.pos = recovery.end;
|
|
1375
|
+
if (!recovery.skipsPastError)
|
|
1376
|
+
return;
|
|
1377
|
+
const handler = this.handlerOf(recovery.end);
|
|
1378
|
+
// Recovery stops at a call's own commas, but the tokens it skips may belong to the argument it is
|
|
1379
|
+
// in, or be arguments after a missing comma. Each construct is left once, so this stays linear.
|
|
1380
|
+
for (let depth = Math.max(handler ?? -1, 0); depth < this.constructs.length; depth++) {
|
|
1381
|
+
const construct = this.constructs[depth];
|
|
1382
|
+
construct.uncertainFrom ??= construct.argumentIndex;
|
|
1383
|
+
construct.recoveredIn = construct.argumentIndex;
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
/**
|
|
1387
|
+
* How many tokens the error at a token covers: an unknown character goes
|
|
1388
|
+
* with the name, number, or string touching it, which may belong to it,
|
|
1389
|
+
* unless the character stands between two operands; see readTokens(). Any
|
|
1390
|
+
* other error, including an opener's, is that token alone.
|
|
1391
|
+
*/
|
|
1392
|
+
errorTokenCount(index) {
|
|
1393
|
+
const token = this.tokens[index];
|
|
1394
|
+
return isUnknownCharacter(token) && !this.operatorCharacters.has(index) && isTouchedByValue(this.tokens, index) ? 2 : 1;
|
|
1395
|
+
}
|
|
1396
|
+
/**
|
|
1397
|
+
* Where recovery from a token stops, and whether it skips more than the
|
|
1398
|
+
* tokens with the error; see errorTokenCount(). What an opener holds up to
|
|
1399
|
+
* its closer is past it, and may hold a comparison operator.
|
|
1400
|
+
*/
|
|
1401
|
+
recoveryEnd(from = this.pos) {
|
|
1402
|
+
const errorEnd = from + this.errorTokenCount(from);
|
|
1403
|
+
let index = from;
|
|
1404
|
+
while (this.handlerOf(index) === null)
|
|
1405
|
+
index = this.recoveryIndexAfter(index);
|
|
1406
|
+
return { end: index, skipsPastError: index > errorEnd };
|
|
1407
|
+
}
|
|
1408
|
+
/**
|
|
1409
|
+
* Whether recovery starts after the operand just read and skips past the
|
|
1410
|
+
* token with the error. That token may stand for a comparison operator,
|
|
1411
|
+
* so the operand may be a comparison's left side; see
|
|
1412
|
+
* InvalidNode.operand.
|
|
1413
|
+
*/
|
|
1414
|
+
cutsShort() {
|
|
1415
|
+
const index = this.indexPastStrayClosers(0);
|
|
1416
|
+
return this.handlerOf(index, true) === null && this.recoveryEnd(index).skipsPastError;
|
|
1417
|
+
}
|
|
1418
|
+
/**
|
|
1419
|
+
* The index recovery goes on from after a token. An opener without its
|
|
1420
|
+
* closer holds everything up to the closer of the construct around it
|
|
1421
|
+
* that has one, or to the end, so recovery does not resume inside it.
|
|
1422
|
+
*/
|
|
1423
|
+
recoveryIndexAfter(index) {
|
|
1424
|
+
if (CLOSER_OF[this.tokens[index].kind] === undefined || this.partners[index] >= 0)
|
|
1425
|
+
return this.indexAfter(index);
|
|
1426
|
+
const closed = this.constructs.at(-1)?.nearest.closed ?? -1;
|
|
1427
|
+
return closed >= 0 ? this.constructs[closed].closer : this.tokens.length - 1;
|
|
1428
|
+
}
|
|
1429
|
+
/** The index after a token, or after the closer of an opener. */
|
|
1430
|
+
indexAfter(index) {
|
|
1431
|
+
const partner = this.partners[index] ?? -1;
|
|
1432
|
+
return partner > index ? partner + 1 : index + 1;
|
|
1433
|
+
}
|
|
1434
|
+
startsLogicalArgument() {
|
|
1435
|
+
const token = this.peek();
|
|
1436
|
+
if (token.kind === 'LParen')
|
|
1437
|
+
return true;
|
|
1438
|
+
if (token.kind === 'Operator')
|
|
1439
|
+
return token.value === 'not';
|
|
1440
|
+
return token.kind === 'Identifier' && (token.value === 'any' || token.value === 'all') && this.peekPastStrayClosers(1).kind === 'LParen';
|
|
1441
|
+
}
|
|
1442
|
+
/**
|
|
1443
|
+
* The comparison an argument value starts, or null when the argument ends
|
|
1444
|
+
* before the comparison operator. In a call without its `)`, the operator
|
|
1445
|
+
* ends the argument, and the call with it, unless the comparison can be
|
|
1446
|
+
* the argument, as coalesce()'s first can: `lower(http.host eq "x"` more
|
|
1447
|
+
* likely misses the `)` after `http.host`, and the comparison then
|
|
1448
|
+
* compares the call's result. The parser decides this at the operator,
|
|
1449
|
+
* from what it has read, so it never reads a comparison it would have to
|
|
1450
|
+
* undo; see takesComparison(). Any other comparison is the argument; see
|
|
1451
|
+
* parseFunctionArg() for a logical operator after it.
|
|
1452
|
+
*/
|
|
1453
|
+
parseArgumentComparison(left, startPos) {
|
|
1454
|
+
if (this.endsAtComparison())
|
|
1455
|
+
return null;
|
|
1456
|
+
return this.parseComparisonRest(left, startPos);
|
|
1457
|
+
}
|
|
1458
|
+
/** The comparison that follows a value, or null when no comparison operator does. */
|
|
1459
|
+
parseComparisonRest(left, startPos) {
|
|
1460
|
+
this.skipStrayClosers();
|
|
510
1461
|
const op = this.tryParseCompOp();
|
|
511
|
-
if (op === null
|
|
1462
|
+
if (op === null)
|
|
1463
|
+
return null;
|
|
1464
|
+
const right = this.parseComparisonValue(op, this.previousTokenEnd());
|
|
1465
|
+
const raw = this.rawSpan(startPos);
|
|
1466
|
+
return { kind: 'Comparison', left, op, right, raw, pos: startPos, length: raw.length };
|
|
1467
|
+
}
|
|
1468
|
+
isKnownFieldName(name) {
|
|
1469
|
+
return !name.startsWith('$') && (KNOWN_AVAILABLE_FIELDS.has(name) || KNOWN_UNAVAILABLE_FIELDS.has(name));
|
|
1470
|
+
}
|
|
1471
|
+
/**
|
|
1472
|
+
* A call where a condition belongs, with the comparison after it, if any.
|
|
1473
|
+
* No comparison is read after starts_with() or ends_with(). Its own
|
|
1474
|
+
* method, so that the frame each nested call adds stays small.
|
|
1475
|
+
*/
|
|
1476
|
+
parseScalarFunctionComparison(name, parsed, startPos) {
|
|
1477
|
+
const funcNode = this.funcNode(name, parsed, this.parseAccessPath(), startPos);
|
|
1478
|
+
const comparison = name === 'starts_with' || name === 'ends_with' ? null : this.parseComparisonRest(funcNode, startPos);
|
|
1479
|
+
return comparison ?? this.functionCondition(funcNode, parsed.cutShort);
|
|
1480
|
+
}
|
|
1481
|
+
/** A call without a comparison, as a condition; see fieldCondition(). */
|
|
1482
|
+
functionCondition(funcNode, cutShort) {
|
|
1483
|
+
if (!(cutShort || this.cutsShort() || this.cutShortAccessPaths.has(funcNode.accessPath)) || !isComparableValue(funcNode))
|
|
512
1484
|
return funcNode;
|
|
513
|
-
|
|
514
|
-
const actualOp = op ?? (this.peek().kind === 'Equals' ? (this.consume(), 'eq') : (this.consume(), 'ne'));
|
|
515
|
-
const right = this.parseComparisonValue(actualOp, this.previousTokenEnd());
|
|
516
|
-
const compRaw = this.rawSpan(startPos);
|
|
517
|
-
return { kind: 'Comparison', left: funcNode, op: actualOp, right, raw: compRaw };
|
|
1485
|
+
return this.invalidNode(funcNode.pos, funcNode.length ?? 0, funcNode);
|
|
518
1486
|
}
|
|
519
1487
|
// any(field[*] op value), any(not field[*] op value), or any(lower(field[*])[*] op value)
|
|
520
1488
|
parseAnyAll(name, startPos) {
|
|
1489
|
+
const quantifier = this.open('quantifier');
|
|
1490
|
+
this.skipStrayClosers();
|
|
521
1491
|
if (this.peek().kind === 'EOF') {
|
|
522
|
-
|
|
523
|
-
this.
|
|
524
|
-
|
|
1492
|
+
// The whole call is what is unfinished.
|
|
1493
|
+
this.close(quantifier, () => this.reportMissingCallCloser(name, {
|
|
1494
|
+
pos: startPos,
|
|
1495
|
+
length: Math.max(this.rawSpan(startPos).length, name.length + 1),
|
|
1496
|
+
}));
|
|
1497
|
+
return this.funcNode(name, quantifierArguments([], 0, true), [], startPos);
|
|
525
1498
|
}
|
|
526
|
-
if (this.
|
|
527
|
-
this.
|
|
1499
|
+
if (this.pos === quantifier.closer) {
|
|
1500
|
+
this.close(quantifier, () => { });
|
|
528
1501
|
const raw = this.rawSpan(startPos);
|
|
529
|
-
this.
|
|
530
|
-
return
|
|
1502
|
+
this.reportAtSpan(`missing argument for function '${name}'`, startPos, Math.max(raw.length, name.length + 2), { id: 'syntax.missing_function_argument', params: { functionName: name } });
|
|
1503
|
+
return this.funcNode(name, quantifierArguments([], undefined, false), [], startPos);
|
|
531
1504
|
}
|
|
532
1505
|
const predicate = this.parseNot();
|
|
533
|
-
|
|
534
|
-
|
|
1506
|
+
this.finishOperand();
|
|
1507
|
+
const closing = this.close(quantifier, () => this.reportMissingCallCloser(name));
|
|
1508
|
+
const parsed = quantifierArguments([predicate], quantifier.uncertainFrom ?? (closing === 'read' ? undefined : 1), quantifier.recoveredIn !== null || closing !== 'read');
|
|
1509
|
+
return this.funcNode(name, parsed, this.parseAccessPath(), startPos);
|
|
1510
|
+
}
|
|
1511
|
+
/**
|
|
1512
|
+
* Reads an integer literal, reporting one Cloudflare rejects: one with a
|
|
1513
|
+
* fraction, an octal one with the digit 8 or 9, or one outside the 64-bit
|
|
1514
|
+
* range. Null means it reported an error.
|
|
1515
|
+
*/
|
|
1516
|
+
readInteger(token, literal) {
|
|
1517
|
+
const value = integerLiteralValue(literal);
|
|
1518
|
+
if (value === null && /^\d+$/.test(literal)) {
|
|
1519
|
+
this.reportAtToken(`integer literal '${literal}' starts with 0, so it is octal, and cannot use the digits 8 and 9`, token, { id: 'syntax.invalid_octal_literal', params: { literal } });
|
|
1520
|
+
return null;
|
|
535
1521
|
}
|
|
536
|
-
|
|
537
|
-
this.
|
|
1522
|
+
if (value === null) {
|
|
1523
|
+
this.reportAtToken(`number literal '${literal}' must be an integer`, token, { id: 'syntax.invalid_integer_literal', params: { literal } });
|
|
1524
|
+
return null;
|
|
538
1525
|
}
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
1526
|
+
if (value >= MIN_INTEGER && value <= MAX_INTEGER)
|
|
1527
|
+
return value;
|
|
1528
|
+
this.reportAtToken(`integer literal '${literal}' is outside the 64-bit integer range`, token, {
|
|
1529
|
+
id: 'syntax.integer_literal_out_of_range',
|
|
1530
|
+
params: { literal, min: String(MIN_INTEGER), max: String(MAX_INTEGER) },
|
|
1531
|
+
});
|
|
1532
|
+
return null;
|
|
542
1533
|
}
|
|
543
1534
|
/**
|
|
544
1535
|
* Reports a Cloudflare hex byte literal, such as 65:78:61, which this
|
|
@@ -547,23 +1538,20 @@ export class Parser {
|
|
|
547
1538
|
reportHexBytesLiteral(token) {
|
|
548
1539
|
if (!/^[\da-fA-F]{2}(?:[:-][\da-fA-F]{2})+$/.test(token.value) || isRuleExpressionIpLiteral(token.value))
|
|
549
1540
|
return false;
|
|
550
|
-
this.
|
|
1541
|
+
this.reportAtToken(`hex byte literal '${token.value}' is not supported; write the value as a quoted string`, token, { id: 'syntax.unsupported_hex_bytes_literal', params: { literal: token.value } });
|
|
551
1542
|
return true;
|
|
552
1543
|
}
|
|
553
|
-
|
|
554
|
-
this.
|
|
1544
|
+
reportAtCurrent(message, metadata) {
|
|
1545
|
+
this.reportAtToken(message, this.peek(), metadata);
|
|
555
1546
|
}
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
return;
|
|
559
|
-
this.pushWarningAtToken(`unexpected identifier '${token.value}' ${VALUE_CONTEXT_LOCATIONS[context]}; quote string literals`, token, {
|
|
1547
|
+
reportUnquotedName(token, context) {
|
|
1548
|
+
this.reportAtToken(`unexpected identifier '${token.value}' ${VALUE_CONTEXT_LOCATIONS[context]}; quote string literals`, token, {
|
|
560
1549
|
id: 'syntax.unquoted_string_literal',
|
|
561
1550
|
params: { identifier: token.value, context },
|
|
562
1551
|
});
|
|
563
1552
|
}
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
pushDiagnosticDetail(this.diagnostics, {
|
|
1553
|
+
reportAtToken(message, token, metadata) {
|
|
1554
|
+
this.report({
|
|
567
1555
|
severity: 'error',
|
|
568
1556
|
message,
|
|
569
1557
|
pos: token.pos >= 0 ? token.pos : null,
|
|
@@ -571,9 +1559,8 @@ export class Parser {
|
|
|
571
1559
|
...metadata,
|
|
572
1560
|
});
|
|
573
1561
|
}
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
pushDiagnosticDetail(this.diagnostics, {
|
|
1562
|
+
reportAtSpan(message, pos, length, metadata) {
|
|
1563
|
+
this.report({
|
|
577
1564
|
severity: 'error',
|
|
578
1565
|
message,
|
|
579
1566
|
pos,
|
|
@@ -581,14 +1568,8 @@ export class Parser {
|
|
|
581
1568
|
...metadata,
|
|
582
1569
|
});
|
|
583
1570
|
}
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
return token.length;
|
|
588
|
-
if (token.kind === 'EOF')
|
|
589
|
-
return 0;
|
|
590
|
-
if (token.kind === 'String')
|
|
591
|
-
return token.value.length + 2;
|
|
592
|
-
return token.value.length;
|
|
1571
|
+
report(detail) {
|
|
1572
|
+
this.diagnostics?.push(detail);
|
|
1573
|
+
}
|
|
593
1574
|
}
|
|
594
1575
|
//# sourceMappingURL=parser.js.map
|