Skip to main content

ctl_input/
yaml_format.rs

1//! The YAML [`Format`]: serde-saphyr's located reader builds the tree, and
2//! serde-saphyr's scalar rules resolve each scalar. No YAML rule is written
3//! here.
4
5use std::borrow::Cow;
6use std::ops::Range;
7use std::sync::OnceLock;
8
9use serde_saphyr::granit_parser::ScalarStyle as Written;
10use serde_saphyr::located::{self, MappingNode, ScalarNode, SequenceNode};
11use serde_saphyr::scalars::{Inferred, Rules, Scalar as Spelled};
12use serde_saphyr::{
13    DefaultMessageFormatter, DuplicateKeyPolicy, Error, Localizer, Location, MergeKeyPolicy,
14    MessageFormatter, NonFiniteFloatPolicy, Options,
15};
16
17use super::exceeded::Exceeded;
18use super::format::{Fault, Format, Mismatch, Raise, Reading, Refusal, Resolved, Wanted};
19use super::limits::Limits;
20use super::messages::printable;
21use super::tree::{Node, Scalar, ScalarStyle, Tag};
22
23/// YAML, read by serde-saphyr's located reader. Its extensions are `yaml` and
24/// `yml`.
25#[derive(Clone, Copy, Debug)]
26pub struct Yaml;
27
28/// The YAML format, for [`Formats::add`](crate::Formats::add).
29pub static YAML: Yaml = Yaml;
30
31impl Format for Yaml {
32    fn name(&self) -> &'static str {
33        "yaml"
34    }
35
36    fn extensions(&self) -> &'static [&'static str] {
37        &["yaml", "yml"]
38    }
39
40    fn read(&self, text: &str, limits: &Limits, reading: Reading) -> Result<Node, Refusal> {
41        let bounds = limits.bounds();
42        if text.len() > bounds.input_bytes {
43            let exceeded = Exceeded::input_bytes(bounds.input_bytes, Raise::FOR_TEXT);
44            return Err(Refusal::new(exceeded.fault(), None, None));
45        }
46        located::read(text, options(limits, reading))
47            .map(|node| convert(text, &node))
48            .map_err(|error| refusal(text, limits, &error))
49    }
50
51    fn resolve<'a>(
52        &self,
53        scalar: &'a Scalar,
54        tag: Option<&Tag>,
55        wanted: Wanted,
56    ) -> Result<Resolved<'a>, Mismatch> {
57        let spelled = Spelled {
58            value: scalar.value(),
59            style: spelled_style(scalar.style()),
60            tag: tag.map(Tag::as_str),
61        };
62        let rules = rules();
63        let at = Location::UNKNOWN;
64        let mismatch = |error: Error| {
65            let detail = if let Error::NonFiniteFloat { value, .. } = &error {
66                printable(&format!("non-finite float `{value}` is not allowed"))
67            } else {
68                plain(&DefaultMessageFormatter.with_localizer(&Unplaced), &error)
69            };
70            Mismatch::new(wanted).with_detail(detail)
71        };
72        match wanted {
73            Wanted::Any => match rules.infer(&spelled, at).map_err(mismatch)? {
74                Inferred::Null => Ok(Resolved::Null),
75                Inferred::Bool(value) => Ok(Resolved::Bool(value)),
76                Inferred::Signed(value) => Ok(Resolved::Int(i128::from(value))),
77                Inferred::Unsigned(value) => Ok(Resolved::Int(i128::from(value))),
78                Inferred::Float(value) => Ok(Resolved::Float(value)),
79                Inferred::String(Cow::Owned(text)) => Ok(Resolved::Str(Cow::Owned(text))),
80                Inferred::String(Cow::Borrowed(_)) => {
81                    Ok(Resolved::Str(Cow::Borrowed(scalar.value())))
82                }
83            },
84            Wanted::Bool => rules
85                .boolean(&spelled, at)
86                .map(Resolved::Bool)
87                .map_err(mismatch),
88            Wanted::Int => match rules.signed::<i128>(&spelled, at) {
89                Ok(value) => Ok(Resolved::Int(value)),
90                Err(_) => rules
91                    .unsigned::<u128>(&spelled, at)
92                    .map(Resolved::Uint)
93                    .map_err(mismatch),
94            },
95            Wanted::Float => rules
96                .float64(&spelled, at)
97                .map(Resolved::Float)
98                .map_err(mismatch),
99            Wanted::Null => rules
100                .is_null(&spelled)
101                .then_some(Resolved::Null)
102                .ok_or_else(|| Mismatch::new(wanted)),
103            Wanted::Str => match rules.string(&spelled, at).map_err(mismatch)? {
104                Cow::Owned(text) => Ok(Resolved::Str(Cow::Owned(text))),
105                Cow::Borrowed(_) => Ok(Resolved::Str(Cow::Borrowed(scalar.value()))),
106            },
107        }
108    }
109}
110
111/// The scalar rules under the strict options, built once.
112fn rules() -> &'static Rules {
113    static RULES: OnceLock<Rules> = OnceLock::new();
114    RULES.get_or_init(|| Rules::new(&options(&Limits::NONE, Reading::Strict)))
115}
116
117/// The scalar style the YAML rules read, for a style of the tree.
118fn spelled_style(style: ScalarStyle) -> Written {
119    match style {
120        ScalarStyle::Plain => Written::Plain,
121        ScalarStyle::SingleQuoted | ScalarStyle::MultilineLiteral => Written::SingleQuoted,
122        ScalarStyle::DoubleQuoted | ScalarStyle::MultilineBasic => Written::DoubleQuoted,
123        ScalarStyle::Literal => Written::Literal,
124        ScalarStyle::Folded => Written::Folded,
125    }
126}
127
128/// The style of the tree for a YAML style, one to one.
129fn style(written: Written) -> ScalarStyle {
130    match written {
131        Written::Plain => ScalarStyle::Plain,
132        Written::SingleQuoted => ScalarStyle::SingleQuoted,
133        Written::DoubleQuoted => ScalarStyle::DoubleQuoted,
134        Written::Literal => ScalarStyle::Literal,
135        Written::Folded => ScalarStyle::Folded,
136    }
137}
138
139/// The bytes of `text` at `location`: the byte offsets the parser gave, or
140/// else an empty range at the offset its line and column name, which is all
141/// the parser gives a scanner error. `None` for a location it never set.
142fn bytes(text: &str, location: Location) -> Option<Range<usize>> {
143    let span = location.span();
144    if let (Some(start), Some(length)) = (span.byte_offset(), span.byte_len()) {
145        let start = usize::try_from(start).ok()?;
146        let length = usize::try_from(length).ok()?;
147        return Some(start..start.saturating_add(length));
148    }
149    let offset = offset_of(text, location)?;
150    Some(offset..offset)
151}
152
153/// The byte offset in `text` of the 1-based line and character column of
154/// `location`, as the parser counts them: a byte order mark that starts line 1
155/// is no column. A column past the end of its line is the end of the line.
156fn offset_of(text: &str, location: Location) -> Option<usize> {
157    let line = usize::try_from(location.line()).ok()?.checked_sub(1)?;
158    let column = usize::try_from(location.column()).ok()?.checked_sub(1)?;
159    let start: usize = text.split_inclusive('\n').take(line).map(str::len).sum();
160    let content = text.get(start..)?.split('\n').next()?;
161    let (bom, counted) = match content.strip_prefix('\u{feff}') {
162        Some(rest) if start == 0 => (content.len() - rest.len(), rest),
163        _ => (0, content),
164    };
165    let within = counted
166        .char_indices()
167        .nth(column)
168        .map_or(counted.len(), |(index, _)| index);
169    Some(start + bom + within)
170}
171
172/// The bytes a node is written at. The parser locates every node it builds,
173/// so the empty range at the start is for a node it never located.
174fn placed(text: &str, location: Location) -> Range<usize> {
175    bytes(text, location).unwrap_or_default()
176}
177
178/// The tree for a located node, with each replayed node marked by the alias
179/// that brought it.
180fn convert(text: &str, node: &located::Node) -> Node {
181    let locations = node.locations();
182    let span = placed(text, locations.defined_location);
183    let built = match node {
184        located::Node::Scalar(ScalarNode {
185            value,
186            style: written,
187            ..
188        }) => Node::scalar(span, Scalar::new(value.as_str(), style(*written))),
189        located::Node::Sequence(SequenceNode { items, .. }) => {
190            Node::sequence(span, items.iter().map(|item| convert(text, item)).collect())
191        }
192        located::Node::Mapping(MappingNode { entries, .. }) => Node::mapping(
193            span,
194            entries
195                .iter()
196                .map(|(key, value)| (convert(text, key), convert(text, value)))
197                .collect(),
198        ),
199    };
200    let built = match node.tag() {
201        Some(tag) => built.with_tag(Tag::new(tag)),
202        None => built,
203    };
204    if locations.reference_location == locations.defined_location {
205        built
206    } else {
207        built.with_used_at(placed(text, locations.reference_location))
208    }
209}
210
211/// The refusal for `error`, by its variant. An alias error sits at the alias
212/// and names where its value is defined, from the error the aliased value
213/// raised, found under any alias reached through another alias.
214fn refusal(text: &str, limits: &Limits, error: &Error) -> Refusal {
215    let mut error = error;
216    while let Error::WithSnippet { error: inner, .. } = error {
217        error = inner;
218    }
219    let Error::AliasError {
220        error: inner,
221        locations,
222        ..
223    } = error
224    else {
225        let span = error
226            .location()
227            .filter(|at| *at != Location::UNKNOWN)
228            .and_then(|at| bytes(text, at));
229        return Refusal::new(fault(text, limits, error), span, None);
230    };
231    let mut failing = inner.as_ref();
232    while let Error::AliasError { error, .. } | Error::WithSnippet { error, .. } = failing {
233        failing = error;
234    }
235    let defined = failing
236        .location()
237        .filter(|at| *at != Location::UNKNOWN)
238        .unwrap_or(locations.defined_location);
239    Refusal::new(
240        fault(text, limits, failing),
241        bytes(text, locations.reference_location),
242        bytes(text, defined),
243    )
244}
245
246/// The fault for `error`, by its variant and never by its text. A key that has
247/// no text of its own reads as it is written.
248#[expect(
249    clippy::wildcard_enum_match_arm,
250    reason = "Error is non_exhaustive: any other error is a syntax fault with serde-saphyr's wording"
251)]
252fn fault(text: &str, limits: &Limits, error: &Error) -> Fault {
253    match error {
254        Error::DuplicateMappingKey { key, location } => Fault::DuplicateKey {
255            key: key.clone().unwrap_or_else(|| {
256                bytes(text, *location)
257                    .and_then(|range| text.get(range))
258                    .unwrap_or_default()
259                    .to_owned()
260            }),
261        },
262        Error::MergeKeyNotAllowed { .. } => Fault::MergeKey,
263        Error::MultipleDocuments { .. } => Fault::Syntax {
264            detail: "the text holds more than one YAML document".to_owned(),
265        },
266        _ => Exceeded::of(
267            error,
268            &limits.budget(),
269            &limits.alias_limits(),
270            Raise::FOR_TEXT,
271        )
272        .map_or_else(
273            || Fault::Syntax {
274                detail: plain(&DefaultMessageFormatter.with_localizer(&Unplaced), error),
275            },
276            |exceeded| exceeded.fault(),
277        ),
278    }
279}
280
281/// What every read of a YAML text uses, under `limits`: its budget and its
282/// alias replay limits. A [`Reading::Listing`] also reads a non-finite float
283/// as a value.
284fn options(limits: &Limits, reading: Reading) -> Options {
285    let (duplicates, merges, floats) = match reading {
286        Reading::Strict => (
287            DuplicateKeyPolicy::Error,
288            MergeKeyPolicy::Error,
289            NonFiniteFloatPolicy::Default,
290        ),
291        Reading::Listing => (
292            DuplicateKeyPolicy::PassThrough,
293            MergeKeyPolicy::AsOrdinary,
294            NonFiniteFloatPolicy::PassThrough,
295        ),
296    };
297    serde_saphyr::options! {
298        budget: Some(limits.budget()),
299        alias_limits: limits.alias_limits(),
300        strict_booleans: true,
301        duplicate_keys: duplicates,
302        merge_keys: merges,
303        non_finite_float_policy: floats,
304        with_snippet: false,
305    }
306}
307
308/// serde-saphyr's wording for `error`, with each control character escaped
309/// as serde-saphyr's renderer escapes it.
310///
311/// It takes the text from [`MessageFormatter::format_message`] and never calls
312/// the renderer, whose snippet code would otherwise stay in every binary that
313/// loads input. The loader turns snippets off, so the renderer writes the same
314/// line ([vsh-serde-saphyr 0.0.1][plain]).
315///
316/// [plain]: https://docs.rs/crate/vsh-serde-saphyr/0.0.2/source/src/de/error.rs#1970
317fn plain(formatter: &dyn MessageFormatter, mut error: &Error) -> String {
318    while let Error::AliasError { error: inner, .. } | Error::WithSnippet { error: inner, .. } =
319        error
320    {
321        error = inner;
322    }
323    printable(&formatter.format_message(error))
324}
325
326/// serde-saphyr's wording without the position it appends. That position
327/// counts from the parsed text, which for frontmatter is not the file, and a
328/// [`Refusal`] already carries the bytes it sits at.
329struct Unplaced;
330
331impl Localizer for Unplaced {
332    fn attach_location<'a>(&self, base: Cow<'a, str>, _: Location) -> Cow<'a, str> {
333        base
334    }
335
336    fn alias_used_at(&self, _: Location) -> String {
337        String::new()
338    }
339}