Skip to main content

granit_parser/
scalar_style.rs

1//! Scalar notation and compact block-header source metadata.
2
3#[cfg(feature = "extended_details")]
4use core::ops::Range;
5
6#[cfg(feature = "extended_details")]
7use crate::Span;
8
9/// How a block scalar handles its final line break and trailing empty lines.
10#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash, Ord, PartialOrd)]
11#[non_exhaustive]
12pub enum Chomping {
13    /// No sign was written: preserve the final line break, but not trailing empty lines.
14    #[default]
15    Clip,
16    /// A `-` was written: remove the final line break and trailing empty lines.
17    Strip,
18    /// A `+` was written: preserve the final line break and trailing empty lines.
19    Keep,
20}
21
22/// Source syntax attached to a literal or folded block scalar.
23///
24/// Available only with `extended_details`.
25///
26/// Coordinates are relative to the **start of the accompanying scalar span**. Keep that span
27/// together with this value: rebasing or replacing its start invalidates these distances.
28/// The ordinary scalar span retains its existing meaning, which need not include the header.
29/// This type does not store another [`crate::Marker`] or retain borrowed source text.
30///
31/// The header ranges cover `|` or `>` and its adjacent indicators, excluding whitespace,
32/// comments, and the header line break. Character and byte distances differ when, for example,
33/// a header comment contains Unicode. Use [`Self::header_byte_range`] to inspect byte distances
34/// when available. Indicator offsets are computed from the chomping mode, indentation digit,
35/// and their order.
36/// Distances and content indentation use `u32`. If a parsed value cannot fit, the scalar's
37/// syntax is `None`; scalar decoding and the accompanying span remain available.
38///
39/// Normal builds provide no equality, ordering, or hashing. Inspect the individual fields
40/// relevant to your use case. The opt-in `test_equality` feature enables equality for testing;
41/// it ignores optional byte distances, like [`crate::Marker`], and irrelevant indicator order.
42/// This is an explicit comparison of source syntax. Equality of [`ScalarStyle`], events, and
43/// tokens instead ignores this metadata altogether, keeping output comparisons independent of
44/// whether `extended_details` is enabled.
45#[cfg_attr(
46    not(feature = "test_equality"),
47    doc = r#"
48Comparing synthetic syntax with parsed syntax is intentionally unavailable by default:
49
50```compile_fail,E0369
51use granit_parser::BlockScalarSyntax;
52let syntax = BlockScalarSyntax::default();
53let _ = syntax == BlockScalarSyntax::default();
54```
55"#
56)]
57#[cfg(feature = "extended_details")]
58#[derive(Clone, Copy, Debug, Default)]
59#[non_exhaustive]
60pub struct BlockScalarSyntax {
61    /// Character distance backwards from the scalar span's start to `|` or `>`.
62    pub header_chars_before_span: u32,
63    /// Byte distance backwards from the scalar span's start to `|` or `>`.
64    ///
65    /// Meaningful only when the accompanying span's start has a byte offset. Otherwise zero.
66    pub header_bytes_before_span: u32,
67    /// Chomping mode selected by the header.
68    pub chomping: Chomping,
69    /// Explicit indentation digit (`1..=9`), or `None` when indentation was inferred.
70    pub indentation_indicator: Option<u8>,
71    /// Whether the indentation digit precedes the chomping sign when both are present.
72    ///
73    /// Ignored when either indicator is absent, including by `test_equality` comparisons.
74    /// Parsed headers set this to `false` in that case.
75    pub digit_first: bool,
76    /// Effective number of leading indentation spaces removed from content lines.
77    ///
78    /// This is an absolute content indentation level, not the explicit indentation digit.
79    /// For an inferred header ending at EOF before its line break, no content line exists:
80    /// this reports the minimum level required by the enclosing block, not the header column.
81    pub content_indent: u32,
82}
83
84#[cfg(feature = "extended_details")]
85impl BlockScalarSyntax {
86    /// Construct synthetic syntax whose header begins at the accompanying span's start.
87    ///
88    /// * `chomping` selects clipping, stripping, or keeping trailing line breaks.
89    /// * `indentation_indicator` is the optional explicit digit, which must be in `1..=9`.
90    /// * `content_indent` is the effective absolute content indentation level.
91    ///
92    /// Returns `None` for an invalid digit or content indentation larger than `u32::MAX`.
93    /// Otherwise the sign precedes the digit when both are present, and both backwards
94    /// distances are zero. Set the public fields to describe a different indicator order or
95    /// a header preceding the scalar span.
96    #[must_use]
97    pub const fn new(
98        chomping: Chomping,
99        indentation_indicator: Option<u8>,
100        content_indent: usize,
101    ) -> Option<Self> {
102        if matches!(indentation_indicator, Some(0 | 10..=u8::MAX))
103            || content_indent > u32::MAX as usize
104        {
105            return None;
106        }
107        // The bound above preserves this constructor's usize parameter and const support.
108        #[allow(clippy::cast_possible_truncation)]
109        let content_indent = content_indent as u32;
110        Some(Self {
111            header_chars_before_span: 0,
112            header_bytes_before_span: 0,
113            chomping,
114            indentation_indicator,
115            digit_first: false,
116            content_indent,
117        })
118    }
119
120    /// Attach scanner-computed distances from the header to the scalar span's start.
121    ///
122    /// * `header_chars_before_span` is the backwards distance in characters.
123    /// * `header_bytes_before_span` is the backwards byte distance, or zero if unavailable.
124    ///
125    /// Returns updated syntax, or `None` if either distance cannot be represented by `u32`.
126    pub(crate) fn with_header_offsets(
127        mut self,
128        header_chars_before_span: usize,
129        header_bytes_before_span: usize,
130    ) -> Option<Self> {
131        self.header_chars_before_span = u32::try_from(header_chars_before_span).ok()?;
132        self.header_bytes_before_span = u32::try_from(header_bytes_before_span).ok()?;
133        Some(self)
134    }
135
136    /// Return the header-indicator length in both characters and bytes, excluding whitespace.
137    ///
138    /// Parsed headers contain one to three ASCII characters.
139    #[must_use]
140    pub const fn header_len(&self) -> usize {
141        1 + !matches!(self.chomping, Chomping::Clip) as usize
142            + self.indentation_indicator.is_some() as usize
143    }
144
145    /// Return the chomping sign's offset from the header start, or `None` for clipping.
146    ///
147    /// Offsets are the same in characters and bytes: a block header contains only ASCII.
148    #[must_use]
149    pub const fn chomping_offset(&self) -> Option<u8> {
150        match self.chomping {
151            Chomping::Clip => None,
152            Chomping::Strip | Chomping::Keep => {
153                if self.digit_first && self.indentation_indicator.is_some() {
154                    Some(2)
155                } else {
156                    Some(1)
157                }
158            }
159        }
160    }
161
162    /// Return the indentation digit's offset from the header start, or `None` if inferred.
163    ///
164    /// Offsets are the same in characters and bytes: a block header contains only ASCII.
165    #[must_use]
166    pub const fn indentation_offset(&self) -> Option<u8> {
167        match self.indentation_indicator {
168            None => None,
169            Some(_) => {
170                if !self.digit_first && !matches!(self.chomping, Chomping::Clip) {
171                    Some(2)
172                } else {
173                    Some(1)
174                }
175            }
176        }
177    }
178
179    /// Return the header's character-index range using its accompanying scalar `span`.
180    ///
181    /// Returns `None` if the coordinates underflow or overflow. The caller must supply the
182    /// original matching span; arithmetic checks cannot detect every mismatched span.
183    #[must_use]
184    pub fn header_char_range(&self, span: &Span) -> Option<Range<usize>> {
185        let start = span
186            .start
187            .index()
188            .checked_sub(usize::try_from(self.header_chars_before_span).ok()?)?;
189        Some(start..start.checked_add(self.header_len())?)
190    }
191
192    /// Return the header's byte range using its accompanying scalar `span`.
193    ///
194    /// Returns `None` for inputs without byte offsets or if coordinates underflow or overflow.
195    /// The caller must supply the original matching span.
196    #[must_use]
197    pub fn header_byte_range(&self, span: &Span) -> Option<Range<usize>> {
198        let start = span
199            .start
200            .byte_offset()?
201            .checked_sub(usize::try_from(self.header_bytes_before_span).ok()?)?;
202        Some(start..start.checked_add(self.header_len())?)
203    }
204
205    /// Return the explicit chomping sign's character range, or `None` if absent/unavailable.
206    #[must_use]
207    pub fn chomping_char_range(&self, span: &Span) -> Option<Range<usize>> {
208        Self::indicator_range(self.header_char_range(span)?, self.chomping_offset()?)
209    }
210
211    /// Return the explicit chomping sign's byte range, or `None` if absent/unavailable.
212    #[must_use]
213    pub fn chomping_byte_range(&self, span: &Span) -> Option<Range<usize>> {
214        Self::indicator_range(self.header_byte_range(span)?, self.chomping_offset()?)
215    }
216
217    /// Return the explicit indentation digit's character range, or `None` if absent/unavailable.
218    #[must_use]
219    pub fn indentation_char_range(&self, span: &Span) -> Option<Range<usize>> {
220        Self::indicator_range(self.header_char_range(span)?, self.indentation_offset()?)
221    }
222
223    /// Return the explicit indentation digit's byte range, or `None` if absent/unavailable.
224    #[must_use]
225    pub fn indentation_byte_range(&self, span: &Span) -> Option<Range<usize>> {
226        Self::indicator_range(self.header_byte_range(span)?, self.indentation_offset()?)
227    }
228
229    /// Return the raw header indicators from the original source.
230    ///
231    /// * `span` is the original accompanying scalar span.
232    /// * `source` is the complete original UTF-8 source, using the span's coordinate origin.
233    ///
234    /// Returns `None` when byte positions are unavailable or outside valid source boundaries.
235    #[must_use]
236    pub fn header_slice<'source>(&self, span: &Span, source: &'source str) -> Option<&'source str> {
237        source.get(self.header_byte_range(span)?)
238    }
239
240    fn indicator_range(header: Range<usize>, offset: u8) -> Option<Range<usize>> {
241        if offset == 0 {
242            return None;
243        }
244        let start = header.start.checked_add(usize::from(offset))?;
245        let end = start.checked_add(1)?;
246        (end <= header.end).then_some(start..end)
247    }
248
249    #[cfg(feature = "test_equality")]
250    fn identity(&self) -> (u32, Chomping, Option<u8>, bool, u32) {
251        // Exhaustive destructuring makes every added field require an explicit equality policy.
252        let Self {
253            header_chars_before_span,
254            header_bytes_before_span: _,
255            chomping,
256            indentation_indicator,
257            digit_first,
258            content_indent,
259        } = *self;
260        (
261            header_chars_before_span,
262            chomping,
263            indentation_indicator,
264            digit_first && !matches!(chomping, Chomping::Clip) && indentation_indicator.is_some(),
265            content_indent,
266        )
267    }
268}
269
270#[cfg(all(feature = "extended_details", feature = "test_equality"))]
271impl PartialEq for BlockScalarSyntax {
272    fn eq(&self, other: &Self) -> bool {
273        self.identity() == other.identity()
274    }
275}
276
277#[cfg(all(feature = "extended_details", feature = "test_equality"))]
278impl Eq for BlockScalarSyntax {}
279
280/// A scalar's notation category, independent of source positions and header metadata.
281#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
282#[non_exhaustive]
283pub enum ScalarKind {
284    /// Plain notation.
285    Plain,
286    /// Single-quoted notation.
287    SingleQuoted,
288    /// Double-quoted notation.
289    DoubleQuoted,
290    /// Literal block notation (`|`).
291    Literal,
292    /// Folded block notation (`>`).
293    Folded,
294}
295
296/// The source notation and applicable syntax metadata of a YAML scalar.
297///
298/// Inspect styles with `matches!`, `if let`, or `match`, using `{ .. }` even for variants
299/// that currently have no fields. The rest pattern ignores metadata you do not need and lets
300/// the library add fields later without changing your code. The enum and every variant are
301/// non-exhaustive, so a complete `match` also needs a fallback arm.
302///
303/// Normal builds provide no equality, ordering, or hashing. Comparing every style field would
304/// make classification depend on all present and future metadata. Match the variant instead,
305/// then inspect the fields relevant to your use case. [`Self::kind`] returns a comparable,
306/// fieldless category when a map key or ordering is needed. The opt-in `test_equality` feature
307/// compares only the notation category for tests. It ignores the `implicit` flag and all
308/// `extended_details` fields: source information may be absent on synthetic values, and enabling
309/// optional capture through another dependency must not change equality. Compare `implicit` or `syntax`
310/// explicitly when testing those details. Metadata defaults are not equality wildcards;
311/// source metadata is always excluded so equality remains transitive.
312///
313/// Constructors create styles for synthetic events and alternative parser implementations.
314/// They are independent of classification: use patterns to inspect the resulting values.
315/// Their signatures are the same with and without `extended_details`. The feature adds
316/// optional block syntax fields and builders; synthetic block styles start without known
317/// source syntax. Omitted-node identity and [`Self::is_omitted`] are available in every build.
318/// This keeps construction independent of future metadata additions.
319///
320/// ```
321/// use granit_parser::{Parser, ScalarStyle};
322/// let (event, _) = Parser::new_from_str("value").nth(2).unwrap().unwrap();
323/// let (_, style) = event.scalar().unwrap();
324/// assert!(matches!(style, ScalarStyle::Plain { .. }));
325/// assert!(!matches!(style, ScalarStyle::SingleQuoted { .. }));
326/// ```
327///
328#[cfg_attr(
329    not(feature = "test_equality"),
330    doc = r#"
331Whole-style equality is intentionally unavailable by default:
332
333```compile_fail,E0369
334use granit_parser::ScalarStyle;
335fn equal_styles(left: ScalarStyle, right: ScalarStyle) -> bool {
336    left == right
337}
338```
339"#
340)]
341/// Styles are not hash keys; use [`ScalarKind`] when only the notation category matters:
342///
343/// ```compile_fail,E0277
344/// use granit_parser::ScalarStyle;
345/// fn require_hash<T: core::hash::Hash>() {}
346/// require_hash::<ScalarStyle>();
347/// ```
348///
349/// Non-exhaustive variants cannot be constructed directly outside this crate:
350///
351/// ```compile_fail,E0603
352/// use granit_parser::ScalarStyle;
353/// let style = ScalarStyle::SingleQuoted;
354/// ```
355///
356/// Use a constructor to create a synthetic style:
357///
358/// ```
359/// use granit_parser::ScalarStyle;
360/// let style = ScalarStyle::literal();
361/// assert!(matches!(style, ScalarStyle::Literal { .. }));
362/// ```
363///
364/// Variant patterns must allow future fields:
365///
366/// ```compile_fail,E0638
367/// use granit_parser::ScalarStyle;
368/// fn inspect(style: ScalarStyle) {
369///     if let ScalarStyle::Literal {} = style {}
370/// }
371/// ```
372#[derive(Clone, Copy, Debug)]
373#[non_exhaustive]
374pub enum ScalarStyle {
375    /// A plain scalar or a synthesized empty node.
376    #[non_exhaustive]
377    Plain {
378        /// Whether the parser synthesized an omitted node instead of reading scalar text.
379        ///
380        /// Explicit tags and anchors can decorate an omitted node. Written empty quoted or
381        /// block scalars have their own styles and are never implicit plain scalars.
382        /// This distinction is available without `extended_details`.
383        implicit: bool,
384    },
385    /// A single-quoted scalar.
386    #[non_exhaustive]
387    SingleQuoted,
388    /// A double-quoted scalar.
389    #[non_exhaustive]
390    DoubleQuoted,
391    /// A literal block, with no escape processing or line folding.
392    #[non_exhaustive]
393    Literal {
394        /// Header syntax relative to the accompanying scalar span, when known.
395        ///
396        /// Parsed block styles contain `Some` when all details fit in `u32`;
397        /// synthetic styles and unrepresentable parsed details use `None`.
398        /// Available only with `extended_details`.
399        #[cfg(feature = "extended_details")]
400        syntax: Option<BlockScalarSyntax>,
401    },
402    /// A folded block, whose line breaks are subject to YAML line folding.
403    #[non_exhaustive]
404    Folded {
405        /// Header syntax relative to the accompanying scalar span, when known.
406        ///
407        /// Parsed block styles contain `Some` when all details fit in `u32`;
408        /// synthetic styles and unrepresentable parsed details use `None`.
409        /// Available only with `extended_details`.
410        #[cfg(feature = "extended_details")]
411        syntax: Option<BlockScalarSyntax>,
412    },
413}
414
415#[cfg(feature = "test_equality")]
416impl PartialEq for ScalarStyle {
417    fn eq(&self, other: &Self) -> bool {
418        self.kind() == other.kind()
419    }
420}
421
422#[cfg(feature = "test_equality")]
423impl Eq for ScalarStyle {}
424
425impl ScalarStyle {
426    /// Return the style of explicitly written plain scalar text.
427    #[must_use]
428    pub const fn plain() -> Self {
429        Self::Plain { implicit: false }
430    }
431
432    /// Return the style of an omitted node synthesized by a parser.
433    #[must_use]
434    pub const fn implicit_plain() -> Self {
435        Self::plain().with_implicit(true)
436    }
437
438    /// Set whether a plain scalar represents an omitted node.
439    ///
440    /// Other styles are returned unchanged because this detail applies only to plain scalars.
441    #[must_use]
442    pub const fn with_implicit(self, implicit: bool) -> Self {
443        match self {
444            Self::Plain { .. } => Self::Plain { implicit },
445            other => other,
446        }
447    }
448
449    /// Return single-quoted notation.
450    #[must_use]
451    pub const fn single_quoted() -> Self {
452        Self::SingleQuoted
453    }
454
455    /// Return double-quoted notation.
456    #[must_use]
457    pub const fn double_quoted() -> Self {
458        Self::DoubleQuoted
459    }
460
461    /// Return literal block style without known source-header syntax.
462    #[must_use]
463    pub const fn literal() -> Self {
464        Self::Literal {
465            #[cfg(feature = "extended_details")]
466            syntax: None,
467        }
468    }
469
470    /// Return folded block style without known source-header syntax.
471    #[must_use]
472    pub const fn folded() -> Self {
473        Self::Folded {
474            #[cfg(feature = "extended_details")]
475            syntax: None,
476        }
477    }
478
479    /// Attach known source-header `syntax` to a literal or folded style.
480    ///
481    /// Other styles are returned unchanged because block-header syntax does not apply to them.
482    /// Available only with `extended_details`.
483    ///
484    /// ```
485    /// use granit_parser::{BlockScalarSyntax, ScalarStyle};
486    /// let style = ScalarStyle::literal();
487    /// assert!(style.block_syntax().is_none());
488    /// let style = style.with_block_syntax(BlockScalarSyntax::default());
489    /// assert!(style.block_syntax().is_some());
490    /// ```
491    #[cfg(feature = "extended_details")]
492    #[must_use]
493    pub const fn with_block_syntax(self, syntax: BlockScalarSyntax) -> Self {
494        match self {
495            Self::Literal { .. } => Self::Literal {
496                syntax: Some(syntax),
497            },
498            Self::Folded { .. } => Self::Folded {
499                syntax: Some(syntax),
500            },
501            other => other,
502        }
503    }
504
505    /// Return the notation category, ignoring source positions and all other metadata.
506    #[must_use]
507    pub const fn kind(&self) -> ScalarKind {
508        match self {
509            Self::Plain { .. } => ScalarKind::Plain,
510            Self::SingleQuoted => ScalarKind::SingleQuoted,
511            Self::DoubleQuoted => ScalarKind::DoubleQuoted,
512            Self::Literal { .. } => ScalarKind::Literal,
513            Self::Folded { .. } => ScalarKind::Folded,
514        }
515    }
516
517    /// Return whether this is plain notation, including synthesized empty nodes.
518    ///
519    /// Equivalent to `matches!(self, ScalarStyle::Plain { .. })`.
520    #[must_use]
521    pub const fn is_plain(&self) -> bool {
522        matches!(self, Self::Plain { .. })
523    }
524
525    /// Return whether the parser synthesized an omitted node rather than reading scalar text.
526    ///
527    /// Written null spellings such as `~` and `null`, empty quoted strings, and empty block
528    /// scalars return `false`. An omitted node can still have an explicit tag or anchor.
529    #[must_use]
530    pub const fn is_omitted(&self) -> bool {
531        matches!(self, Self::Plain { implicit: true })
532    }
533
534    /// Return whether this is single-quoted notation.
535    #[must_use]
536    pub const fn is_single_quoted(&self) -> bool {
537        matches!(self, Self::SingleQuoted)
538    }
539
540    /// Return whether this is double-quoted notation.
541    #[must_use]
542    pub const fn is_double_quoted(&self) -> bool {
543        matches!(self, Self::DoubleQuoted)
544    }
545
546    /// Return whether this is literal block notation.
547    #[must_use]
548    pub const fn is_literal(&self) -> bool {
549        matches!(self, Self::Literal { .. })
550    }
551
552    /// Return whether this is folded block notation.
553    #[must_use]
554    pub const fn is_folded(&self) -> bool {
555        matches!(self, Self::Folded { .. })
556    }
557
558    /// Return known block-header syntax for literal and folded scalars.
559    ///
560    /// Returns `None` for other styles, synthetic block styles with no attached syntax, and
561    /// parsed block styles whose header distances or content indentation exceed `u32::MAX`.
562    /// Available only with `extended_details`.
563    #[cfg(feature = "extended_details")]
564    #[must_use]
565    pub const fn block_syntax(&self) -> Option<&BlockScalarSyntax> {
566        match self {
567            Self::Literal { syntax } | Self::Folded { syntax } => syntax.as_ref(),
568            _ => None,
569        }
570    }
571}
572
573#[cfg(test)]
574mod tests {
575    use super::{ScalarKind, ScalarStyle};
576
577    #[cfg(all(feature = "extended_details", target_pointer_width = "64"))]
578    #[test]
579    fn header_offsets_reject_overflow_without_truncating() {
580        use super::BlockScalarSyntax;
581
582        let maximum = usize::try_from(u32::MAX).unwrap();
583        let overflow = maximum + 1;
584        for (characters, bytes) in [(0, 0), (maximum, 0), (0, maximum), (maximum, maximum)] {
585            let syntax = BlockScalarSyntax::default()
586                .with_header_offsets(characters, bytes)
587                .unwrap();
588            assert_eq!(
589                usize::try_from(syntax.header_chars_before_span).unwrap(),
590                characters
591            );
592            assert_eq!(
593                usize::try_from(syntax.header_bytes_before_span).unwrap(),
594                bytes
595            );
596        }
597        for (characters, bytes) in [
598            (overflow, 0),
599            (0, overflow),
600            (maximum, overflow),
601            (overflow, maximum),
602        ] {
603            assert!(BlockScalarSyntax::default()
604                .with_header_offsets(characters, bytes)
605                .is_none());
606        }
607    }
608
609    #[test]
610    fn basic_constructors_keep_the_same_signature_with_either_feature_set() {
611        let constructors: [(fn() -> ScalarStyle, ScalarKind); 5] = [
612            (ScalarStyle::plain, ScalarKind::Plain),
613            (ScalarStyle::single_quoted, ScalarKind::SingleQuoted),
614            (ScalarStyle::double_quoted, ScalarKind::DoubleQuoted),
615            (ScalarStyle::literal, ScalarKind::Literal),
616            (ScalarStyle::folded, ScalarKind::Folded),
617        ];
618        for (construct, kind) in constructors {
619            assert_eq!(construct().kind(), kind);
620        }
621    }
622
623    #[test]
624    fn omission_builders_only_change_plain_scalars() {
625        assert!(ScalarStyle::implicit_plain().is_omitted());
626        assert!(!ScalarStyle::implicit_plain()
627            .with_implicit(false)
628            .is_omitted());
629        assert!(ScalarStyle::plain().with_implicit(true).is_omitted());
630        for style in [
631            ScalarStyle::single_quoted(),
632            ScalarStyle::double_quoted(),
633            ScalarStyle::literal(),
634            ScalarStyle::folded(),
635        ] {
636            assert!(!style.with_implicit(true).is_omitted());
637        }
638    }
639
640    #[cfg(feature = "extended_details")]
641    #[test]
642    fn synthetic_block_styles_have_unknown_source_syntax() {
643        assert!(matches!(
644            ScalarStyle::literal(),
645            ScalarStyle::Literal { syntax: None }
646        ));
647        assert!(matches!(
648            ScalarStyle::folded(),
649            ScalarStyle::Folded { syntax: None }
650        ));
651        assert!(ScalarStyle::literal().block_syntax().is_none());
652        assert!(ScalarStyle::folded().block_syntax().is_none());
653    }
654
655    #[cfg(feature = "extended_details")]
656    #[test]
657    fn detail_builders_apply_only_to_relevant_styles() {
658        use super::{BlockScalarSyntax, Chomping};
659
660        let syntax = BlockScalarSyntax::new(Chomping::Keep, Some(2), 4).unwrap();
661        for style in [ScalarStyle::literal(), ScalarStyle::folded()] {
662            let kind = style.kind();
663            let detailed = style.with_block_syntax(syntax).with_implicit(true);
664            assert_eq!(detailed.kind(), kind);
665            let actual = detailed.block_syntax().unwrap();
666            assert_eq!(actual.chomping, Chomping::Keep);
667            assert_eq!(actual.indentation_indicator, Some(2));
668            assert_eq!(actual.content_indent, 4);
669        }
670        assert!(matches!(
671            ScalarStyle::plain()
672                .with_implicit(true)
673                .with_block_syntax(syntax),
674            ScalarStyle::Plain { implicit: true }
675        ));
676        assert!(matches!(
677            ScalarStyle::implicit_plain().with_implicit(false),
678            ScalarStyle::Plain { implicit: false }
679        ));
680        assert!(matches!(
681            ScalarStyle::single_quoted()
682                .with_implicit(true)
683                .with_block_syntax(syntax),
684            ScalarStyle::SingleQuoted
685        ));
686    }
687}