Skip to main content

yaml_rt_schema/
lib.rs

1//! JSON Schema validation and schema inference over yaml-rt documents.
2
3mod generate;
4mod model;
5mod numeric;
6mod validate;
7mod value;
8
9use std::fmt;
10use std::fs::File;
11use std::io::Read;
12use std::path::{Path, PathBuf};
13
14pub use value::Value;
15use yaml_rt_core::{JsonPointer, ResourceLimits, Span, YamlDoc};
16
17pub use generate::generate_schema;
18
19const DIALECT: &str = "https://json-schema.org/draft/2020-12/schema";
20
21/// A schema loading, instance conversion, or validation error.
22#[derive(Debug, Clone)]
23pub struct Error {
24    message: String,
25    instance_path: Option<String>,
26    schema_path: Option<String>,
27    source_span: Option<Span>,
28}
29
30impl Error {
31    fn source(error: impl fmt::Display) -> Self {
32        Self::new(error.to_string())
33    }
34    fn new(message: impl Into<String>) -> Self {
35        Self {
36            message: message.into(),
37            instance_path: None,
38            schema_path: None,
39            source_span: None,
40        }
41    }
42    fn instance(path: impl Into<String>, message: impl Into<String>, span: Option<Span>) -> Self {
43        Self {
44            message: message.into(),
45            instance_path: Some(path.into()),
46            schema_path: None,
47            source_span: span,
48        }
49    }
50    fn keyword(
51        path: impl Into<String>,
52        schema: impl Into<String>,
53        message: impl Into<String>,
54        span: Option<Span>,
55    ) -> Self {
56        Self {
57            message: message.into(),
58            instance_path: Some(path.into()),
59            schema_path: Some(schema.into()),
60            source_span: span,
61        }
62    }
63    /// JSON Pointer to the failing instance value, if available.
64    pub fn instance_path(&self) -> Option<&str> {
65        self.instance_path.as_deref()
66    }
67    /// JSON Pointer to the failing schema keyword, if available.
68    pub fn schema_path(&self) -> Option<&str> {
69        self.schema_path.as_deref()
70    }
71    /// Span of the failing YAML value, if available.
72    pub fn source_span(&self) -> Option<Span> {
73        self.source_span
74    }
75    /// Primary error message without location metadata.
76    pub fn message(&self) -> &str {
77        &self.message
78    }
79}
80
81impl fmt::Display for Error {
82    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        if let Some(path) = &self.instance_path {
84            write!(f, "at instance {path:?}: ")?;
85        }
86        write!(f, "{}", self.message)?;
87        if let Some(path) = &self.schema_path {
88            write!(f, " (schema {path})")?;
89        }
90        Ok(())
91    }
92}
93impl std::error::Error for Error {}
94
95/// Parsed JSON Schema reusable across YAML documents.
96pub struct Schema {
97    root: Value,
98    #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
99    origin: Option<PathBuf>,
100    format_assertion: bool,
101    resources: std::collections::HashMap<String, Value>,
102}
103
104impl Schema {
105    /// Parses a JSON or YAML schema. `base_path` locates relative file references.
106    pub fn parse(source: &str, base_path: Option<&Path>) -> Result<Self, Error> {
107        let root = parse_schema(source, base_path)?;
108        let attach_source = |mut error: Error| {
109            if let Ok(doc) = YamlDoc::parse(source)
110                && let Ok(instance) = model::from_document(&doc, 0)
111            {
112                error.source_span = error
113                    .schema_path
114                    .as_ref()
115                    .and_then(|path| instance.spans.get(path).copied());
116            }
117            error
118        };
119        validate::check_schema(&root, "").map_err(attach_source)?;
120        validate::check_meta_schema(&root).map_err(attach_source)?;
121        let origin = base_path.map(Path::to_path_buf);
122        Ok(Self {
123            root,
124            origin,
125            format_assertion: false,
126            resources: Default::default(),
127        })
128    }
129
130    /// Reads and compiles a JSON or YAML schema file.
131    pub fn from_path(path: &Path) -> Result<Self, Error> {
132        let source = read_source_file(path)?;
133        Self::parse(&source, Some(path))
134    }
135
136    /// Validates one document in a parsed YAML stream.
137    pub fn validate(&self, doc: &YamlDoc, document: usize) -> Result<(), Error> {
138        let instance = model::from_document(doc, document)?;
139        validate::validate(self, &instance)
140    }
141
142    /// Validates one selected YAML value while retaining its source spans.
143    pub fn validate_pointer(
144        &self,
145        doc: &YamlDoc,
146        document: usize,
147        pointer: &JsonPointer,
148    ) -> Result<(), Error> {
149        let node = doc
150            .resolve_pointer(document, pointer)
151            .map_err(Error::source)?;
152        let instance = model::from_node(doc, Some(node))?;
153        validate::validate(self, &instance)
154    }
155
156    /// Validates an already parsed JSON instance.
157    pub fn validate_json(&self, value: &Value) -> Result<(), Error> {
158        validate::validate(
159            self,
160            &model::Instance {
161                value: value.clone(),
162                spans: Default::default(),
163            },
164        )
165    }
166
167    /// Enables or disables assertion checks for standard `format` names.
168    pub fn with_format_assertions(mut self, enabled: bool) -> Self {
169        self.format_assertion = enabled;
170        self
171    }
172
173    /// Registers an already available schema resource under an absolute URI.
174    /// This does not enable network access.
175    pub fn register_resource(&mut self, uri: &str, source: &str) -> Result<(), Error> {
176        let url = url::Url::parse(uri).map_err(Error::source)?;
177        let value = Value::parse(source)?;
178        validate::check_schema(&value, "")?;
179        validate::check_meta_schema(&value)?;
180        self.resources.insert(url.to_string(), value);
181        Ok(())
182    }
183}
184
185fn read_source_file(path: &Path) -> Result<String, Error> {
186    let byte_limit = ResourceLimits::default().max_source_bytes;
187    let read_limit = byte_limit.saturating_add(1).min(u32::MAX as usize);
188    let mut source = Vec::new();
189    File::open(path)
190        .map_err(Error::source)?
191        .take(read_limit as u64)
192        .read_to_end(&mut source)
193        .map_err(Error::source)?;
194    if source.len() > byte_limit {
195        return Err(Error::new(format!(
196            "schema source exceeds byte limit of {byte_limit}"
197        )));
198    }
199    String::from_utf8(source).map_err(Error::source)
200}
201
202fn parse_schema(source: &str, path: Option<&Path>) -> Result<Value, Error> {
203    if path.is_some_and(|path| {
204        path.extension()
205            .is_some_and(|extension| extension == "json")
206    }) {
207        return Value::parse(source);
208    }
209    let doc = YamlDoc::parse(source).map_err(|error| {
210        let span = error.diagnostic.span;
211        let mut result = Error::source(error);
212        result.source_span = Some(span);
213        result
214    })?;
215    if doc.document_count() != 1 {
216        return Err(Error::new("schema must contain exactly one document"));
217    }
218    Ok(model::from_document(&doc, 0)?.value)
219}