corvus_json_schema 0.1.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.
- checksums.yaml +7 -0
- data/Cargo.lock +390 -0
- data/Cargo.toml +8 -0
- data/LICENSE +201 -0
- data/README.md +111 -0
- data/VERSIONHISTORY.md +7 -0
- data/ext/corvus_json_schema/Cargo.toml +18 -0
- data/ext/corvus_json_schema/extconf.rb +6 -0
- data/ext/corvus_json_schema/rustfmt.toml +2 -0
- data/ext/corvus_json_schema/src/lib.rs +643 -0
- data/ext/corvus_json_schema/vendor/corvus-json-schema/Cargo.toml +35 -0
- data/ext/corvus_json_schema/vendor/corvus-json-schema/LICENSE +201 -0
- data/ext/corvus_json_schema/vendor/corvus-json-schema/README.md +139 -0
- data/ext/corvus_json_schema/vendor/corvus-json-schema/src/compiler.rs +1118 -0
- data/ext/corvus_json_schema/vendor/corvus-json-schema/src/dialect.rs +108 -0
- data/ext/corvus_json_schema/vendor/corvus-json-schema/src/document.rs +905 -0
- data/ext/corvus_json_schema/vendor/corvus-json-schema/src/eval/plan/fused.rs +1187 -0
- data/ext/corvus_json_schema/vendor/corvus-json-schema/src/eval/plan.rs +1728 -0
- data/ext/corvus_json_schema/vendor/corvus-json-schema/src/eval.rs +1451 -0
- data/ext/corvus_json_schema/vendor/corvus-json-schema/src/formats.rs +1021 -0
- data/ext/corvus_json_schema/vendor/corvus-json-schema/src/instance.rs +228 -0
- data/ext/corvus_json_schema/vendor/corvus-json-schema/src/lib.rs +189 -0
- data/ext/corvus_json_schema/vendor/corvus-json-schema/src/loader.rs +403 -0
- data/ext/corvus_json_schema/vendor/corvus-json-schema/src/metaschemas.rs +29 -0
- data/ext/corvus_json_schema/vendor/corvus-json-schema/src/node.rs +417 -0
- data/ext/corvus_json_schema/vendor/corvus-json-schema/src/numbers.rs +244 -0
- data/ext/corvus_json_schema/vendor/corvus-json-schema/src/options.rs +108 -0
- data/ext/corvus_json_schema/vendor/corvus-json-schema/src/pattern.rs +1591 -0
- data/ext/corvus_json_schema/vendor/corvus-json-schema/src/results.rs +316 -0
- data/ext/corvus_json_schema/vendor/corvus-json-schema/src/uri.rs +274 -0
- data/lib/corvus_json_schema/version.rb +5 -0
- data/lib/corvus_json_schema.rb +65 -0
- metadata +94 -0
|
@@ -0,0 +1,1728 @@
|
|
|
1
|
+
//! Fail-fast evaluation plans: each node compiled to only the keywords it has, as a flat list of operations, with the
|
|
2
|
+
//! object keywords fused into one pass over the instance's properties (declared names resolved through a lookup table,
|
|
3
|
+
//! `required` checked as a bit mask of the declared properties seen) and children that are nothing but a type check
|
|
4
|
+
//! tested inline. The idea of the C# evaluator's fused plans (`FusedObjectPlan`, leaf and type-dispatch plans), in the
|
|
5
|
+
//! shape a Rust interpreter wants.
|
|
6
|
+
//!
|
|
7
|
+
//! Plans only drive fail-fast evaluation without a dynamic scope. A node that tracks evaluated properties or items
|
|
8
|
+
//! (`unevaluatedProperties`/`unevaluatedItems`) runs through the general evaluator, whose children come back to their
|
|
9
|
+
//! plans.
|
|
10
|
+
|
|
11
|
+
use std::sync::Arc;
|
|
12
|
+
|
|
13
|
+
use serde_json::{Number, Value};
|
|
14
|
+
|
|
15
|
+
mod fused;
|
|
16
|
+
|
|
17
|
+
use super::{Evaluator, Fast, Program, all_unique, code_points, content_ok, json_equal};
|
|
18
|
+
use crate::dialect::Dialect;
|
|
19
|
+
use crate::formats::FormatKind;
|
|
20
|
+
use crate::instance::{ArrayView, Instance, Kind, ObjectView, View, str_eq};
|
|
21
|
+
use crate::node::*;
|
|
22
|
+
use crate::numbers::{Divisor, Num, cmp};
|
|
23
|
+
use crate::options::FormatValidator;
|
|
24
|
+
use crate::pattern::Pattern;
|
|
25
|
+
|
|
26
|
+
/// Every JSON type (a node without `type`).
|
|
27
|
+
const ANY: u8 = 0x7f;
|
|
28
|
+
|
|
29
|
+
/// A child that accepts anything and is never entered (an undeclared name without additionalProperties).
|
|
30
|
+
const NO_CHILD: Child = Child { id: u32::MAX, types: ANY, shape: Shape::Trivial };
|
|
31
|
+
|
|
32
|
+
/// A child application, with its type check hoisted so that a child that is only a type check needs no call.
|
|
33
|
+
#[derive(Clone, Copy)]
|
|
34
|
+
pub(crate) struct Child {
|
|
35
|
+
id: NodeId,
|
|
36
|
+
/// The types the child accepts (0 for `false`).
|
|
37
|
+
types: u8,
|
|
38
|
+
/// What the child's keywords come to, so that entering it skips the dispatch it does not need.
|
|
39
|
+
shape: Shape,
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/// The shape of a node's plan, as its callers enter it.
|
|
43
|
+
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
|
44
|
+
enum Shape {
|
|
45
|
+
/// Nothing to check beyond the types.
|
|
46
|
+
Trivial,
|
|
47
|
+
/// Only its own value (const, enum, number and string keywords): no children, no calls.
|
|
48
|
+
Leaf,
|
|
49
|
+
/// Only an enum of strings (the C# StrictEntry's InlineEnum).
|
|
50
|
+
StringEnum,
|
|
51
|
+
/// Only string keywords (length, pattern, format).
|
|
52
|
+
Strings,
|
|
53
|
+
/// Nothing but an object plan: an object value enters its loop directly (the C# NestedObject).
|
|
54
|
+
Object,
|
|
55
|
+
/// Nothing but an array plan: an array value enters its loop directly.
|
|
56
|
+
Array,
|
|
57
|
+
/// Nothing but in-place applicators (the C# TypeDispatch/Forward entries): straight to them.
|
|
58
|
+
Apply,
|
|
59
|
+
/// Anything else, or on an in-place cycle (entered through the guarded path).
|
|
60
|
+
General,
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
impl Child {
|
|
64
|
+
#[inline(always)]
|
|
65
|
+
fn trivial(&self) -> bool {
|
|
66
|
+
self.shape == Shape::Trivial
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
pub(crate) struct Plan {
|
|
71
|
+
types: u8,
|
|
72
|
+
/// Evaluated in place under the depth guard (part of an in-place cycle).
|
|
73
|
+
guard: bool,
|
|
74
|
+
/// Everything beyond the type check (none for `true`, `false` and type-only schemas).
|
|
75
|
+
body: Option<Box<Body>>,
|
|
76
|
+
/// The body's shape, for entering it directly (a node evaluated as a program's or an applicator's target, not
|
|
77
|
+
/// only as a child): `General` goes through `run_keywords`, whose generality costs a small object tens of
|
|
78
|
+
/// instructions.
|
|
79
|
+
shape: Shape,
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/// A node's keywords, grouped so that only the ones for the instance's type are looked at.
|
|
83
|
+
#[derive(Default)]
|
|
84
|
+
struct Body {
|
|
85
|
+
/// For an object instance, the whole node in one pass (see `fused`), in place of everything below.
|
|
86
|
+
fused: Option<Box<fused::FusedObject>>,
|
|
87
|
+
/// Instance kinds (`type_mask::OBJECT`, `type_mask::ARRAY`) whose evaluated properties/items the general
|
|
88
|
+
/// evaluator must track (unevaluatedProperties/unevaluatedItems), and the node it runs.
|
|
89
|
+
general: u8,
|
|
90
|
+
node: NodeId,
|
|
91
|
+
/// unevaluatedItems with a static coverage: the items from this index on, against the child.
|
|
92
|
+
unevaluated_items: Option<(usize, Child)>,
|
|
93
|
+
/// const and enum.
|
|
94
|
+
values: Box<[Op]>,
|
|
95
|
+
number: Box<[NumberOp]>,
|
|
96
|
+
string: Box<[StringOp]>,
|
|
97
|
+
object: Option<ObjectPlan>,
|
|
98
|
+
array: Option<ArrayPlan>,
|
|
99
|
+
/// In-place applicators (children resolved through pure-$ref hops), in the general evaluator's order.
|
|
100
|
+
apply: Box<[Op]>,
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
enum NumberOp {
|
|
104
|
+
Minimum(Num),
|
|
105
|
+
Maximum(Num),
|
|
106
|
+
ExclusiveMinimum(Num),
|
|
107
|
+
ExclusiveMaximum(Num),
|
|
108
|
+
MultipleOf(Divisor),
|
|
109
|
+
Format(FormatCheck),
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
enum StringOp {
|
|
113
|
+
Length { min: u64, max: u64 },
|
|
114
|
+
Pattern(Arc<Pattern>),
|
|
115
|
+
Format(FormatCheck),
|
|
116
|
+
Content(ContentKind),
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
enum Op {
|
|
120
|
+
Const(Value),
|
|
121
|
+
/// An enum of strings only.
|
|
122
|
+
EnumStrings(Names),
|
|
123
|
+
Enum(Box<[Value]>),
|
|
124
|
+
Ref(NodeId),
|
|
125
|
+
AllOf(Box<[Child]>),
|
|
126
|
+
AnyOf(Box<Branches>),
|
|
127
|
+
OneOf(Box<Branches>),
|
|
128
|
+
Not(NodeId),
|
|
129
|
+
/// A `$dynamicRef`/`$recursiveRef` resolved against the dynamic scope at run time (the C# DynamicRef plan).
|
|
130
|
+
DynamicRef(Box<DynamicRefTarget>),
|
|
131
|
+
If {
|
|
132
|
+
cond: NodeId,
|
|
133
|
+
then: Option<NodeId>,
|
|
134
|
+
else_: Option<NodeId>,
|
|
135
|
+
},
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
enum FormatCheck {
|
|
139
|
+
Custom(FormatValidator),
|
|
140
|
+
Builtin(FormatKind, bool),
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
impl FormatCheck {
|
|
144
|
+
fn string(&self, s: &str) -> bool {
|
|
145
|
+
match self {
|
|
146
|
+
FormatCheck::Custom(f) => f(s),
|
|
147
|
+
FormatCheck::Builtin(kind, legacy) => kind.check_string(s, *legacy),
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
fn number(&self, n: &Number) -> bool {
|
|
152
|
+
match self {
|
|
153
|
+
FormatCheck::Custom(f) => f(&n.to_string()),
|
|
154
|
+
FormatCheck::Builtin(kind, _) => kind.check_number(n),
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
struct ObjectPlan {
|
|
160
|
+
min: u64,
|
|
161
|
+
max: u64,
|
|
162
|
+
/// How the properties are visited (for properties, patternProperties, additionalProperties, propertyNames).
|
|
163
|
+
visit: Visit,
|
|
164
|
+
/// The declared names, then the names only `required` and dependencies mention (so that the pass sees them too;
|
|
165
|
+
/// C# registers required names as property entries): the first `declared` have a schema.
|
|
166
|
+
names: Names,
|
|
167
|
+
declared: usize,
|
|
168
|
+
/// Per name: the declared schema, or for the others the additionalProperties child (or nothing, `NO_CHILD`).
|
|
169
|
+
children: Box<[Child]>,
|
|
170
|
+
/// Bit `i` set: name `i` is required (the names checked by the mask: at most 64 names in all).
|
|
171
|
+
required_mask: u64,
|
|
172
|
+
/// Required names checked by lookup (when the mask cannot cover them).
|
|
173
|
+
required: Box<[Box<str>]>,
|
|
174
|
+
patterns: Box<[(Arc<Pattern>, Child)]>,
|
|
175
|
+
/// For each declared name, the patterns (indexes into `patterns`) it matches, worked out at compile time: only
|
|
176
|
+
/// undeclared names are tested against the patterns at run time.
|
|
177
|
+
name_patterns: Box<[Box<[u16]>]>,
|
|
178
|
+
additional: Option<Child>,
|
|
179
|
+
property_names: Option<NodeId>,
|
|
180
|
+
dependencies: Box<[Dependency]>,
|
|
181
|
+
/// No required names by lookup and no dependencies: nothing after the property loop but the required mask.
|
|
182
|
+
rest_free: bool,
|
|
183
|
+
/// `Visit::Names` and `rest_free`: the strict loop (`run_strict_object`) decides it.
|
|
184
|
+
strict: bool,
|
|
185
|
+
/// `Visit::Names` with at most `LOOKUP_NAMES` names and no additionalProperties: undeclared properties need no
|
|
186
|
+
/// visit, so a small object is decided by looking each name up in it (see `visit_lookup`).
|
|
187
|
+
lookup: bool,
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/// Plans with at most this many names may look them up in the instance instead of visiting its properties.
|
|
191
|
+
const LOOKUP_NAMES: usize = 4;
|
|
192
|
+
/// ...when the instance's properties times the names are at most this (each lookup scans the properties).
|
|
193
|
+
const LOOKUP_BUDGET: usize = 24;
|
|
194
|
+
|
|
195
|
+
/// The property loop, specialised by which keywords apply.
|
|
196
|
+
#[derive(Clone, Copy, PartialEq, Eq)]
|
|
197
|
+
enum Visit {
|
|
198
|
+
/// No keyword looks at the properties.
|
|
199
|
+
None,
|
|
200
|
+
/// Only additionalProperties (a map): every value against one child.
|
|
201
|
+
Values,
|
|
202
|
+
/// Declared properties, and additionalProperties for the rest.
|
|
203
|
+
Names,
|
|
204
|
+
/// One patternProperties entry and nothing declared: each name against the pattern, else additionalProperties
|
|
205
|
+
/// (the C# PatternMap).
|
|
206
|
+
Pattern,
|
|
207
|
+
/// Anything else (patternProperties, propertyNames).
|
|
208
|
+
General,
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/// anyOf/oneOf branches, dispatched by the instance's type: only the branches whose `type` admits it are tried (the
|
|
212
|
+
/// C# evaluator's type-dispatch plans), and a branch that is only a type check is decided without a call.
|
|
213
|
+
struct Branches {
|
|
214
|
+
children: Box<[Child]>,
|
|
215
|
+
/// For each instance kind (see `kind`), the branches that can accept it.
|
|
216
|
+
by_kind: [Box<[u32]>; 6],
|
|
217
|
+
discriminator: Option<Box<(Discriminator, DiscriminatorIndex)>>,
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/// A discriminator's known values by lookup (C# keys them in a hashed map): string values through a name table,
|
|
221
|
+
/// the few others (numbers, booleans, null) by scan.
|
|
222
|
+
struct DiscriminatorIndex {
|
|
223
|
+
strings: Names,
|
|
224
|
+
/// For each string in `strings`, its entry in `Discriminator::known`.
|
|
225
|
+
string_entries: Box<[u32]>,
|
|
226
|
+
others: Box<[u32]>,
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
impl DiscriminatorIndex {
|
|
230
|
+
fn new(d: &Discriminator) -> DiscriminatorIndex {
|
|
231
|
+
let mut names: Vec<Box<str>> = Vec::new();
|
|
232
|
+
let mut string_entries = Vec::new();
|
|
233
|
+
let mut others = Vec::new();
|
|
234
|
+
for (i, (value, _)) in d.known.iter().enumerate() {
|
|
235
|
+
match value {
|
|
236
|
+
DiscriminatorValue::String(s) => {
|
|
237
|
+
names.push(s.as_str().into());
|
|
238
|
+
string_entries.push(i as u32);
|
|
239
|
+
}
|
|
240
|
+
_ => others.push(i as u32),
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
DiscriminatorIndex {
|
|
244
|
+
strings: Names::new(names),
|
|
245
|
+
string_entries: string_entries.into_boxed_slice(),
|
|
246
|
+
others: others.into_boxed_slice(),
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/// The branches a discriminator value selects.
|
|
251
|
+
#[inline]
|
|
252
|
+
fn select<'d, 'x, I: Instance<'x>>(&self, d: &'d Discriminator, v: I) -> &'d [u32] {
|
|
253
|
+
let entry = match v.view() {
|
|
254
|
+
View::String(s) => self.strings.contains_at(s).map(|i| self.string_entries[i]),
|
|
255
|
+
_ => self.others.iter().copied().find(|&i| d.known[i as usize].0.matches(v)),
|
|
256
|
+
};
|
|
257
|
+
entry.map_or(&d.unknown, |i| &d.known[i as usize].1)
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
impl Branches {
|
|
262
|
+
fn new(children: Box<[Child]>, discriminator: Option<Box<Discriminator>>) -> Branches {
|
|
263
|
+
let discriminator = discriminator.map(|d| {
|
|
264
|
+
let index = DiscriminatorIndex::new(&d);
|
|
265
|
+
Box::new((*d, index))
|
|
266
|
+
});
|
|
267
|
+
Branches { children, by_kind: Default::default(), discriminator }
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/// Recomputes the dispatch table once the children's types are known.
|
|
271
|
+
fn dispatch(&mut self) {
|
|
272
|
+
const KIND_TYPES: [u8; 6] = [
|
|
273
|
+
type_mask::NULL,
|
|
274
|
+
type_mask::BOOLEAN,
|
|
275
|
+
type_mask::NUMBER | type_mask::INTEGER,
|
|
276
|
+
type_mask::STRING,
|
|
277
|
+
type_mask::ARRAY,
|
|
278
|
+
type_mask::OBJECT,
|
|
279
|
+
];
|
|
280
|
+
for (k, types) in KIND_TYPES.iter().enumerate() {
|
|
281
|
+
self.by_kind[k] =
|
|
282
|
+
(0..self.children.len() as u32).filter(|&i| self.children[i as usize].types & types != 0).collect();
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/// The index of an instance's kind in `Branches::by_kind`.
|
|
288
|
+
#[inline(always)]
|
|
289
|
+
fn kind<'x, I: Instance<'x>>(x: I) -> usize {
|
|
290
|
+
match x.kind() {
|
|
291
|
+
Kind::Null => 0,
|
|
292
|
+
Kind::Bool => 1,
|
|
293
|
+
Kind::Number => 2,
|
|
294
|
+
Kind::String => 3,
|
|
295
|
+
Kind::Array => 4,
|
|
296
|
+
Kind::Object => 5,
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
struct Dependency {
|
|
301
|
+
name: Box<str>,
|
|
302
|
+
required: Box<[Box<str>]>,
|
|
303
|
+
schema: Option<NodeId>,
|
|
304
|
+
/// The seen bits of the name and of the names it requires, when every one is a known name.
|
|
305
|
+
bits: Option<(u64, u64)>,
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
struct ArrayPlan {
|
|
309
|
+
min: u64,
|
|
310
|
+
max: u64,
|
|
311
|
+
prefix: Box<[Child]>,
|
|
312
|
+
items: Option<Child>,
|
|
313
|
+
contains: Option<(NodeId, u64, Option<u64>)>,
|
|
314
|
+
unique: bool,
|
|
315
|
+
/// Bounds and type-only items, nothing else (the C# SimpleArray): the items' type mask (`ANY`: no test).
|
|
316
|
+
simple: Option<u8>,
|
|
317
|
+
/// Items that are themselves simple arrays (GeoJSON's positions): their bounds and item types, checked inline.
|
|
318
|
+
nested: Option<SimpleArray>,
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
#[derive(Clone, Copy)]
|
|
322
|
+
struct SimpleArray {
|
|
323
|
+
min: u64,
|
|
324
|
+
max: u64,
|
|
325
|
+
types: u8,
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// ---------------------------------------------------------------------------------------------------------------------
|
|
329
|
+
// Property name lookup
|
|
330
|
+
|
|
331
|
+
/// A name of at most eight bytes as one word, unique among names of the same length: the first and last four bytes
|
|
332
|
+
/// (overlapping, so every byte is in one of them), or for shorter names the first, middle and last byte.
|
|
333
|
+
#[inline(always)]
|
|
334
|
+
fn name_word(b: &[u8]) -> u64 {
|
|
335
|
+
let n = b.len();
|
|
336
|
+
if n >= 4 {
|
|
337
|
+
let first = u32::from_le_bytes(b[..4].try_into().unwrap()) as u64;
|
|
338
|
+
let last = u32::from_le_bytes(b[n - 4..].try_into().unwrap()) as u64;
|
|
339
|
+
first | last << 32
|
|
340
|
+
} else if n > 0 {
|
|
341
|
+
b[0] as u64 | (b[n / 2] as u64) << 8 | (b[n - 1] as u64) << 16
|
|
342
|
+
} else {
|
|
343
|
+
0
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/// At most this many names of one length are compared in turn; more get a table on their most distinguishing byte.
|
|
348
|
+
const MAX_CANDIDATES: usize = 3;
|
|
349
|
+
|
|
350
|
+
/// Names longer than this are compared in turn (no per-length entry).
|
|
351
|
+
const MAX_INDEXED_LENGTH: usize = 128;
|
|
352
|
+
|
|
353
|
+
/// Property names by length (the C# evaluator's Utf8NameMap): a few names of a length are compared directly (names of
|
|
354
|
+
/// up to eight bytes as a single word each, so a miss never touches the text), and more are split by the byte
|
|
355
|
+
/// position that best tells them apart, through a table from that byte to a chain of candidates.
|
|
356
|
+
struct NameMap {
|
|
357
|
+
names: Box<[Box<str>]>,
|
|
358
|
+
by_length: Box<[ByLength]>,
|
|
359
|
+
/// Names longer than `MAX_INDEXED_LENGTH`.
|
|
360
|
+
long: Box<[u32]>,
|
|
361
|
+
/// The next candidate (index + 1, 0: none) after each name in its table chain.
|
|
362
|
+
next: Box<[u32]>,
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
enum ByLength {
|
|
366
|
+
None,
|
|
367
|
+
/// Names of at most eight bytes: their words and indexes.
|
|
368
|
+
Words(Box<[(u64, u32)]>),
|
|
369
|
+
/// A few longer names.
|
|
370
|
+
Few(Box<[u32]>),
|
|
371
|
+
/// The byte position that best splits the names, and the first candidate (index + 1, 0: none) for each byte.
|
|
372
|
+
Table {
|
|
373
|
+
at: usize,
|
|
374
|
+
first: Box<[u32; 256]>,
|
|
375
|
+
},
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
impl NameMap {
|
|
379
|
+
fn new(names: Vec<Box<str>>) -> NameMap {
|
|
380
|
+
let max = names.iter().map(|n| n.len()).filter(|&l| l <= MAX_INDEXED_LENGTH).max().map_or(0, |m| m + 1);
|
|
381
|
+
let mut groups: Vec<Vec<u32>> = vec![Vec::new(); max];
|
|
382
|
+
let mut long = Vec::new();
|
|
383
|
+
for (i, n) in names.iter().enumerate() {
|
|
384
|
+
match groups.get_mut(n.len()) {
|
|
385
|
+
Some(g) => g.push(i as u32),
|
|
386
|
+
None => long.push(i as u32),
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
let mut next = vec![0u32; names.len()];
|
|
390
|
+
let by_length = groups
|
|
391
|
+
.into_iter()
|
|
392
|
+
.enumerate()
|
|
393
|
+
.map(|(len, group)| {
|
|
394
|
+
if group.is_empty() {
|
|
395
|
+
ByLength::None
|
|
396
|
+
} else if len <= 8 && (group.len() <= MAX_CANDIDATES || len == 0) {
|
|
397
|
+
ByLength::Words(group.iter().map(|&i| (name_word(names[i as usize].as_bytes()), i)).collect())
|
|
398
|
+
} else if group.len() <= MAX_CANDIDATES {
|
|
399
|
+
ByLength::Few(group.into())
|
|
400
|
+
} else {
|
|
401
|
+
// The position with the most distinct bytes (the shortest chains).
|
|
402
|
+
let at = (0..len)
|
|
403
|
+
.max_by_key(|&at| {
|
|
404
|
+
let mut seen = [false; 256];
|
|
405
|
+
group
|
|
406
|
+
.iter()
|
|
407
|
+
.filter(|&&i| {
|
|
408
|
+
!std::mem::replace(&mut seen[names[i as usize].as_bytes()[at] as usize], true)
|
|
409
|
+
})
|
|
410
|
+
.count()
|
|
411
|
+
})
|
|
412
|
+
.unwrap();
|
|
413
|
+
let mut first = Box::new([0u32; 256]);
|
|
414
|
+
// Built back to front so each chain keeps the names' order.
|
|
415
|
+
for &i in group.iter().rev() {
|
|
416
|
+
let b = names[i as usize].as_bytes()[at] as usize;
|
|
417
|
+
next[i as usize] = first[b];
|
|
418
|
+
first[b] = i + 1;
|
|
419
|
+
}
|
|
420
|
+
ByLength::Table { at, first }
|
|
421
|
+
}
|
|
422
|
+
})
|
|
423
|
+
.collect();
|
|
424
|
+
NameMap { names: names.into(), by_length, long: long.into(), next: next.into() }
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
#[inline]
|
|
428
|
+
fn find(&self, name: &str) -> Option<usize> {
|
|
429
|
+
let b = name.as_bytes();
|
|
430
|
+
let Some(entry) = self.by_length.get(b.len()) else {
|
|
431
|
+
return self.long.iter().map(|&i| i as usize).find(|&i| str_eq(&self.names[i], name));
|
|
432
|
+
};
|
|
433
|
+
match entry {
|
|
434
|
+
ByLength::None => None,
|
|
435
|
+
ByLength::Words(words) => {
|
|
436
|
+
let w = name_word(b);
|
|
437
|
+
words.iter().find(|(k, _)| *k == w).map(|&(_, i)| i as usize)
|
|
438
|
+
}
|
|
439
|
+
ByLength::Few(few) => few.iter().map(|&i| i as usize).find(|&i| str_eq(&self.names[i], name)),
|
|
440
|
+
ByLength::Table { at, first } => {
|
|
441
|
+
let mut c = first[b[*at] as usize];
|
|
442
|
+
while c != 0 {
|
|
443
|
+
let i = c as usize - 1;
|
|
444
|
+
if str_eq(&self.names[i], name) {
|
|
445
|
+
return Some(i);
|
|
446
|
+
}
|
|
447
|
+
c = self.next[i];
|
|
448
|
+
}
|
|
449
|
+
None
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/// Declared property names to their index.
|
|
456
|
+
struct Names {
|
|
457
|
+
/// Bit `n` set: some name has length `n` (lengths of 63 and more share bit 63). A name whose length is not in the
|
|
458
|
+
/// set is not declared, which settles most misses without a search.
|
|
459
|
+
lengths: u64,
|
|
460
|
+
map: NameMap,
|
|
461
|
+
/// For a hint `h` (the index after the previous match), the name after that match in sorted order (entry 0: the
|
|
462
|
+
/// first name in sorted order); `u32::MAX` after the last.
|
|
463
|
+
sorted_next: Box<[u32]>,
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
#[inline(always)]
|
|
467
|
+
fn length_bit(len: usize) -> u64 {
|
|
468
|
+
1 << len.min(63)
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
impl Names {
|
|
472
|
+
fn new(names: Vec<Box<str>>) -> Names {
|
|
473
|
+
let lengths = names.iter().fold(0, |m, n| m | length_bit(n.len()));
|
|
474
|
+
let mut order: Vec<u32> = (0..names.len() as u32).collect();
|
|
475
|
+
order.sort_by(|&a, &b| names[a as usize].cmp(&names[b as usize]));
|
|
476
|
+
let mut sorted_next = vec![u32::MAX; names.len() + 1];
|
|
477
|
+
sorted_next[0] = order.first().copied().unwrap_or(u32::MAX);
|
|
478
|
+
for pair in order.windows(2) {
|
|
479
|
+
sorted_next[pair[0] as usize + 1] = pair[1];
|
|
480
|
+
}
|
|
481
|
+
Names { lengths, map: NameMap::new(names), sorted_next: sorted_next.into() }
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
fn find(&self, name: &str) -> Option<usize> {
|
|
485
|
+
self.find_from(name, &mut 0)
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/// The index of a name, without the ordering hint.
|
|
489
|
+
#[inline]
|
|
490
|
+
fn contains_at(&self, name: &str) -> Option<usize> {
|
|
491
|
+
if self.lengths & length_bit(name.len()) == 0 {
|
|
492
|
+
return None;
|
|
493
|
+
}
|
|
494
|
+
self.map.find(name)
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/// Membership only (for string enums: no order to hint at).
|
|
498
|
+
#[inline]
|
|
499
|
+
fn contains(&self, name: &str) -> bool {
|
|
500
|
+
if self.lengths & length_bit(name.len()) == 0 {
|
|
501
|
+
return false;
|
|
502
|
+
}
|
|
503
|
+
self.map.find(name).is_some()
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/// Finds a name, trying the one after the previous match first: instances tend to list their properties in the
|
|
507
|
+
/// schema's order, so the next name is usually the next one declared; failing that, the next name in sorted order
|
|
508
|
+
/// (instances written by tools that sort their keys).
|
|
509
|
+
#[inline(always)]
|
|
510
|
+
fn find_from(&self, name: &str, hint: &mut usize) -> Option<usize> {
|
|
511
|
+
if self.lengths & length_bit(name.len()) == 0 {
|
|
512
|
+
return None;
|
|
513
|
+
}
|
|
514
|
+
if let Some(expected) = self.map.names.get(*hint)
|
|
515
|
+
&& str_eq(expected, name)
|
|
516
|
+
{
|
|
517
|
+
*hint += 1;
|
|
518
|
+
return Some(*hint - 1);
|
|
519
|
+
}
|
|
520
|
+
if let Some(&next) = self.sorted_next.get(*hint)
|
|
521
|
+
&& let Some(expected) = self.map.names.get(next as usize)
|
|
522
|
+
&& str_eq(expected, name)
|
|
523
|
+
{
|
|
524
|
+
*hint = next as usize + 1;
|
|
525
|
+
return Some(next as usize);
|
|
526
|
+
}
|
|
527
|
+
// A few names are compared in turn (inline: lengths settle most), more are searched.
|
|
528
|
+
let i = if self.map.names.len() <= LOOKUP_NAMES {
|
|
529
|
+
self.map.names.iter().position(|n| str_eq(n, name))?
|
|
530
|
+
} else {
|
|
531
|
+
self.map.find(name)?
|
|
532
|
+
};
|
|
533
|
+
*hint = i + 1;
|
|
534
|
+
Some(i)
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
// ---------------------------------------------------------------------------------------------------------------------
|
|
539
|
+
// Compilation
|
|
540
|
+
|
|
541
|
+
#[inline(always)]
|
|
542
|
+
fn type_ok<'x, I: Instance<'x>>(mask: u8, x: I) -> bool {
|
|
543
|
+
// A kind's discriminant is its type bit.
|
|
544
|
+
let bit = x.kind() as u8;
|
|
545
|
+
if mask & bit != 0 {
|
|
546
|
+
return true;
|
|
547
|
+
}
|
|
548
|
+
// A number that is not accepted as a number may still be an integer.
|
|
549
|
+
bit == type_mask::NUMBER && mask & type_mask::INTEGER != 0 && is_integer_value(x)
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
/// Whether a number is an integer (out of line: the type test that calls it stays small enough to inline).
|
|
553
|
+
#[inline(never)]
|
|
554
|
+
fn is_integer_value<'x, I: Instance<'x>>(x: I) -> bool {
|
|
555
|
+
matches!(x.view(), View::Number(n) if super::is_integer(&n))
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
pub(crate) fn compile_plans(p: &Program) -> Vec<Plan> {
|
|
559
|
+
let nodes = &p.nodes;
|
|
560
|
+
let target = |id: NodeId| p.fast_target[id as usize];
|
|
561
|
+
let mut plans: Vec<Plan> = nodes.iter().enumerate().map(|(id, n)| plan_node(p, id as NodeId, n, &target)).collect();
|
|
562
|
+
// Hoist the children's type checks now that every plan is known.
|
|
563
|
+
let summary: Vec<(u8, Shape)> = plans.iter().map(|pl| (pl.types, shape_of(pl, p.uses_dynamic_scope))).collect();
|
|
564
|
+
let resolved = |id: NodeId| {
|
|
565
|
+
let (types, shape) = summary[id as usize];
|
|
566
|
+
// Not `Object`: a node may still take a fused plan below.
|
|
567
|
+
Child { id, types, shape: if shape == Shape::Object { Shape::General } else { shape } }
|
|
568
|
+
};
|
|
569
|
+
// Fused object plans, for nodes whose object semantics span in-place applicators.
|
|
570
|
+
// A fused plan applies its contributors' keywords without entering them as nodes, so the dynamic scope below it
|
|
571
|
+
// would differ from the general path's where a contributor is in another resource: nodes that can reach a live
|
|
572
|
+
// dynamic reference fuse only contributors in their own resource (which the general path would not push again).
|
|
573
|
+
let reaches_dynamic = reaches_dynamic_reference(p);
|
|
574
|
+
for (id, plan) in plans.iter_mut().enumerate() {
|
|
575
|
+
if let Some(f) = fused::try_fuse(p, id as NodeId, reaches_dynamic[id], &resolved) {
|
|
576
|
+
let body = plan.body.get_or_insert_with(|| Box::new(Body { node: id as NodeId, ..Body::default() }));
|
|
577
|
+
body.fused = Some(Box::new(f));
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
let fused_nodes: Vec<bool> = plans.iter().map(|pl| pl.body.as_ref().is_some_and(|b| b.fused.is_some())).collect();
|
|
581
|
+
let fix = |c: &mut Child| {
|
|
582
|
+
if c.id == u32::MAX {
|
|
583
|
+
return;
|
|
584
|
+
}
|
|
585
|
+
let (types, shape) = summary[c.id as usize];
|
|
586
|
+
c.types = types;
|
|
587
|
+
c.shape = if shape == Shape::Object && fused_nodes[c.id as usize] { Shape::General } else { shape };
|
|
588
|
+
};
|
|
589
|
+
for body in plans.iter_mut().filter_map(|pl| pl.body.as_deref_mut()) {
|
|
590
|
+
if let Some(o) = &mut body.object {
|
|
591
|
+
o.children.iter_mut().for_each(fix);
|
|
592
|
+
o.patterns.iter_mut().for_each(|(_, c)| fix(c));
|
|
593
|
+
o.additional.iter_mut().for_each(fix);
|
|
594
|
+
}
|
|
595
|
+
if let Some(a) = &mut body.array {
|
|
596
|
+
a.prefix.iter_mut().for_each(fix);
|
|
597
|
+
a.items.iter_mut().for_each(fix);
|
|
598
|
+
let items = a.items.map_or(Some(ANY), |c| c.trivial().then_some(c.types));
|
|
599
|
+
a.simple = items.filter(|_| a.prefix.is_empty() && a.contains.is_none() && !a.unique);
|
|
600
|
+
}
|
|
601
|
+
if let Some((_, c)) = &mut body.unevaluated_items {
|
|
602
|
+
fix(c);
|
|
603
|
+
}
|
|
604
|
+
for op in body.apply.iter_mut() {
|
|
605
|
+
match op {
|
|
606
|
+
Op::AllOf(list) => list.iter_mut().for_each(fix),
|
|
607
|
+
Op::AnyOf(b) | Op::OneOf(b) => {
|
|
608
|
+
b.children.iter_mut().for_each(fix);
|
|
609
|
+
b.dispatch();
|
|
610
|
+
}
|
|
611
|
+
_ => {}
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
// Arrays whose items are simple arrays check them inline, without entering each one.
|
|
616
|
+
let simple: Vec<Option<SimpleArray>> = plans
|
|
617
|
+
.iter()
|
|
618
|
+
.map(|pl| {
|
|
619
|
+
let b = pl.body.as_deref()?;
|
|
620
|
+
let a = b.array.as_ref()?;
|
|
621
|
+
let types = a.simple?;
|
|
622
|
+
(shape_of(pl, p.uses_dynamic_scope) == Shape::Array).then_some(SimpleArray {
|
|
623
|
+
min: a.min,
|
|
624
|
+
max: a.max,
|
|
625
|
+
types,
|
|
626
|
+
})
|
|
627
|
+
})
|
|
628
|
+
.collect();
|
|
629
|
+
for a in plans.iter_mut().filter_map(|pl| pl.body.as_deref_mut()?.array.as_mut()) {
|
|
630
|
+
a.nested = a.items.filter(|c| c.shape == Shape::Array).and_then(|c| simple[c.id as usize]);
|
|
631
|
+
}
|
|
632
|
+
for pl in plans.iter_mut() {
|
|
633
|
+
pl.shape = shape_of(pl, p.uses_dynamic_scope);
|
|
634
|
+
}
|
|
635
|
+
plans
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
fn plan_node(p: &Program, id: NodeId, n: &SchemaNode, target: &dyn Fn(NodeId) -> NodeId) -> Plan {
|
|
639
|
+
let guard = n.in_place_cycle;
|
|
640
|
+
if n.always_true {
|
|
641
|
+
return Plan { types: ANY, guard, body: None, shape: Shape::General };
|
|
642
|
+
}
|
|
643
|
+
if n.always_false {
|
|
644
|
+
return Plan { types: 0, guard, body: None, shape: Shape::General };
|
|
645
|
+
}
|
|
646
|
+
let child = |id: NodeId| Child { id: target(id), types: ANY, shape: Shape::General };
|
|
647
|
+
let mut ops = Vec::new();
|
|
648
|
+
let mut number = Vec::new();
|
|
649
|
+
let mut string = Vec::new();
|
|
650
|
+
|
|
651
|
+
if let Some(c) = &n.const_value {
|
|
652
|
+
ops.push(Op::Const(c.clone()));
|
|
653
|
+
}
|
|
654
|
+
if let Some(values) = &n.enum_values {
|
|
655
|
+
if values.iter().all(Value::is_string) {
|
|
656
|
+
ops.push(Op::EnumStrings(Names::new(values.iter().map(|v| v.as_str().unwrap().into()).collect())));
|
|
657
|
+
} else {
|
|
658
|
+
ops.push(Op::Enum(values.clone().into_boxed_slice()));
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
let format_check = |numeric: bool| -> Option<FormatCheck> {
|
|
663
|
+
if !n.assert_format || n.format_kind.is_numeric() != numeric {
|
|
664
|
+
return None;
|
|
665
|
+
}
|
|
666
|
+
let f = n.format.as_ref()?;
|
|
667
|
+
match p.formats.get(f) {
|
|
668
|
+
Some(custom) => Some(FormatCheck::Custom(custom.clone())),
|
|
669
|
+
None if n.format_kind == FormatKind::Unknown => None,
|
|
670
|
+
None => Some(FormatCheck::Builtin(n.format_kind, n.dialect <= Dialect::Draft6)),
|
|
671
|
+
}
|
|
672
|
+
};
|
|
673
|
+
|
|
674
|
+
// Numbers.
|
|
675
|
+
if let Some(f) = format_check(true) {
|
|
676
|
+
number.push(NumberOp::Format(f));
|
|
677
|
+
}
|
|
678
|
+
if let Some(b) = &n.minimum {
|
|
679
|
+
number.push(NumberOp::Minimum(Num::of(b)));
|
|
680
|
+
}
|
|
681
|
+
if let Some(b) = &n.maximum {
|
|
682
|
+
number.push(NumberOp::Maximum(Num::of(b)));
|
|
683
|
+
}
|
|
684
|
+
if let Some(b) = &n.exclusive_minimum {
|
|
685
|
+
number.push(NumberOp::ExclusiveMinimum(Num::of(b)));
|
|
686
|
+
}
|
|
687
|
+
if let Some(b) = &n.exclusive_maximum {
|
|
688
|
+
number.push(NumberOp::ExclusiveMaximum(Num::of(b)));
|
|
689
|
+
}
|
|
690
|
+
if let Some(d) = &n.multiple_of {
|
|
691
|
+
number.push(NumberOp::MultipleOf(Divisor::new(d)));
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
// Strings.
|
|
695
|
+
if n.min_length.is_some() || n.max_length.is_some() {
|
|
696
|
+
string.push(StringOp::Length { min: n.min_length.unwrap_or(0), max: n.max_length.unwrap_or(u64::MAX) });
|
|
697
|
+
}
|
|
698
|
+
if let Some(pattern) = &n.pattern {
|
|
699
|
+
string.push(StringOp::Pattern(pattern.clone()));
|
|
700
|
+
}
|
|
701
|
+
if let Some(f) = format_check(false) {
|
|
702
|
+
string.push(StringOp::Format(f));
|
|
703
|
+
}
|
|
704
|
+
if n.assert_content {
|
|
705
|
+
string.push(StringOp::Content(n.content));
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
let values = std::mem::take(&mut ops);
|
|
709
|
+
|
|
710
|
+
// Objects (unless the type excludes objects: then the keywords apply to nothing and must not cost the node its
|
|
711
|
+
// shape, as C#'s LiveObjectKeywords).
|
|
712
|
+
let own_types = if n.has_type { n.type_mask } else { ANY };
|
|
713
|
+
let mut object = None;
|
|
714
|
+
if n.has_object_keywords() && own_types & type_mask::OBJECT != 0 {
|
|
715
|
+
let declared: Vec<(String, NodeId)> = n.properties.clone().unwrap_or_default();
|
|
716
|
+
let required = n.required.clone().unwrap_or_default();
|
|
717
|
+
// Names only required or dependencies mention join the declared ones, up to 64 names in all (one mask word).
|
|
718
|
+
let mut known: Vec<String> = declared.iter().map(|(k, _)| k.clone()).collect();
|
|
719
|
+
let mut extras: Vec<String> = Vec::new();
|
|
720
|
+
let dependency_names =
|
|
721
|
+
n.dependencies.iter().flatten().flat_map(|d| std::iter::once(&d.name).chain(d.required.iter().flatten()));
|
|
722
|
+
for name in required.iter().chain(dependency_names) {
|
|
723
|
+
if !known.contains(name) && !extras.contains(name) {
|
|
724
|
+
extras.push(name.clone());
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
let with_extras = known.len() + extras.len() <= 64;
|
|
728
|
+
if with_extras {
|
|
729
|
+
known.extend(extras);
|
|
730
|
+
}
|
|
731
|
+
let names = Names::new(known.iter().map(|k| k.as_str().into()).collect());
|
|
732
|
+
let undeclared = n.additional_properties.map_or(NO_CHILD, child);
|
|
733
|
+
let children: Box<[Child]> = declared
|
|
734
|
+
.iter()
|
|
735
|
+
.map(|&(_, c)| child(c))
|
|
736
|
+
.chain(std::iter::repeat_n(undeclared, known.len() - declared.len()))
|
|
737
|
+
.collect();
|
|
738
|
+
let has_names = !known.is_empty();
|
|
739
|
+
let visit = if n.property_names.is_none()
|
|
740
|
+
&& !has_names
|
|
741
|
+
&& n.pattern_properties.as_ref().is_some_and(|p| p.len() == 1)
|
|
742
|
+
{
|
|
743
|
+
Visit::Pattern
|
|
744
|
+
} else if n.pattern_properties.is_some() || n.property_names.is_some() {
|
|
745
|
+
Visit::General
|
|
746
|
+
} else if has_names {
|
|
747
|
+
Visit::Names
|
|
748
|
+
} else if n.additional_properties.is_some() {
|
|
749
|
+
Visit::Values
|
|
750
|
+
} else {
|
|
751
|
+
Visit::None
|
|
752
|
+
};
|
|
753
|
+
let visited = matches!(visit, Visit::Names | Visit::General) && known.len() <= 64;
|
|
754
|
+
let bit = |name: &str| names.find(name).filter(|_| visited).map(|i| 1u64 << i);
|
|
755
|
+
let mut required_mask = 0u64;
|
|
756
|
+
let mut by_lookup = Vec::new();
|
|
757
|
+
for r in &required {
|
|
758
|
+
match bit(r) {
|
|
759
|
+
Some(b) => required_mask |= b,
|
|
760
|
+
None => by_lookup.push(r.as_str().into()),
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
let dependencies: Box<[Dependency]> = n
|
|
764
|
+
.dependencies
|
|
765
|
+
.iter()
|
|
766
|
+
.flatten()
|
|
767
|
+
.map(|d| {
|
|
768
|
+
let required: Option<u64> =
|
|
769
|
+
d.required.iter().flatten().try_fold(0u64, |mask, r| bit(r).map(|b| mask | b));
|
|
770
|
+
Dependency {
|
|
771
|
+
name: d.name.as_str().into(),
|
|
772
|
+
required: d.required.iter().flatten().map(|r| r.as_str().into()).collect(),
|
|
773
|
+
schema: d.schema.map(target),
|
|
774
|
+
bits: bit(&d.name).zip(required),
|
|
775
|
+
}
|
|
776
|
+
})
|
|
777
|
+
.collect();
|
|
778
|
+
let by_lookup_empty = by_lookup.is_empty();
|
|
779
|
+
object = Some(ObjectPlan {
|
|
780
|
+
min: n.min_properties.unwrap_or(0),
|
|
781
|
+
max: n.max_properties.unwrap_or(u64::MAX),
|
|
782
|
+
visit,
|
|
783
|
+
names,
|
|
784
|
+
declared: declared.len(),
|
|
785
|
+
children,
|
|
786
|
+
required_mask,
|
|
787
|
+
required: by_lookup.into_boxed_slice(),
|
|
788
|
+
patterns: n.pattern_properties.iter().flatten().map(|pp| (pp.pattern.clone(), child(pp.node))).collect(),
|
|
789
|
+
name_patterns: known
|
|
790
|
+
.iter()
|
|
791
|
+
.map(|name| {
|
|
792
|
+
let patterns = n.pattern_properties.iter().flatten().enumerate();
|
|
793
|
+
patterns.filter(|(_, pp)| pp.pattern.is_match(name)).map(|(j, _)| j as u16).collect()
|
|
794
|
+
})
|
|
795
|
+
.collect(),
|
|
796
|
+
additional: n.additional_properties.map(child),
|
|
797
|
+
property_names: n.property_names.map(target),
|
|
798
|
+
dependencies,
|
|
799
|
+
rest_free: by_lookup_empty && n.dependencies.is_none(),
|
|
800
|
+
strict: visit == Visit::Names && by_lookup_empty && n.dependencies.is_none(),
|
|
801
|
+
lookup: visit == Visit::Names && n.additional_properties.is_none() && known.len() <= LOOKUP_NAMES,
|
|
802
|
+
});
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
// Arrays.
|
|
806
|
+
let mut array = None;
|
|
807
|
+
if n.has_array_keywords() && own_types & type_mask::ARRAY != 0 {
|
|
808
|
+
array = Some(ArrayPlan {
|
|
809
|
+
min: n.min_items.unwrap_or(0),
|
|
810
|
+
max: n.max_items.unwrap_or(u64::MAX),
|
|
811
|
+
prefix: n.prefix_items.iter().flatten().map(|&c| child(c)).collect(),
|
|
812
|
+
items: n.items.map(child),
|
|
813
|
+
contains: n.contains.map(|c| (target(c), n.min_contains, n.max_contains)),
|
|
814
|
+
unique: n.unique_items,
|
|
815
|
+
simple: None,
|
|
816
|
+
nested: None,
|
|
817
|
+
});
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
// In-place applicators, in the general evaluator's order.
|
|
821
|
+
if let Some(r) = n.ref_ {
|
|
822
|
+
ops.push(Op::Ref(target(r)));
|
|
823
|
+
}
|
|
824
|
+
if let Some(r) = n.static_dynamic_ref {
|
|
825
|
+
ops.push(Op::Ref(target(r)));
|
|
826
|
+
}
|
|
827
|
+
if let Some(d) = &n.dynamic_ref {
|
|
828
|
+
if p.uses_dynamic_scope {
|
|
829
|
+
ops.push(Op::DynamicRef(d.clone()));
|
|
830
|
+
} else {
|
|
831
|
+
// Without a dynamic scope the reference always takes its fallback.
|
|
832
|
+
ops.push(Op::Ref(target(d.fallback)));
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
if let Some(list) = &n.all_of {
|
|
836
|
+
ops.push(Op::AllOf(list.iter().map(|&c| child(c)).collect()));
|
|
837
|
+
}
|
|
838
|
+
// An anyOf of type-only branches, or a oneOf of type-only branches with no type in common, is one type test
|
|
839
|
+
// (the C# evaluator's TypeUnion plan): it narrows the node's own types instead of adding a keyword.
|
|
840
|
+
let mut union = ANY;
|
|
841
|
+
if let Some(list) = &n.any_of {
|
|
842
|
+
match type_union(p, list, false) {
|
|
843
|
+
Some(mask) => union = meet(union, mask),
|
|
844
|
+
None => ops.push(Op::AnyOf(Box::new(Branches::new(
|
|
845
|
+
list.iter().map(|&c| child(c)).collect(),
|
|
846
|
+
n.any_of_discriminator.clone(),
|
|
847
|
+
)))),
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
if let Some(list) = &n.one_of {
|
|
851
|
+
match type_union(p, list, true) {
|
|
852
|
+
Some(mask) => union = meet(union, mask),
|
|
853
|
+
None => ops.push(Op::OneOf(Box::new(Branches::new(
|
|
854
|
+
list.iter().map(|&c| child(c)).collect(),
|
|
855
|
+
n.one_of_discriminator.clone(),
|
|
856
|
+
)))),
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
if let Some(not) = n.not {
|
|
860
|
+
ops.push(Op::Not(target(not)));
|
|
861
|
+
}
|
|
862
|
+
if let Some(cond) = n.if_ {
|
|
863
|
+
let (then, else_) = (n.then.map(target), n.else_.map(target));
|
|
864
|
+
if then.is_some() || else_.is_some() {
|
|
865
|
+
ops.push(Op::If { cond: target(cond), then, else_ });
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
// unevaluatedProperties is left to the general evaluator (or a fused object plan); unevaluatedItems takes the
|
|
870
|
+
// items after a static prefix when every contribution to the evaluated items is unconditional.
|
|
871
|
+
let mut general = 0;
|
|
872
|
+
if n.unevaluated_properties.is_some() {
|
|
873
|
+
general |= type_mask::OBJECT;
|
|
874
|
+
}
|
|
875
|
+
let mut unevaluated_items = None;
|
|
876
|
+
if let Some(u) = n.unevaluated_items {
|
|
877
|
+
match static_item_coverage(p, id) {
|
|
878
|
+
Some(Coverage::All) => {}
|
|
879
|
+
Some(Coverage::From(from)) => unevaluated_items = Some((from, child(u))),
|
|
880
|
+
None => general |= type_mask::ARRAY,
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
let types = meet(if n.has_type { n.type_mask } else { ANY }, union);
|
|
885
|
+
if values.is_empty()
|
|
886
|
+
&& number.is_empty()
|
|
887
|
+
&& string.is_empty()
|
|
888
|
+
&& object.is_none()
|
|
889
|
+
&& array.is_none()
|
|
890
|
+
&& ops.is_empty()
|
|
891
|
+
&& general == 0
|
|
892
|
+
&& unevaluated_items.is_none()
|
|
893
|
+
{
|
|
894
|
+
return Plan { types, guard, body: None, shape: Shape::General };
|
|
895
|
+
}
|
|
896
|
+
let body = Body {
|
|
897
|
+
fused: None,
|
|
898
|
+
general,
|
|
899
|
+
node: id,
|
|
900
|
+
unevaluated_items,
|
|
901
|
+
values: values.into_boxed_slice(),
|
|
902
|
+
number: number.into_boxed_slice(),
|
|
903
|
+
string: string.into_boxed_slice(),
|
|
904
|
+
object,
|
|
905
|
+
array,
|
|
906
|
+
apply: ops.into_boxed_slice(),
|
|
907
|
+
};
|
|
908
|
+
Plan { types, guard, body: Some(Box::new(body)), shape: Shape::General }
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
/// How callers can enter a plan (see `Shape`). The shortcuts skip the scope push, so a program that keeps a dynamic
|
|
912
|
+
/// scope takes them only for leaves; a node on an in-place cycle is entered through its guard.
|
|
913
|
+
fn shape_of(pl: &Plan, dynamic_scope: bool) -> Shape {
|
|
914
|
+
if pl.guard {
|
|
915
|
+
return Shape::General;
|
|
916
|
+
}
|
|
917
|
+
let Some(b) = pl.body.as_deref() else { return Shape::Trivial };
|
|
918
|
+
let plain = b.fused.is_none() && b.general == 0 && b.unevaluated_items.is_none();
|
|
919
|
+
let values = !b.values.is_empty() || !b.number.is_empty() || !b.string.is_empty();
|
|
920
|
+
let (object, array, apply) = (b.object.is_some(), b.array.is_some(), !b.apply.is_empty());
|
|
921
|
+
match (plain, values, object, array, apply) {
|
|
922
|
+
(true, true, false, false, false)
|
|
923
|
+
if b.number.is_empty() && b.string.is_empty() && matches!(&*b.values, [Op::EnumStrings(_)]) =>
|
|
924
|
+
{
|
|
925
|
+
Shape::StringEnum
|
|
926
|
+
}
|
|
927
|
+
(true, true, false, false, false) if b.number.is_empty() && b.values.is_empty() => Shape::Strings,
|
|
928
|
+
(true, _, false, false, false) => Shape::Leaf,
|
|
929
|
+
(true, false, true, false, false) if !dynamic_scope => Shape::Object,
|
|
930
|
+
(true, false, false, true, false) if !dynamic_scope => Shape::Array,
|
|
931
|
+
(true, false, false, false, true) if !dynamic_scope => Shape::Apply,
|
|
932
|
+
_ => Shape::General,
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
/// Marks every node from which a live dynamic reference is reachable through any child.
|
|
937
|
+
fn reaches_dynamic_reference(p: &Program) -> Vec<bool> {
|
|
938
|
+
let mut reaches: Vec<bool> = p.nodes.iter().map(|n| p.uses_dynamic_scope && n.dynamic_ref.is_some()).collect();
|
|
939
|
+
if !p.uses_dynamic_scope {
|
|
940
|
+
return reaches;
|
|
941
|
+
}
|
|
942
|
+
let children: Vec<Vec<NodeId>> = p.nodes.iter().map(|n| n.children()).collect();
|
|
943
|
+
let mut changed = true;
|
|
944
|
+
while changed {
|
|
945
|
+
changed = false;
|
|
946
|
+
for (i, c) in children.iter().enumerate() {
|
|
947
|
+
if !reaches[i] && c.iter().any(|&c| reaches[c as usize]) {
|
|
948
|
+
reaches[i] = true;
|
|
949
|
+
changed = true;
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
reaches
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
/// A type mask with `integer` made explicit wherever `number` is (every integer is a number).
|
|
957
|
+
fn expand(mask: u8) -> u8 {
|
|
958
|
+
if mask & type_mask::NUMBER != 0 { mask | type_mask::INTEGER } else { mask }
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
/// The types both masks admit.
|
|
962
|
+
fn meet(a: u8, b: u8) -> u8 {
|
|
963
|
+
let m = expand(a) & expand(b);
|
|
964
|
+
// `number` in both keeps `number`; `integer` alone stays `integer`.
|
|
965
|
+
if a & b & type_mask::NUMBER == 0 && m & type_mask::NUMBER != 0 { m & !type_mask::NUMBER } else { m }
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
/// A schema that tests only the type (`true` admits everything, `false` nothing).
|
|
969
|
+
fn type_only_mask(n: &SchemaNode) -> Option<u8> {
|
|
970
|
+
if n.always_true {
|
|
971
|
+
return Some(ANY);
|
|
972
|
+
}
|
|
973
|
+
if n.always_false {
|
|
974
|
+
return Some(0);
|
|
975
|
+
}
|
|
976
|
+
let only_type = n.has_type
|
|
977
|
+
&& !n.in_place_cycle
|
|
978
|
+
&& n.const_value.is_none()
|
|
979
|
+
&& n.enum_values.is_none()
|
|
980
|
+
&& !n.has_number_keywords()
|
|
981
|
+
&& !n.has_string_keywords()
|
|
982
|
+
&& !n.has_object_keywords()
|
|
983
|
+
&& !n.has_array_keywords()
|
|
984
|
+
&& !n.has_in_place_applicators()
|
|
985
|
+
&& n.dynamic_ref.is_none();
|
|
986
|
+
only_type.then_some(n.type_mask)
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
/// The union of anyOf/oneOf branches that all test only the type; for oneOf, only when no two branches admit a
|
|
990
|
+
/// common value (so that "exactly one" is "any").
|
|
991
|
+
fn type_union(p: &Program, list: &[NodeId], exactly_one: bool) -> Option<u8> {
|
|
992
|
+
let masks: Vec<u8> =
|
|
993
|
+
list.iter().map(|&c| type_only_mask(&p.nodes[p.fast_target[c as usize] as usize])).collect::<Option<_>>()?;
|
|
994
|
+
if exactly_one {
|
|
995
|
+
for (i, a) in masks.iter().enumerate() {
|
|
996
|
+
if masks[i + 1..].iter().any(|b| expand(*a) & expand(*b) != 0) {
|
|
997
|
+
return None;
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
Some(masks.iter().fold(0, |u, m| u | m))
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
enum Coverage {
|
|
1005
|
+
All,
|
|
1006
|
+
From(usize),
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
/// The items a node's evaluation always marks evaluated, when that is static: the longest prefixItems of the node and
|
|
1010
|
+
/// the contributors it always applies ($ref and allOf chains), or all of them when one has items (or, below the node,
|
|
1011
|
+
/// unevaluatedItems). `None` when an in-place child that applies conditionally (anyOf, oneOf, if/then/else, a
|
|
1012
|
+
/// dependent schema, a dynamic reference) can mark items, or contains marks them.
|
|
1013
|
+
fn static_item_coverage(p: &Program, id: NodeId) -> Option<Coverage> {
|
|
1014
|
+
let mut prefix = 0;
|
|
1015
|
+
let mut all = false;
|
|
1016
|
+
let mut stack = vec![(id, true)];
|
|
1017
|
+
let mut visited = vec![id];
|
|
1018
|
+
while let Some((at, root)) = stack.pop() {
|
|
1019
|
+
let n = &p.nodes[at as usize];
|
|
1020
|
+
if n.always_true || n.always_false {
|
|
1021
|
+
continue;
|
|
1022
|
+
}
|
|
1023
|
+
if n.in_place_cycle || n.dynamic_ref.is_some() || (n.contains.is_some() && n.contains_marks_evaluated) {
|
|
1024
|
+
return None;
|
|
1025
|
+
}
|
|
1026
|
+
prefix = prefix.max(n.prefix_items.as_ref().map_or(0, Vec::len));
|
|
1027
|
+
all |= n.items.is_some() || (!root && n.unevaluated_items.is_some());
|
|
1028
|
+
let conditional: Vec<NodeId> = n
|
|
1029
|
+
.any_of
|
|
1030
|
+
.iter()
|
|
1031
|
+
.flatten()
|
|
1032
|
+
.chain(n.one_of.iter().flatten())
|
|
1033
|
+
.copied()
|
|
1034
|
+
.chain([n.if_, n.then, n.else_].into_iter().flatten())
|
|
1035
|
+
.chain(n.dependencies.iter().flatten().filter_map(|d| d.schema))
|
|
1036
|
+
.collect();
|
|
1037
|
+
for c in conditional {
|
|
1038
|
+
if p.nodes[c as usize].marks_items {
|
|
1039
|
+
return None;
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
for c in [n.ref_, n.static_dynamic_ref].into_iter().flatten().chain(n.all_of.iter().flatten().copied()) {
|
|
1043
|
+
if !visited.contains(&c) {
|
|
1044
|
+
visited.push(c);
|
|
1045
|
+
stack.push((c, false));
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
Some(if all { Coverage::All } else { Coverage::From(prefix) })
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
// ---------------------------------------------------------------------------------------------------------------------
|
|
1053
|
+
// Evaluation
|
|
1054
|
+
|
|
1055
|
+
impl Evaluator<'_, '_> {
|
|
1056
|
+
/// Evaluates a node's plan (at a new instance location, or where no depth guard applies).
|
|
1057
|
+
#[inline(always)]
|
|
1058
|
+
pub(super) fn run<'x, I: Instance<'x>>(&mut self, id: NodeId, x: I) -> bool {
|
|
1059
|
+
let plan = &self.p.plans[id as usize];
|
|
1060
|
+
if plan.types != ANY && !type_ok(plan.types, x) {
|
|
1061
|
+
return false;
|
|
1062
|
+
}
|
|
1063
|
+
match plan.body.as_deref() {
|
|
1064
|
+
None => true,
|
|
1065
|
+
Some(b) if plan.shape == Shape::General => self.run_body(b, x),
|
|
1066
|
+
Some(b) => self.enter(plan.shape, b, x),
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
/// A child at a new instance location: its type check inline, its other keywords (if any) by call.
|
|
1071
|
+
#[inline(always)]
|
|
1072
|
+
fn run_child<'x, I: Instance<'x>>(&mut self, c: Child, x: I) -> bool {
|
|
1073
|
+
if c.types != ANY && !type_ok(c.types, x) {
|
|
1074
|
+
return false;
|
|
1075
|
+
}
|
|
1076
|
+
if c.trivial() {
|
|
1077
|
+
return true;
|
|
1078
|
+
}
|
|
1079
|
+
match self.p.plans[c.id as usize].body.as_deref() {
|
|
1080
|
+
None => true,
|
|
1081
|
+
Some(b) => self.enter(c.shape, b, x),
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
/// A body entered by shape (its types already tested, and not on an in-place cycle unless `General`).
|
|
1086
|
+
#[inline(always)]
|
|
1087
|
+
fn enter<'x, I: Instance<'x>>(&mut self, shape: Shape, b: &Body, x: I) -> bool {
|
|
1088
|
+
match shape {
|
|
1089
|
+
Shape::Leaf => run_leaf(b, x),
|
|
1090
|
+
Shape::StringEnum => match (&b.values[0], x.view()) {
|
|
1091
|
+
(Op::EnumStrings(values), View::String(s)) => values.contains(s),
|
|
1092
|
+
_ => false,
|
|
1093
|
+
},
|
|
1094
|
+
Shape::Strings => match x.view() {
|
|
1095
|
+
View::String(s) => run_string(&b.string, s),
|
|
1096
|
+
_ => true,
|
|
1097
|
+
},
|
|
1098
|
+
Shape::Object => match x.view() {
|
|
1099
|
+
View::Object(o) => {
|
|
1100
|
+
let plan = b.object.as_ref().unwrap();
|
|
1101
|
+
if plan.strict { self.run_strict_object::<I>(plan, o) } else { self.run_object(plan, o, x) }
|
|
1102
|
+
}
|
|
1103
|
+
_ => true,
|
|
1104
|
+
},
|
|
1105
|
+
Shape::Array => match x.view() {
|
|
1106
|
+
View::Array(a) => self.run_array::<I>(b.array.as_ref().unwrap(), a),
|
|
1107
|
+
_ => true,
|
|
1108
|
+
},
|
|
1109
|
+
Shape::Apply => self.run_apply(&b.apply, x),
|
|
1110
|
+
Shape::Trivial | Shape::General => self.run_body(b, x),
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
/// Evaluates an in-place child under the depth guard.
|
|
1115
|
+
#[inline]
|
|
1116
|
+
fn run_in_place<'x, I: Instance<'x>>(&mut self, id: NodeId, x: I) -> bool {
|
|
1117
|
+
if !self.p.plans[id as usize].guard {
|
|
1118
|
+
return self.run(id, x);
|
|
1119
|
+
}
|
|
1120
|
+
self.depth += 1;
|
|
1121
|
+
if self.depth > self.p.max_depth {
|
|
1122
|
+
self.depth_exceeded = true;
|
|
1123
|
+
self.depth -= 1;
|
|
1124
|
+
return false;
|
|
1125
|
+
}
|
|
1126
|
+
let ok = self.run(id, x);
|
|
1127
|
+
self.depth -= 1;
|
|
1128
|
+
ok
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
/// Evaluates a property name as a string instance, in a buffer reused across names.
|
|
1132
|
+
fn run_name(&mut self, id: NodeId, name: &str) -> bool {
|
|
1133
|
+
// A name is a string: a plan with nothing beyond its types is decided without building the value.
|
|
1134
|
+
let plan = &self.p.plans[id as usize];
|
|
1135
|
+
if plan.body.is_none() {
|
|
1136
|
+
return plan.types & type_mask::STRING != 0;
|
|
1137
|
+
}
|
|
1138
|
+
let mut s = std::mem::take(&mut self.name_buffer);
|
|
1139
|
+
s.clear();
|
|
1140
|
+
s.push_str(name);
|
|
1141
|
+
let buffer = Value::String(s);
|
|
1142
|
+
let ok = self.run::<&Value>(id, &buffer);
|
|
1143
|
+
if let Value::String(s) = buffer {
|
|
1144
|
+
self.name_buffer = s;
|
|
1145
|
+
}
|
|
1146
|
+
ok
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
/// An in-place child with its type check inline, then its keywords under the depth guard (without testing the
|
|
1150
|
+
/// type again).
|
|
1151
|
+
#[inline(always)]
|
|
1152
|
+
fn run_branch<'x, I: Instance<'x>>(&mut self, c: Child, x: I) -> bool {
|
|
1153
|
+
if c.types != ANY && !type_ok(c.types, x) {
|
|
1154
|
+
return false;
|
|
1155
|
+
}
|
|
1156
|
+
if c.trivial() {
|
|
1157
|
+
return true;
|
|
1158
|
+
}
|
|
1159
|
+
let plan = &self.p.plans[c.id as usize];
|
|
1160
|
+
let Some(b) = plan.body.as_deref() else { return self.run_in_place(c.id, x) };
|
|
1161
|
+
if plan.guard {
|
|
1162
|
+
return self.run_in_place(c.id, x);
|
|
1163
|
+
}
|
|
1164
|
+
self.enter(c.shape, b, x)
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1167
|
+
/// The anyOf/oneOf branches that can match: those a discriminator selects, or those admitting the instance type.
|
|
1168
|
+
#[inline(always)]
|
|
1169
|
+
fn candidates<'b, 'x, I: Instance<'x>>(&self, b: &'b Branches, x: I) -> &'b [u32] {
|
|
1170
|
+
let Some(disc) = b.discriminator.as_deref() else { return &b.by_kind[kind(x)] };
|
|
1171
|
+
let View::Object(o) = x.view() else { return &b.by_kind[kind(x)] };
|
|
1172
|
+
let (d, index) = disc;
|
|
1173
|
+
match o.get(&d.property) {
|
|
1174
|
+
Some(v) => index.select(d, v),
|
|
1175
|
+
None if d.all_require => &[],
|
|
1176
|
+
None => &b.by_kind[kind(x)],
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
|
|
1180
|
+
/// A node's keywords. Where the program keeps a dynamic scope, entering a node of another resource pushes that
|
|
1181
|
+
/// resource (as the general evaluator does), for the dynamic references below it.
|
|
1182
|
+
#[inline]
|
|
1183
|
+
fn run_body<'x, I: Instance<'x>>(&mut self, b: &Body, x: I) -> bool {
|
|
1184
|
+
if !self.p.uses_dynamic_scope {
|
|
1185
|
+
return self.run_keywords(b, x);
|
|
1186
|
+
}
|
|
1187
|
+
let resource = self.p.nodes[b.node as usize].resource_id;
|
|
1188
|
+
let pushed = self.scope.last() != Some(&resource);
|
|
1189
|
+
if pushed {
|
|
1190
|
+
self.scope.push(resource);
|
|
1191
|
+
}
|
|
1192
|
+
let ok = self.run_keywords(b, x);
|
|
1193
|
+
if pushed {
|
|
1194
|
+
self.scope.pop();
|
|
1195
|
+
}
|
|
1196
|
+
ok
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
fn run_keywords<'x, I: Instance<'x>>(&mut self, b: &Body, x: I) -> bool {
|
|
1200
|
+
let view = x.view();
|
|
1201
|
+
match view {
|
|
1202
|
+
View::Object(o) => {
|
|
1203
|
+
if let Some(f) = &b.fused {
|
|
1204
|
+
return self.run_fused::<I>(f, o);
|
|
1205
|
+
}
|
|
1206
|
+
if b.general & type_mask::OBJECT != 0 {
|
|
1207
|
+
return self.eval_node::<Fast, I>(b.node, x, None);
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
View::Array(_) if b.general & type_mask::ARRAY != 0 => return self.eval_node::<Fast, I>(b.node, x, None),
|
|
1211
|
+
_ => {}
|
|
1212
|
+
}
|
|
1213
|
+
if !b.values.is_empty() {
|
|
1214
|
+
for op in b.values.iter() {
|
|
1215
|
+
if !self.run_op(op, x) {
|
|
1216
|
+
return false;
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
}
|
|
1220
|
+
let ok = match view {
|
|
1221
|
+
View::Number(n) => b.number.is_empty() || run_number(&b.number, &n),
|
|
1222
|
+
View::String(s) => b.string.is_empty() || run_string(&b.string, s),
|
|
1223
|
+
View::Object(o) => b.object.as_ref().is_none_or(|plan| self.run_object(plan, o, x)),
|
|
1224
|
+
View::Array(a) => {
|
|
1225
|
+
b.array.as_ref().is_none_or(|plan| self.run_array::<I>(plan, a))
|
|
1226
|
+
&& b.unevaluated_items.is_none_or(|(from, c)| a.tail(from).all(|item| self.run_child(c, item)))
|
|
1227
|
+
}
|
|
1228
|
+
_ => true,
|
|
1229
|
+
};
|
|
1230
|
+
ok && (b.apply.is_empty() || self.run_apply(&b.apply, x))
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
fn run_apply<'x, I: Instance<'x>>(&mut self, ops: &[Op], x: I) -> bool {
|
|
1234
|
+
for op in ops {
|
|
1235
|
+
if !self.run_op(op, x) {
|
|
1236
|
+
return false;
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
true
|
|
1240
|
+
}
|
|
1241
|
+
|
|
1242
|
+
#[inline]
|
|
1243
|
+
fn run_op<'x, I: Instance<'x>>(&mut self, op: &Op, x: I) -> bool {
|
|
1244
|
+
match op {
|
|
1245
|
+
Op::Const(c) => json_equal(x, c),
|
|
1246
|
+
Op::EnumStrings(values) => match x.view() {
|
|
1247
|
+
View::String(s) => values.contains(s),
|
|
1248
|
+
_ => false,
|
|
1249
|
+
},
|
|
1250
|
+
Op::Enum(values) => values.iter().any(|v| json_equal(x, v)),
|
|
1251
|
+
Op::Ref(r) => self.run_in_place(*r, x),
|
|
1252
|
+
Op::AllOf(list) => list.iter().all(|&c| self.run_branch(c, x)),
|
|
1253
|
+
Op::AnyOf(b) => self.candidates(b, x).iter().any(|&i| self.run_branch(b.children[i as usize], x)),
|
|
1254
|
+
Op::OneOf(b) => {
|
|
1255
|
+
let candidates = self.candidates(b, x);
|
|
1256
|
+
// The instance's type (or the discriminator) leaves one branch: that branch decides.
|
|
1257
|
+
if let [only] = candidates {
|
|
1258
|
+
return self.run_branch(b.children[*only as usize], x);
|
|
1259
|
+
}
|
|
1260
|
+
let mut matched = 0;
|
|
1261
|
+
for &i in candidates {
|
|
1262
|
+
if self.run_branch(b.children[i as usize], x) {
|
|
1263
|
+
matched += 1;
|
|
1264
|
+
if matched > 1 {
|
|
1265
|
+
break;
|
|
1266
|
+
}
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
matched == 1
|
|
1270
|
+
}
|
|
1271
|
+
Op::Not(c) => !self.run(*c, x),
|
|
1272
|
+
Op::DynamicRef(d) => {
|
|
1273
|
+
let target = self.p.fast_target[self.resolve_dynamic(d) as usize];
|
|
1274
|
+
self.run_in_place(target, x)
|
|
1275
|
+
}
|
|
1276
|
+
Op::If { cond, then, else_ } => {
|
|
1277
|
+
let next = if self.run_in_place(*cond, x) { then } else { else_ };
|
|
1278
|
+
next.is_none_or(|c| self.run_in_place(c, x))
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
/// An object plan: the size bounds, the property loop for its shape (each in its own function, so that this entry
|
|
1284
|
+
/// stays small), then the required names and dependencies.
|
|
1285
|
+
fn run_object<'x, I: Instance<'x>>(&mut self, plan: &ObjectPlan, o: I::Object, x: I) -> bool {
|
|
1286
|
+
let len = o.len() as u64;
|
|
1287
|
+
if len < plan.min || len > plan.max {
|
|
1288
|
+
return false;
|
|
1289
|
+
}
|
|
1290
|
+
let seen = match plan.visit {
|
|
1291
|
+
Visit::None => Some(0),
|
|
1292
|
+
Visit::Values => self.visit_values::<I>(plan, o).then_some(0),
|
|
1293
|
+
Visit::Names if plan.lookup && o.len() * plan.names.map.names.len() <= LOOKUP_BUDGET => {
|
|
1294
|
+
self.visit_lookup::<I>(plan, o)
|
|
1295
|
+
}
|
|
1296
|
+
Visit::Names => self.visit_names::<I>(plan, o),
|
|
1297
|
+
Visit::Pattern => self.visit_pattern::<I>(plan, o).then_some(0),
|
|
1298
|
+
Visit::General => self.visit_general::<I>(plan, o),
|
|
1299
|
+
};
|
|
1300
|
+
let Some(seen) = seen else { return false };
|
|
1301
|
+
if seen & plan.required_mask != plan.required_mask {
|
|
1302
|
+
return false;
|
|
1303
|
+
}
|
|
1304
|
+
plan.rest_free || self.object_rest(plan, o, x, seen)
|
|
1305
|
+
}
|
|
1306
|
+
|
|
1307
|
+
/// The C# StrictObject loop: bounds, declared names (additionalProperties for the rest), and the required mask;
|
|
1308
|
+
/// a small function of its own, since nested objects enter it directly.
|
|
1309
|
+
fn run_strict_object<'x, I: Instance<'x>>(&mut self, plan: &ObjectPlan, o: I::Object) -> bool {
|
|
1310
|
+
let len = o.len() as u64;
|
|
1311
|
+
if len < plan.min || len > plan.max {
|
|
1312
|
+
return false;
|
|
1313
|
+
}
|
|
1314
|
+
if plan.lookup && o.len() * plan.names.map.names.len() <= LOOKUP_BUDGET {
|
|
1315
|
+
return self.visit_lookup::<I>(plan, o).is_some_and(|seen| seen & plan.required_mask == plan.required_mask);
|
|
1316
|
+
}
|
|
1317
|
+
let mut seen = 0u64;
|
|
1318
|
+
let mut hint = 0;
|
|
1319
|
+
for (k, v) in o.iter() {
|
|
1320
|
+
match plan.names.find_from(k, &mut hint) {
|
|
1321
|
+
Some(i) => {
|
|
1322
|
+
seen |= 1 << (i & 63);
|
|
1323
|
+
if !self.run_child(plan.children[i], v) {
|
|
1324
|
+
return false;
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
None => {
|
|
1328
|
+
if let Some(c) = plan.additional
|
|
1329
|
+
&& !self.run_child(c, v)
|
|
1330
|
+
{
|
|
1331
|
+
return false;
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
}
|
|
1336
|
+
seen & plan.required_mask == plan.required_mask
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
/// Each name looked up in the object (a plan with `lookup`: the other properties need no visit); the names seen,
|
|
1340
|
+
/// or `None` on failure.
|
|
1341
|
+
#[inline(always)]
|
|
1342
|
+
fn visit_lookup<'x, I: Instance<'x>>(&mut self, plan: &ObjectPlan, o: I::Object) -> Option<u64> {
|
|
1343
|
+
let mut seen = 0u64;
|
|
1344
|
+
for (i, name) in plan.names.map.names.iter().enumerate() {
|
|
1345
|
+
if let Some(v) = o.get(name) {
|
|
1346
|
+
seen |= 1 << i;
|
|
1347
|
+
if !self.run_child(plan.children[i], v) {
|
|
1348
|
+
return None;
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
Some(seen)
|
|
1353
|
+
}
|
|
1354
|
+
|
|
1355
|
+
/// Required names checked by lookup, and dependencies.
|
|
1356
|
+
#[inline(never)]
|
|
1357
|
+
fn object_rest<'x, I: Instance<'x>>(&mut self, plan: &ObjectPlan, o: I::Object, x: I, seen: u64) -> bool {
|
|
1358
|
+
if !plan.required.iter().all(|r| o.contains_key(r)) {
|
|
1359
|
+
return false;
|
|
1360
|
+
}
|
|
1361
|
+
for d in plan.dependencies.iter() {
|
|
1362
|
+
match d.bits {
|
|
1363
|
+
Some((name, required)) => {
|
|
1364
|
+
if seen & name == 0 {
|
|
1365
|
+
continue;
|
|
1366
|
+
}
|
|
1367
|
+
if seen & required != required {
|
|
1368
|
+
return false;
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
None => {
|
|
1372
|
+
if !o.contains_key(&d.name) {
|
|
1373
|
+
continue;
|
|
1374
|
+
}
|
|
1375
|
+
if !d.required.iter().all(|r| o.contains_key(r)) {
|
|
1376
|
+
return false;
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
}
|
|
1380
|
+
if let Some(s) = d.schema
|
|
1381
|
+
&& !self.run_in_place(s, x)
|
|
1382
|
+
{
|
|
1383
|
+
return false;
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
true
|
|
1387
|
+
}
|
|
1388
|
+
|
|
1389
|
+
/// Only additionalProperties: every value against one child.
|
|
1390
|
+
fn visit_values<'x, I: Instance<'x>>(&mut self, plan: &ObjectPlan, o: I::Object) -> bool {
|
|
1391
|
+
let c = plan.additional.unwrap();
|
|
1392
|
+
if c.trivial() {
|
|
1393
|
+
return c.types == ANY || o.values().all(|v| type_ok(c.types, v));
|
|
1394
|
+
}
|
|
1395
|
+
o.values().all(|v| self.run_child(c, v))
|
|
1396
|
+
}
|
|
1397
|
+
|
|
1398
|
+
/// Declared properties, and additionalProperties for the rest; the declared names seen, or `None` on failure.
|
|
1399
|
+
fn visit_names<'x, I: Instance<'x>>(&mut self, plan: &ObjectPlan, o: I::Object) -> Option<u64> {
|
|
1400
|
+
let mut seen = 0u64;
|
|
1401
|
+
let mut hint = 0;
|
|
1402
|
+
for (k, v) in o.iter() {
|
|
1403
|
+
match plan.names.find_from(k, &mut hint) {
|
|
1404
|
+
Some(i) => {
|
|
1405
|
+
seen |= 1 << (i & 63);
|
|
1406
|
+
if !self.run_child(plan.children[i], v) {
|
|
1407
|
+
return None;
|
|
1408
|
+
}
|
|
1409
|
+
}
|
|
1410
|
+
None => {
|
|
1411
|
+
if let Some(c) = plan.additional
|
|
1412
|
+
&& !self.run_child(c, v)
|
|
1413
|
+
{
|
|
1414
|
+
return None;
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
Some(seen)
|
|
1420
|
+
}
|
|
1421
|
+
|
|
1422
|
+
fn visit_pattern<'x, I: Instance<'x>>(&mut self, plan: &ObjectPlan, o: I::Object) -> bool {
|
|
1423
|
+
let (pattern, c) = &plan.patterns[0];
|
|
1424
|
+
for (k, v) in o.iter() {
|
|
1425
|
+
let applies = if pattern.is_match(k) { Some(*c) } else { plan.additional };
|
|
1426
|
+
if let Some(c) = applies
|
|
1427
|
+
&& !self.run_child(c, v)
|
|
1428
|
+
{
|
|
1429
|
+
return false;
|
|
1430
|
+
}
|
|
1431
|
+
}
|
|
1432
|
+
true
|
|
1433
|
+
}
|
|
1434
|
+
|
|
1435
|
+
fn visit_general<'x, I: Instance<'x>>(&mut self, plan: &ObjectPlan, o: I::Object) -> Option<u64> {
|
|
1436
|
+
let mut seen = 0u64;
|
|
1437
|
+
let mut hint = 0;
|
|
1438
|
+
for (k, v) in o.iter() {
|
|
1439
|
+
let mut matched = false;
|
|
1440
|
+
if let Some(i) = plan.names.find_from(k, &mut hint) {
|
|
1441
|
+
seen |= 1 << (i & 63);
|
|
1442
|
+
// A name only required (or a dependency) mentions is undeclared: patterns, else additionalProperties.
|
|
1443
|
+
if i < plan.declared {
|
|
1444
|
+
matched = true;
|
|
1445
|
+
if !self.run_child(plan.children[i], v) {
|
|
1446
|
+
return None;
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
for &j in plan.name_patterns[i].iter() {
|
|
1450
|
+
matched = true;
|
|
1451
|
+
if !self.run_child(plan.patterns[j as usize].1, v) {
|
|
1452
|
+
return None;
|
|
1453
|
+
}
|
|
1454
|
+
}
|
|
1455
|
+
} else {
|
|
1456
|
+
for (pattern, c) in plan.patterns.iter() {
|
|
1457
|
+
if pattern.is_match(k) {
|
|
1458
|
+
matched = true;
|
|
1459
|
+
if !self.run_child(*c, v) {
|
|
1460
|
+
return None;
|
|
1461
|
+
}
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
}
|
|
1465
|
+
if !matched
|
|
1466
|
+
&& let Some(c) = plan.additional
|
|
1467
|
+
&& !self.run_child(c, v)
|
|
1468
|
+
{
|
|
1469
|
+
return None;
|
|
1470
|
+
}
|
|
1471
|
+
if let Some(pn) = plan.property_names
|
|
1472
|
+
&& !self.run_name(pn, k)
|
|
1473
|
+
{
|
|
1474
|
+
return None;
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
Some(seen)
|
|
1478
|
+
}
|
|
1479
|
+
|
|
1480
|
+
fn run_array<'x, I: Instance<'x>>(&mut self, plan: &ArrayPlan, a: I::Array) -> bool {
|
|
1481
|
+
let len = a.len() as u64;
|
|
1482
|
+
if len < plan.min || len > plan.max {
|
|
1483
|
+
return false;
|
|
1484
|
+
}
|
|
1485
|
+
if let Some(types) = plan.simple {
|
|
1486
|
+
return all_of_type(a.iter(), types);
|
|
1487
|
+
}
|
|
1488
|
+
let prefix = plan.prefix.len().min(a.len());
|
|
1489
|
+
for (c, item) in plan.prefix.iter().zip(a.iter()) {
|
|
1490
|
+
if !self.run_child(*c, item) {
|
|
1491
|
+
return false;
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
if let Some(items) = plan.items {
|
|
1495
|
+
let rest = a.tail(prefix);
|
|
1496
|
+
if let Some(n) = plan.nested {
|
|
1497
|
+
for item in rest {
|
|
1498
|
+
let ok = match item.view() {
|
|
1499
|
+
View::Array(x) => {
|
|
1500
|
+
let len = x.len() as u64;
|
|
1501
|
+
items.types & type_mask::ARRAY != 0
|
|
1502
|
+
&& len >= n.min
|
|
1503
|
+
&& len <= n.max
|
|
1504
|
+
&& all_of_type(x.iter(), n.types)
|
|
1505
|
+
}
|
|
1506
|
+
// Not an array: only the items' type test applies.
|
|
1507
|
+
_ => type_ok(items.types, item),
|
|
1508
|
+
};
|
|
1509
|
+
if !ok {
|
|
1510
|
+
return false;
|
|
1511
|
+
}
|
|
1512
|
+
}
|
|
1513
|
+
} else if items.trivial() {
|
|
1514
|
+
// A type-only items schema: one tight loop (the C# evaluator's SimpleArray plan), or none for `true`.
|
|
1515
|
+
if !all_of_type(rest, items.types) {
|
|
1516
|
+
return false;
|
|
1517
|
+
}
|
|
1518
|
+
} else {
|
|
1519
|
+
for item in rest {
|
|
1520
|
+
if !self.run_child(items, item) {
|
|
1521
|
+
return false;
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
if let Some((c, min, max)) = plan.contains {
|
|
1527
|
+
let mut count = 0u64;
|
|
1528
|
+
for item in a.iter() {
|
|
1529
|
+
if self.run(c, item) {
|
|
1530
|
+
count += 1;
|
|
1531
|
+
if max.is_none() && count >= min {
|
|
1532
|
+
break;
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
}
|
|
1536
|
+
if count < min || max.is_some_and(|m| count > m) {
|
|
1537
|
+
return false;
|
|
1538
|
+
}
|
|
1539
|
+
}
|
|
1540
|
+
!plan.unique || all_unique(a)
|
|
1541
|
+
}
|
|
1542
|
+
}
|
|
1543
|
+
|
|
1544
|
+
/// Whether every value is of the types in a mask, with the common masks as tight loops.
|
|
1545
|
+
#[inline]
|
|
1546
|
+
fn all_of_type<'x, I: Instance<'x>>(mut items: impl Iterator<Item = I>, types: u8) -> bool {
|
|
1547
|
+
const NUMBERS: u8 = type_mask::NUMBER | type_mask::INTEGER;
|
|
1548
|
+
match types {
|
|
1549
|
+
ANY => true,
|
|
1550
|
+
// Masks of the kind bits (a kind's discriminant is its bit), which compile to a table lookup per item.
|
|
1551
|
+
type_mask::STRING => items.all(|v| v.kind() as u8 & type_mask::STRING != 0),
|
|
1552
|
+
t if t & !NUMBERS == 0 && t & type_mask::NUMBER != 0 => items.all(|v| v.kind() as u8 & type_mask::NUMBER != 0),
|
|
1553
|
+
t => items.all(|v| type_ok(t, v)),
|
|
1554
|
+
}
|
|
1555
|
+
}
|
|
1556
|
+
|
|
1557
|
+
/// A leaf's keywords: its value constraints, then those for the instance's type.
|
|
1558
|
+
#[inline]
|
|
1559
|
+
fn run_leaf<'x, I: Instance<'x>>(b: &Body, x: I) -> bool {
|
|
1560
|
+
for op in b.values.iter() {
|
|
1561
|
+
let ok = match op {
|
|
1562
|
+
Op::Const(c) => json_equal(x, c),
|
|
1563
|
+
Op::EnumStrings(values) => matches!(x.view(), View::String(s) if values.contains(s)),
|
|
1564
|
+
Op::Enum(values) => values.iter().any(|v| json_equal(x, v)),
|
|
1565
|
+
_ => unreachable!("a leaf has only value keywords"),
|
|
1566
|
+
};
|
|
1567
|
+
if !ok {
|
|
1568
|
+
return false;
|
|
1569
|
+
}
|
|
1570
|
+
}
|
|
1571
|
+
match x.view() {
|
|
1572
|
+
View::Number(n) => b.number.is_empty() || run_number(&b.number, &n),
|
|
1573
|
+
View::String(s) => b.string.is_empty() || run_string(&b.string, s),
|
|
1574
|
+
_ => true,
|
|
1575
|
+
}
|
|
1576
|
+
}
|
|
1577
|
+
|
|
1578
|
+
#[inline(never)]
|
|
1579
|
+
fn run_number(ops: &[NumberOp], n: &Number) -> bool {
|
|
1580
|
+
let v = Num::of(n);
|
|
1581
|
+
ops.iter().all(|op| match op {
|
|
1582
|
+
NumberOp::Minimum(b) => cmp(v, *b).is_ge(),
|
|
1583
|
+
NumberOp::Maximum(b) => cmp(v, *b).is_le(),
|
|
1584
|
+
NumberOp::ExclusiveMinimum(b) => cmp(v, *b).is_gt(),
|
|
1585
|
+
NumberOp::ExclusiveMaximum(b) => cmp(v, *b).is_lt(),
|
|
1586
|
+
NumberOp::MultipleOf(d) => d.divides(n),
|
|
1587
|
+
NumberOp::Format(f) => f.number(n),
|
|
1588
|
+
})
|
|
1589
|
+
}
|
|
1590
|
+
|
|
1591
|
+
#[inline(never)]
|
|
1592
|
+
fn run_string(ops: &[StringOp], s: &str) -> bool {
|
|
1593
|
+
ops.iter().all(|op| match op {
|
|
1594
|
+
StringOp::Length { min, max } => length_ok(s, *min, *max),
|
|
1595
|
+
StringOp::Pattern(p) => p.is_match(s),
|
|
1596
|
+
StringOp::Format(f) => f.string(s),
|
|
1597
|
+
StringOp::Content(kind) => content_ok(s, *kind),
|
|
1598
|
+
})
|
|
1599
|
+
}
|
|
1600
|
+
|
|
1601
|
+
/// minLength/maxLength, counting code points only when the byte length cannot decide (a code point is 1–4 bytes).
|
|
1602
|
+
#[inline]
|
|
1603
|
+
fn length_ok(s: &str, min: u64, max: u64) -> bool {
|
|
1604
|
+
let bytes = s.len() as u64;
|
|
1605
|
+
if bytes < min {
|
|
1606
|
+
return false;
|
|
1607
|
+
}
|
|
1608
|
+
if bytes <= max && bytes.div_ceil(4) >= min {
|
|
1609
|
+
return true;
|
|
1610
|
+
}
|
|
1611
|
+
// Every code point is at most four bytes: more than `max` of them for sure.
|
|
1612
|
+
if bytes.div_ceil(4) > max {
|
|
1613
|
+
return false;
|
|
1614
|
+
}
|
|
1615
|
+
let chars = code_points(s);
|
|
1616
|
+
chars >= min && chars <= max
|
|
1617
|
+
}
|
|
1618
|
+
|
|
1619
|
+
#[cfg(test)]
|
|
1620
|
+
mod tests {
|
|
1621
|
+
use super::*;
|
|
1622
|
+
|
|
1623
|
+
#[test]
|
|
1624
|
+
fn meet_treats_integers_as_numbers() {
|
|
1625
|
+
use type_mask::*;
|
|
1626
|
+
assert_eq!(meet(INTEGER, NUMBER), INTEGER);
|
|
1627
|
+
assert_eq!(meet(NUMBER, NUMBER | STRING), NUMBER | INTEGER);
|
|
1628
|
+
assert_eq!(meet(ANY, STRING | ARRAY), STRING | ARRAY);
|
|
1629
|
+
assert_eq!(meet(STRING, INTEGER), 0);
|
|
1630
|
+
for x in [serde_json::json!(1), serde_json::json!(1.5), serde_json::json!("a")] {
|
|
1631
|
+
for (a, b) in [(INTEGER, NUMBER), (NUMBER, INTEGER), (NUMBER | STRING, INTEGER | STRING), (ANY, NUMBER)] {
|
|
1632
|
+
assert_eq!(type_ok(meet(a, b), &x), type_ok(a, &x) && type_ok(b, &x), "{a} {b} {x}");
|
|
1633
|
+
}
|
|
1634
|
+
}
|
|
1635
|
+
}
|
|
1636
|
+
|
|
1637
|
+
#[test]
|
|
1638
|
+
fn str_eq_agrees_with_equality() {
|
|
1639
|
+
let words =
|
|
1640
|
+
["", "a", "ab", "abc", "abcd", "abcde", "abcdefgh", "abcdefghi", "abcdefghijklmnop", "abcdefghijklmnopq"];
|
|
1641
|
+
for a in words {
|
|
1642
|
+
for b in words {
|
|
1643
|
+
assert_eq!(str_eq(a, b), a == b, "{a:?} {b:?}");
|
|
1644
|
+
let mut c = b.to_string();
|
|
1645
|
+
if !c.is_empty() {
|
|
1646
|
+
let mid = c.len() / 2;
|
|
1647
|
+
c.replace_range(mid..mid + 1, "Z");
|
|
1648
|
+
assert_eq!(str_eq(a, &c), a == c, "{a:?} {c:?}");
|
|
1649
|
+
}
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
1652
|
+
}
|
|
1653
|
+
|
|
1654
|
+
#[test]
|
|
1655
|
+
fn name_map_finds_every_name() {
|
|
1656
|
+
let mut names: Vec<Box<str>> = (0..200).map(|i| format!("p{i}{}", "x".repeat(i % 13)).into()).collect();
|
|
1657
|
+
names.extend(["", "a", "ab", "abc", "abcd", "abcdefgh", "abcdefghi", "é", "日本"].map(Into::into));
|
|
1658
|
+
names.push("y".repeat(300).into());
|
|
1659
|
+
let map = NameMap::new(names.clone());
|
|
1660
|
+
for (i, n) in names.iter().enumerate() {
|
|
1661
|
+
assert_eq!(map.find(n), Some(i), "{n}");
|
|
1662
|
+
}
|
|
1663
|
+
for miss in ["p", "q1", "p1000", "p0x", "b", "abce", "abcdefgj", "abcdefghj", "è", "y"] {
|
|
1664
|
+
assert_eq!(map.find(miss), None, "{miss}");
|
|
1665
|
+
}
|
|
1666
|
+
assert_eq!(map.find(&"y".repeat(299)), None);
|
|
1667
|
+
for few in
|
|
1668
|
+
[vec!["a"], vec!["ab", "ba"], vec!["alpha", "gamma", "delta", "omega"], vec!["abcdefghij", "abcdefghik"]]
|
|
1669
|
+
{
|
|
1670
|
+
let names: Vec<Box<str>> = few.iter().map(|&s| s.into()).collect();
|
|
1671
|
+
let map = NameMap::new(names);
|
|
1672
|
+
for (i, n) in few.iter().enumerate() {
|
|
1673
|
+
assert_eq!(map.find(n), Some(i));
|
|
1674
|
+
}
|
|
1675
|
+
assert_eq!(map.find("zeta!"), None);
|
|
1676
|
+
}
|
|
1677
|
+
}
|
|
1678
|
+
|
|
1679
|
+
#[test]
|
|
1680
|
+
fn names_follow_declared_or_sorted_order() {
|
|
1681
|
+
let declared = ["name", "version", "repository", "alias"];
|
|
1682
|
+
let names = Names::new(declared.iter().map(|&n| n.into()).collect());
|
|
1683
|
+
// Every order of the names, from every starting hint, finds each one.
|
|
1684
|
+
let orders: [&[&str]; 4] = [
|
|
1685
|
+
&["name", "version", "repository", "alias"],
|
|
1686
|
+
&["alias", "name", "repository", "version"],
|
|
1687
|
+
&["version", "alias", "name", "repository"],
|
|
1688
|
+
&["repository", "repository", "name"],
|
|
1689
|
+
];
|
|
1690
|
+
for order in orders {
|
|
1691
|
+
for start in 0..=declared.len() {
|
|
1692
|
+
let mut hint = start;
|
|
1693
|
+
for n in order {
|
|
1694
|
+
let i = declared.iter().position(|d| d == n).unwrap();
|
|
1695
|
+
assert_eq!(names.find_from(n, &mut hint), Some(i), "{n} in {order:?} from {start}");
|
|
1696
|
+
}
|
|
1697
|
+
}
|
|
1698
|
+
}
|
|
1699
|
+
assert_eq!(names.find_from("other", &mut 0), None);
|
|
1700
|
+
assert_eq!(names.find_from("names", &mut 2), None);
|
|
1701
|
+
// Sorted successors: after "name" (index 0) comes "repository" (2), after it "version" (1), then none.
|
|
1702
|
+
assert_eq!(&*names.sorted_next, &[3, 2, u32::MAX, 1, 0]);
|
|
1703
|
+
}
|
|
1704
|
+
|
|
1705
|
+
#[test]
|
|
1706
|
+
fn linear_names_find_from_any_hint() {
|
|
1707
|
+
let names = Names::new(vec!["a".into(), "b".into(), "c".into()]);
|
|
1708
|
+
for start in 0..3 {
|
|
1709
|
+
for (i, n) in ["a", "b", "c"].iter().enumerate() {
|
|
1710
|
+
let mut hint = start;
|
|
1711
|
+
assert_eq!(names.find_from(n, &mut hint), Some(i));
|
|
1712
|
+
}
|
|
1713
|
+
assert_eq!(names.find_from("d", &mut 0), None);
|
|
1714
|
+
}
|
|
1715
|
+
}
|
|
1716
|
+
|
|
1717
|
+
#[test]
|
|
1718
|
+
fn length_ok_agrees_with_counting() {
|
|
1719
|
+
for s in ["", "a", "abcd", "é", "éé", "😀😀", "a😀b"] {
|
|
1720
|
+
let chars = s.chars().count() as u64;
|
|
1721
|
+
for min in 0..6 {
|
|
1722
|
+
for max in 0..6 {
|
|
1723
|
+
assert_eq!(length_ok(s, min, max), chars >= min && chars <= max, "{s:?} {min} {max}");
|
|
1724
|
+
}
|
|
1725
|
+
}
|
|
1726
|
+
}
|
|
1727
|
+
}
|
|
1728
|
+
}
|