Debian Codegraph @

src/keywords/prefix_items.rs

raw symbols SCIP
1 use crate::{
2 compiler,
3 error::{no_error, ErrorIterator, ValidationError},
4 evaluation::Annotations,
5 node::SchemaNode,
6 paths::{LazyLocation, Location},
7 types::JsonType,
8 validator::{EvaluationResult, Validate, ValidationContext},
9 };
10 use serde_json::{Map, Value};
11
12 use super::CompilationResult;
13
14 pub(crate) struct PrefixItemsValidator {
15 schemas: Vec<SchemaNode>,
16 }
17
18 impl PrefixItemsValidator {
19 #[inline]
20 pub(crate) fn compile<'a>(
21 ctx: &compiler::Context,
22 items: &'a [Value],
23 ) -> CompilationResult<'a> {
24 let ctx = ctx.new_at_location("prefixItems");
25 let mut schemas = Vec::with_capacity(items.len());
26 for (idx, item) in items.iter().enumerate() {
27 let ctx = ctx.new_at_location(idx);
28 let validators = compiler::compile(&ctx, ctx.as_resource_ref(item))?;
29 schemas.push(validators);
30 }
31 Ok(Box::new(PrefixItemsValidator { schemas }))
32 }
33 }
34
35 impl Validate for PrefixItemsValidator {
36 fn is_valid(&self, instance: &Value, ctx: &mut ValidationContext) -> bool {
37 if let Value::Array(items) = instance {
38 for (schema, item) in self.schemas.iter().zip(items.iter()) {
39 if !schema.is_valid(item, ctx) {
40 return false;
41 }
42 }
43 true
44 } else {
45 true
46 }
47 }
48
49 fn validate<'i>(
50 &self,
51 instance: &'i Value,
52 location: &LazyLocation,
53 ctx: &mut ValidationContext,
54 ) -> Result<(), ValidationError<'i>> {
55 if let Value::Array(items) = instance {
56 for (idx, (schema, item)) in self.schemas.iter().zip(items.iter()).enumerate() {
57 schema.validate(item, &location.push(idx), ctx)?;
58 }
59 }
60 Ok(())
61 }
62
63 fn iter_errors<'i>(
64 &self,
65 instance: &'i Value,
66 location: &LazyLocation,
67 ctx: &mut ValidationContext,
68 ) -> ErrorIterator<'i> {
69 if let Value::Array(items) = instance {
70 let mut errors = Vec::new();
71 for (idx, (schema, item)) in self.schemas.iter().zip(items.iter()).enumerate() {
72 errors.extend(schema.iter_errors(item, &location.push(idx), ctx));
73 }
74 ErrorIterator::from_iterator(errors.into_iter())
75 } else {
76 no_error()
77 }
78 }
79
80 fn evaluate(
81 &self,
82 instance: &Value,
83 location: &LazyLocation,
84 ctx: &mut ValidationContext,
85 ) -> EvaluationResult {
86 if let Value::Array(items) = instance {
87 if !items.is_empty() {
88 let mut children = Vec::with_capacity(self.schemas.len().min(items.len()));
89 let mut max_index_applied = 0usize;
90 for (idx, (schema_node, item)) in self.schemas.iter().zip(items.iter()).enumerate()
91 {
92 children.push(schema_node.evaluate_instance(item, &location.push(idx), ctx));
93 max_index_applied = idx;
94 }
95 let annotation = if children.len() == items.len() {
96 Value::Bool(true)
97 } else {
98 Value::from(max_index_applied)
99 };
100 let mut result = EvaluationResult::from_children(children);
101 result.annotate(Annotations::new(annotation));
102 return result;
103 }
104 }
105 EvaluationResult::valid_empty()
106 }
107 }
108
109 #[inline]
110 pub(crate) fn compile<'a>(
111 ctx: &compiler::Context,
112 _: &'a Map<String, Value>,
113 schema: &'a Value,
114 ) -> Option<CompilationResult<'a>> {
115 if let Value::Array(items) = schema {
116 Some(PrefixItemsValidator::compile(ctx, items))
117 } else {
118 Some(Err(ValidationError::single_type_error(
119 Location::new(),
120 ctx.location().clone(),
121 schema,
122 JsonType::Array,
123 )))
124 }
125 }
126
127 #[cfg(test)]
128 mod tests {
129 use crate::tests_util;
130 use serde_json::{json, Value};
131 use test_case::test_case;
132
133 #[test_case(&json!({"$schema": "https://json-schema.org/draft/2020-12/schema", "prefixItems": [{"type": "integer"}, {"maximum": 5}]}), &json!(["string"]), "/prefixItems/0/type")]
134 #[test_case(&json!({"$schema": "https://json-schema.org/draft/2020-12/schema", "prefixItems": [{"type": "integer"}, {"maximum": 5}]}), &json!([42, 42]), "/prefixItems/1/maximum")]
135 #[test_case(&json!({"$schema": "https://json-schema.org/draft/2020-12/schema", "prefixItems": [{"type": "integer"}, {"maximum": 5}], "items": {"type": "boolean"}}), &json!([42, 1, 42]), "/items/type")]
136 #[test_case(&json!({"$schema": "https://json-schema.org/draft/2020-12/schema", "prefixItems": [{"type": "integer"}, {"maximum": 5}], "items": {"type": "boolean"}}), &json!([42, 42, true]), "/prefixItems/1/maximum")]
137 fn location(schema: &Value, instance: &Value, expected: &str) {
138 tests_util::assert_schema_location(schema, instance, expected);
139 }
140
141 #[test]
142 fn evaluation_outputs_cover_prefix_items() {
143 let schema = json!({
144 "type": "object",
145 "properties": {"name": {"type": "string"}, "age": {"type": "number", "minimum": 0}},
146 "required": ["name"]
147 });
148 let validator = crate::validator_for(&schema).expect("schema compiles");
149 let evaluation = validator.evaluate(&json!({"name": "Alice", "age": 1}));
150
151 assert_eq!(
152 serde_json::to_value(evaluation.list()).unwrap(),
153 json!({
154 "valid": true,
155 "details": [
156 {"evaluationPath": "", "instanceLocation": "", "schemaLocation": "", "valid": true},
157 {
158 "valid": true,
159 "evaluationPath": "/properties",
160 "instanceLocation": "",
161 "schemaLocation": "/properties",
162 "annotations": ["age", "name"]
163 },
164 {
165 "valid": true,
166 "evaluationPath": "/properties/age",
167 "instanceLocation": "/age",
168 "schemaLocation": "/properties/age"
169 },
170 {
171 "valid": true,
172 "evaluationPath": "/properties/age/minimum",
173 "instanceLocation": "/age",
174 "schemaLocation": "/properties/age/minimum"
175 },
176 {
177 "valid": true,
178 "evaluationPath": "/properties/age/type",
179 "instanceLocation": "/age",
180 "schemaLocation": "/properties/age/type"
181 },
182 {
183 "valid": true,
184 "evaluationPath": "/properties/name",
185 "instanceLocation": "/name",
186 "schemaLocation": "/properties/name"
187 },
188 {
189 "valid": true,
190 "evaluationPath": "/properties/name/type",
191 "instanceLocation": "/name",
192 "schemaLocation": "/properties/name/type"
193 },
194 {
195 "valid": true,
196 "evaluationPath": "/required",
197 "instanceLocation": "",
198 "schemaLocation": "/required"
199 },
200 {
201 "valid": true,
202 "evaluationPath": "/type",
203 "instanceLocation": "",
204 "schemaLocation": "/type"
205 }
206 ]
207 })
208 );
209
210 assert_eq!(
211 serde_json::to_value(evaluation.hierarchical()).unwrap(),
212 json!({
213 "valid": true,
214 "evaluationPath": "",
215 "instanceLocation": "",
216 "schemaLocation": "",
217 "details": [
218 {
219 "valid": true,
220 "evaluationPath": "/properties",
221 "instanceLocation": "",
222 "schemaLocation": "/properties",
223 "annotations": ["age", "name"],
224 "details": [
225 {
226 "valid": true,
227 "evaluationPath": "/properties/age",
228 "instanceLocation": "/age",
229 "schemaLocation": "/properties/age",
230 "details": [
231 {
232 "valid": true,
233 "evaluationPath": "/properties/age/minimum",
234 "instanceLocation": "/age",
235 "schemaLocation": "/properties/age/minimum"
236 },
237 {
238 "valid": true,
239 "evaluationPath": "/properties/age/type",
240 "instanceLocation": "/age",
241 "schemaLocation": "/properties/age/type"
242 }
243 ]
244 },
245 {
246 "valid": true,
247 "evaluationPath": "/properties/name",
248 "instanceLocation": "/name",
249 "schemaLocation": "/properties/name",
250 "details": [
251 {
252 "valid": true,
253 "evaluationPath": "/properties/name/type",
254 "instanceLocation": "/name",
255 "schemaLocation": "/properties/name/type"
256 }
257 ]
258 }
259 ]
260 },
261 {
262 "valid": true,
263 "evaluationPath": "/required",
264 "instanceLocation": "",
265 "schemaLocation": "/required"
266 },
267 {
268 "valid": true,
269 "evaluationPath": "/type",
270 "instanceLocation": "",
271 "schemaLocation": "/type"
272 }
273 ]
274 })
275 );
276 }
277 }