jsonschema_rs 0.61.2 → 0.63.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.
data/src/lib.rs CHANGED
@@ -8,6 +8,7 @@
8
8
  mod canonical;
9
9
  mod error_kind;
10
10
  mod evaluation;
11
+ mod json_text;
11
12
  mod options;
12
13
  mod registry;
13
14
  mod retriever;
@@ -18,7 +19,8 @@ mod validator_map;
18
19
  use jsonschema::{
19
20
  json::{
20
21
  magnus_child, magnus_invalidate_members_cache, magnus_is_object, magnus_probe_root,
21
- magnus_take_pending_error, Magnus, MagnusPendingErrorScope, RbNode,
22
+ magnus_take_pending_error, Array, Json, JsonText, JsonTextNode, Magnus,
23
+ MagnusPendingErrorScope, Node, Object, RbNode,
22
24
  },
23
25
  paths::LocationSegment,
24
26
  ValidationOptions,
@@ -46,6 +48,7 @@ use std::{
46
48
  use crate::{
47
49
  error_kind::ValidationErrorKind,
48
50
  evaluation::Evaluation,
51
+ json_text::text_node_to_ruby,
49
52
  options::{
50
53
  extract_evaluate_kwargs, extract_kwargs, extract_kwargs_no_draft, make_options_from_kwargs,
51
54
  parse_draft_symbol, CallbackRoots, CompilationRoots, CompilationRootsRef, ExtractedKwargs,
@@ -86,21 +89,21 @@ define_rb_intern!(static ID_SYM_SCHEMA_PATH_POINTER: "schema_path_pointer");
86
89
  define_rb_intern!(static ID_SYM_EVALUATION_PATH_POINTER: "evaluation_path_pointer");
87
90
  define_rb_intern!(static ID_SYM_ABSOLUTE_KEYWORD_LOCATION: "absolute_keyword_location");
88
91
 
89
- struct BuiltValidator {
90
- validator: jsonschema::Validator<Magnus>,
92
+ struct BuiltValidator<F: Json = Magnus> {
93
+ validator: jsonschema::Validator<F>,
91
94
  callback_roots: CallbackRoots,
92
95
  compilation_roots: CompilationRootsRef,
93
96
  }
94
97
 
95
- fn build_validator(
98
+ fn build_validator<F: Json>(
96
99
  ruby: &Ruby,
97
- options: ValidationOptions<'_, Arc<dyn jsonschema::Retrieve>, Magnus>,
100
+ options: ValidationOptions<'_, Arc<dyn jsonschema::Retrieve>, F>,
98
101
  registry: Option<&jsonschema::Registry<'_>>,
99
102
  retriever: Option<RubyRetriever>,
100
103
  callback_roots: CallbackRoots,
101
104
  compilation_roots: Arc<CompilationRoots>,
102
105
  schema: &serde_json::Value,
103
- ) -> Result<BuiltValidator, Error> {
106
+ ) -> Result<BuiltValidator<F>, Error> {
104
107
  let mut options = match retriever {
105
108
  Some(ret) => options.with_retriever(ret),
106
109
  None => options,
@@ -128,53 +131,14 @@ fn build_validator(
128
131
  })
129
132
  }
130
133
 
131
- /// RAII guard that registers Ruby callback values as GC roots for the duration
132
- /// of a one-off validation call (module-level `valid?`, `validate!`, etc.).
133
- ///
134
- /// Persistent `Validator` instances protect their callbacks via the GC mark phase
135
- /// (see `Validator::mark_callback_roots`). One-off calls have no such wrapper, so
136
- /// this guard calls `gc_register_address` on construction and `gc_unregister_address` on
137
- /// drop to keep callbacks alive while validation runs.
138
- struct CallbackRootGuard {
139
- roots: Vec<Value>,
140
- }
141
-
142
- impl CallbackRootGuard {
143
- fn new(ruby: &Ruby, callback_roots: &CallbackRoots) -> Self {
144
- let roots = {
145
- let roots_guard = match callback_roots.lock() {
146
- Ok(roots) => roots,
147
- Err(poisoned) => poisoned.into_inner(),
148
- };
149
- roots_guard
150
- .iter()
151
- .map(|root| ruby.get_inner(*root))
152
- .collect::<Vec<_>>()
153
- };
154
- // We do not mutate `roots` after this point, so references used for GC address
155
- // registration remain valid for the lifetime of the guard.
156
- for root in &roots {
157
- ruby.gc_register_address(root);
158
- }
159
-
160
- Self { roots }
161
- }
162
- }
163
-
164
- impl Drop for CallbackRootGuard {
165
- fn drop(&mut self) {
166
- let ruby = Ruby::get().expect("Ruby VM should be initialized");
167
- for root in &self.roots {
168
- ruby.gc_unregister_address(root);
169
- }
170
- }
171
- }
172
-
173
- fn build_parsed_options(
134
+ fn build_parsed_options<F: Json>(
174
135
  ruby: &Ruby,
175
136
  kw: ExtractedKwargs,
176
137
  draft_override: Option<jsonschema::Draft>,
177
- ) -> Result<ParsedOptions<'_>, Error> {
138
+ ) -> Result<ParsedOptions<'_, F>, Error>
139
+ where
140
+ options::RubyKeyword: for<'i> jsonschema::Keyword<'i, F>,
141
+ {
178
142
  let (
179
143
  draft_val,
180
144
  validate_formats,
@@ -218,7 +182,7 @@ thread_local! {
218
182
  static SUPPRESS_PANIC_OUTPUT: RefCell<bool> = const { RefCell::new(false) };
219
183
  }
220
184
 
221
- // RAII scope giving each surfacing call its own keyword-cause queue and restoring the caller's on
185
+ // RAII scope giving each validation call its own keyword-cause queue and restoring the caller's on
222
186
  // exit. This discards causes a call leaves unconsumed (`evaluate`, an abandoned enumeration, a
223
187
  // panic — the drop still runs) and lets a keyword re-enter validation without clobbering the outer
224
188
  // call's pending causes.
@@ -290,7 +254,7 @@ fn build_verbose_message(
290
254
  mut message: String,
291
255
  schema_path: &jsonschema::paths::Location,
292
256
  instance_path: &jsonschema::paths::Location,
293
- root_instance: Option<RbNode<'_>>,
257
+ root_instance: Option<InstanceRoot<'_>>,
294
258
  failing_instance: &serde_json::Value,
295
259
  mask: Option<&str>,
296
260
  ) -> String {
@@ -358,14 +322,14 @@ fn build_verbose_message(
358
322
  let segment = unescape_segment(segment);
359
323
  let segment = segment.as_ref();
360
324
  let is_index = match current {
361
- Some(node) if magnus_is_object(node) => false,
325
+ Some(node) if node.is_object() => false,
362
326
  _ => is_index_segment(segment),
363
327
  };
364
328
  message.push('[');
365
329
  push_segment(&mut message, segment, is_index);
366
330
  message.push(']');
367
331
 
368
- current = current.and_then(|node| magnus_child(node, segment, is_index));
332
+ current = current.and_then(|node| node.child(segment, is_index));
369
333
  }
370
334
  message.push_str(":\n ");
371
335
 
@@ -388,8 +352,59 @@ fn error_message(error: &jsonschema::ValidationError<'_>, mask: Option<&str>) ->
388
352
  }
389
353
  }
390
354
 
391
- // The object at `location` under `root`, when it and everything in it are plain JSON types, which
392
- // convert to and from JSON unchanged. Other values keep their JSON form.
355
+ /// Where an error reads its instance from: the Ruby object validated, or the JSON text.
356
+ #[derive(Clone, Copy)]
357
+ pub(crate) enum InstanceRoot<'a> {
358
+ Object(RbNode<'a>),
359
+ Text(JsonTextNode<'a>),
360
+ }
361
+
362
+ impl InstanceRoot<'_> {
363
+ fn is_object(self) -> bool {
364
+ match self {
365
+ InstanceRoot::Object(node) => magnus_is_object(node),
366
+ InstanceRoot::Text(node) => node.as_object().is_some(),
367
+ }
368
+ }
369
+
370
+ fn child(self, segment: &str, is_index: bool) -> Option<Self> {
371
+ match self {
372
+ InstanceRoot::Object(node) => magnus_child(node, segment, is_index).map(Self::Object),
373
+ InstanceRoot::Text(node) => if is_index {
374
+ node.as_array()?.elements().nth(segment.parse().ok()?)
375
+ } else {
376
+ node.as_object()?.get(&JsonText::prepare_key(segment))
377
+ }
378
+ .map(Self::Text),
379
+ }
380
+ }
381
+
382
+ // The instance at `location`, or `None` to convert the error's JSON copy instead. JSON text
383
+ // builds only that value, as `JSON.parse` would, never the rest of the document.
384
+ fn instance_at(self, ruby: &Ruby, location: &str) -> Result<Option<Value>, Error> {
385
+ match self {
386
+ InstanceRoot::Object(root) => Ok(plain_instance_at(ruby, root, location)),
387
+ InstanceRoot::Text(root) => text_node_at(root, location)
388
+ .map(|node| text_node_to_ruby(ruby, &node))
389
+ .transpose(),
390
+ }
391
+ }
392
+ }
393
+
394
+ fn text_node_at<'a>(root: JsonTextNode<'a>, location: &str) -> Option<JsonTextNode<'a>> {
395
+ let mut current = root;
396
+ for segment in location.split('/').skip(1) {
397
+ current = if let Some(object) = current.as_object() {
398
+ object.get(&JsonText::prepare_key(&unescape_segment(segment)))?
399
+ } else {
400
+ current.as_array()?.elements().nth(parse_index(segment)?)?
401
+ };
402
+ }
403
+ Some(current)
404
+ }
405
+
406
+ // The Ruby value at `location` under `root` when it holds only plain JSON types; `None` makes the
407
+ // caller convert the JSON copy.
393
408
  fn plain_instance_at(ruby: &Ruby, root: RbNode<'_>, location: &str) -> Option<Value> {
394
409
  #[allow(unsafe_code)]
395
410
  let mut current: Value = unsafe { magnus::rb_sys::FromRawValue::from_raw(root.raw()) };
@@ -463,7 +478,7 @@ fn is_plain_json(ruby: &Ruby, value: Value, depth: u16) -> bool {
463
478
  fn into_ruby_error(
464
479
  ruby: &Ruby,
465
480
  error: jsonschema::ValidationError<'_>,
466
- root_instance: Option<RbNode<'_>>,
481
+ root_instance: Option<InstanceRoot<'_>>,
467
482
  message: &str,
468
483
  mask: Option<&str>,
469
484
  ) -> Result<Value, Error> {
@@ -497,8 +512,10 @@ fn into_ruby_error(
497
512
  let kind_obj = ValidationErrorKind::new(ruby, &parts.kind, mask)?;
498
513
  // Scalars convert faster than the path to them is followed.
499
514
  let original = match parts.instance.as_ref() {
500
- serde_json::Value::Array(_) | serde_json::Value::Object(_) => root_instance
501
- .and_then(|root| plain_instance_at(ruby, root, parts.instance_path.as_str())),
515
+ serde_json::Value::Array(_) | serde_json::Value::Object(_) => match root_instance {
516
+ Some(root) => root.instance_at(ruby, parts.instance_path.as_str())?,
517
+ None => None,
518
+ },
502
519
  _ => None,
503
520
  };
504
521
  let rb_instance = match original {
@@ -554,7 +571,7 @@ fn into_ruby_error(
554
571
  fn to_ruby_error_value(
555
572
  ruby: &Ruby,
556
573
  error: jsonschema::ValidationError<'_>,
557
- root_instance: Option<RbNode<'_>>,
574
+ root_instance: Option<InstanceRoot<'_>>,
558
575
  mask: Option<&str>,
559
576
  ) -> Result<Value, Error> {
560
577
  let message = error_message(&error, mask);
@@ -569,7 +586,7 @@ pub(crate) fn referencing_error(ruby: &Ruby, message: String) -> Error {
569
586
  fn raise_validation_error(
570
587
  ruby: &Ruby,
571
588
  error: jsonschema::ValidationError<'_>,
572
- root_instance: Option<RbNode<'_>>,
589
+ root_instance: Option<InstanceRoot<'_>>,
573
590
  mask: Option<&str>,
574
591
  ) -> Error {
575
592
  let message = error_message(&error, mask);
@@ -586,9 +603,7 @@ fn raise_validation_error(
586
603
  }
587
604
  }
588
605
 
589
- /// RAII guard that sets `SUPPRESS_PANIC_OUTPUT` to `true` on creation and
590
- /// resets it to `false` on drop, ensuring the flag is always restored even
591
- /// if `catch_unwind` itself encounters a double-panic.
606
+ /// RAII guard that sets `SUPPRESS_PANIC_OUTPUT` for one `catch_unwind_silent` call.
592
607
  struct SuppressPanicGuard;
593
608
 
594
609
  impl SuppressPanicGuard {
@@ -631,9 +646,9 @@ fn handle_callback_panic(ruby: &Ruby, err: Box<dyn std::any::Any + Send>) -> Err
631
646
  })
632
647
  }
633
648
 
634
- /// Run validation over `instance` in place, raising anything the representation could only record.
649
+ /// Run `run` on `instance` read in place, then raise any read error the Magnus accessors recorded.
635
650
  ///
636
- /// Accessors cannot fail, so a value the representation cannot read is stashed and surfaced here.
651
+ /// Accessors cannot fail, so they stash what they cannot read for this function to raise.
637
652
  fn surface_pending_errors<T>(
638
653
  instance: Value,
639
654
  run: impl FnOnce(RbNode<'_>) -> Result<T, Error>,
@@ -721,7 +736,7 @@ impl Validator {
721
736
  Ok(Err(error)) => Err(raise_validation_error(
722
737
  ruby,
723
738
  error,
724
- Some(node),
739
+ Some(InstanceRoot::Object(node)),
725
740
  rb_self.mask.as_deref(),
726
741
  )),
727
742
  Err(err) => Err(handle_callback_panic(ruby, err)),
@@ -734,8 +749,11 @@ impl Validator {
734
749
  let _scope = KeywordCauseScope::enter();
735
750
 
736
751
  if ruby.block_given() {
737
- // Lazy path: yield errors one at a time to the block
738
- let mut iter = rb_self.validator.iter_errors(node);
752
+ // Lazy path: yield errors one at a time to the block. Building the iterator
753
+ // validates, which can run Ruby callbacks.
754
+ let mut iter =
755
+ catch_unwind_silent(AssertUnwindSafe(|| rb_self.validator.iter_errors(node)))
756
+ .map_err(|err| handle_callback_panic(ruby, err))?;
739
757
  loop {
740
758
  let result = catch_unwind_silent(AssertUnwindSafe(|| iter.next()));
741
759
  match result {
@@ -743,7 +761,7 @@ impl Validator {
743
761
  let ruby_error = to_ruby_error_value(
744
762
  ruby,
745
763
  error,
746
- Some(node),
764
+ Some(InstanceRoot::Object(node)),
747
765
  rb_self.mask.as_deref(),
748
766
  )?;
749
767
  ruby.yield_value::<Value, Value>(ruby_error)?;
@@ -765,7 +783,7 @@ impl Validator {
765
783
  arr.push(to_ruby_error_value(
766
784
  ruby,
767
785
  error,
768
- Some(node),
786
+ Some(InstanceRoot::Object(node)),
769
787
  rb_self.mask.as_deref(),
770
788
  )?)?;
771
789
  }
@@ -805,10 +823,8 @@ impl Validator {
805
823
  /// Detect the JSON Schema draft for a schema and return the corresponding validator class.
806
824
  /// Draft is detected automatically from the `$schema` field. Defaults to Draft202012Validator.
807
825
  ///
808
- /// >>> cls = JSONSchema.validator_cls_for({"type" => "string"})
809
- /// >>> validator = cls.new({"type" => "string"})
810
- /// >>> cls = JSONSchema.validator_cls_for({"$schema" => "http://json-schema.org/draft-07/schema#", "type" => "string"})
811
- /// >>> validator = cls.new({"$schema" => "http://json-schema.org/draft-07/schema#", "type" => "string"})
826
+ /// JSONSchema.validator_cls_for({ "type" => "string" }) # => JSONSchema::Draft202012Validator
827
+ /// JSONSchema.validator_cls_for({ "$schema" => "http://json-schema.org/draft-07/schema#" }) # => JSONSchema::Draft7Validator
812
828
  ///
813
829
  fn validator_cls_for(ruby: &Ruby, schema: Value) -> Result<RClass, Error> {
814
830
  let draft = if let Some(hash) = RHash::from_value(schema) {
@@ -856,7 +872,7 @@ fn validator_for(ruby: &Ruby, args: &[Value]) -> Result<Validator, Error> {
856
872
  let kw = extract_kwargs_no_draft(ruby, parsed_args.keywords)?;
857
873
 
858
874
  let json_schema = to_schema_value(ruby, schema)?;
859
- let parsed = build_parsed_options(ruby, kw, None)?;
875
+ let parsed = build_parsed_options::<Magnus>(ruby, kw, None)?;
860
876
  let BuiltValidator {
861
877
  validator,
862
878
  callback_roots,
@@ -884,7 +900,7 @@ fn validator_map_for(ruby: &Ruby, args: &[Value]) -> Result<validator_map::Valid
884
900
  let kw = extract_kwargs_no_draft(ruby, parsed_args.keywords)?;
885
901
 
886
902
  let json_schema = to_schema_value(ruby, schema)?;
887
- let parsed = build_parsed_options(ruby, kw, None)?;
903
+ let parsed = build_parsed_options::<Magnus>(ruby, kw, None)?;
888
904
  let callback_roots = parsed.callback_roots;
889
905
  let compilation_roots = parsed.compilation_roots;
890
906
  let mask = parsed.mask;
@@ -925,7 +941,7 @@ fn bundle(ruby: &Ruby, args: &[Value]) -> Result<Value, Error> {
925
941
  let kw = extract_kwargs(ruby, parsed_args.keywords)?;
926
942
 
927
943
  let json_schema = to_schema_value(ruby, schema)?;
928
- let parsed = build_parsed_options(ruby, kw, None)?;
944
+ let parsed = build_parsed_options::<Magnus>(ruby, kw, None)?;
929
945
  let mut options = match parsed.retriever {
930
946
  Some(ret) => parsed.options.with_retriever(ret),
931
947
  None => parsed.options,
@@ -948,7 +964,7 @@ fn dereference(ruby: &Ruby, args: &[Value]) -> Result<Value, Error> {
948
964
  let kw = extract_kwargs(ruby, parsed_args.keywords)?;
949
965
 
950
966
  let json_schema = to_schema_value(ruby, schema)?;
951
- let parsed = build_parsed_options(ruby, kw, None)?;
967
+ let parsed = build_parsed_options::<Magnus>(ruby, kw, None)?;
952
968
  let mut options = match parsed.retriever {
953
969
  Some(ret) => parsed.options.with_retriever(ret),
954
970
  None => parsed.options,
@@ -980,12 +996,11 @@ fn is_valid(ruby: &Ruby, args: &[Value]) -> Result<bool, Error> {
980
996
  let kw = extract_kwargs(ruby, parsed_args.keywords)?;
981
997
 
982
998
  let json_schema = to_schema_value(ruby, schema)?;
983
- let parsed = build_parsed_options(ruby, kw, None)?;
984
- let has_ruby_callbacks = parsed.has_ruby_callbacks;
999
+ let parsed = build_parsed_options::<Magnus>(ruby, kw, None)?;
985
1000
  let BuiltValidator {
986
1001
  validator,
987
- callback_roots,
988
1002
  compilation_roots: _compilation_roots,
1003
+ ..
989
1004
  } = build_validator(
990
1005
  ruby,
991
1006
  parsed.options,
@@ -997,8 +1012,6 @@ fn is_valid(ruby: &Ruby, args: &[Value]) -> Result<bool, Error> {
997
1012
  )?;
998
1013
 
999
1014
  surface_pending_errors(instance, |node| {
1000
- let _callback_roots =
1001
- has_ruby_callbacks.then(|| CallbackRootGuard::new(ruby, &callback_roots));
1002
1015
  catch_unwind_silent(AssertUnwindSafe(|| validator.is_valid(node)))
1003
1016
  .map_err(|err| handle_callback_panic(ruby, err))
1004
1017
  })
@@ -1011,12 +1024,11 @@ fn validate(ruby: &Ruby, args: &[Value]) -> Result<(), Error> {
1011
1024
  let kw = extract_kwargs(ruby, parsed_args.keywords)?;
1012
1025
 
1013
1026
  let json_schema = to_schema_value(ruby, schema)?;
1014
- let parsed = build_parsed_options(ruby, kw, None)?;
1015
- let has_ruby_callbacks = parsed.has_ruby_callbacks;
1027
+ let parsed = build_parsed_options::<Magnus>(ruby, kw, None)?;
1016
1028
  let BuiltValidator {
1017
1029
  validator,
1018
- callback_roots,
1019
1030
  compilation_roots: _compilation_roots,
1031
+ ..
1020
1032
  } = build_validator(
1021
1033
  ruby,
1022
1034
  parsed.options,
@@ -1028,14 +1040,12 @@ fn validate(ruby: &Ruby, args: &[Value]) -> Result<(), Error> {
1028
1040
  )?;
1029
1041
 
1030
1042
  surface_pending_errors(instance, |node| {
1031
- let _callback_roots =
1032
- has_ruby_callbacks.then(|| CallbackRootGuard::new(ruby, &callback_roots));
1033
1043
  match catch_unwind_silent(AssertUnwindSafe(|| validator.validate(node))) {
1034
1044
  Ok(Ok(())) => Ok(()),
1035
1045
  Ok(Err(error)) => Err(raise_validation_error(
1036
1046
  ruby,
1037
1047
  error,
1038
- Some(node),
1048
+ Some(InstanceRoot::Object(node)),
1039
1049
  parsed.mask.as_deref(),
1040
1050
  )),
1041
1051
  Err(err) => Err(handle_callback_panic(ruby, err)),
@@ -1050,12 +1060,11 @@ fn each_error(ruby: &Ruby, args: &[Value]) -> Result<Value, Error> {
1050
1060
  let kw = extract_kwargs(ruby, parsed_args.keywords)?;
1051
1061
 
1052
1062
  let json_schema = to_schema_value(ruby, schema)?;
1053
- let parsed = build_parsed_options(ruby, kw, None)?;
1054
- let has_ruby_callbacks = parsed.has_ruby_callbacks;
1063
+ let parsed = build_parsed_options::<Magnus>(ruby, kw, None)?;
1055
1064
  let BuiltValidator {
1056
1065
  validator,
1057
- callback_roots,
1058
1066
  compilation_roots: _compilation_roots,
1067
+ ..
1059
1068
  } = build_validator(
1060
1069
  ruby,
1061
1070
  parsed.options,
@@ -1067,17 +1076,18 @@ fn each_error(ruby: &Ruby, args: &[Value]) -> Result<Value, Error> {
1067
1076
  )?;
1068
1077
 
1069
1078
  surface_pending_errors(instance, |node| {
1070
- let _callback_roots =
1071
- has_ruby_callbacks.then(|| CallbackRootGuard::new(ruby, &callback_roots));
1072
-
1073
1079
  if ruby.block_given() {
1074
1080
  // Lazy path: yield errors one at a time to the block
1075
1081
  let mut iter = validator.iter_errors(node);
1076
1082
  loop {
1077
1083
  match catch_unwind_silent(AssertUnwindSafe(|| iter.next())) {
1078
1084
  Ok(Some(error)) => {
1079
- let ruby_error =
1080
- to_ruby_error_value(ruby, error, Some(node), parsed.mask.as_deref())?;
1085
+ let ruby_error = to_ruby_error_value(
1086
+ ruby,
1087
+ error,
1088
+ Some(InstanceRoot::Object(node)),
1089
+ parsed.mask.as_deref(),
1090
+ )?;
1081
1091
  ruby.yield_value::<Value, Value>(ruby_error)?;
1082
1092
  }
1083
1093
  Ok(None) => break,
@@ -1096,7 +1106,7 @@ fn each_error(ruby: &Ruby, args: &[Value]) -> Result<Value, Error> {
1096
1106
  arr.push(to_ruby_error_value(
1097
1107
  ruby,
1098
1108
  error,
1099
- Some(node),
1109
+ Some(InstanceRoot::Object(node)),
1100
1110
  parsed.mask.as_deref(),
1101
1111
  )?)?;
1102
1112
  }
@@ -1114,12 +1124,11 @@ fn evaluate(ruby: &Ruby, args: &[Value]) -> Result<Evaluation, Error> {
1114
1124
  let kw = extract_evaluate_kwargs(ruby, parsed_args.keywords)?;
1115
1125
 
1116
1126
  let json_schema = to_schema_value(ruby, schema)?;
1117
- let parsed = build_parsed_options(ruby, kw, None)?;
1118
- let has_ruby_callbacks = parsed.has_ruby_callbacks;
1127
+ let parsed = build_parsed_options::<Magnus>(ruby, kw, None)?;
1119
1128
  let BuiltValidator {
1120
1129
  validator,
1121
- callback_roots,
1122
1130
  compilation_roots: _compilation_roots,
1131
+ ..
1123
1132
  } = build_validator(
1124
1133
  ruby,
1125
1134
  parsed.options,
@@ -1131,8 +1140,6 @@ fn evaluate(ruby: &Ruby, args: &[Value]) -> Result<Evaluation, Error> {
1131
1140
  )?;
1132
1141
 
1133
1142
  surface_pending_errors(instance, |node| {
1134
- let _callback_roots =
1135
- has_ruby_callbacks.then(|| CallbackRootGuard::new(ruby, &callback_roots));
1136
1143
  match catch_unwind_silent(AssertUnwindSafe(|| validator.evaluate(node))) {
1137
1144
  Ok(output) => Ok(Evaluation::new(output)),
1138
1145
  Err(err) => Err(handle_callback_panic(ruby, err)),
@@ -1161,7 +1168,7 @@ macro_rules! define_draft_validator {
1161
1168
  let kw = extract_kwargs_no_draft(ruby, parsed_args.keywords)?;
1162
1169
 
1163
1170
  let json_schema = to_schema_value(ruby, schema)?;
1164
- let parsed = build_parsed_options(ruby, kw, Some($draft))?;
1171
+ let parsed = build_parsed_options::<Magnus>(ruby, kw, Some($draft))?;
1165
1172
  let BuiltValidator {
1166
1173
  validator,
1167
1174
  callback_roots,
@@ -1242,8 +1249,8 @@ fn json_text_schema(schema: Value) -> Option<serde_json::Value> {
1242
1249
  serde_json::from_slice(bytes).ok()
1243
1250
  }
1244
1251
 
1245
- // The bundled meta-schemas are compiled in and read the Ruby object in place; `None` sends a
1246
- // `$schema` outside them through its chain.
1252
+ // Checks against a compiled-in meta-schema, reading the Ruby object in place; `None` when `$schema`
1253
+ // names none of them.
1247
1254
  fn compiled_meta_is_valid(schema: Value) -> Option<Result<bool, Error>> {
1248
1255
  #[allow(unsafe_code)]
1249
1256
  let node = RbNode::new(schema.as_raw());
@@ -1322,7 +1329,7 @@ fn meta_validate(ruby: &Ruby, args: &[Value]) -> Result<(), Error> {
1322
1329
  }
1323
1330
  #[allow(unsafe_code)]
1324
1331
  let node = RbNode::new(schema.as_raw());
1325
- raise_validation_error(ruby, error, Some(node), None)
1332
+ raise_validation_error(ruby, error, Some(InstanceRoot::Object(node)), None)
1326
1333
  };
1327
1334
  if let Some(registry) = registry {
1328
1335
  let json_schema = to_schema_value(ruby, schema)?;
@@ -1398,9 +1405,8 @@ fn validation_error_hash(ruby: &Ruby, rb_self: Value) -> Result<Value, Error> {
1398
1405
 
1399
1406
  #[magnus::init(name = "jsonschema_rb")]
1400
1407
  fn init(ruby: &Ruby) -> Result<(), Error> {
1401
- // Conditionally suppress panic output — only when inside `catch_unwind`
1402
- // blocks used for Ruby callback panics (format checkers, custom keywords).
1403
- // Other panics pass through to the default handler to preserve debugging output.
1408
+ // Silence panic output inside `catch_unwind_silent`, which wraps every validation call; other
1409
+ // panics keep the default output.
1404
1410
  let default_hook = std::panic::take_hook();
1405
1411
  std::panic::set_hook(Box::new(move |info| {
1406
1412
  let suppress = SUPPRESS_PANIC_OUTPUT.with(|flag| *flag.borrow());
@@ -1455,6 +1461,7 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
1455
1461
  canonical::init_canonical(ruby, &module)?;
1456
1462
 
1457
1463
  // Validator class
1464
+ json_text::define_class(ruby, &module)?;
1458
1465
  let validator_class = module.define_class("Validator", ruby.class_object())?;
1459
1466
  validator_class.define_method("valid?", method!(Validator::is_valid, 1))?;
1460
1467
  validator_class.define_method("validate!", method!(Validator::validate, 1))?;