Debian Codegraph @

src/keywords/type_.rs

raw symbols SCIP
1 use crate::{
2 compiler,
3 error::ValidationError,
4 keywords::CompilationResult,
5 paths::Location,
6 types::{JsonType, JsonTypeSet},
7 validator::{Validate, ValidationContext},
8 };
9 use serde_json::{json, Map, Number, Value};
10 use std::str::FromStr;
11
12 use crate::paths::LazyLocation;
13
14 pub(crate) struct MultipleTypesValidator {
15 types: JsonTypeSet,
16 location: Location,
17 }
18
19 impl MultipleTypesValidator {
20 #[inline]
21 pub(crate) fn compile(items: &[Value], location: Location) -> CompilationResult<'_> {
22 let mut types = JsonTypeSet::empty();
23 for item in items {
24 match item {
25 Value::String(string) => {
26 if let Ok(ty) = JsonType::from_str(string.as_str()) {
27 types = types.insert(ty);
28 } else {
29 return Err(ValidationError::enumeration(
30 Location::new(),
31 location,
32 item,
33 &json!([
34 "array", "boolean", "integer", "null", "number", "object", "string"
35 ]),
36 ));
37 }
38 }
39 _ => {
40 return Err(ValidationError::single_type_error(
41 location,
42 Location::new(),
43 item,
44 JsonType::String,
45 ))
46 }
47 }
48 }
49 Ok(Box::new(MultipleTypesValidator { types, location }))
50 }
51 }
52
53 impl Validate for MultipleTypesValidator {
54 fn is_valid(&self, instance: &Value, _ctx: &mut ValidationContext) -> bool {
55 self.types.contains_value_type(instance)
56 }
57 fn validate<'i>(
58 &self,
59 instance: &'i Value,
60 location: &LazyLocation,
61 ctx: &mut ValidationContext,
62 ) -> Result<(), ValidationError<'i>> {
63 if self.is_valid(instance, ctx) {
64 Ok(())
65 } else {
66 Err(ValidationError::multiple_type_error(
67 self.location.clone(),
68 location.into(),
69 instance,
70 self.types,
71 ))
72 }
73 }
74 }
75
76 pub(crate) struct NullTypeValidator {
77 location: Location,
78 }
79
80 impl NullTypeValidator {
81 #[inline]
82 pub(crate) fn compile<'a>(location: Location) -> CompilationResult<'a> {
83 Ok(Box::new(NullTypeValidator { location }))
84 }
85 }
86
87 impl Validate for NullTypeValidator {
88 fn is_valid(&self, instance: &Value, _ctx: &mut ValidationContext) -> bool {
89 instance.is_null()
90 }
91 fn validate<'i>(
92 &self,
93 instance: &'i Value,
94 location: &LazyLocation,
95 ctx: &mut ValidationContext,
96 ) -> Result<(), ValidationError<'i>> {
97 if self.is_valid(instance, ctx) {
98 Ok(())
99 } else {
100 Err(ValidationError::single_type_error(
101 self.location.clone(),
102 location.into(),
103 instance,
104 JsonType::Null,
105 ))
106 }
107 }
108 }
109
110 pub(crate) struct BooleanTypeValidator {
111 location: Location,
112 }
113
114 impl BooleanTypeValidator {
115 #[inline]
116 pub(crate) fn compile<'a>(location: Location) -> CompilationResult<'a> {
117 Ok(Box::new(BooleanTypeValidator { location }))
118 }
119 }
120
121 impl Validate for BooleanTypeValidator {
122 fn is_valid(&self, instance: &Value, _ctx: &mut ValidationContext) -> bool {
123 instance.is_boolean()
124 }
125 fn validate<'i>(
126 &self,
127 instance: &'i Value,
128 location: &LazyLocation,
129 ctx: &mut ValidationContext,
130 ) -> Result<(), ValidationError<'i>> {
131 if self.is_valid(instance, ctx) {
132 Ok(())
133 } else {
134 Err(ValidationError::single_type_error(
135 self.location.clone(),
136 location.into(),
137 instance,
138 JsonType::Boolean,
139 ))
140 }
141 }
142 }
143
144 pub(crate) struct StringTypeValidator {
145 location: Location,
146 }
147
148 impl StringTypeValidator {
149 #[inline]
150 pub(crate) fn compile<'a>(location: Location) -> CompilationResult<'a> {
151 Ok(Box::new(StringTypeValidator { location }))
152 }
153 }
154
155 impl Validate for StringTypeValidator {
156 fn is_valid(&self, instance: &Value, _ctx: &mut ValidationContext) -> bool {
157 instance.is_string()
158 }
159
160 fn validate<'i>(
161 &self,
162 instance: &'i Value,
163 location: &LazyLocation,
164 ctx: &mut ValidationContext,
165 ) -> Result<(), ValidationError<'i>> {
166 if self.is_valid(instance, ctx) {
167 Ok(())
168 } else {
169 Err(ValidationError::single_type_error(
170 self.location.clone(),
171 location.into(),
172 instance,
173 JsonType::String,
174 ))
175 }
176 }
177 }
178
179 pub(crate) struct ArrayTypeValidator {
180 location: Location,
181 }
182
183 impl ArrayTypeValidator {
184 #[inline]
185 pub(crate) fn compile<'a>(location: Location) -> CompilationResult<'a> {
186 Ok(Box::new(ArrayTypeValidator { location }))
187 }
188 }
189
190 impl Validate for ArrayTypeValidator {
191 fn is_valid(&self, instance: &Value, _ctx: &mut ValidationContext) -> bool {
192 instance.is_array()
193 }
194
195 fn validate<'i>(
196 &self,
197 instance: &'i Value,
198 location: &LazyLocation,
199 ctx: &mut ValidationContext,
200 ) -> Result<(), ValidationError<'i>> {
201 if self.is_valid(instance, ctx) {
202 Ok(())
203 } else {
204 Err(ValidationError::single_type_error(
205 self.location.clone(),
206 location.into(),
207 instance,
208 JsonType::Array,
209 ))
210 }
211 }
212 }
213
214 pub(crate) struct ObjectTypeValidator {
215 location: Location,
216 }
217
218 impl ObjectTypeValidator {
219 #[inline]
220 pub(crate) fn compile<'a>(location: Location) -> CompilationResult<'a> {
221 Ok(Box::new(ObjectTypeValidator { location }))
222 }
223 }
224
225 impl Validate for ObjectTypeValidator {
226 fn is_valid(&self, instance: &Value, _ctx: &mut ValidationContext) -> bool {
227 instance.is_object()
228 }
229 fn validate<'i>(
230 &self,
231 instance: &'i Value,
232 location: &LazyLocation,
233 ctx: &mut ValidationContext,
234 ) -> Result<(), ValidationError<'i>> {
235 if self.is_valid(instance, ctx) {
236 Ok(())
237 } else {
238 Err(ValidationError::single_type_error(
239 self.location.clone(),
240 location.into(),
241 instance,
242 JsonType::Object,
243 ))
244 }
245 }
246 }
247
248 pub(crate) struct NumberTypeValidator {
249 location: Location,
250 }
251
252 impl NumberTypeValidator {
253 #[inline]
254 pub(crate) fn compile<'a>(location: Location) -> CompilationResult<'a> {
255 Ok(Box::new(NumberTypeValidator { location }))
256 }
257 }
258
259 impl Validate for NumberTypeValidator {
260 fn is_valid(&self, instance: &Value, _ctx: &mut ValidationContext) -> bool {
261 instance.is_number()
262 }
263 fn validate<'i>(
264 &self,
265 instance: &'i Value,
266 location: &LazyLocation,
267 ctx: &mut ValidationContext,
268 ) -> Result<(), ValidationError<'i>> {
269 if self.is_valid(instance, ctx) {
270 Ok(())
271 } else {
272 Err(ValidationError::single_type_error(
273 self.location.clone(),
274 location.into(),
275 instance,
276 JsonType::Number,
277 ))
278 }
279 }
280 }
281
282 pub(crate) struct IntegerTypeValidator {
283 location: Location,
284 }
285
286 impl IntegerTypeValidator {
287 #[inline]
288 pub(crate) fn compile<'a>(location: Location) -> CompilationResult<'a> {
289 Ok(Box::new(IntegerTypeValidator { location }))
290 }
291 }
292
293 impl Validate for IntegerTypeValidator {
294 fn is_valid(&self, instance: &Value, _ctx: &mut ValidationContext) -> bool {
295 if let Value::Number(num) = instance {
296 is_integer(num)
297 } else {
298 false
299 }
300 }
301 fn validate<'i>(
302 &self,
303 instance: &'i Value,
304 location: &LazyLocation,
305 ctx: &mut ValidationContext,
306 ) -> Result<(), ValidationError<'i>> {
307 if self.is_valid(instance, ctx) {
308 Ok(())
309 } else {
310 Err(ValidationError::single_type_error(
311 self.location.clone(),
312 location.into(),
313 instance,
314 JsonType::Integer,
315 ))
316 }
317 }
318 }
319
320 fn is_integer(num: &Number) -> bool {
321 if num.is_u64() || num.is_i64() {
322 return true;
323 }
324 #[cfg(feature = "arbitrary-precision")]
325 {
326 use crate::ext::numeric::bignum;
327 use num_traits::One;
328
329 // Check huge plain integers first (no decimal point)
330 if bignum::try_parse_bigint(num).is_some() {
331 return true;
332 }
333
334 // Check huge decimals - must do this BEFORE as_f64() to avoid precision loss
335 if let Some(bigfrac) = bignum::try_parse_bigfraction(num) {
336 return bigfrac.denom().is_none_or(One::is_one);
337 }
338
339 // For numbers that fit in f64 range
340 if let Some(f) = num.as_f64() {
341 return f.fract() == 0.;
342 }
343
344 // Numbers that overflow to infinity (as_f64() returns None) are not integers
345 false
346 }
347 #[cfg(not(feature = "arbitrary-precision"))]
348 {
349 if let Some(f) = num.as_f64() {
350 return f.fract() == 0.;
351 }
352 unreachable!("Numbers always fit in u64/i64/f64 without arbitrary-precision")
353 }
354 }
355
356 #[inline]
357 pub(crate) fn compile<'a>(
358 ctx: &compiler::Context,
359 _: &'a Map<String, Value>,
360 schema: &'a Value,
361 ) -> Option<CompilationResult<'a>> {
362 let location = ctx.location().join("type");
363 match schema {
364 Value::String(item) => Some(compile_single_type(item.as_str(), location, schema)),
365 Value::Array(items) => {
366 if items.len() == 1 {
367 let item = &items[0];
368 if let Value::String(ty) = item {
369 Some(compile_single_type(ty.as_str(), location, item))
370 } else {
371 Some(Err(ValidationError::single_type_error(
372 Location::new(),
373 location,
374 item,
375 JsonType::String,
376 )))
377 }
378 } else {
379 Some(MultipleTypesValidator::compile(items, location))
380 }
381 }
382 _ => Some(Err(ValidationError::multiple_type_error(
383 Location::new(),
384 ctx.location().clone(),
385 schema,
386 JsonTypeSet::empty()
387 .insert(JsonType::String)
388 .insert(JsonType::Array),
389 ))),
390 }
391 }
392
393 fn compile_single_type<'a>(
394 item: &str,
395 location: Location,
396 instance: &'a Value,
397 ) -> CompilationResult<'a> {
398 match JsonType::from_str(item) {
399 Ok(JsonType::Array) => ArrayTypeValidator::compile(location),
400 Ok(JsonType::Boolean) => BooleanTypeValidator::compile(location),
401 Ok(JsonType::Integer) => IntegerTypeValidator::compile(location),
402 Ok(JsonType::Null) => NullTypeValidator::compile(location),
403 Ok(JsonType::Number) => NumberTypeValidator::compile(location),
404 Ok(JsonType::Object) => ObjectTypeValidator::compile(location),
405 Ok(JsonType::String) => StringTypeValidator::compile(location),
406 Err(()) => Err(ValidationError::custom(
407 Location::new(),
408 location,
409 instance,
410 "Unexpected type",
411 )),
412 }
413 }
414
415 #[cfg(test)]
416 mod tests {
417 use crate::tests_util;
418 use serde_json::{json, Value};
419 use test_case::test_case;
420
421 #[test_case(&json!({"type": "array"}), &json!(1), "/type")]
422 #[test_case(&json!({"type": "boolean"}), &json!(1), "/type")]
423 #[test_case(&json!({"type": "integer"}), &json!("f"), "/type")]
424 #[test_case(&json!({"type": "null"}), &json!(1), "/type")]
425 #[test_case(&json!({"type": "number"}), &json!("f"), "/type")]
426 #[test_case(&json!({"type": "object"}), &json!(1), "/type")]
427 #[test_case(&json!({"type": "string"}), &json!(1), "/type")]
428 #[test_case(&json!({"type": ["string", "object"]}), &json!(1), "/type")]
429 fn location(schema: &Value, instance: &Value, expected: &str) {
430 tests_util::assert_schema_location(schema, instance, expected);
431 }
432
433 fn parse_json(s: &str) -> Value {
434 serde_json::from_str(s).unwrap()
435 }
436
437 #[test_case(r#"{"type": "integer"}"#, "42", true; "plain integer")]
438 #[test_case(r#"{"type": "integer"}"#, "-42", true; "negative integer")]
439 #[test_case(r#"{"type": "integer"}"#, "0", true; "zero")]
440 #[test_case(r#"{"type": "integer"}"#, "1.0", true; "float with .0")]
441 #[test_case(r#"{"type": "integer"}"#, "42.0", true; "integer as float")]
442 #[test_case(r#"{"type": "integer"}"#, "-42.0", true; "negative float with .0")]
443 #[test_case(r#"{"type": "integer"}"#, "1.5", false; "decimal")]
444 #[test_case(r#"{"type": "integer"}"#, "0.1", false; "small decimal")]
445 #[test_case(r#"{"type": "integer"}"#, "42.7", false; "float with decimal")]
446 #[test_case(r#"{"type": "integer"}"#, "9223372036854775807", true; "i64::MAX")]
447 #[test_case(r#"{"type": "integer"}"#, "-9223372036854775808", true; "i64::MIN")]
448 #[test_case(r#"{"type": "integer"}"#, "18446744073709551615", true; "u64::MAX")]
449 #[test_case(r#"{"type": "integer"}"#, "1e10", true; "scientific int 1e10")]
450 #[test_case(r#"{"type": "integer"}"#, "1.0e10", true; "scientific 1.0e10")]
451 #[test_case(r#"{"type": "integer"}"#, "1.5e10", true; "scientific 1.5e10 equals 15000000000")]
452 #[test_case(r#"{"type": "integer"}"#, "1e-10", false; "scientific small 1e-10")]
453 #[test_case(r#"{"type": "integer"}"#, "true", false; "boolean")]
454 #[test_case(r#"{"type": "integer"}"#, r#""42""#, false; "string")]
455 #[test_case(r#"{"type": "integer"}"#, "[]", false; "array")]
456 #[test_case(r#"{"type": "integer"}"#, "{}", false; "object")]
457 #[test_case(r#"{"type": "integer"}"#, "null", false; "null")]
458 fn integer_type_validation(schema_json: &str, instance_json: &str, expected: bool) {
459 let schema = parse_json(schema_json);
460 let instance = parse_json(instance_json);
461 if expected {
462 tests_util::is_valid(&schema, &instance);
463 } else {
464 tests_util::is_not_valid(&schema, &instance);
465 }
466 }
467
468 #[cfg(feature = "arbitrary-precision")]
469 mod arbitrary_precision {
470 use crate::tests_util;
471 use serde_json::Value;
472 use test_case::test_case;
473
474 fn parse_json(s: &str) -> Value {
475 serde_json::from_str(s).unwrap()
476 }
477
478 #[test_case(r#"{"type": "integer"}"#, "18446744073709551616", true; "u64_max_plus_1_plain")]
479 #[test_case(r#"{"type": "integer"}"#, "18446744073709551616.0", true; "u64_max_plus_1_with_dot_0")]
480 #[test_case(r#"{"type": "integer"}"#, "99999999999999999999", true; "huge_plain_integer")]
481 #[test_case(r#"{"type": "integer"}"#, "99999999999999999999.0", true; "huge_integer_with_dot_0")]
482 #[test_case(
483 r#"{"type": "integer"}"#,
484 "999999999999999999999999999999999999999999999999999999999999999999999999999999",
485 true;
486 "very_huge_plain_integer"
487 )]
488 #[test_case(
489 r#"{"type": "integer"}"#,
490 "999999999999999999999999999999999999999999999999999999999999999999999999999999.0",
491 true;
492 "very_huge_integer_with_dot_0"
493 )]
494 #[test_case(r#"{"type": "integer"}"#, "-18446744073709551616", true; "negative_huge_integer")]
495 #[test_case(r#"{"type": "integer"}"#, "-18446744073709551616.0", true; "negative_huge_integer_with_dot_0")]
496 #[test_case(r#"{"type": "integer"}"#, "-99999999999999999999", true; "negative_huge_plain")]
497 #[test_case(r#"{"type": "integer"}"#, "-99999999999999999999.0", true; "negative_huge_plain_with_dot_0")]
498 #[test_case(r#"{"type": "integer"}"#, "18446744073709551616.5", false; "huge decimal")]
499 #[test_case(r#"{"type": "integer"}"#, "99999999999999999999.5", false; "huge float")]
500 #[test_case(
501 r#"{"type": "integer"}"#,
502 "999999999999999999999999999999999999999999999999999999999999999999999999999999.5",
503 false;
504 "very huge float"
505 )]
506 #[test_case(r#"{"type": "integer"}"#, "0.3", false; "bigfrac 0.3")]
507 #[test_case(r#"{"type": "integer"}"#, "0.1", false; "bigfrac 0.1")]
508 #[test_case(r#"{"type": "integer"}"#, "123.456", false; "bigfrac 123.456")]
509 #[test_case(r#"{"type": "integer"}"#, "1e1000", true; "huge scientific notation integer")]
510 #[test_case(r#"{"type": "integer"}"#, "1e1000001", false; "infinity positive")]
511 #[test_case(r#"{"type": "integer"}"#, "-1e1000001", false; "infinity negative")]
512 #[test_case(r#"{"type": "integer"}"#, "1.5e-1000", false; "huge scientific float")]
513 #[test_case(r#"{"type": "number"}"#, "18446744073709551616", true; "huge int valid as number")]
514 #[test_case(r#"{"type": "number"}"#, "18446744073709551616.0", true; "huge .0 valid as number")]
515 #[test_case(r#"{"type": "number"}"#, "18446744073709551616.5", true; "huge float valid as number")]
516 #[test_case(r#"{"type": "number"}"#, "1e10000", true; "infinity valid as number")]
517 #[test_case(r#"{"type": ["integer", "string"]}"#, "18446744073709551616", true; "huge int in union")]
518 #[test_case(r#"{"type": ["integer", "string"]}"#, "18446744073709551616.0", true; "huge .0 in union")]
519 #[test_case(r#"{"type": ["integer", "string"]}"#, "18446744073709551616.5", false; "huge float not in union")]
520 #[test_case(r#"{"type": ["integer", "string"]}"#, r#""foo""#, true; "string in union")]
521 #[test_case(r#"{"type": ["number", "string"]}"#, "18446744073709551616.5", true; "huge float with number")]
522 #[test_case(r#"{"type": "integer"}"#, "true", false; "boolean not integer")]
523 #[test_case(r#"{"type": "integer"}"#, r#""42""#, false; "string not integer")]
524 #[test_case(r#"{"type": "integer"}"#, "[]", false; "array not integer")]
525 #[test_case(r#"{"type": "integer"}"#, "{}", false; "object not integer")]
526 #[test_case(r#"{"type": "integer"}"#, "null", false; "null not integer")]
527 fn huge_number_integer_validation(schema_json: &str, instance_json: &str, expected: bool) {
528 let schema = parse_json(schema_json);
529 let instance = parse_json(instance_json);
530 if expected {
531 tests_util::is_valid(&schema, &instance);
532 } else {
533 tests_util::is_not_valid(&schema, &instance);
534 }
535 }
536 }
537 }