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