Skip to main content

graphrt_core/
yaml.rs

1//! The one YAML entry point of graphrt: YAML text to a [`serde_json::Value`].
2//!
3//! Every YAML document graphrt reads (workflows, plugin manifests, bundles,
4//! eval and knowledge configs, the gateway config) is parsed here and then
5//! deserialized from the `Value`. `serde_saphyr`'s deserializer is generic over
6//! the visitor, so deserializing each type straight from YAML compiles its whole
7//! deserializer again per type and per crate (≈ 430 KiB of a gateway binary
8//! before this module). Going through one non-generic function keeps a single
9//! copy. Types then deserialize from `Value`, which the JSON inputs use anyway;
10//! errors name the offending path ([`crate::value_path`]) and, with a
11//! [`crate::source_map::SourceMap`], its line.
12
13/// A YAML syntax error, with its location.
14pub use serde_saphyr::Error;
15
16/// Parses YAML text into a `Value`. With `strict_booleans`, only `true` and
17/// `false` are booleans (YAML 1.2: `yes`, `no`, `on`, `off` stay strings).
18///
19/// Unquoted scalars become numbers, booleans or null as YAML resolves them, so
20/// a string field given `123` must quote it (`"123"`).
21///
22/// # Errors
23/// Syntax errors, with their location.
24#[inline(never)]
25pub fn to_value(text: &str, strict_booleans: bool) -> Result<serde_json::Value, Error> {
26    let options = serde_saphyr::options! { strict_booleans: strict_booleans };
27    serde_saphyr::from_str_with_options(text, options)
28}
29
30/// Parses YAML text into `T` through [`to_value`]. An error reads
31/// `path (line L, column C): message`, or just the message for a syntax error
32/// (which carries its own location).
33///
34/// # Errors
35/// The syntax or deserialization error as text.
36pub fn from_str<T: serde::de::DeserializeOwned>(text: &str, strict_booleans: bool) -> Result<T, String> {
37    let value = to_value(text, strict_booleans).map_err(|error| error.to_string())?;
38    T::deserialize(&value).map_err(|error| describe(text, &value, &error))
39}
40
41/// `path (line L, column C): message` for an error deserializing `value`, parsed from `text`.
42#[inline(never)]
43pub fn describe(text: &str, value: &serde_json::Value, error: &serde_json::Error) -> String {
44    let path = crate::value_path::error_path(value, error);
45    if path.is_root() {
46        return error.to_string();
47    }
48    let prefer_key = error.to_string().starts_with("unknown field");
49    match crate::source_map::SourceMap::from_text(text).locate(&path, prefer_key) {
50        Some(span) => format!("{path} (line {}, column {}): {error}", span.line, span.column),
51        None => format!("{path}: {error}"),
52    }
53}
54
55#[cfg(test)]
56mod tests {
57    use serde_json::json;
58
59    use super::*;
60
61    #[test]
62    fn parses_yaml_into_values() {
63        let value = to_value("a: 1\nb: [x, true]\nc: yes\n", true).unwrap();
64        assert_eq!(value, json!({ "a": 1, "b": ["x", true], "c": "yes" }));
65        assert_eq!(to_value("c: yes\n", false).unwrap(), json!({ "c": true }));
66        let error = to_value("a: [1\n", true).unwrap_err();
67        assert!(error.location().is_some(), "{error}");
68    }
69
70    #[derive(Debug, serde::Deserialize)]
71    #[serde(deny_unknown_fields)]
72    #[allow(dead_code)]
73    struct Pool {
74        max_active_runs: u32,
75    }
76
77    #[derive(Debug, serde::Deserialize)]
78    #[allow(dead_code)]
79    struct File {
80        name: String,
81        pool: Pool,
82    }
83
84    #[test]
85    fn typed_errors_name_path_and_line() {
86        let ok: File = from_str("name: shop\npool: { max_active_runs: 4 }\n", false).unwrap();
87        assert_eq!(ok.pool.max_active_runs, 4);
88        let error = from_str::<File>("name: shop\npool:\n  max_active_runs: many\n", false).unwrap_err();
89        assert!(
90            error.starts_with("pool.max_active_runs (line 3, column 20): invalid type: string \"many\""),
91            "{error}"
92        );
93        let error = from_str::<File>("name: shop\npool:\n  max_active: 1\n", false).unwrap_err();
94        assert!(error.starts_with("pool.max_active (line 3, column 3): unknown field `max_active`"), "{error}");
95        assert!(from_str::<File>("name: [\n", false).unwrap_err().contains("line"));
96    }
97}