#[cfg(feature = "extended_details")]
use core::ops::Range;
#[cfg(feature = "extended_details")]
use crate::Span;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash, Ord, PartialOrd)]
#[non_exhaustive]
pub enum Chomping {
#[default]
Clip,
Strip,
Keep,
}
#[cfg_attr(
not(feature = "test_equality"),
doc = r"
Comparing synthetic syntax with parsed syntax is intentionally unavailable by default:
```compile_fail,E0369
use granit_parser::BlockScalarSyntax;
let syntax = BlockScalarSyntax::default();
let _ = syntax == BlockScalarSyntax::default();
```
"
)]
#[cfg(feature = "extended_details")]
#[derive(Clone, Copy, Debug, Default)]
#[non_exhaustive]
pub struct BlockScalarSyntax {
pub header_chars_before_span: u32,
pub header_bytes_before_span: u32,
pub chomping: Chomping,
pub indentation_indicator: Option<u8>,
pub digit_first: bool,
pub content_indent: u32,
}
#[cfg(feature = "extended_details")]
impl BlockScalarSyntax {
#[must_use]
pub const fn new(
chomping: Chomping,
indentation_indicator: Option<u8>,
content_indent: usize,
) -> Option<Self> {
if matches!(indentation_indicator, Some(0 | 10..=u8::MAX))
|| content_indent > u32::MAX as usize
{
return None;
}
#[allow(clippy::cast_possible_truncation)]
let content_indent = content_indent as u32;
Some(Self {
header_chars_before_span: 0,
header_bytes_before_span: 0,
chomping,
indentation_indicator,
digit_first: false,
content_indent,
})
}
pub(crate) fn with_header_offsets(
mut self,
header_chars_before_span: usize,
header_bytes_before_span: usize,
) -> Option<Self> {
self.header_chars_before_span = u32::try_from(header_chars_before_span).ok()?;
self.header_bytes_before_span = u32::try_from(header_bytes_before_span).ok()?;
Some(self)
}
#[must_use]
pub const fn header_len(&self) -> usize {
1 + !matches!(self.chomping, Chomping::Clip) as usize
+ self.indentation_indicator.is_some() as usize
}
#[must_use]
pub const fn chomping_offset(&self) -> Option<u8> {
match self.chomping {
Chomping::Clip => None,
Chomping::Strip | Chomping::Keep => {
if self.digit_first && self.indentation_indicator.is_some() {
Some(2)
} else {
Some(1)
}
}
}
}
#[must_use]
pub const fn indentation_offset(&self) -> Option<u8> {
match self.indentation_indicator {
None => None,
Some(_) => {
if !self.digit_first && !matches!(self.chomping, Chomping::Clip) {
Some(2)
} else {
Some(1)
}
}
}
}
#[must_use]
pub fn header_char_range(&self, span: &Span) -> Option<Range<usize>> {
let start = span
.start
.index()
.checked_sub(usize::try_from(self.header_chars_before_span).ok()?)?;
Some(start..start.checked_add(self.header_len())?)
}
#[must_use]
pub fn header_byte_range(&self, span: &Span) -> Option<Range<usize>> {
let start = span
.start
.byte_offset()?
.checked_sub(usize::try_from(self.header_bytes_before_span).ok()?)?;
Some(start..start.checked_add(self.header_len())?)
}
#[must_use]
pub fn chomping_char_range(&self, span: &Span) -> Option<Range<usize>> {
Self::indicator_range(self.header_char_range(span)?, self.chomping_offset()?)
}
#[must_use]
pub fn chomping_byte_range(&self, span: &Span) -> Option<Range<usize>> {
Self::indicator_range(self.header_byte_range(span)?, self.chomping_offset()?)
}
#[must_use]
pub fn indentation_char_range(&self, span: &Span) -> Option<Range<usize>> {
Self::indicator_range(self.header_char_range(span)?, self.indentation_offset()?)
}
#[must_use]
pub fn indentation_byte_range(&self, span: &Span) -> Option<Range<usize>> {
Self::indicator_range(self.header_byte_range(span)?, self.indentation_offset()?)
}
#[must_use]
pub fn header_slice<'source>(&self, span: &Span, source: &'source str) -> Option<&'source str> {
source.get(self.header_byte_range(span)?)
}
fn indicator_range(header: Range<usize>, offset: u8) -> Option<Range<usize>> {
if offset == 0 {
return None;
}
let start = header.start.checked_add(usize::from(offset))?;
let end = start.checked_add(1)?;
(end <= header.end).then_some(start..end)
}
#[cfg(feature = "test_equality")]
fn identity(&self) -> (u32, Chomping, Option<u8>, bool, u32) {
let Self {
header_chars_before_span,
header_bytes_before_span: _,
chomping,
indentation_indicator,
digit_first,
content_indent,
} = *self;
(
header_chars_before_span,
chomping,
indentation_indicator,
digit_first && !matches!(chomping, Chomping::Clip) && indentation_indicator.is_some(),
content_indent,
)
}
}
#[cfg(all(feature = "extended_details", feature = "test_equality"))]
impl PartialEq for BlockScalarSyntax {
fn eq(&self, other: &Self) -> bool {
self.identity() == other.identity()
}
}
#[cfg(all(feature = "extended_details", feature = "test_equality"))]
impl Eq for BlockScalarSyntax {}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
#[non_exhaustive]
pub enum ScalarKind {
Plain,
SingleQuoted,
DoubleQuoted,
Literal,
Folded,
}
#[cfg_attr(
not(feature = "test_equality"),
doc = r"
Whole-style equality is intentionally unavailable by default:
```compile_fail,E0369
use granit_parser::ScalarStyle;
fn equal_styles(left: ScalarStyle, right: ScalarStyle) -> bool {
left == right
}
```
"
)]
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub enum ScalarStyle {
#[non_exhaustive]
Plain {
implicit: bool,
},
#[non_exhaustive]
SingleQuoted,
#[non_exhaustive]
DoubleQuoted,
#[non_exhaustive]
Literal {
#[cfg(feature = "extended_details")]
syntax: Option<BlockScalarSyntax>,
},
#[non_exhaustive]
Folded {
#[cfg(feature = "extended_details")]
syntax: Option<BlockScalarSyntax>,
},
}
#[cfg(feature = "test_equality")]
impl PartialEq for ScalarStyle {
fn eq(&self, other: &Self) -> bool {
self.kind() == other.kind()
}
}
#[cfg(feature = "test_equality")]
impl Eq for ScalarStyle {}
impl ScalarStyle {
#[must_use]
pub const fn plain() -> Self {
Self::Plain { implicit: false }
}
#[must_use]
pub const fn implicit_plain() -> Self {
Self::plain().with_implicit(true)
}
#[must_use]
pub const fn with_implicit(self, implicit: bool) -> Self {
match self {
Self::Plain { .. } => Self::Plain { implicit },
other => other,
}
}
#[must_use]
pub const fn single_quoted() -> Self {
Self::SingleQuoted
}
#[must_use]
pub const fn double_quoted() -> Self {
Self::DoubleQuoted
}
#[must_use]
pub const fn literal() -> Self {
Self::Literal {
#[cfg(feature = "extended_details")]
syntax: None,
}
}
#[must_use]
pub const fn folded() -> Self {
Self::Folded {
#[cfg(feature = "extended_details")]
syntax: None,
}
}
#[cfg(feature = "extended_details")]
#[must_use]
pub const fn with_block_syntax(self, syntax: BlockScalarSyntax) -> Self {
match self {
Self::Literal { .. } => Self::Literal {
syntax: Some(syntax),
},
Self::Folded { .. } => Self::Folded {
syntax: Some(syntax),
},
other => other,
}
}
#[must_use]
pub const fn kind(&self) -> ScalarKind {
match self {
Self::Plain { .. } => ScalarKind::Plain,
Self::SingleQuoted => ScalarKind::SingleQuoted,
Self::DoubleQuoted => ScalarKind::DoubleQuoted,
Self::Literal { .. } => ScalarKind::Literal,
Self::Folded { .. } => ScalarKind::Folded,
}
}
#[must_use]
pub const fn is_plain(&self) -> bool {
matches!(self, Self::Plain { .. })
}
#[must_use]
pub const fn is_omitted(&self) -> bool {
matches!(self, Self::Plain { implicit: true })
}
#[must_use]
pub const fn is_single_quoted(&self) -> bool {
matches!(self, Self::SingleQuoted)
}
#[must_use]
pub const fn is_double_quoted(&self) -> bool {
matches!(self, Self::DoubleQuoted)
}
#[must_use]
pub const fn is_literal(&self) -> bool {
matches!(self, Self::Literal { .. })
}
#[must_use]
pub const fn is_folded(&self) -> bool {
matches!(self, Self::Folded { .. })
}
#[cfg(feature = "extended_details")]
#[must_use]
pub const fn block_syntax(&self) -> Option<&BlockScalarSyntax> {
match self {
Self::Literal { syntax } | Self::Folded { syntax } => syntax.as_ref(),
_ => None,
}
}
}
#[cfg(test)]
mod tests {
use super::{ScalarKind, ScalarStyle};
#[cfg(all(feature = "extended_details", target_pointer_width = "64"))]
#[test]
fn header_offsets_reject_overflow_without_truncating() {
use super::BlockScalarSyntax;
let maximum = usize::try_from(u32::MAX).unwrap();
let overflow = maximum + 1;
for (characters, bytes) in [(0, 0), (maximum, 0), (0, maximum), (maximum, maximum)] {
let syntax = BlockScalarSyntax::default()
.with_header_offsets(characters, bytes)
.unwrap();
assert_eq!(
usize::try_from(syntax.header_chars_before_span).unwrap(),
characters
);
assert_eq!(
usize::try_from(syntax.header_bytes_before_span).unwrap(),
bytes
);
}
for (characters, bytes) in [
(overflow, 0),
(0, overflow),
(maximum, overflow),
(overflow, maximum),
] {
assert!(BlockScalarSyntax::default()
.with_header_offsets(characters, bytes)
.is_none());
}
}
#[test]
fn basic_constructors_keep_the_same_signature_with_either_feature_set() {
let constructors: [(fn() -> ScalarStyle, ScalarKind); 5] = [
(ScalarStyle::plain, ScalarKind::Plain),
(ScalarStyle::single_quoted, ScalarKind::SingleQuoted),
(ScalarStyle::double_quoted, ScalarKind::DoubleQuoted),
(ScalarStyle::literal, ScalarKind::Literal),
(ScalarStyle::folded, ScalarKind::Folded),
];
for (construct, kind) in constructors {
assert_eq!(construct().kind(), kind);
}
}
#[test]
fn omission_builders_only_change_plain_scalars() {
assert!(ScalarStyle::implicit_plain().is_omitted());
assert!(!ScalarStyle::implicit_plain()
.with_implicit(false)
.is_omitted());
assert!(ScalarStyle::plain().with_implicit(true).is_omitted());
for style in [
ScalarStyle::single_quoted(),
ScalarStyle::double_quoted(),
ScalarStyle::literal(),
ScalarStyle::folded(),
] {
assert!(!style.with_implicit(true).is_omitted());
}
}
#[cfg(feature = "extended_details")]
#[test]
fn synthetic_block_styles_have_unknown_source_syntax() {
assert!(matches!(
ScalarStyle::literal(),
ScalarStyle::Literal { syntax: None }
));
assert!(matches!(
ScalarStyle::folded(),
ScalarStyle::Folded { syntax: None }
));
assert!(ScalarStyle::literal().block_syntax().is_none());
assert!(ScalarStyle::folded().block_syntax().is_none());
}
#[cfg(feature = "extended_details")]
#[test]
fn detail_builders_apply_only_to_relevant_styles() {
use super::{BlockScalarSyntax, Chomping};
let syntax = BlockScalarSyntax::new(Chomping::Keep, Some(2), 4).unwrap();
for style in [ScalarStyle::literal(), ScalarStyle::folded()] {
let kind = style.kind();
let detailed = style.with_block_syntax(syntax).with_implicit(true);
assert_eq!(detailed.kind(), kind);
let actual = detailed.block_syntax().unwrap();
assert_eq!(actual.chomping, Chomping::Keep);
assert_eq!(actual.indentation_indicator, Some(2));
assert_eq!(actual.content_indent, 4);
}
assert!(matches!(
ScalarStyle::plain()
.with_implicit(true)
.with_block_syntax(syntax),
ScalarStyle::Plain { implicit: true }
));
assert!(matches!(
ScalarStyle::implicit_plain().with_implicit(false),
ScalarStyle::Plain { implicit: false }
));
assert!(matches!(
ScalarStyle::single_quoted()
.with_implicit(true)
.with_block_syntax(syntax),
ScalarStyle::SingleQuoted
));
}
}