Skip to main content

serde_saphyr/de/
options.rs

1use crate::budget::Budget;
2use crate::indentation::RequireIndent;
3#[cfg(feature = "properties")]
4use std::collections::HashMap;
5#[cfg(feature = "include_fs")]
6use std::io;
7#[cfg(feature = "include_fs")]
8use std::path::Path;
9use std::rc::Rc;
10
11#[cfg(all(feature = "serde_derived_types", feature = "comments"))]
12const fn default_emit_comments() -> bool {
13    true
14}
15
16/// Duplicate key handling policy for mappings.
17///
18/// Except with [`Self::PassThrough`], YAML integer keys are compared by their
19/// parsed integer value, so `0xB` and `11` are duplicates even when the target
20/// key type is `String`. The retained key preserves its original spelling when
21/// deserialized into a string. Merge expansion always uses YAML key identity.
22#[non_exhaustive]
23#[derive(Clone, Copy, Debug)]
24#[cfg_attr(
25    feature = "serde_derived_types",
26    derive(serde::Serialize, serde::Deserialize)
27)]
28#[cfg_attr(feature = "serde_derived_types", serde(rename_all = "snake_case"))]
29pub enum DuplicateKeyPolicy {
30    /// Error out on encountering a duplicate key.
31    Error,
32    /// First key wins: later duplicate pairs are skipped (key+value are consumed and ignored).
33    FirstWins,
34    /// Last key wins: retain the later value. Struct fields are buffered and
35    /// collapsed before Serde sees them. Maps stream until an integer-containing
36    /// key requires numeric comparison, then buffer the remaining entries to
37    /// retain the last key's original spelling and value.
38    LastWins,
39    /// Forward repeated explicit mapping entries to the receiving Serde visitor.
40    ///
41    /// This matches `serde_yaml`'s visitor-driven handling of explicit entries:
42    /// derived structs reject repeated fields, standard maps keep the last value,
43    /// and custom visitors decide whether to reject, replace, or retain duplicates.
44    /// Integer-equivalent keys such as `0xB` and `11` are also forwarded separately.
45    ///
46    /// Merge expansion still follows [`MergeKeyPolicy`] and suppresses overridden
47    /// entries. Repeated keys within a merge source retain the first entry. Use
48    /// [`MergeKeyPolicy::AsOrdinary`] to forward literal `<<` entries as well.
49    ///
50    /// This is a permissive extension: YAML requires unique mapping keys.
51    /// [`Self::Error`] remains the default.
52    PassThrough,
53}
54
55/// Handling of non-finite floats in `deserialize_any`.
56///
57/// By default, non-finite floats are rejected. This policy applies to inferred values,
58/// including Serde's buffering for untagged enums and flattened fields. Direct `f32`/`f64`
59/// deserialization is unaffected.
60#[non_exhaustive]
61#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
62#[cfg_attr(
63    feature = "serde_derived_types",
64    derive(serde::Serialize, serde::Deserialize)
65)]
66#[cfg_attr(feature = "serde_derived_types", serde(rename_all = "snake_case"))]
67pub enum NonFiniteFloatPolicy {
68    // Compatibility sentinel: defer to the deprecated boolean until it is removed,
69    // then use the unconfigured policy (Reject).
70    #[doc(hidden)]
71    #[default]
72    Default,
73    /// Pass NaN and positive/negative infinity to the visitor as `f64` values.
74    ///
75    /// The receiving visitor determines how to represent them. For example,
76    /// `serde_json::Value` converts them to `Null` without returning an error.
77    PassThrough,
78    /// Return [`crate::Error::NonFiniteFloat`] before calling the visitor.
79    Reject,
80    /// Pass canonical strings (`.nan`, `.inf`, `-.inf`) to the visitor.
81    AsString,
82}
83
84/// Syntax and expansion rules for `${NAME}` / `$NAME` property interpolation.
85#[cfg(feature = "properties")]
86#[non_exhaustive]
87#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
88#[cfg_attr(
89    feature = "serde_derived_types",
90    derive(serde::Serialize, serde::Deserialize)
91)]
92#[cfg_attr(feature = "serde_derived_types", serde(rename_all = "snake_case"))]
93pub enum PropertySyntax {
94    /// Only the braced `${NAME}` form is interpolated. Bare `$NAME` stays literal.
95    #[default]
96    Braced,
97
98    /// Both `${NAME}` and the unbraced shorthand `$NAME` are interpolated.
99    /// The unbraced form uses Required semantics (missing values error).
100    BracedOrBare,
101
102    /// Property interpolation compatible with [Docker Compose]'s syntax and value expansion.
103    /// [Docker Compose]: https://docs.docker.com/reference/compose-file/interpolation/
104    DockerCompose,
105
106    /// [`DockerCompose`](Self::DockerCompose) interpolation, except that an expanded value
107    /// can become YAML null:
108    ///
109    /// - A value consisting solely of `$NAME` or `${NAME}` is null when `NAME` is unset.
110    /// - A value whose expansion is exactly `null`, `Null`, `NULL`, or `~` is null.
111    ///
112    /// Everything else keeps the Compose behavior: an explicitly empty property and an empty
113    /// selected default (`${A:-${B}}` with both unset) are empty strings, surrounding text is
114    /// kept (`prefix-$MISSING` is `prefix-`), and numbers and booleans convert as before.
115    ///
116    /// The rules apply to the scalar's text whatever its style, so a quoted `"$NAME"` is null
117    /// as well, while a `|` block keeps its trailing newline and is therefore not a sole
118    /// reference. String-forcing tags (`!!str`, `!`) and other explicit tags keep their
119    /// meaning, and scalars without an expansion are resolved exactly as in other modes.
120    DockerComposeWithNulls,
121}
122
123#[cfg(feature = "properties")]
124impl PropertySyntax {
125    /// Whether this syntax uses Docker Compose interpolation rules.
126    pub(crate) const fn is_docker_compose(self) -> bool {
127        matches!(self, Self::DockerCompose | Self::DockerComposeWithNulls)
128    }
129}
130
131/// Merge key handling policy for YAML mappings.
132#[non_exhaustive]
133#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
134#[cfg_attr(
135    feature = "serde_derived_types",
136    derive(serde::Serialize, serde::Deserialize)
137)]
138#[cfg_attr(feature = "serde_derived_types", serde(rename_all = "snake_case"))]
139pub enum MergeKeyPolicy {
140    /// Expand YAML merge keys (`<<` and explicit `!!merge <<`) into the surrounding mapping,
141    /// as per the YAML 1.1 specification.
142    #[default]
143    Merge,
144
145    /// Treat YAML merge keys (`<<` and explicit `!!merge <<`) as ordinary mapping keys.
146    AsOrdinary,
147
148    /// Error out on encountering a YAML merge key (`<<` or explicit `!!merge <<`), reporting
149    /// the location.
150    Error,
151}
152
153/// Limits applied to alias replay to harden against alias bombs.
154///
155/// These limits also apply while aliases are expanded from anchored `!include` fragments.
156///
157/// Prefer constructing this via the [`alias_limits!`](crate::alias_limits!) macro instead of a
158/// struct literal. This keeps call sites stable if new fields are added in the future.
159///
160/// ```rust
161/// # #[cfg(feature = "deserialize")]
162/// # {
163/// let limits = serde_saphyr::alias_limits! {
164///     max_replay_stack_depth: 32,
165/// };
166///
167/// assert_eq!(limits.max_replay_stack_depth, 32);
168/// # }
169/// ```
170#[non_exhaustive]
171#[derive(Clone, Copy, Debug)]
172#[cfg_attr(
173    feature = "serde_derived_types",
174    derive(serde::Serialize, serde::Deserialize)
175)]
176pub struct AliasLimits {
177    /// Maximum total number of **replayed** events injected from aliases across the entire parse.
178    /// When exceeded, deserialization errors (alias replay limit exceeded).
179    pub max_total_replayed_events: usize,
180    /// Maximum depth of the alias replay stack (nested alias → injected buffer → alias, etc.).
181    pub max_replay_stack_depth: usize,
182    /// Maximum number of times a **single anchor id** may be expanded via alias.
183    /// Use `usize::MAX` for "unlimited".
184    pub max_alias_expansions_per_anchor: usize,
185}
186
187impl Default for AliasLimits {
188    fn default() -> Self {
189        Self {
190            max_total_replayed_events: 1_000_000,
191            max_replay_stack_depth: 64,
192            max_alias_expansions_per_anchor: usize::MAX,
193        }
194    }
195}
196
197/// Parser configuration options.
198///
199/// Use this to configure comment emission, duplicate-key policy, alias-replay limits, and an
200/// optional pre-parse YAML [`Budget`].
201///
202/// Example: parse a small `Config` using custom `Options`.
203///
204/// ```rust
205/// use serde::Deserialize;
206///
207/// use serde_saphyr::options::DuplicateKeyPolicy;
208/// use serde_saphyr::{from_str_with_options, Budget, Options};
209///
210/// #[derive(Deserialize)]
211/// struct Config {
212///     name: String,
213///     enabled: bool,
214///     retries: i32,
215/// }
216///
217/// let yaml = r#"
218/// name: My Application
219/// enabled: true
220/// retries: 5
221/// "#;
222///
223/// let options = serde_saphyr::options! {
224///     budget: serde_saphyr::budget! {
225///         max_documents: 2,
226///     },
227///     duplicate_keys: DuplicateKeyPolicy::LastWins,
228/// };
229///
230/// let cfg: Config = from_str_with_options(yaml, options).unwrap();
231/// assert_eq!(cfg.name, "My Application");
232/// ```
233#[non_exhaustive]
234#[derive(Clone)]
235#[cfg_attr(
236    feature = "serde_derived_types",
237    derive(serde::Serialize, serde::Deserialize)
238)]
239pub struct Options {
240    /// Optional YAML budget enforced during parsing and deserialization, including raw events,
241    /// retained anchor copies, and property interpolation. `None` disables budget enforcement.
242    pub budget: Option<Budget>,
243    /// Optional callback invoked with the final budget report after parsing.
244    /// It is invoked both when parsing is successful and when budget was breached.
245    #[cfg_attr(feature = "serde_derived_types", serde(skip))]
246    pub budget_report: Option<fn(&crate::budget::BudgetReport)>,
247
248    /// Invoked both when parsing is successful and when budget was breached.
249    #[cfg_attr(feature = "serde_derived_types", serde(skip))]
250    pub budget_report_cb: Option<BudgetReportCallback>,
251
252    /// Whether the parser emits comment events for deserialization.
253    ///
254    /// The default is `true`. When this is `false`, comments are still recognized and validated
255    /// as YAML syntax, but their text is not captured and [`crate::Commented`] values receive an
256    /// empty comment string.
257    /// Comment bytes are still consumed and validated, so disabling emission is not an input-size
258    /// or processing-time limit.
259    ///
260    /// Comment-related budget accounting follows emitted, retained parser data. Setting this to
261    /// `false` also:
262    ///
263    /// - disables enforcement of [`Budget::max_total_comment_bytes`];
264    /// - makes [`Budget::max_buffered_comment_events`] ineffective;
265    /// - excludes comments from [`Budget::max_events`]; and
266    /// - keeps [`crate::budget::BudgetReport::total_comment_bytes`] at zero.
267    #[cfg_attr(
268        feature = "serde_derived_types",
269        serde(default = "default_emit_comments")
270    )]
271    #[cfg(feature = "comments")]
272    pub emit_comments: bool,
273
274    /// Enforce YAML indentation rules for flow collections (`[...]` and `{...}`)
275    /// and scalar continuations.
276    ///
277    /// When enabled, flow entries, delimiters, and scalar continuation lines must be
278    /// indented beyond the enclosing block collection. Quoted scalar continuations
279    /// in block context must also be indented and cannot use tabs for indentation.
280    /// Applies to included YAML as well. Default: false (accept under-indented flow
281    /// collections and relaxed quoted scalar continuations for compatibility).
282    ///
283    /// Accepted with `strict_indentation: true`: entries and closing delimiters are
284    /// indented beyond the enclosing block mapping.
285    ///
286    /// ```yaml
287    /// sequence: [
288    ///   first,
289    ///   second
290    ///  ]
291    /// mapping: {
292    ///   first: one,
293    ///   second: two
294    ///  }
295    /// ```
296    ///
297    /// Accepted with `strict_indentation: false`, but rejected with `true` because
298    /// the closing delimiters are at the same indentation as the enclosing block mapping:
299    ///
300    /// ```yaml
301    /// sequence: [
302    ///   first,
303    ///   second
304    /// ]
305    /// mapping: {
306    ///   first: one,
307    ///   second: two
308    /// }
309    /// ```
310    ///
311    /// Relaxed mode also accepts under-indented entries, not just closing delimiters.
312    /// This is accepted with `strict_indentation: false`, but rejected with `true`
313    /// at the unindented `"value"` entry:
314    ///
315    /// ```yaml
316    /// key: [
317    /// "value",
318    /// ]
319    /// ```
320    #[cfg_attr(feature = "serde_derived_types", serde(default))]
321    pub strict_indentation: bool,
322
323    /// Treat a byte-order mark (U+FEFF) at the start of a token inside a document
324    /// as the start of a plain scalar, preserving it in the scalar's text.
325    ///
326    /// Default: false (report a parser error for such a BOM). When enabled, this
327    /// matches libyaml's behavior and applies to included YAML as well. A BOM in
328    /// a document prefix is still skipped. BOMs within an existing plain or quoted
329    /// scalar remain content in either mode.
330    ///
331    /// A preserved BOM is part of a mapping key, so `\u{FEFF}key` does not match
332    /// a struct field named `key`.
333    #[cfg_attr(feature = "serde_derived_types", serde(default))]
334    pub bom_inside_document_as_content: bool,
335
336    /// Policy for duplicate keys.
337    pub duplicate_keys: DuplicateKeyPolicy,
338    /// Policy for YAML merge keys (`<<` and explicit `!!merge <<`).
339    ///
340    /// [`MergeKeyPolicy::Merge`] expands merge keys and counts them against
341    /// [`Budget::max_merge_keys`]. [`MergeKeyPolicy::AsOrdinary`] accepts `<<`
342    /// as a regular key. [`MergeKeyPolicy::Error`] rejects merge keys.
343    ///
344    /// Default: [`MergeKeyPolicy::Merge`].
345    #[cfg_attr(feature = "serde_derived_types", serde(default))]
346    pub merge_keys: MergeKeyPolicy,
347    /// Limits for alias replay to harden against alias bombs.
348    pub alias_limits: AliasLimits,
349    /// Enable legacy octal parsing where values starting with `0` are treated as base-8.
350    /// They are deprecated in YAML 1.2. Default: false.
351    pub legacy_octal_numbers: bool,
352    /// Preserve plain decimal integer spellings with redundant leading zeros as
353    /// strings during implicit type inference (`deserialize_any`).
354    ///
355    /// Examples include `0755`, `-007`, and `+00`. Floating-point spellings such as
356    /// `0.5`, `00.5`, and `01e2`, and explicit radix prefixes, are unaffected.
357    /// This supports compatibility with `serde_yaml` when reading untyped values.
358    /// Default: false.
359    ///
360    /// Applies to untyped values and Serde's buffering for untagged enums and
361    /// flattened fields. Takes precedence over [`Self::legacy_octal_numbers`]
362    /// during inference. Direct typed deserialization, explicit `!!int`/`!!float`
363    /// tags, and mapping-key equality retain their existing behavior.
364    #[cfg_attr(feature = "serde_derived_types", serde(default))]
365    pub leading_zero_numbers_as_strings: bool,
366    /// Preserve plain scalars containing underscores as strings during implicit
367    /// type inference (`deserialize_any`), including numeric spellings such as
368    /// `1_000`, `0xFF_FF`, and `0b10_01`.
369    ///
370    /// This supports compatibility with `serde_yaml` when reading untyped values.
371    /// It also applies to untagged enums and flattened fields, and takes precedence
372    /// over [`Self::legacy_octal_numbers`] during inference. Direct typed
373    /// deserialization, explicit `!!int`/`!!float` tags, and mapping-key equality
374    /// retain their existing behavior. Default: false.
375    #[cfg_attr(feature = "serde_derived_types", serde(default))]
376    pub underscored_numbers_as_strings: bool,
377    /// If true, accept only YAML 1.2 Core boolean spellings:
378    /// `true`, `True`, `TRUE`, `false`, `False`, and `FALSE`.
379    /// Other spellings, including YAML 1.1 forms such as `yes`/`no`/`on`/`off`,
380    /// are rejected for boolean targets and are not inferred as booleans.
381    /// Default: false (accept YAML 1.1 boolean forms).
382    pub strict_booleans: bool,
383    /// Preserve plain null-like scalars (`null`, `Null`, `NULL`, `~`, and empty)
384    /// as their text when deserializing directly into a string target.
385    ///
386    /// Applies to both mapping keys and values, including `String`, `&str`, and
387    /// `Cow<str>`. Borrowed targets retain the usual input borrowing requirements.
388    /// Default: false (reject null-like scalars for string targets).
389    ///
390    /// Explicit `!!null` tags remain errors for string targets. `Option<T>`, unit,
391    /// and implicit type inference (`deserialize_any`, including untyped values,
392    /// untagged enums, and flattened fields) retain their existing null semantics.
393    /// [`Self::no_schema`] still requires ambiguous plain strings to be quoted.
394    #[cfg_attr(feature = "serde_derived_types", serde(default))]
395    pub null_as_string: bool,
396    /// When a field marked with the `!!binary` tag is deserialized into a `String`,
397    /// `serde-saphyr` normally expects the value to be base64-encoded UTF-8.
398    /// If you want to treat the value as a plain string and ignore the `!!binary` tag,
399    /// set this to `true` (the default is `false`).
400    pub ignore_binary_tag_for_string: bool,
401    /// Activates YAML conventions common in robotics community. These extensions support
402    /// conversion functions (deg, rad) and simple mathematical expressions such as deg(180),
403    /// rad(pi), 1 + 2*(3 - 4/5), or rad(pi/2). `robotics` feature must also be enabled.
404    /// The `!degrees`, `!radians`, and `!time` tags select floating-point conversions.
405    /// `!time` represents a duration in seconds; the standard `!!timestamp` tag does not.
406    pub angle_conversions: bool,
407    /// If true, values that can be parsed as booleans or numbers are rejected as
408    /// unquoted strings. This flag is intended for teams that want to enforce
409    /// compatibility with YAML parsers that infer types from unquoted values,
410    /// requiring such strings to be explicitly quoted.
411    /// Signed NaN spellings such as `+.nan` and `-.nan` remain strings, matching
412    /// implicit inference, even though direct float targets accept them as NaN.
413    /// The default is false (a number or boolean will be stored in the string
414    /// field exactly as provided, without quoting).
415    pub no_schema: bool,
416
417    /// Reject explicitly specified YAML tags that `serde-saphyr` does not recognize.
418    ///
419    /// This includes application-specific local and global tags. YAML 1.1 `!!merge`
420    /// and `!!value` tags are accepted only on their exact scalar mapping keys, `<<`
421    /// and `=` respectively. Known scalar, sequence, and mapping tags are accepted
422    /// only on matching node kinds; this node-kind requirement is enforced regardless
423    /// of this option. Robotics-only `!degrees`, `!radians`, and `!time` tags are
424    /// supported only when the `robotics` crate feature and
425    /// [`Self::angle_conversions`] are both enabled. The `!include` tag is supported
426    /// only when the `include` crate feature is enabled and an include resolver is
427    /// configured.
428    ///
429    /// Default: false (preserve unsupported tags for compatibility with tagged enums
430    /// and otherwise ignore them where possible).
431    #[cfg_attr(feature = "serde_derived_types", serde(default))]
432    pub reject_unsupported_tags: bool,
433
434    /// Reject explicit tags on struct field names, except standard string tags.
435    ///
436    /// A derived struct normally matches each mapping key by its text alone. A
437    /// custom tag on that key can therefore be discarded without the struct ever
438    /// seeing it. Such a tag has no effect on field selection and may be a value
439    /// annotation accidentally placed on the field name. Enable this option to
440    /// report [`crate::Error::TaggedStructFieldName`] instead of silently accepting it.
441    ///
442    /// For example, an application can inspect a value's `!secret` tag by reading
443    /// that value as [`crate::Tagged<T>`]:
444    ///
445    /// ```yaml
446    /// password: !secret API_TOKEN
447    /// ```
448    ///
449    /// This misplaced annotation is rejected when the option is enabled:
450    ///
451    /// ```yaml
452    /// !secret password: API_TOKEN
453    /// ```
454    ///
455    /// Untagged and quoted field names remain accepted. Explicit standard string tags
456    /// (`!!str`, including equivalent verbatim or directive-expanded forms) and
457    /// the non-specific `!` tag are also accepted. Field names are the external
458    /// strings used by Serde: `!!str 0.0: Alice` can populate a Rust field marked
459    /// `#[serde(rename = "0.0")]`. Here `!!str` explicitly gives `0.0` string
460    /// semantics, and Serde's rename handles the external field name.
461    /// The exception uses the resolved tag identity; a local `!str` tag is still
462    /// rejected, including when a directive rebinds `!!` to an application namespace.
463    ///
464    /// This option applies only to struct mappings entered through Serde's
465    /// `deserialize_struct`, including externally tagged struct enum variants.
466    /// It checks every key in such a mapping, including unknown keys that Serde
467    /// would otherwise ignore without `#[serde(deny_unknown_fields)]`.
468    /// It also checks field names replayed through aliases and expanded merges.
469    /// Keys are checked before duplicate-key or merge precedence filtering, even
470    /// when their values would otherwise be discarded.
471    /// Ordinary map keys, including string, numeric, and enum keys, and tags on
472    /// values retain their existing behavior. Unlike
473    /// [`Self::reject_unsupported_tags`], it does not reject application tags
474    /// throughout the document.
475    /// Tags consumed by enabled preprocessing, such as `!include`, retain that
476    /// behavior before this check.
477    ///
478    /// Serde can match fields without calling `deserialize_struct`: structs using
479    /// `#[serde(flatten)]` enter through `deserialize_map`, while internally tagged
480    /// and untagged enums buffer their fields first. Adjacently tagged enums also
481    /// buffer content that precedes the discriminator. Fields handled by those
482    /// paths, including structs nested in their buffers, are not covered by this
483    /// option; it is not a document-wide guarantee against tagged field names.
484    ///
485    /// Default: false (retain existing field-name handling).
486    #[cfg_attr(feature = "serde_derived_types", serde(default))]
487    pub reject_tagged_field_names: bool,
488
489    /// Handling of NaN, positive/negative infinity, and decimal literals that overflow
490    /// `f64` (e.g. `1e999`) in `deserialize_any`.
491    ///
492    /// If left at its default, this uses [`Self::reject_non_finite_typeless_float`],
493    /// preserving rejection by default and string conversion when that legacy flag is
494    /// false. Explicit [`NonFiniteFloatPolicy::PassThrough`], [`NonFiniteFloatPolicy::Reject`],
495    /// and [`NonFiniteFloatPolicy::AsString`] values override the legacy flag.
496    ///
497    /// `PassThrough` lets float-capable visitors preserve non-finite values, including
498    /// untagged enums and flattened float fields. `serde_json::Value` instead converts
499    /// them to `Null` without an error. `Reject` prevents that loss; `AsString` passes
500    /// canonical strings (`.nan`, `.inf`, `-.inf`) to the visitor.
501    ///
502    /// Untagged quoted scalars and `!!str` scalars remain strings under every policy.
503    /// Direct `f32`/`f64` targets are unaffected: YAML non-finite spellings remain
504    /// accepted, while overflowing decimal/exponential literals remain invalid.
505    #[cfg_attr(feature = "serde_derived_types", serde(default))]
506    pub non_finite_float_policy: NonFiniteFloatPolicy,
507
508    /// Legacy handling of non-finite floats in `deserialize_any`.
509    ///
510    /// When [`Self::non_finite_float_policy`] is left at its default, true (the default)
511    /// rejects non-finite floats and false converts them to canonical strings.
512    /// An explicit policy overrides this flag.
513    ///
514    /// [`Options::default()`] sets this to true. When deserializing options with
515    /// `serde_derived_types`, an omitted flag defaults to false for compatibility
516    /// with 1.3.0. If the policy is also omitted, non-finite values become strings.
517    ///
518    /// Use [`Self::non_finite_float_policy`] with [`NonFiniteFloatPolicy::Reject`] instead
519    /// of true, or [`NonFiniteFloatPolicy::AsString`] instead of false.
520    #[deprecated(since = "2.0.0", note = "use non_finite_float_policy instead")]
521    #[cfg_attr(feature = "serde_derived_types", serde(default))]
522    pub reject_non_finite_typeless_float: bool,
523
524    /// If true (default), public APIs that have access to the original YAML input
525    /// will wrap returned errors with a snippet wrapper, enabling rustc-like snippet
526    /// rendering when a location is available.
527    pub with_snippet: bool,
528
529    /// Horizontal crop radius (in character columns) when rendering snippet diagnostics.
530    ///
531    /// The renderer crops all displayed lines (including the context lines) to the same
532    /// column window around the reported error column, so they stay vertically aligned.
533    ///
534    /// If set to `0`, snippet wrapping is disabled (the original, unwrapped error is returned).
535    pub crop_radius: usize,
536
537    /// Indentation requirement for the parsed document.
538    pub require_indent: RequireIndent,
539
540    /// Optional include resolver callback.
541    ///
542    /// When provided, it can push parsers onto the internal parser stack to resolve `!include`
543    ///-like constructs.
544    #[cfg(feature = "include")]
545    #[cfg_attr(feature = "serde_derived_types", serde(skip))]
546    pub include_resolver: Option<IncludeResolverCallback>,
547
548    /// A map of properties to substitute in scalar values.
549    /// Used for docker-compose-style interpolation like `${VAR}`.
550    #[cfg(feature = "properties")]
551    #[cfg_attr(feature = "serde_derived_types", serde(skip))]
552    pub property_map: Option<Rc<HashMap<String, String>>>,
553
554    /// Which property-interpolation syntaxes are recognized.
555    /// Defaults to [`PropertySyntax::Braced`] (only `${NAME}`).
556    #[cfg(feature = "properties")]
557    #[cfg_attr(feature = "serde_derived_types", serde(default))]
558    pub property_syntax: PropertySyntax,
559}
560
561#[cfg(feature = "include")]
562pub type IncludeResolverCallback = Rc<
563    std::cell::RefCell<
564        dyn for<'res> FnMut(
565                crate::input_source::IncludeRequest<'res>,
566            )
567                -> Result<crate::ResolvedInclude, crate::IncludeResolveError>
568            + 'static,
569    >,
570>;
571
572pub type BudgetReportCallback =
573    Rc<std::cell::RefCell<dyn FnMut(crate::budget::BudgetReport) + 'static>>;
574
575impl Options {
576    pub(crate) fn parser_options(&self) -> granit_parser::Options {
577        let default_budget = Budget::default();
578        let budget = self.budget.as_ref().unwrap_or(&default_budget);
579        let mut parser_options = budget.parser_options();
580        #[cfg(feature = "comments")]
581        {
582            parser_options.emit_comments = self.emit_comments;
583        }
584        parser_options.strict_indentation = self.strict_indentation;
585        parser_options.bom_inside_document_as_content = self.bom_inside_document_as_content;
586        parser_options
587    }
588
589    pub(crate) fn validate(&self) -> Result<(), crate::de_error::Error> {
590        self.require_indent.validate()
591    }
592
593    /// Registers a budget-report callback. Any closure can be used,  including ones that
594    /// capture state from the surrounding scope.
595    ///
596    /// The callback is invoked with the final [`crate::budget::BudgetReport`] after parsing
597    /// completes, both on success and when the budget is breached.
598    ///
599    /// ```rust
600    /// use serde_saphyr::options;
601    /// use serde_saphyr::budget::BudgetReport;
602    ///
603    /// let options = options! {}.with_budget_report(|report: BudgetReport| {
604    ///     // e.g. update your state / emit metrics / log the report
605    ///     let _ = report;
606    /// });
607    /// ```
608    #[must_use]
609    pub fn with_budget_report<F>(mut self, cb: F) -> Self
610    where
611        F: FnMut(crate::budget::BudgetReport) + 'static,
612    {
613        self.budget_report_cb = Some(Rc::new(std::cell::RefCell::new(cb)));
614        self
615    }
616
617    /// Installs a property map used for `${NAME}` interpolation.
618    ///
619    /// [`PropertySyntax::DockerCompose`] and [`PropertySyntax::DockerComposeWithNulls`] also
620    /// interpolate quoted and block string values; the other modes interpolate only plain scalars.
621    ///
622    /// This is the intended public API for the `properties` feature. It consumes the provided
623    /// [`HashMap`] and stores it in the internal shared representation used by nested
624    /// deserializers, so callers do not have to construct `Rc` or `Some(...)` manually.
625    ///
626    /// ```rust
627    /// # #[cfg(feature = "properties")]
628    /// # {
629    /// use std::collections::HashMap;
630    /// use serde_saphyr::Options;
631    ///
632    /// let mut properties = HashMap::new();
633    /// properties.insert("MODE".to_string(), "production".to_string());
634    ///
635    /// let options = Options::default().with_properties(properties);
636    /// # let _ = options;
637    /// # }
638    /// ```
639    #[cfg(feature = "properties")]
640    #[must_use]
641    pub fn with_properties(mut self, properties: HashMap<String, String>) -> Self {
642        self.property_map = Some(Rc::new(properties));
643        self
644    }
645
646    /// Sets the include resolver callback to be used during parsing.
647    ///
648    /// This method is for advances use cases. If you just want to include files from the
649    /// filesystem, use [`Options::with_filesystem_root`] instead that will use [`crate::SafeFileResolver`]
650    ///
651    /// The callback is invoked each time the parser encounters a `!include` tag. It receives an
652    /// [`crate::input_source::IncludeRequest`] describing the requested include target, the source
653    /// that triggered it, the include stack, and the source location. The callback must then
654    /// return either a [`crate::ResolvedInclude`] or a [`crate::IncludeResolveError`].
655    ///
656    /// This is useful for virtual filesystems, embedded configuration bundles, network-backed
657    /// resolvers, or custom caching layers.
658    ///
659    /// ```rust
660    /// # #[cfg(feature = "include")]
661    /// # {
662    /// use serde::Deserialize;
663    /// use serde_saphyr::{
664    ///     from_str_with_options, options, IncludeRequest, IncludeResolveError, InputSource,
665    ///     ResolvedInclude,
666    /// };
667    ///
668    /// #[derive(Debug, Deserialize, PartialEq)]
669    /// struct Config {
670    ///     users: Vec<User>,
671    /// }
672    ///
673    /// #[derive(Debug, Deserialize, PartialEq)]
674    /// struct User {
675    ///     name: String,
676    /// }
677    ///
678    /// let root_yaml = "users: !include virtual://users.yaml\n";
679    /// let users_yaml = "- name: Alice\n- name: Bob\n";
680    ///
681    /// let options = options! {}.with_include_resolver(|req: IncludeRequest<'_>| {
682    ///     assert_eq!(req.spec, "virtual://users.yaml");
683    ///     assert_eq!(req.from_name, "<input>");
684    ///
685    ///     if req.spec == "virtual://users.yaml" {
686    ///         Ok(ResolvedInclude::new(
687    ///             req.spec,
688    ///             "virtual users",
689    ///             InputSource::from_string(users_yaml.to_owned()),
690    ///         ))
691    ///     } else {
692    ///         Err(IncludeResolveError::Message(format!("unknown include: {}", req.spec)))
693    ///     }
694    /// });
695    ///
696    /// let config: Config = from_str_with_options(root_yaml, options).unwrap();
697    /// assert_eq!(config.users.len(), 2);
698    /// assert_eq!(config.users[0].name, "Alice");
699    /// # }
700    /// ```
701    #[cfg(feature = "include")]
702    #[must_use]
703    pub fn with_include_resolver<F>(mut self, cb: F) -> Self
704    where
705        F: for<'res> FnMut(
706                crate::input_source::IncludeRequest<'res>,
707            )
708                -> Result<crate::ResolvedInclude, crate::IncludeResolveError>
709            + 'static,
710    {
711        self.include_resolver = Some(Rc::new(std::cell::RefCell::new(cb)));
712        self
713    }
714
715    /// Configures a [`crate::SafeFileResolver`] rooted at `path` for `!include` lookups.
716    ///
717    /// This is a convenience for:
718    ///
719    /// ```rust,no_run
720    /// # #[cfg(feature = "include_fs")]
721    /// # fn main() -> Result<(), std::io::Error> {
722    /// # use serde_saphyr::{options, SafeFileResolver};
723    /// let options = options! {}
724    ///     .with_include_resolver(SafeFileResolver::new("./configs")?.into_callback());
725    /// # let _ = options;
726    /// # Ok(())
727    /// # }
728    /// ```
729    ///
730    /// It enables filesystem-backed `!include` resolution.
731    ///
732    /// ```rust,no_run
733    /// # #[cfg(feature = "include_fs")]
734    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
735    /// use serde::Deserialize;
736    /// use serde_saphyr::{from_str_with_options, options};
737    ///
738    /// #[derive(Debug, Deserialize)]
739    /// struct User {
740    ///     name: String,
741    /// }
742    ///
743    /// #[derive(Debug, Deserialize)]
744    /// struct Config {
745    ///     users: Vec<User>,
746    /// }
747    ///
748    /// let yaml = "users: !include#users value.yaml\n";
749    /// let options = options! {}.with_filesystem_root("./examples")?;
750    /// let config: Config = from_str_with_options(yaml, options)?;
751    /// # let _ = config;
752    /// # Ok(())
753    /// # }
754    /// ```
755    #[cfg(feature = "include_fs")]
756    pub fn with_filesystem_root<P>(self, path: P) -> io::Result<Self>
757    where
758        P: AsRef<Path>,
759    {
760        Ok(self.with_include_resolver(crate::SafeFileResolver::new(path)?.into_callback()))
761    }
762}
763
764#[allow(deprecated)] // Preserve the legacy default while the new field is unconfigured.
765impl Default for Options {
766    fn default() -> Self {
767        Self {
768            budget: Some(Budget::default()),
769            budget_report: None,
770            budget_report_cb: None,
771            #[cfg(feature = "comments")]
772            emit_comments: true,
773            strict_indentation: false,
774            bom_inside_document_as_content: false,
775            duplicate_keys: DuplicateKeyPolicy::Error,
776            merge_keys: MergeKeyPolicy::Merge,
777            alias_limits: AliasLimits::default(),
778            legacy_octal_numbers: false,
779            leading_zero_numbers_as_strings: false,
780            underscored_numbers_as_strings: false,
781            strict_booleans: false,
782            null_as_string: false,
783            angle_conversions: false,
784            ignore_binary_tag_for_string: false,
785            no_schema: false,
786            reject_unsupported_tags: false,
787            reject_tagged_field_names: false,
788            reject_non_finite_typeless_float: true,
789            with_snippet: true,
790            crop_radius: 64,
791            require_indent: RequireIndent::Unchecked,
792
793            #[cfg(feature = "include")]
794            include_resolver: None,
795            #[cfg(feature = "properties")]
796            property_map: None,
797            #[cfg(feature = "properties")]
798            property_syntax: PropertySyntax::Braced,
799            non_finite_float_policy: NonFiniteFloatPolicy::default(),
800        }
801    }
802}
803
804#[allow(deprecated)] // Include the legacy setting in diagnostics.
805impl std::fmt::Debug for Options {
806    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
807        let mut debug = f.debug_struct("Options");
808        debug
809            .field("budget", &self.budget)
810            .field("budget_report", &self.budget_report)
811            .field(
812                "budget_report_cb",
813                &if self.budget_report_cb.is_some() {
814                    "set"
815                } else {
816                    "none"
817                },
818            );
819        #[cfg(feature = "comments")]
820        debug.field("emit_comments", &self.emit_comments);
821        debug
822            .field("strict_indentation", &self.strict_indentation)
823            .field(
824                "bom_inside_document_as_content",
825                &self.bom_inside_document_as_content,
826            )
827            .field("duplicate_keys", &self.duplicate_keys)
828            .field("merge_keys", &self.merge_keys)
829            .field("alias_limits", &self.alias_limits)
830            .field("legacy_octal_numbers", &self.legacy_octal_numbers)
831            .field(
832                "leading_zero_numbers_as_strings",
833                &self.leading_zero_numbers_as_strings,
834            )
835            .field(
836                "underscored_numbers_as_strings",
837                &self.underscored_numbers_as_strings,
838            )
839            .field("strict_booleans", &self.strict_booleans)
840            .field("null_as_string", &self.null_as_string)
841            .field(
842                "ignore_binary_tag_for_string",
843                &self.ignore_binary_tag_for_string,
844            )
845            .field("angle_conversions", &self.angle_conversions)
846            .field("no_schema", &self.no_schema)
847            .field("reject_unsupported_tags", &self.reject_unsupported_tags)
848            .field("reject_tagged_field_names", &self.reject_tagged_field_names)
849            .field("non_finite_float_policy", &self.non_finite_float_policy)
850            .field(
851                "reject_non_finite_typeless_float",
852                &self.reject_non_finite_typeless_float,
853            )
854            .field("with_snippet", &self.with_snippet)
855            .field("crop_radius", &self.crop_radius)
856            .field("require_indent", &self.require_indent)
857            .field("include_resolver", &{
858                #[cfg(feature = "include")]
859                {
860                    if self.include_resolver.is_some() {
861                        "set"
862                    } else {
863                        "none"
864                    }
865                }
866                #[cfg(not(feature = "include"))]
867                {
868                    "disabled"
869                }
870            })
871            .field("property_map", &{
872                #[cfg(feature = "properties")]
873                {
874                    if self.property_map.is_some() {
875                        "set"
876                    } else {
877                        "none"
878                    }
879                }
880                #[cfg(not(feature = "properties"))]
881                {
882                    "disabled"
883                }
884            })
885            .field("property_syntax", &{
886                #[cfg(feature = "properties")]
887                {
888                    format!("{:?}", self.property_syntax)
889                }
890                #[cfg(not(feature = "properties"))]
891                {
892                    "disabled".to_string()
893                }
894            })
895            .finish()
896    }
897}
898
899#[cfg(test)]
900mod tests {
901    use super::*;
902
903    #[cfg(feature = "include_fs")]
904    use crate::input_source::{IncludeRequest, InputSource};
905    #[cfg(feature = "include_fs")]
906    use std::path::PathBuf;
907    #[cfg(feature = "include_fs")]
908    use tempfile::tempdir;
909
910    #[test]
911    fn test_options_default() {
912        let opts = Options::default();
913        assert!(opts.budget.is_some());
914        assert!(opts.budget_report.is_none());
915        assert!(opts.budget_report_cb.is_none());
916        #[cfg(feature = "comments")]
917        assert!(opts.emit_comments);
918        assert!(!opts.strict_indentation);
919        assert!(!opts.bom_inside_document_as_content);
920        assert!(matches!(opts.duplicate_keys, DuplicateKeyPolicy::Error));
921        assert!(matches!(opts.merge_keys, MergeKeyPolicy::Merge));
922        assert_eq!(opts.alias_limits.max_total_replayed_events, 1_000_000);
923        assert!(!opts.legacy_octal_numbers);
924        assert!(!opts.leading_zero_numbers_as_strings);
925        assert!(!opts.underscored_numbers_as_strings);
926        assert!(!opts.strict_booleans);
927        assert!(!opts.null_as_string);
928        assert!(!opts.ignore_binary_tag_for_string);
929        assert!(!opts.angle_conversions);
930        assert!(!opts.no_schema);
931        assert!(!opts.reject_unsupported_tags);
932        assert!(!opts.reject_tagged_field_names);
933        assert_eq!(
934            opts.non_finite_float_policy,
935            NonFiniteFloatPolicy::default()
936        );
937        assert!(opts.with_snippet);
938        assert_eq!(opts.crop_radius, 64);
939        assert_eq!(opts.require_indent, RequireIndent::Unchecked);
940
941        #[cfg(feature = "include")]
942        assert!(opts.include_resolver.is_none());
943        #[cfg(feature = "properties")]
944        {
945            assert!(opts.property_map.is_none());
946            assert_eq!(opts.property_syntax, PropertySyntax::Braced);
947        }
948    }
949
950    #[cfg(feature = "serde_derived_types")]
951    #[test]
952    fn duplicate_key_policy_serde_uses_snake_case() {
953        assert_eq!(
954            serde_json::to_string(&DuplicateKeyPolicy::FirstWins).unwrap(),
955            "\"first_wins\""
956        );
957        assert!(matches!(
958            serde_json::from_str::<DuplicateKeyPolicy>("\"last_wins\"").unwrap(),
959            DuplicateKeyPolicy::LastWins
960        ));
961        assert!(serde_json::from_str::<DuplicateKeyPolicy>("\"FirstWins\"").is_err());
962    }
963
964    #[cfg(feature = "serde_derived_types")]
965    #[test]
966    fn null_as_string_serde_roundtrip_and_missing_default() {
967        let options = crate::options! { null_as_string: true };
968        let mut json = serde_json::to_value(&options).unwrap();
969        let restored: Options = serde_json::from_value(json.clone()).unwrap();
970        assert!(restored.null_as_string);
971
972        json.as_object_mut().unwrap().remove("null_as_string");
973        let legacy: Options = serde_json::from_value(json).unwrap();
974        assert!(!legacy.null_as_string);
975    }
976
977    #[cfg(feature = "serde_derived_types")]
978    #[test]
979    fn tagged_field_name_policy_serde_roundtrip_and_missing_default() {
980        let options = crate::options! { reject_tagged_field_names: true };
981        let mut json = serde_json::to_value(&options).unwrap();
982        let restored: Options = serde_json::from_value(json.clone()).unwrap();
983        assert!(restored.reject_tagged_field_names);
984
985        json.as_object_mut()
986            .unwrap()
987            .remove("reject_tagged_field_names");
988        let legacy: Options = serde_json::from_value(json).unwrap();
989        assert!(!legacy.reject_tagged_field_names);
990    }
991
992    #[cfg(feature = "serde_derived_types")]
993    #[test]
994    fn strict_indentation_serde_roundtrip_and_missing_default() {
995        let options = crate::options! { strict_indentation: true };
996        let mut json = serde_json::to_value(&options).unwrap();
997        let restored: Options = serde_json::from_value(json.clone()).unwrap();
998        assert!(restored.strict_indentation);
999
1000        json.as_object_mut().unwrap().remove("strict_indentation");
1001        let legacy: Options = serde_json::from_value(json).unwrap();
1002        assert!(!legacy.strict_indentation);
1003    }
1004
1005    #[cfg(feature = "serde_derived_types")]
1006    #[test]
1007    fn bom_inside_document_serde_roundtrip_and_missing_default() {
1008        let options = crate::options! { bom_inside_document_as_content: true };
1009        let mut json = serde_json::to_value(&options).unwrap();
1010        let restored: Options = serde_json::from_value(json.clone()).unwrap();
1011        assert!(restored.bom_inside_document_as_content);
1012
1013        json.as_object_mut()
1014            .unwrap()
1015            .remove("bom_inside_document_as_content");
1016        let legacy: Options = serde_json::from_value(json).unwrap();
1017        assert!(!legacy.bom_inside_document_as_content);
1018    }
1019
1020    #[cfg(feature = "serde_derived_types")]
1021    #[test]
1022    fn non_finite_float_policy_serde_uses_snake_case() {
1023        for (policy, name) in [
1024            (NonFiniteFloatPolicy::Default, "default"),
1025            (NonFiniteFloatPolicy::PassThrough, "pass_through"),
1026            (NonFiniteFloatPolicy::Reject, "reject"),
1027            (NonFiniteFloatPolicy::AsString, "as_string"),
1028        ] {
1029            let json = serde_json::to_string(&policy).unwrap();
1030            assert_eq!(json, format!("\"{name}\""));
1031            assert_eq!(
1032                serde_json::from_str::<NonFiniteFloatPolicy>(&json).unwrap(),
1033                policy
1034            );
1035        }
1036        assert!(serde_json::from_str::<NonFiniteFloatPolicy>("\"PassThrough\"").is_err());
1037    }
1038
1039    #[test]
1040    fn test_options_debug_format() {
1041        let opts = Options::default();
1042        let debug_str = format!("{:?}", opts);
1043        assert!(debug_str.contains("Options"));
1044        assert!(debug_str.contains("budget"));
1045        assert!(debug_str.contains("budget_report_cb: \"none\""));
1046        #[cfg(feature = "comments")]
1047        assert!(debug_str.contains("emit_comments: true"));
1048        assert!(debug_str.contains("strict_indentation: false"));
1049        assert!(debug_str.contains("bom_inside_document_as_content: false"));
1050        assert!(debug_str.contains("reject_unsupported_tags: false"));
1051        assert!(debug_str.contains("reject_tagged_field_names: false"));
1052        assert!(debug_str.contains("non_finite_float_policy: Default"));
1053        assert!(debug_str.contains("reject_non_finite_typeless_float: true"));
1054
1055        #[cfg(feature = "include")]
1056        assert!(debug_str.contains("include_resolver: \"none\""));
1057        #[cfg(feature = "properties")]
1058        {
1059            assert!(debug_str.contains("property_map: \"none\""));
1060        }
1061        #[cfg(not(feature = "properties"))]
1062        {
1063            assert!(debug_str.contains("property_map: \"disabled\""));
1064        }
1065
1066        // Test with callback
1067        let opts_with_cb = opts.with_budget_report(|_| {});
1068        let debug_str_cb = format!("{:?}", opts_with_cb);
1069        assert!(debug_str_cb.contains("budget_report_cb: \"set\""));
1070    }
1071
1072    #[cfg(feature = "properties")]
1073    #[test]
1074    fn test_with_properties_sets_property_map() {
1075        let mut properties = std::collections::HashMap::new();
1076        properties.insert("MODE".to_string(), "production".to_string());
1077
1078        let opts = Options::default().with_properties(properties);
1079
1080        assert_eq!(
1081            opts.property_map.as_deref().unwrap().get("MODE"),
1082            Some(&"production".to_string())
1083        );
1084    }
1085
1086    #[test]
1087    fn test_alias_limits_default() {
1088        let limits = AliasLimits::default();
1089        assert_eq!(limits.max_total_replayed_events, 1_000_000);
1090        assert_eq!(limits.max_replay_stack_depth, 64);
1091        assert_eq!(limits.max_alias_expansions_per_anchor, usize::MAX);
1092    }
1093
1094    #[test]
1095    fn test_alias_limits_macro() {
1096        let limits = crate::alias_limits! {
1097            max_total_replayed_events: 42,
1098            max_replay_stack_depth: 7,
1099        };
1100        assert_eq!(limits.max_total_replayed_events, 42);
1101        assert_eq!(limits.max_replay_stack_depth, 7);
1102        assert_eq!(limits.max_alias_expansions_per_anchor, usize::MAX);
1103
1104        let opts = crate::options! {
1105            alias_limits: crate::alias_limits! {
1106                max_alias_expansions_per_anchor: 9,
1107            },
1108        };
1109        assert_eq!(opts.alias_limits.max_alias_expansions_per_anchor, 9);
1110    }
1111
1112    #[cfg(feature = "include_fs")]
1113    #[test]
1114    #[cfg_attr(miri, ignore)]
1115    fn test_with_filesystem_root_sets_include_resolver() {
1116        let root = PathBuf::from(".");
1117        let opts = Options::default().with_filesystem_root(&root).unwrap();
1118        assert!(opts.include_resolver.is_some());
1119    }
1120
1121    #[cfg(feature = "include_fs")]
1122    #[test]
1123    #[cfg_attr(miri, ignore)]
1124    fn test_with_filesystem_root_uses_reader_default_for_regular_files() {
1125        let dir = tempdir().unwrap();
1126        std::fs::write(dir.path().join("child.yaml"), "value: 1\n").unwrap();
1127
1128        let opts = Options::default().with_filesystem_root(dir.path()).unwrap();
1129        let mut resolver = opts
1130            .include_resolver
1131            .as_ref()
1132            .expect("resolver set")
1133            .borrow_mut();
1134        let resolved = resolver(IncludeRequest {
1135            spec: "child.yaml",
1136            from_name: "<input>",
1137            from_id: None,
1138            stack: vec!["<input>".to_string()],
1139            location: crate::Location::UNKNOWN,
1140            size_remaining: None,
1141        })
1142        .unwrap();
1143
1144        assert!(matches!(resolved.source, InputSource::Reader(_)));
1145    }
1146}