1#![allow(clippy::cast_possible_wrap)]
10#![allow(clippy::cast_sign_loss)]
11
12use alloc::{
13 borrow::{Cow, ToOwned},
14 collections::VecDeque,
15 string::String,
16 vec::Vec,
17};
18use core::char;
19
20use crate::{
21 char_traits::{
22 as_hex, find_non_printable, is_anchor_char, is_blank_or_breakz, is_bom, is_break,
23 is_breakz, is_flow, is_hex, is_printable, is_tag_char, is_uri_char, is_yaml_non_space,
24 is_z,
25 },
26 error::{ErrorKind, ScanError},
27 input::{BorrowedInput, SkipTabs, WhitespaceResult},
28 Options,
29};
30
31#[derive(Clone, Copy, PartialEq, Debug, Eq, Hash, PartialOrd, Ord)]
33pub enum ScalarStyle {
34 Plain,
36 SingleQuoted,
38 DoubleQuoted,
40
41 Literal,
47 Folded,
54}
55
56#[derive(Clone, Copy, Debug, Default)]
63struct MarkerOffsets {
64 chars: usize,
66 bytes: Option<usize>,
68}
69
70impl PartialEq for MarkerOffsets {
71 fn eq(&self, other: &Self) -> bool {
72 self.chars == other.chars
76 }
77}
78
79impl Eq for MarkerOffsets {}
80
81#[derive(Clone, Copy, PartialEq, Debug, Eq, Default)]
83pub struct Marker {
84 offsets: MarkerOffsets,
86 line: usize,
88 col: usize,
90}
91
92impl Marker {
93 #[must_use]
95 pub fn new(index: usize, line: usize, col: usize) -> Marker {
96 Marker {
97 offsets: MarkerOffsets {
98 chars: index,
99 bytes: None,
100 },
101 line,
102 col,
103 }
104 }
105
106 #[must_use]
108 pub fn with_byte_offset(mut self, byte_offset: Option<usize>) -> Marker {
109 self.offsets.bytes = byte_offset;
110 self
111 }
112
113 #[must_use]
115 pub fn index(&self) -> usize {
116 self.offsets.chars
117 }
118
119 #[must_use]
121 pub fn byte_offset(&self) -> Option<usize> {
122 self.offsets.bytes
123 }
124
125 #[must_use]
127 pub fn line(&self) -> usize {
128 self.line
129 }
130
131 #[must_use]
133 pub fn col(&self) -> usize {
134 self.col
135 }
136}
137
138#[non_exhaustive]
174#[derive(Clone, Copy, PartialEq, Debug, Eq, Default)]
175pub struct Span {
176 pub start: Marker,
178 pub end: Marker,
180
181 pub indent: Option<usize>,
186
187 pub tag_start: Option<Marker>,
196
197 tag_length: u32,
200}
201
202impl Span {
203 #[must_use]
205 pub fn new(start: Marker, end: Marker) -> Span {
206 Span {
207 start,
208 end,
209 indent: None,
210 tag_start: None,
211 tag_length: 0,
212 }
213 }
214
215 #[must_use]
222 pub fn empty(mark: Marker) -> Span {
223 Span {
224 start: mark,
225 end: mark,
226 indent: None,
227 tag_start: None,
228 tag_length: 0,
229 }
230 }
231
232 #[must_use]
234 pub fn with_indent(mut self, indent: Option<usize>) -> Span {
235 self.indent = indent;
236 self
237 }
238
239 #[deprecated(
245 since = "2.1.0",
246 note = "Only sets a tag start (.tag_span() then returns None). Use with_tag_span."
247 )]
248 #[must_use]
249 pub fn with_tag_start(mut self, tag_start: Option<Marker>) -> Span {
250 self.tag_start = tag_start;
251 self.tag_length = 0;
252 self
253 }
254
255 #[must_use]
257 pub fn with_tag_span(mut self, tag_span: Option<(Marker, u32)>) -> Span {
258 let (start, length) = tag_span.map_or((None, 0), |(start, length)| (Some(start), length));
259 self.tag_start = start;
260 self.tag_length = length;
261 self
262 }
263
264 #[must_use]
270 pub fn tag_start(&self) -> Option<Marker> {
271 self.tag_start
272 }
273
274 #[must_use]
296 pub fn tag_span(&self) -> Option<Span> {
297 let start = self.tag_start?;
298 if self.tag_length == 0 {
299 return None;
300 }
301 let length = usize::try_from(self.tag_length).ok()?;
302 let end = Marker::new(
305 start.index().checked_add(length)?,
306 start.line(),
307 start.col().checked_add(length)?,
308 )
309 .with_byte_offset(match start.byte_offset() {
310 Some(byte_offset) => Some(byte_offset.checked_add(length)?),
311 None => None,
312 });
313 Some(Span::new(start, end))
314 }
315
316 #[track_caller]
321 #[must_use]
322 pub fn len(&self) -> usize {
323 self.end.index() - self.start.index()
324 }
325
326 #[track_caller]
331 #[must_use]
332 pub fn is_empty(&self) -> bool {
333 self.len() == 0
334 }
335
336 #[must_use]
347 pub fn byte_range(&self) -> Option<core::ops::Range<usize>> {
348 Some(self.start.byte_offset()?..self.end.byte_offset()?)
349 }
350
351 #[must_use]
358 pub fn slice<'source>(&self, source: &'source str) -> Option<&'source str> {
359 source.get(self.byte_range()?)
360 }
361}
362
363#[non_exhaustive]
378#[derive(Clone, Copy, PartialEq, Debug, Eq, Default)]
379#[cfg(feature = "comments")]
380pub enum Placement {
381 Above,
387 Right,
390 #[default]
396 Free,
397 Last,
402}
403
404#[derive(Clone, PartialEq, Debug, Eq)]
409#[cfg(feature = "comments")]
410pub struct Comment<'input> {
411 text: Cow<'input, str>,
415 placement: Placement,
417}
418
419#[cfg(feature = "comments")]
420impl<'input> Comment<'input> {
421 #[must_use]
426 pub fn new(text: impl Into<Cow<'input, str>>) -> Self {
427 Self {
428 text: text.into(),
429 placement: Placement::Free,
430 }
431 }
432
433 #[must_use]
435 pub fn with_placement(mut self, placement: Placement) -> Self {
436 self.placement = placement;
437 self
438 }
439
440 #[must_use]
442 pub fn text(&self) -> &str {
443 self.text.as_ref()
444 }
445
446 #[must_use]
448 pub const fn placement(&self) -> Placement {
449 self.placement
450 }
451
452 #[must_use]
454 pub fn into_text(self) -> Cow<'input, str> {
455 self.text
456 }
457
458 #[must_use]
462 pub fn trimmed_text(&self) -> &str {
463 self.text.trim()
464 }
465}
466
467#[cfg(feature = "comments")]
468impl AsRef<str> for Comment<'_> {
469 fn as_ref(&self) -> &str {
470 self.text.as_ref()
471 }
472}
473
474#[non_exhaustive]
476#[derive(Clone, PartialEq, Debug, Eq)]
477pub enum TokenType<'input> {
478 StreamStart,
480 StreamEnd,
482 VersionDirective(
484 u32,
486 u32,
488 ),
489 TagDirective(
491 Cow<'input, str>,
493 Cow<'input, str>,
495 ),
496 DocumentStart,
498 DocumentEnd,
500 BlockSequenceStart,
504 BlockMappingStart,
508 BlockEnd,
510 FlowSequenceStart,
512 FlowSequenceEnd,
514 FlowMappingStart,
516 FlowMappingEnd,
518 BlockEntry,
520 FlowEntry,
522 Key,
524 Value,
526 Alias(Cow<'input, str>),
528 Anchor(Cow<'input, str>),
530 Tag(
532 Cow<'input, str>,
534 Cow<'input, str>,
536 ),
537 Scalar(ScalarStyle, Cow<'input, str>),
539 #[cfg(feature = "comments")]
545 Comment(
546 Comment<'input>,
548 ),
549 ReservedDirective(
551 String,
553 Vec<String>,
555 ),
556}
557
558#[derive(Clone, PartialEq, Debug, Eq)]
560pub struct Token<'input>(Span, TokenType<'input>);
561
562impl<'input> Token<'input> {
563 #[must_use]
565 pub const fn new(span: Span, token_type: TokenType<'input>) -> Self {
566 Self(span, token_type)
567 }
568
569 #[must_use]
571 pub const fn span(&self) -> Span {
572 self.0
573 }
574
575 #[must_use]
577 pub const fn token_type(&self) -> &TokenType<'input> {
578 &self.1
579 }
580
581 #[must_use]
583 pub fn into_parts(self) -> (Span, TokenType<'input>) {
584 (self.0, self.1)
585 }
586}
587
588#[derive(Clone, PartialEq, Debug, Eq)]
592pub(crate) enum QueuedTokenType<'input> {
593 StreamStart,
594 StreamEnd,
595 VersionDirective(u32, u32),
596 TagDirective(Cow<'input, str>, Cow<'input, str>),
597 DocumentStart,
598 DocumentEnd,
599 BlockSequenceStart,
600 BlockMappingStart,
601 BlockEnd,
602 FlowSequenceStart,
603 FlowSequenceEnd,
604 FlowMappingStart,
605 FlowMappingEnd,
606 BlockEntry,
607 FlowEntry,
608 Key,
609 Value,
610 Alias(Cow<'input, str>),
611 Anchor(Cow<'input, str>),
612 Tag(Cow<'input, str>, Cow<'input, str>),
613 Scalar(ScalarStyle, Cow<'input, str>),
614 #[cfg(feature = "comments")]
615 Comment(Comment<'input>),
616 ReservedDirective(String, Vec<String>),
617}
618
619impl<'input> QueuedTokenType<'input> {
620 fn into_public(self) -> TokenType<'input> {
621 match self {
622 Self::StreamStart => TokenType::StreamStart,
623 Self::StreamEnd => TokenType::StreamEnd,
624 Self::VersionDirective(major, minor) => TokenType::VersionDirective(major, minor),
625 Self::TagDirective(handle, prefix) => TokenType::TagDirective(handle, prefix),
626 Self::DocumentStart => TokenType::DocumentStart,
627 Self::DocumentEnd => TokenType::DocumentEnd,
628 Self::BlockSequenceStart => TokenType::BlockSequenceStart,
629 Self::BlockMappingStart => TokenType::BlockMappingStart,
630 Self::BlockEnd => TokenType::BlockEnd,
631 Self::FlowSequenceStart => TokenType::FlowSequenceStart,
632 Self::FlowSequenceEnd => TokenType::FlowSequenceEnd,
633 Self::FlowMappingStart => TokenType::FlowMappingStart,
634 Self::FlowMappingEnd => TokenType::FlowMappingEnd,
635 Self::BlockEntry => TokenType::BlockEntry,
636 Self::FlowEntry => TokenType::FlowEntry,
637 Self::Key => TokenType::Key,
638 Self::Value => TokenType::Value,
639 Self::Alias(name) => TokenType::Alias(name),
640 Self::Anchor(name) => TokenType::Anchor(name),
641 Self::Tag(handle, suffix) => TokenType::Tag(handle, suffix),
642 Self::Scalar(style, value) => TokenType::Scalar(style, value),
643 #[cfg(feature = "comments")]
644 Self::Comment(comment) => TokenType::Comment(comment),
645 Self::ReservedDirective(name, params) => TokenType::ReservedDirective(name, params),
646 }
647 }
648}
649
650impl<'input> From<TokenType<'input>> for QueuedTokenType<'input> {
651 fn from(token: TokenType<'input>) -> Self {
652 match token {
653 TokenType::StreamStart => Self::StreamStart,
654 TokenType::StreamEnd => Self::StreamEnd,
655 TokenType::VersionDirective(major, minor) => Self::VersionDirective(major, minor),
656 TokenType::TagDirective(handle, prefix) => Self::TagDirective(handle, prefix),
657 TokenType::DocumentStart => Self::DocumentStart,
658 TokenType::DocumentEnd => Self::DocumentEnd,
659 TokenType::BlockSequenceStart => Self::BlockSequenceStart,
660 TokenType::BlockMappingStart => Self::BlockMappingStart,
661 TokenType::BlockEnd => Self::BlockEnd,
662 TokenType::FlowSequenceStart => Self::FlowSequenceStart,
663 TokenType::FlowSequenceEnd => Self::FlowSequenceEnd,
664 TokenType::FlowMappingStart => Self::FlowMappingStart,
665 TokenType::FlowMappingEnd => Self::FlowMappingEnd,
666 TokenType::BlockEntry => Self::BlockEntry,
667 TokenType::FlowEntry => Self::FlowEntry,
668 TokenType::Key => Self::Key,
669 TokenType::Value => Self::Value,
670 TokenType::Alias(name) => Self::Alias(name),
671 TokenType::Anchor(name) => Self::Anchor(name),
672 TokenType::Tag(handle, suffix) => Self::Tag(handle, suffix),
673 TokenType::Scalar(style, value) => Self::Scalar(style, value),
674 #[cfg(feature = "comments")]
675 TokenType::Comment(comment) => Self::Comment(comment),
676 TokenType::ReservedDirective(name, params) => Self::ReservedDirective(name, params),
677 }
678 }
679}
680
681#[derive(Clone, PartialEq, Debug, Eq)]
683pub(crate) struct QueuedToken<'input>(pub(crate) Span, pub(crate) QueuedTokenType<'input>);
684
685impl<'input> QueuedToken<'input> {
686 fn into_public(self) -> Token<'input> {
687 Token(self.0, self.1.into_public())
688 }
689}
690
691impl<'input> From<Token<'input>> for QueuedToken<'input> {
692 fn from(token: Token<'input>) -> Self {
693 Self(token.0, token.1.into())
694 }
695}
696
697#[derive(Clone, Copy, PartialEq, Debug, Eq)]
732struct SimpleKey {
733 possible: bool,
746 required: bool,
755 token_number: usize,
761 mark: Marker,
763}
764
765impl SimpleKey {
766 fn new(mark: Marker) -> SimpleKey {
768 SimpleKey {
769 possible: false,
770 required: false,
771 token_number: 0,
772 mark,
773 }
774 }
775}
776
777#[derive(Clone, Debug, Default)]
779struct Indent {
780 indent: isize,
782 needs_block_end: bool,
800}
801
802#[derive(Debug, PartialEq)]
824enum ImplicitMappingState {
825 Possible,
830 Inside(usize),
834}
835
836#[derive(Debug)]
849#[allow(clippy::struct_excessive_bools)]
850pub struct Scanner<'input, T> {
851 input: T,
855 options: Options,
857 mark: Marker,
859 tokens: VecDeque<QueuedToken<'input>>,
866 failed: bool,
868 source_error: Option<ScanError>,
870 #[cfg(feature = "comments")]
872 deferred_error: Option<ScanError>,
873 #[cfg(feature = "comments")]
879 comments_possible: bool,
880
881 stream_start_produced: bool,
883 stream_end_produced: bool,
885 document_prefix_allowed: bool,
891 in_directive_prefix: bool,
893 adjacent_value_allowed_at: usize,
896 simple_key_allowed: bool,
900 simple_keys: smallvec::SmallVec<[SimpleKey; 8]>,
905 first_simple_key: Option<usize>,
911 indent: isize,
913 indents: smallvec::SmallVec<[Indent; 8]>,
915 flow_level: usize,
917 block_level: usize,
919 tokens_parsed: usize,
923 token_available: bool,
925 leading_whitespace: bool,
927 flow_mapping_started: smallvec::SmallVec<[bool; 8]>,
934 implicit_flow_mapping_states: smallvec::SmallVec<[ImplicitMappingState; 8]>,
947 interrupted_plain_by_comment: Option<Marker>,
950 explicit_key_tab_check_pending: bool,
956 flow_markers: smallvec::SmallVec<[(Marker, char); 8]>,
958 buf_leading_break: String,
959 buf_trailing_breaks: String,
960 buf_whitespaces: String,
961}
962
963impl<'input, T: BorrowedInput<'input>> Iterator for Scanner<'input, T> {
964 type Item = Result<Token<'input>, ScanError>;
965
966 fn next(&mut self) -> Option<Self::Item> {
967 if self.failed {
968 return None;
969 }
970 match self.next_token() {
971 Ok(Some(tok)) => {
972 debug_print!(
973 " \x1B[;32m\u{21B3} {:?} \x1B[;36m{:?}\x1B[;m",
974 tok.1,
975 tok.0
976 );
977 Some(Ok(tok))
978 }
979 Ok(None) => None,
980 Err(error) => {
981 self.failed = true;
982 Some(Err(error))
983 }
984 }
985 }
986}
987
988impl<'input, T: BorrowedInput<'input>> core::iter::FusedIterator for Scanner<'input, T> {}
989
990type ScanResult = Result<(), ScanError>;
992
993#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
998struct SkipToNextTokenOutcome {
999 saw_comment: bool,
1000 #[cfg(feature = "comments")]
1001 queued_comment: bool,
1002}
1003
1004#[derive(Debug)]
1005enum FlowScalarBuf {
1006 Borrowed {
1012 start: usize,
1013 end: usize,
1014 pending_ws_start: Option<usize>,
1015 pending_ws_end: usize,
1016 },
1017 Owned(String),
1018}
1019
1020impl FlowScalarBuf {
1021 #[inline]
1022 fn new_borrowed(start: usize) -> Self {
1023 Self::Borrowed {
1024 start,
1025 end: start,
1026 pending_ws_start: None,
1027 pending_ws_end: start,
1028 }
1029 }
1030
1031 #[inline]
1032 fn new_owned() -> Self {
1033 Self::Owned(String::new())
1034 }
1035
1036 #[inline]
1037 fn as_owned_mut(&mut self) -> Option<&mut String> {
1038 match self {
1039 Self::Owned(s) => Some(s),
1040 Self::Borrowed { .. } => None,
1041 }
1042 }
1043
1044 #[inline]
1045 fn commit_pending_ws(&mut self) {
1046 if let Self::Borrowed {
1047 end,
1048 pending_ws_start,
1049 pending_ws_end,
1050 ..
1051 } = self
1052 {
1053 if pending_ws_start.is_some() {
1054 *end = *pending_ws_end;
1055 *pending_ws_start = None;
1056 }
1057 }
1058 }
1059
1060 #[inline]
1061 fn note_pending_ws(&mut self, ws_start: usize, ws_end: usize) {
1062 if let Self::Borrowed {
1063 pending_ws_start,
1064 pending_ws_end,
1065 ..
1066 } = self
1067 {
1068 if pending_ws_start.is_none() {
1069 *pending_ws_start = Some(ws_start);
1070 }
1071 *pending_ws_end = ws_end;
1072 }
1073 }
1074
1075 #[inline]
1076 fn discard_pending_ws(&mut self) {
1077 if let Self::Borrowed {
1078 pending_ws_start,
1079 pending_ws_end,
1080 end,
1081 ..
1082 } = self
1083 {
1084 *pending_ws_start = None;
1085 *pending_ws_end = *end;
1086 }
1087 }
1088}
1089
1090impl<'input, T: BorrowedInput<'input>> Scanner<'input, T> {
1091 #[inline]
1092 fn promote_flow_scalar_buf_to_owned(
1093 &self,
1094 start_mark: &Marker,
1095 buf: &mut FlowScalarBuf,
1096 ) -> Result<(), ScanError> {
1097 let FlowScalarBuf::Borrowed {
1098 start,
1099 end,
1100 pending_ws_start: _,
1101 pending_ws_end: _,
1102 } = *buf
1103 else {
1104 return Ok(());
1105 };
1106
1107 let slice = self.input.slice_bytes(start, end).ok_or_else(|| {
1108 ScanError::from_kind(*start_mark, ErrorKind::InputOffsetsWithoutSlice)
1109 })?;
1110 *buf = FlowScalarBuf::Owned(slice.to_owned());
1111 Ok(())
1112 }
1113 #[inline]
1119 fn try_borrow_slice(&self, start: usize, end: usize) -> Option<&'input str> {
1120 self.input.slice_borrowed(start, end)
1121 }
1122
1123 fn scan_tag_handle_directive_cow(
1128 &mut self,
1129 mark: &Marker,
1130 budget: &mut usize,
1131 ) -> Result<Cow<'input, str>, ScanError> {
1132 let Some(start) = self.input.byte_offset() else {
1133 return Ok(Cow::Owned(
1134 self.scan_tag_handle_directive_owned(mark, budget)?,
1135 ));
1136 };
1137
1138 if self.input.look_ch() != '!' {
1139 return Err(ScanError::from_kind(*mark, ErrorKind::ExpectedTagBang));
1140 }
1141
1142 self.spend_directive_bytes(budget, 1, *mark)?;
1144 self.skip_non_blank();
1145
1146 self.input.lookahead(1);
1149 while self.input.next_is_alpha() {
1150 self.spend_directive_bytes(budget, 1, *mark)?;
1151 self.skip_non_blank();
1152 self.input.lookahead(1);
1153 }
1154
1155 if self.input.peek() == '!' {
1157 self.spend_directive_bytes(budget, 1, *mark)?;
1158 self.skip_non_blank();
1159 }
1160
1161 let Some(end) = self.input.byte_offset() else {
1162 return Err(ScanError::from_kind(
1163 *mark,
1164 ErrorKind::InputSlicingUnavailable,
1165 ));
1166 };
1167
1168 let Some(slice) = self.try_borrow_slice(start, end) else {
1169 let slice = self
1171 .input
1172 .slice_bytes(start, end)
1173 .ok_or_else(|| ScanError::from_kind(*mark, ErrorKind::InputSlicingUnavailable))?;
1174 if !slice.ends_with('!') && slice != "!" {
1175 return Err(ScanError::from_kind(
1176 *mark,
1177 ErrorKind::ExpectedTagDirectiveBang,
1178 ));
1179 }
1180 return Ok(Cow::Owned(slice.to_owned()));
1181 };
1182
1183 if !slice.ends_with('!') && slice != "!" {
1184 return Err(ScanError::from_kind(
1185 *mark,
1186 ErrorKind::ExpectedTagDirectiveBang,
1187 ));
1188 }
1189
1190 Ok(Cow::Borrowed(slice))
1191 }
1192
1193 fn scan_tag_handle_directive_owned(
1195 &mut self,
1196 mark: &Marker,
1197 budget: &mut usize,
1198 ) -> Result<String, ScanError> {
1199 let mut string = String::new();
1200 if self.input.look_ch() != '!' {
1201 return Err(ScanError::from_kind(*mark, ErrorKind::ExpectedTagBang));
1202 }
1203
1204 self.spend_directive_bytes(budget, 1, *mark)?;
1205 string.push('!');
1206 self.skip_non_blank();
1207
1208 self.input.lookahead(1);
1209 while self.input.next_is_alpha() {
1210 self.spend_directive_bytes(budget, 1, *mark)?;
1211 string.push(self.input.peek());
1212 self.skip_non_blank();
1213 self.input.lookahead(1);
1214 }
1215
1216 if self.input.peek() == '!' {
1217 self.spend_directive_bytes(budget, 1, *mark)?;
1218 string.push('!');
1219 self.skip_non_blank();
1220 } else if string != "!" {
1221 return Err(ScanError::from_kind(
1222 *mark,
1223 ErrorKind::ExpectedTagDirectiveBang,
1224 ));
1225 }
1226
1227 Ok(string)
1228 }
1229
1230 fn scan_tag_prefix_directive_cow(
1235 &mut self,
1236 start_mark: &Marker,
1237 budget: &mut usize,
1238 ) -> Result<Cow<'input, str>, ScanError> {
1239 let Some(start) = self.input.byte_offset() else {
1240 return Ok(Cow::Owned(
1241 self.scan_tag_prefix_directive_owned(start_mark, budget)?,
1242 ));
1243 };
1244
1245 if self.input.look_ch() == '!' {
1247 self.spend_directive_bytes(budget, 1, *start_mark)?;
1248 self.skip_non_blank();
1249 } else if !is_tag_char(self.input.peek()) {
1250 return Err(ScanError::from_kind(
1251 *start_mark,
1252 ErrorKind::InvalidGlobalTagCharacter,
1253 ));
1254 } else if self.input.peek() == '%' {
1255 } else {
1257 self.spend_directive_bytes(budget, 1, *start_mark)?;
1258 self.skip_non_blank();
1259 }
1260
1261 while is_uri_char(self.input.look_ch()) {
1263 if self.input.peek() == '%' {
1264 break;
1265 }
1266 self.spend_directive_bytes(budget, 1, *start_mark)?;
1267 self.skip_non_blank();
1268 }
1269
1270 if self.input.peek() == '%' {
1272 let current = self
1273 .input
1274 .byte_offset()
1275 .expect("byte_offset() must remain available once enabled");
1276 let mut out = if let Some(slice) = self.input.slice_bytes(start, current) {
1277 slice.to_owned()
1278 } else {
1279 String::new()
1280 };
1281
1282 while is_uri_char(self.input.look_ch()) {
1283 if self.input.peek() == '%' {
1284 out.push(self.scan_uri_escapes_with_budget(start_mark, Some(budget))?);
1285 } else {
1286 self.spend_directive_bytes(budget, 1, *start_mark)?;
1287 out.push(self.input.peek());
1288 self.skip_non_blank();
1289 }
1290 }
1291 return Ok(Cow::Owned(out));
1292 }
1293
1294 let Some(end) = self.input.byte_offset() else {
1295 return Err(ScanError::from_kind(
1296 *start_mark,
1297 ErrorKind::InputSlicingUnavailable,
1298 ));
1299 };
1300
1301 let Some(slice) = self.try_borrow_slice(start, end) else {
1302 let slice = self.input.slice_bytes(start, end).ok_or_else(|| {
1304 ScanError::from_kind(*start_mark, ErrorKind::InputSlicingUnavailable)
1305 })?;
1306 return Ok(Cow::Owned(slice.to_owned()));
1307 };
1308
1309 Ok(Cow::Borrowed(slice))
1310 }
1311
1312 fn scan_tag_prefix_directive_owned(
1314 &mut self,
1315 start_mark: &Marker,
1316 budget: &mut usize,
1317 ) -> Result<String, ScanError> {
1318 let mut string = String::new();
1319
1320 if self.input.look_ch() == '!' {
1321 self.spend_directive_bytes(budget, 1, *start_mark)?;
1322 string.push('!');
1323 self.skip_non_blank();
1324 } else if !is_tag_char(self.input.peek()) {
1325 return Err(ScanError::from_kind(
1326 *start_mark,
1327 ErrorKind::InvalidGlobalTagCharacter,
1328 ));
1329 } else if self.input.peek() == '%' {
1330 string.push(self.scan_uri_escapes_with_budget(start_mark, Some(budget))?);
1331 } else {
1332 self.spend_directive_bytes(budget, 1, *start_mark)?;
1333 string.push(self.input.peek());
1334 self.skip_non_blank();
1335 }
1336
1337 while is_uri_char(self.input.look_ch()) {
1338 if self.input.peek() == '%' {
1339 string.push(self.scan_uri_escapes_with_budget(start_mark, Some(budget))?);
1340 } else {
1341 self.spend_directive_bytes(budget, 1, *start_mark)?;
1342 string.push(self.input.peek());
1343 self.skip_non_blank();
1344 }
1345 }
1346
1347 Ok(string)
1348 }
1349 #[must_use]
1351 pub fn new(input: T) -> Self {
1352 Self::with_options(input, Options::default())
1353 }
1354
1355 #[cfg_attr(
1357 feature = "comments",
1358 doc = "\n[`Options::emit_comments`] controls comment emission. \
1359 [`Options::max_buffered_comment_events`] has no effect when using a scanner \
1360 directly, because comment-event buffering is performed by [`crate::Parser`]."
1361 )]
1362 #[must_use]
1363 pub fn with_options(input: T, options: Options) -> Self {
1364 let initial_byte_offset = input.byte_offset();
1365 #[cfg(feature = "comments")]
1368 let comments_possible = !options.emit_comments || input.may_contain_comments();
1369 Scanner {
1370 input,
1371 options,
1372 mark: Marker::new(0, 1, 0).with_byte_offset(initial_byte_offset),
1373 tokens: VecDeque::with_capacity(64),
1374 failed: false,
1375 source_error: None,
1376 #[cfg(feature = "comments")]
1377 deferred_error: None,
1378 #[cfg(feature = "comments")]
1379 comments_possible,
1380
1381 stream_start_produced: false,
1382 stream_end_produced: false,
1383 document_prefix_allowed: true,
1384 in_directive_prefix: false,
1385 adjacent_value_allowed_at: 0,
1386 simple_key_allowed: true,
1387 simple_keys: smallvec::SmallVec::new(),
1388 first_simple_key: None,
1389 indent: -1,
1390 indents: smallvec::SmallVec::new(),
1391 flow_level: 0,
1392 block_level: 0,
1393 tokens_parsed: 0,
1394 token_available: false,
1395 leading_whitespace: true,
1396 flow_mapping_started: smallvec::SmallVec::new(),
1397 implicit_flow_mapping_states: smallvec::SmallVec::new(),
1398 flow_markers: smallvec::SmallVec::new(),
1399 interrupted_plain_by_comment: None,
1400 explicit_key_tab_check_pending: false,
1401
1402 buf_leading_break: String::with_capacity(128),
1403 buf_trailing_breaks: String::with_capacity(128),
1404 buf_whitespaces: String::with_capacity(128),
1405 }
1406 }
1407
1408 #[cold]
1409 fn scan_error(&self, kind: ErrorKind) -> ScanError {
1410 ScanError::from_kind(self.mark, kind)
1411 }
1412
1413 #[inline]
1414 fn ensure_current_char_is_printable(&self) -> ScanResult {
1415 let character = self.input.peek();
1416 if self.input.next_is_z() || is_printable(character) {
1417 Ok(())
1418 } else {
1419 Err(self.scan_error(ErrorKind::UnexpectedCharacter { character }))
1420 }
1421 }
1422
1423 #[cold]
1424 fn simple_key_expected(mark: Marker) -> ScanError {
1425 ScanError::from_kind(mark, ErrorKind::SimpleKeyExpected)
1426 }
1427
1428 #[cold]
1429 fn unclosed_bracket(mark: Marker, bracket: char) -> ScanError {
1430 ScanError::from_kind(mark, ErrorKind::UnclosedFlowCollection { open: bracket })
1431 }
1432
1433 #[inline]
1435 fn skip_blank(&mut self) {
1436 self.input.skip();
1437
1438 self.mark.offsets.chars += 1;
1439 self.mark.col += 1;
1440 self.mark.offsets.bytes = self.input.byte_offset();
1441 }
1442
1443 #[inline]
1445 fn skip_non_blank(&mut self) {
1446 self.input.skip();
1447
1448 self.mark.offsets.chars += 1;
1449 self.mark.col += 1;
1450 self.mark.offsets.bytes = self.input.byte_offset();
1451 self.leading_whitespace = false;
1452 }
1453
1454 #[inline]
1459 fn skip_bom(&mut self) {
1460 self.input.skip();
1461
1462 self.mark.offsets.chars += 1;
1463 self.mark.offsets.bytes = self.input.byte_offset();
1464 }
1465
1466 #[inline]
1472 fn skip_comment_char(&mut self) {
1473 self.input.skip();
1474
1475 self.mark.offsets.chars += 1;
1476 self.mark.col += 1;
1477 self.mark.offsets.bytes = self.input.byte_offset();
1478 }
1479
1480 #[inline]
1482 fn skip_n_non_blank(&mut self, count: usize) {
1483 for _ in 0..count {
1484 self.input.skip();
1485 self.mark.offsets.chars += 1;
1486 self.mark.col += 1;
1487 }
1488 self.mark.offsets.bytes = self.input.byte_offset();
1489 self.leading_whitespace = false;
1490 }
1491
1492 #[inline]
1494 fn skip_nl(&mut self) {
1495 self.input.skip();
1496
1497 self.mark.offsets.chars += 1;
1498 self.mark.col = 0;
1499 self.mark.line += 1;
1500 self.mark.offsets.bytes = self.input.byte_offset();
1501 self.leading_whitespace = true;
1502 }
1503
1504 #[inline]
1506 fn skip_linebreak(&mut self) {
1507 if self.input.next_2_are('\r', '\n') {
1508 self.skip_blank();
1511 self.skip_nl();
1512 } else if self.input.next_is_break() {
1513 self.skip_nl();
1514 }
1515 }
1516
1517 #[cfg(all(test, feature = "comments"))]
1518 fn scan_comment_token(&mut self) -> Result<Token<'input>, ScanError> {
1519 Ok(self.scan_comment_queued_token()?.into_public())
1520 }
1521
1522 #[cfg(feature = "comments")]
1523 fn scan_comment_queued_token(&mut self) -> Result<QueuedToken<'input>, ScanError> {
1524 let start_mark = self.mark;
1525 debug_assert_eq!(self.input.peek(), '#');
1526 let placement = if self.leading_whitespace {
1527 Placement::Free
1528 } else {
1529 Placement::Right
1530 };
1531
1532 self.skip_comment_char();
1533
1534 let text = if let Some(start) = self.input.byte_offset() {
1535 let n = self.input.skip_while_non_breakz();
1537 self.mark.offsets.chars += n;
1538 self.mark.col += n;
1539 let byte_offset = self.input.byte_offset();
1540 self.mark.offsets.bytes = byte_offset;
1541 let end = byte_offset.expect("byte_offset must remain available once enabled");
1542
1543 if let Some(slice) = self.try_borrow_slice(start, end) {
1544 Cow::Borrowed(slice)
1545 } else if let Some(slice) = self.input.slice_bytes(start, end) {
1546 Cow::Owned(slice.to_owned())
1548 } else {
1549 return Err(ScanError::from_kind(
1550 start_mark,
1551 ErrorKind::InputOffsetsWithoutSlice,
1552 ));
1553 }
1554 } else {
1555 let mut owned = String::new();
1557 while {
1558 let character = self.input.look_ch();
1559 !is_breakz(character) && is_printable(character)
1560 } {
1561 owned.push(self.input.peek());
1562 self.skip_comment_char();
1563 }
1564 Cow::Owned(owned)
1565 };
1566
1567 self.ensure_current_char_is_printable()?;
1568
1569 let end_mark = self.mark;
1570 let span = Span::new(start_mark, end_mark);
1571 Ok(QueuedToken(
1572 span,
1573 QueuedTokenType::Comment(Comment { text, placement }),
1574 ))
1575 }
1576
1577 #[cfg(feature = "comments")]
1578 fn push_comment_token(&mut self) -> ScanResult {
1579 let token = self.scan_comment_queued_token()?;
1580 self.tokens.push_back(token);
1581 Ok(())
1582 }
1583
1584 fn consume_comment(&mut self) -> Result<bool, ScanError> {
1586 #[cfg(feature = "comments")]
1587 if self.options.emit_comments {
1588 self.push_comment_token()?;
1589 return Ok(true);
1590 }
1591 self.skip_comment()?;
1592 Ok(false)
1593 }
1594
1595 fn skip_comment(&mut self) -> ScanResult {
1596 debug_assert_eq!(self.input.peek(), '#');
1597
1598 self.skip_comment_char();
1599 let n = self.input.skip_while_non_breakz();
1600 self.mark.offsets.chars += n;
1601 self.mark.col += n;
1602 self.mark.offsets.bytes = self.input.byte_offset();
1603 self.ensure_current_char_is_printable()
1604 }
1605
1606 #[inline]
1608 #[must_use]
1609 pub fn stream_started(&self) -> bool {
1610 self.stream_start_produced
1611 }
1612
1613 #[inline]
1615 #[must_use]
1616 pub fn stream_ended(&self) -> bool {
1617 self.stream_end_produced
1618 }
1619
1620 #[inline]
1622 #[must_use]
1623 pub fn mark(&self) -> Marker {
1624 self.mark
1625 }
1626
1627 pub(crate) fn in_directive_prefix(&self) -> bool {
1629 self.in_directive_prefix
1630 }
1631
1632 pub(crate) fn proceed_next_document(
1637 &mut self,
1638 token: Option<QueuedToken<'input>>,
1639 ) -> ScanResult {
1640 self.check_source_error()?;
1641 self.input.lookahead(4);
1642 self.check_source_error()?;
1643
1644 let cursor = self.mark;
1645 let at_line_end = self.input.next_is_z() || self.input.next_is_break();
1646 let at_real_nul = !self.input.next_is_z() && self.input.peek() == '\0';
1647 let boundary = token
1648 .into_iter()
1649 .chain(self.tokens.drain(..))
1650 .find(|token| {
1651 match token.1 {
1652 QueuedTokenType::DocumentStart => {
1653 cursor != token.0.end || !at_real_nul
1655 }
1656 QueuedTokenType::DocumentEnd => {
1657 cursor.line > token.0.end.line || at_line_end
1660 }
1661 QueuedTokenType::StreamEnd => true,
1662 _ => false,
1663 }
1664 });
1665 self.reset_document_state();
1666 if let Some(boundary) = boundary {
1667 self.queue_recovery_boundary(boundary);
1668 return Ok(());
1669 }
1670
1671 loop {
1672 self.input.lookahead(4);
1673 self.check_source_error()?;
1674 if self.input.next_is_z() {
1675 self.queue_recovery_boundary(QueuedToken(
1676 Span::empty(self.mark),
1677 QueuedTokenType::StreamEnd,
1678 ));
1679 return Ok(());
1680 }
1681
1682 if self.mark.col == 0 {
1683 if is_bom(self.input.peek()) {
1684 self.skip_bom();
1685 continue;
1686 }
1687 let start = self.input.next_is_document_start();
1688 if start || self.input.next_is_document_end() {
1689 let mark = self.mark;
1690 self.skip_n_non_blank(3);
1691 let span = Span::new(mark, self.mark);
1692 self.input.lookahead(1);
1693 self.check_source_error()?;
1694 if self.input.next_is_z()
1697 || matches!(self.input.peek(), ' ' | '\t' | '\r' | '\n')
1698 {
1699 if start {
1700 self.queue_recovery_boundary(QueuedToken(
1701 span,
1702 QueuedTokenType::DocumentStart,
1703 ));
1704 return Ok(());
1705 }
1706 if self.skip_recovery_document_end_line()? {
1707 self.queue_recovery_boundary(QueuedToken(
1708 span,
1709 QueuedTokenType::DocumentEnd,
1710 ));
1711 return Ok(());
1712 }
1713 }
1714 }
1715 }
1716
1717 self.input.lookahead(2);
1718 self.check_source_error()?;
1719 if self.input.next_is_break() {
1720 self.skip_linebreak();
1721 } else if !self.input.next_is_z() {
1722 self.skip_non_blank();
1723 }
1724 }
1725 }
1726
1727 fn skip_recovery_document_end_line(&mut self) -> Result<bool, ScanError> {
1729 let mut comment = false;
1730 loop {
1731 self.input.lookahead(2);
1732 self.check_source_error()?;
1733 if self.input.next_is_z() || self.input.next_is_break() {
1734 return Ok(true);
1735 }
1736 let ch = self.input.peek();
1737 if !is_printable(ch) {
1738 return Ok(false);
1739 }
1740 if comment || matches!(ch, ' ' | '\t') {
1741 self.skip_non_blank();
1742 } else if ch == '#' {
1743 comment = true;
1744 self.skip_non_blank();
1745 } else {
1746 return Ok(false);
1747 }
1748 }
1749 }
1750
1751 fn reset_document_state(&mut self) {
1753 self.tokens.clear();
1754 self.failed = false;
1755 #[cfg(feature = "comments")]
1756 {
1757 self.deferred_error = None;
1758 }
1759 self.stream_start_produced = true;
1760 self.stream_end_produced = false;
1761 self.document_prefix_allowed = true;
1762 self.in_directive_prefix = false;
1763 self.adjacent_value_allowed_at = 0;
1764 self.simple_key_allowed = true;
1765 self.simple_keys.clear();
1766 self.simple_keys.push(SimpleKey::new(self.mark));
1767 self.first_simple_key = None;
1768 self.indent = -1;
1769 self.indents.clear();
1770 self.flow_level = 0;
1771 self.block_level = 0;
1772 self.tokens_parsed = 0;
1773 self.token_available = false;
1774 self.leading_whitespace = self.mark.col == 0;
1775 self.flow_mapping_started.clear();
1776 self.implicit_flow_mapping_states.clear();
1777 self.flow_markers.clear();
1778 self.interrupted_plain_by_comment = None;
1779 self.explicit_key_tab_check_pending = false;
1780 self.buf_leading_break.clear();
1781 self.buf_trailing_breaks.clear();
1782 self.buf_whitespaces.clear();
1783 }
1784
1785 fn queue_recovery_boundary(&mut self, token: QueuedToken<'input>) {
1786 self.document_prefix_allowed = matches!(token.1, QueuedTokenType::DocumentEnd);
1787 self.disallow_simple_key();
1788 self.tokens.push_back(token);
1789 self.token_available = true;
1790 }
1791
1792 pub(crate) fn check_source_error(&mut self) -> ScanResult {
1794 if let Some(kind) = self.input.take_source_error() {
1795 self.source_error
1796 .get_or_insert_with(|| ScanError::from_kind(self.mark, kind));
1797 }
1798 match &self.source_error {
1799 Some(error) => Err(error.clone()),
1800 None => Ok(()),
1801 }
1802 }
1803
1804 #[cfg(feature = "comments")]
1806 #[inline]
1807 pub(crate) fn comments_possible(&self) -> bool {
1808 self.options.emit_comments && self.comments_possible
1809 }
1810
1811 #[track_caller]
1818 #[inline]
1819 fn read_break(&mut self, s: &mut String) {
1820 self.skip_break();
1821 s.push('\n');
1822 }
1823
1824 #[track_caller]
1829 #[inline]
1830 fn skip_break(&mut self) {
1831 let c = self.input.peek();
1832 let nc = self.input.peek_nth(1);
1833 debug_assert!(is_break(c));
1834 if c == '\r' && nc == '\n' {
1835 self.skip_blank();
1836 }
1837 self.skip_nl();
1838 }
1839
1840 #[track_caller]
1845 fn insert_token(&mut self, pos: usize, tok: Token<'input>) {
1846 let old_len = self.tokens.len();
1847 assert!(pos <= old_len);
1848 self.tokens.insert(pos, tok.into());
1849 }
1850
1851 fn simple_key_token_index(&self, sk: &SimpleKey, mark: Marker) -> Result<usize, ScanError> {
1852 let Some(index) = sk.token_number.checked_sub(self.tokens_parsed) else {
1853 return Err(ScanError::from_kind(mark, ErrorKind::InvalidSimpleKey));
1854 };
1855 if index > self.tokens.len() {
1856 return Err(ScanError::from_kind(mark, ErrorKind::InvalidSimpleKey));
1857 }
1858 Ok(index)
1859 }
1860
1861 #[inline]
1862 fn allow_simple_key(&mut self) {
1863 self.simple_key_allowed = true;
1864 }
1865
1866 #[inline]
1867 fn disallow_simple_key(&mut self) {
1868 self.simple_key_allowed = false;
1869 }
1870
1871 fn fetch_next_token(&mut self) -> ScanResult {
1876 let result = self.fetch_next_token_impl();
1877 self.check_source_error()?;
1878 result
1879 }
1880
1881 fn fetch_next_token_impl(&mut self) -> ScanResult {
1882 self.input.lookahead(1);
1883
1884 if !self.stream_start_produced {
1885 self.fetch_stream_start();
1886 return Ok(());
1887 }
1888 loop {
1889 let outcome = self.skip_to_next_token()?;
1890 #[cfg(feature = "comments")]
1891 if outcome.queued_comment {
1892 return Ok(());
1893 }
1894 if outcome.saw_comment && !self.tokens.is_empty() {
1895 return Ok(());
1896 }
1897 if !outcome.saw_comment {
1898 break;
1899 }
1900 }
1903
1904 debug_print!(
1905 " \x1B[38;5;244m\u{2192} fetch_next_token after whitespace {:?} {:?}\x1B[m",
1906 self.mark,
1907 self.input.peek()
1908 );
1909
1910 self.stale_simple_keys()?;
1911
1912 let mark = self.mark;
1913 self.unroll_indent(mark.col as isize);
1914
1915 self.input.lookahead(4);
1916
1917 if self.input.next_is_z() {
1918 self.fetch_stream_end()?;
1919 return Ok(());
1920 }
1921
1922 self.ensure_current_char_is_printable()?;
1923
1924 if self.mark.col == 0 {
1925 if self.input.next_char_is('%') {
1926 self.in_directive_prefix = true;
1927 return self.fetch_directive();
1928 } else if self.input.next_is_document_start() {
1929 return self.fetch_document_indicator(TokenType::DocumentStart);
1930 } else if self.input.next_is_document_end() {
1931 self.fetch_document_indicator(TokenType::DocumentEnd)?;
1932 self.skip_ws_to_eol(SkipTabs::Yes)?;
1933 if !self.input.next_is_breakz() {
1934 return Err(self.scan_error(ErrorKind::InvalidDocumentEnd));
1935 }
1936 return Ok(());
1937 }
1938 }
1939
1940 self.in_directive_prefix = false;
1941 if self.document_prefix_allowed {
1942 self.document_prefix_allowed = false;
1943 }
1944
1945 if self.options.strict_indentation
1948 && self.flow_level > 0
1949 && (self.mark.col as isize) <= self.flow_block_indent()
1950 {
1951 return Err(self.scan_error(ErrorKind::InvalidIndentation));
1952 }
1953
1954 let c = self.input.peek();
1955 let nc = self.input.peek_nth(1);
1956 match c {
1957 '[' => self.fetch_flow_collection_start(TokenType::FlowSequenceStart),
1958 '{' => self.fetch_flow_collection_start(TokenType::FlowMappingStart),
1959 ']' => self.fetch_flow_collection_end(TokenType::FlowSequenceEnd, '[', ']'),
1960 '}' => self.fetch_flow_collection_end(TokenType::FlowMappingEnd, '{', '}'),
1961 ',' => self.fetch_flow_entry(),
1962 '-' if is_blank_or_breakz(nc) => self.fetch_block_entry(),
1963 '?' if is_blank_or_breakz(nc) => self.fetch_key(),
1964 ':' if is_blank_or_breakz(nc) => self.fetch_value(),
1965 ':' if self.flow_level > 0
1966 && (is_flow(nc) || self.mark.index() == self.adjacent_value_allowed_at) =>
1967 {
1968 self.fetch_flow_value()
1969 }
1970 '*' => self.fetch_anchor(true),
1972 '&' => self.fetch_anchor(false),
1974 '!' => self.fetch_tag(),
1975 '|' if self.flow_level == 0 => self.fetch_block_scalar(true),
1977 '>' if self.flow_level == 0 => self.fetch_block_scalar(false),
1979 '\'' => self.fetch_flow_scalar(true),
1980 '"' => self.fetch_flow_scalar(false),
1981 '-' if !is_blank_or_breakz(nc) => self.fetch_plain_scalar(),
1983 ':' | '?' if !is_blank_or_breakz(nc) && self.flow_level == 0 => {
1984 self.fetch_plain_scalar()
1985 }
1986 c if is_bom(c) && !self.options.bom_inside_document_as_content => {
1988 Err(self.scan_error(ErrorKind::BomInsideDocument))
1989 }
1990 '|' | '>' | '%' | '@' | '`' => {
1991 Err(self.scan_error(ErrorKind::UnexpectedCharacter { character: c }))
1992 }
1993 _ => self.fetch_plain_scalar(),
1994 }
1995 }
1996
1997 pub(crate) fn next_queued_token(&mut self) -> Result<Option<QueuedToken<'input>>, ScanError> {
2002 #[cfg(feature = "comments")]
2003 if self.deferred_error.is_some() {
2004 if !matches!(
2005 self.tokens.front().map(|token| &token.1),
2006 Some(QueuedTokenType::Comment(_))
2007 ) {
2008 if let Some(error) = self.deferred_error.take() {
2009 return error.into_result();
2010 }
2011 }
2012 self.token_available = true;
2013 }
2014
2015 if self.stream_end_produced {
2016 return Ok(None);
2017 }
2018
2019 if !self.token_available {
2020 #[cfg(feature = "comments")]
2021 if let Err(error) = self.fetch_more_tokens() {
2022 if matches!(
2023 self.tokens.front().map(|token| &token.1),
2024 Some(QueuedTokenType::Comment(_))
2025 ) {
2026 self.deferred_error = Some(error);
2027 } else {
2028 return Err(error);
2029 }
2030 }
2031 #[cfg(not(feature = "comments"))]
2032 self.fetch_more_tokens()?;
2033 }
2034 let Some(t) = self.tokens.pop_front() else {
2035 unreachable!("fetch_more_tokens succeeded without producing a token")
2036 };
2037 self.token_available = false;
2038 self.tokens_parsed += 1;
2039
2040 let is_stream_end = matches!(t.1, QueuedTokenType::StreamEnd);
2041 if is_stream_end {
2042 self.stream_end_produced = true;
2043 }
2044 Ok(Some(t))
2045 }
2046
2047 fn next_token(&mut self) -> Result<Option<Token<'input>>, ScanError> {
2052 Ok(self.next_queued_token()?.map(QueuedToken::into_public))
2053 }
2054
2055 fn fetch_more_tokens(&mut self) -> ScanResult {
2060 let mut need_more;
2061 loop {
2062 if self.tokens.is_empty() {
2063 need_more = true;
2064 } else {
2065 #[cfg(feature = "comments")]
2066 {
2067 need_more = false;
2068 }
2069 self.stale_simple_keys()?;
2071 #[cfg(feature = "comments")]
2072 if !matches!(
2073 self.tokens.front().map(|token| &token.1),
2074 Some(QueuedTokenType::Comment(_))
2075 ) {
2076 need_more = self.first_simple_key.is_some_and(|index| {
2078 self.simple_keys[index].token_number == self.tokens_parsed
2079 });
2080 }
2081 #[cfg(not(feature = "comments"))]
2082 {
2083 need_more = self.first_simple_key.is_some_and(|index| {
2084 self.simple_keys[index].token_number == self.tokens_parsed
2085 });
2086 }
2087 }
2088
2089 if let Some(token) = self.tokens.back() {
2092 if matches!(
2093 token.1,
2094 QueuedTokenType::DocumentEnd | QueuedTokenType::DocumentStart
2095 ) {
2096 break;
2097 }
2098 }
2099
2100 if !need_more {
2101 break;
2102 }
2103 self.fetch_next_token()?;
2104 }
2105 self.token_available = true;
2106
2107 Ok(())
2108 }
2109
2110 fn stale_simple_keys(&mut self) -> ScanResult {
2119 while let Some(index) = self.first_simple_key {
2120 let sk = &mut self.simple_keys[index];
2121 debug_assert!(sk.possible);
2122 let is_line_stale = self.flow_level == 0 && sk.mark.line < self.mark.line;
2123 let is_length_stale = self.mark.index().saturating_sub(sk.mark.index())
2126 > self.options.simple_key_max_lookahead;
2127
2128 if !is_line_stale && !is_length_stale {
2129 break;
2131 }
2132 if sk.required {
2133 return Err(Self::simple_key_expected(sk.mark));
2134 }
2135 sk.possible = false;
2136 self.first_simple_key = self.simple_keys[index + 1..]
2139 .iter()
2140 .position(|key| key.possible)
2141 .map(|offset| index + 1 + offset);
2142 }
2143 Ok(())
2144 }
2145
2146 #[cfg_attr(
2151 feature = "comments",
2152 doc = "\nWhen comment emission is enabled, encountered comments are queued as \
2153 [`TokenType::Comment`] tokens so the parser can emit presentation events."
2154 )]
2155 fn skip_to_next_token(&mut self) -> Result<SkipToNextTokenOutcome, ScanError> {
2160 let consume_linebreak = |this: &mut Self| {
2163 this.input.lookahead(2);
2164 this.skip_linebreak();
2165 if this.flow_level == 0 {
2166 this.allow_simple_key();
2167 }
2168 };
2169
2170 let mut outcome = SkipToNextTokenOutcome::default();
2171 loop {
2172 let ch = self.input.look_ch();
2173 if self.explicit_key_tab_check_pending {
2174 match ch {
2175 '\t' => {
2176 self.skip_explicit_key_tab()?;
2177 continue;
2178 }
2179 ' ' | '\n' | '\r' | '#' => {}
2180 '&' | '!' if self.options.strict_indentation => {}
2181 _ => self.explicit_key_tab_check_pending = false,
2182 }
2183 }
2184
2185 match ch {
2186 '\t' => {
2188 let indent = if self.options.strict_indentation && self.flow_level > 0 {
2189 self.flow_block_indent() + 1
2190 } else {
2191 self.indent
2192 };
2193 if self.is_within_block()
2194 && self.leading_whitespace
2195 && (self.mark.col as isize) < indent
2196 {
2197 let (chars_consumed, _) = self.input.skip_ws_to_eol_blanks(SkipTabs::Yes);
2198 self.mark.col += chars_consumed;
2199 self.mark.offsets.chars += chars_consumed;
2200 self.mark.offsets.bytes = self.input.byte_offset();
2201
2202 if self.input.look_ch() == '#' {
2204 continue;
2205 }
2206
2207 if !self.input.next_is_breakz() {
2209 return Err(self.scan_error(ErrorKind::TabInBlockIndentation));
2210 }
2211
2212 if matches!(self.input.look_ch(), '\n' | '\r') {
2214 consume_linebreak(self);
2215 }
2216 } else {
2217 self.skip_blank();
2219 }
2220 }
2221
2222 ' ' => self.skip_blank(),
2223
2224 '\n' | '\r' => consume_linebreak(self),
2225
2226 c if is_bom(c)
2227 && self.document_prefix_allowed
2228 && self.flow_level == 0
2229 && self.mark.col == 0 =>
2230 {
2231 self.skip_bom();
2232 }
2233
2234 '#' => {
2235 outcome.saw_comment = true;
2236 #[cfg(feature = "comments")]
2237 {
2238 outcome.queued_comment |= self.consume_comment()?;
2239 }
2240 #[cfg(not(feature = "comments"))]
2241 self.skip_comment()?;
2242
2243 if matches!(self.input.look_ch(), '\n' | '\r') {
2245 consume_linebreak(self);
2246 }
2247 return Ok(outcome);
2248 }
2249
2250 _ => break,
2251 }
2252 }
2253
2254 if let Some(err_mark) = self.interrupted_plain_by_comment.take() {
2257 let is_immediate_next_line = self.mark.line == err_mark.line + 1;
2261
2262 if self.flow_level == 0
2264 && is_immediate_next_line
2265 && (self.mark.col as isize) > self.indent
2266 {
2267 self.input.lookahead(4);
2271
2272 if !self.input.next_is_z()
2273 && !self.input.next_is_document_indicator()
2274 && self.input.next_can_be_plain_scalar(false)
2275 {
2276 return Err(ScanError::from_kind(
2277 err_mark,
2278 ErrorKind::CommentInterceptedScalar,
2279 ));
2280 }
2281 }
2282 }
2283
2284 Ok(outcome)
2285 }
2286
2287 fn skip_explicit_key_tab(&mut self) -> ScanResult {
2289 if self.leading_whitespace && (self.mark.col as isize) <= self.indent {
2290 let tab_mark = self.mark;
2291 let (chars_consumed, _) = self.input.skip_ws_to_eol_blanks(SkipTabs::Yes);
2292 self.mark.col += chars_consumed;
2293 self.mark.offsets.chars += chars_consumed;
2294 self.mark.offsets.bytes = self.input.byte_offset();
2295 if self.input.look_ch() != '#' && !self.input.next_is_breakz() {
2297 return Err(ScanError::from_kind(tab_mark, ErrorKind::TabNotAllowed));
2298 }
2299 } else {
2300 self.skip_blank();
2301 }
2302 self.disallow_simple_key();
2305 Ok(())
2306 }
2307
2308 fn skip_yaml_whitespace(&mut self) -> Result<bool, ScanError> {
2317 let mut need_whitespace = true;
2318 loop {
2319 match self.input.look_ch() {
2320 ' ' => {
2321 self.skip_blank();
2322
2323 need_whitespace = false;
2324 }
2325 '\t' => {
2326 self.skip_explicit_key_tab()?;
2327 need_whitespace = false;
2328 }
2329 '\n' | '\r' => {
2330 self.input.lookahead(2);
2331 self.skip_linebreak();
2332 if self.flow_level == 0 {
2333 self.allow_simple_key();
2334 }
2335 need_whitespace = false;
2336 }
2337 '#' => {
2338 if need_whitespace {
2339 self.skip_comment()?;
2340 } else {
2341 self.consume_comment()?;
2342 return Ok(true);
2343 }
2344 }
2345 _ => break,
2346 }
2347 }
2348
2349 if need_whitespace && !self.input.next_is_z() {
2353 Err(self.scan_error(ErrorKind::ExpectedWhitespace))
2354 } else {
2355 Ok(false)
2356 }
2357 }
2358
2359 fn skip_ws_to_eol(&mut self, skip_tabs: SkipTabs) -> Result<WhitespaceResult, ScanError> {
2361 #[cfg(feature = "comments")]
2362 if !self.comments_possible {
2363 let (chars_consumed, result) = self.input.skip_ws_to_eol(skip_tabs);
2364 self.mark.col += chars_consumed;
2365 self.mark.offsets.chars += chars_consumed;
2366 self.mark.offsets.bytes = self.input.byte_offset();
2367 return result.map_err(|kind| self.scan_error(kind));
2368 }
2369
2370 let (chars_consumed, whitespace) = self.input.skip_ws_to_eol_blanks(skip_tabs);
2371 self.mark.col += chars_consumed;
2372 self.mark.offsets.chars += chars_consumed;
2373 self.mark.offsets.bytes = self.input.byte_offset();
2374
2375 if self.input.look_ch() != '#' {
2376 return Ok(whitespace);
2377 }
2378
2379 if !whitespace.found_tabs() && !whitespace.has_valid_yaml_ws() {
2380 return Err(self.scan_error(ErrorKind::CommentNotSeparated));
2381 }
2382
2383 self.consume_comment()?;
2384 Ok(whitespace)
2385 }
2386
2387 fn fetch_stream_start(&mut self) {
2388 let mark = self.mark;
2389 self.indent = -1;
2390 self.stream_start_produced = true;
2391 self.allow_simple_key();
2392 self.tokens
2393 .push_back(Token(Span::empty(mark), TokenType::StreamStart).into());
2394 self.simple_keys.push(SimpleKey::new(Marker::new(0, 0, 0)));
2395 }
2396
2397 fn fetch_stream_end(&mut self) -> ScanResult {
2398 if let Some((mark, bracket)) = self.flow_markers.pop() {
2401 return Err(Self::unclosed_bracket(mark, bracket));
2402 }
2403
2404 for sk in &mut self.simple_keys {
2407 if sk.required && sk.possible {
2408 return Err(Self::simple_key_expected(sk.mark));
2409 }
2410 sk.possible = false;
2411 }
2412 self.first_simple_key = None;
2413
2414 self.unroll_indent(-1);
2415 self.remove_simple_key()?;
2416 self.disallow_simple_key();
2417
2418 self.tokens
2419 .push_back(Token(Span::empty(self.mark), TokenType::StreamEnd).into());
2420 Ok(())
2421 }
2422
2423 fn fetch_directive(&mut self) -> ScanResult {
2424 if self.options.disallow_directives {
2425 return Err(self.scan_error(ErrorKind::DirectiveDisallowed));
2426 }
2427
2428 self.unroll_indent(-1);
2429 self.remove_simple_key()?;
2430
2431 self.disallow_simple_key();
2432
2433 let token_index = self.tokens.len();
2434 let tok = self.scan_directive()?;
2435 self.insert_token(token_index, tok);
2436
2437 Ok(())
2438 }
2439
2440 fn scan_directive(&mut self) -> Result<Token<'input>, ScanError> {
2441 let start_mark = self.mark;
2442 self.skip_non_blank();
2443
2444 let mut budget = self.options.max_directive_bytes;
2447
2448 let name = self.scan_directive_name(&mut budget)?;
2449 let mut separated_comment = false;
2450 let tok = match name.as_ref() {
2451 "YAML" => self.scan_version_directive_value(&start_mark)?,
2452 "TAG" => self.scan_tag_directive_value(&start_mark, &mut budget)?,
2453 _ => {
2454 let mut params = Vec::new();
2455 while self.input.next_is_blank() {
2456 let n_blanks = self.input.skip_while_blank();
2457 self.mark.offsets.chars += n_blanks;
2458 self.mark.col += n_blanks;
2459 self.mark.offsets.bytes = self.input.byte_offset();
2460
2461 if self.input.peek() == '#' {
2462 separated_comment = true;
2463 break;
2464 }
2465
2466 if !is_blank_or_breakz(self.input.peek()) {
2467 self.spend_directive_bytes(&mut budget, n_blanks, start_mark)?;
2468 if params.len() >= self.options.max_reserved_directive_params {
2469 return Err(ScanError::from_kind(
2470 start_mark,
2471 ErrorKind::TooManyReservedDirectiveParams {
2472 limit: self.options.max_reserved_directive_params,
2473 },
2474 ));
2475 }
2476
2477 let mut param = String::new();
2478 let Some(n_chars) = self.fetch_directive_word(&mut param, &mut budget)
2479 else {
2480 return Err(self.directive_byte_limit(start_mark));
2481 };
2482 self.mark.offsets.chars += n_chars;
2483 self.mark.col += n_chars;
2484 self.mark.offsets.bytes = self.input.byte_offset();
2485 params.push(param);
2486 }
2487 }
2488
2489 Token(
2490 Span::new(start_mark, self.mark),
2491 TokenType::ReservedDirective(name, params),
2492 )
2493 }
2494 };
2495
2496 if separated_comment {
2497 self.consume_comment()?;
2499 } else {
2500 self.skip_ws_to_eol(SkipTabs::Yes)?;
2501 }
2502
2503 if self.input.next_is_breakz() {
2504 self.input.lookahead(2);
2505 self.skip_linebreak();
2506 Ok(tok)
2507 } else {
2508 Err(ScanError::from_kind(
2509 start_mark,
2510 ErrorKind::InvalidDirectiveTerminator,
2511 ))
2512 }
2513 }
2514
2515 fn scan_version_directive_value(&mut self, mark: &Marker) -> Result<Token<'input>, ScanError> {
2516 let n_blanks = self.input.skip_while_blank();
2517 self.mark.offsets.chars += n_blanks;
2518 self.mark.col += n_blanks;
2519 self.mark.offsets.bytes = self.input.byte_offset();
2520
2521 let major = self.scan_version_directive_number(mark)?;
2522
2523 if self.input.peek() != '.' {
2524 return Err(ScanError::from_kind(
2525 *mark,
2526 ErrorKind::MissingYamlVersionSeparator,
2527 ));
2528 }
2529 self.skip_non_blank();
2530
2531 let minor = self.scan_version_directive_number(mark)?;
2532
2533 Ok(Token(
2534 Span::new(*mark, self.mark),
2535 TokenType::VersionDirective(major, minor),
2536 ))
2537 }
2538
2539 fn directive_byte_limit(&self, start_mark: Marker) -> ScanError {
2541 ScanError::from_kind(
2542 start_mark,
2543 ErrorKind::DirectiveByteLimitExceeded {
2544 limit: self.options.max_directive_bytes,
2545 },
2546 )
2547 }
2548
2549 fn spend_directive_bytes(
2551 &self,
2552 budget: &mut usize,
2553 bytes: usize,
2554 start_mark: Marker,
2555 ) -> ScanResult {
2556 let Some(remaining) = budget.checked_sub(bytes) else {
2557 return Err(self.directive_byte_limit(start_mark));
2558 };
2559 *budget = remaining;
2560 Ok(())
2561 }
2562
2563 fn fetch_directive_word(&mut self, out: &mut String, budget: &mut usize) -> Option<usize> {
2570 let mut n_chars = 0;
2571
2572 loop {
2573 let c = self.input.look_ch();
2574 if !is_yaml_non_space(c) || is_z(c) {
2575 break;
2576 }
2577
2578 let len = c.len_utf8();
2579 if len > *budget {
2580 return None;
2581 }
2582 *budget -= len;
2583
2584 out.push(c);
2585 self.input.skip();
2586 n_chars += 1;
2587 }
2588
2589 Some(n_chars)
2590 }
2591
2592 fn scan_directive_name(&mut self, budget: &mut usize) -> Result<String, ScanError> {
2593 let start_mark = self.mark;
2594 let mut string = String::new();
2595
2596 let Some(n_chars) = self.fetch_directive_word(&mut string, budget) else {
2597 return Err(self.directive_byte_limit(start_mark));
2598 };
2599 self.mark.offsets.chars += n_chars;
2600 self.mark.col += n_chars;
2601 self.mark.offsets.bytes = self.input.byte_offset();
2602
2603 if string.is_empty() {
2604 return Err(ScanError::from_kind(
2605 start_mark,
2606 ErrorKind::MissingDirectiveName,
2607 ));
2608 }
2609
2610 if !is_blank_or_breakz(self.input.peek()) {
2611 return Err(ScanError::from_kind(
2612 start_mark,
2613 ErrorKind::InvalidDirectiveName,
2614 ));
2615 }
2616
2617 Ok(string)
2618 }
2619
2620 fn scan_version_directive_number(&mut self, mark: &Marker) -> Result<u32, ScanError> {
2621 let mut val = 0u32;
2622 let mut length = 0usize;
2623 while let Some(digit) = self.input.look_ch().to_digit(10) {
2624 if length + 1 > 9 {
2625 return Err(ScanError::from_kind(*mark, ErrorKind::YamlVersionTooLong));
2626 }
2627 length += 1;
2628 val = val * 10 + digit;
2629 self.skip_non_blank();
2630 }
2631
2632 if length == 0 {
2633 return Err(ScanError::from_kind(*mark, ErrorKind::MissingYamlVersion));
2634 }
2635
2636 Ok(val)
2637 }
2638
2639 fn scan_tag_directive_value(
2640 &mut self,
2641 mark: &Marker,
2642 budget: &mut usize,
2643 ) -> Result<Token<'input>, ScanError> {
2644 let n_blanks = self.input.skip_while_blank();
2645 self.mark.offsets.chars += n_blanks;
2646 self.mark.col += n_blanks;
2647 self.mark.offsets.bytes = self.input.byte_offset();
2648 self.spend_directive_bytes(budget, n_blanks, *mark)?;
2649
2650 let handle = self.scan_tag_handle_directive_cow(mark, budget)?;
2651
2652 let n_blanks = self.input.skip_while_blank();
2653 self.mark.offsets.chars += n_blanks;
2654 self.mark.col += n_blanks;
2655 self.mark.offsets.bytes = self.input.byte_offset();
2656 self.spend_directive_bytes(budget, n_blanks, *mark)?;
2657
2658 let prefix = self.scan_tag_prefix_directive_cow(mark, budget)?;
2659
2660 self.input.lookahead(1);
2661
2662 if self.input.next_is_blank_or_breakz() {
2663 Ok(Token(
2664 Span::new(*mark, self.mark),
2665 TokenType::TagDirective(handle, prefix),
2666 ))
2667 } else {
2668 Err(ScanError::from_kind(
2669 *mark,
2670 ErrorKind::InvalidTagDirectiveTerminator,
2671 ))
2672 }
2673 }
2674
2675 fn fetch_tag(&mut self) -> ScanResult {
2676 self.save_simple_key();
2677 self.disallow_simple_key();
2678
2679 let tok = self.scan_tag()?;
2680 self.tokens.push_back(tok.into());
2681 Ok(())
2682 }
2683
2684 fn scan_tag(&mut self) -> Result<Token<'input>, ScanError> {
2685 let start_mark = self.mark;
2686
2687 self.input.lookahead(2);
2689
2690 if self.input.byte_offset().is_none() {
2692 return self.scan_tag_owned(&start_mark);
2693 }
2694
2695 let (handle, suffix): (Cow<'input, str>, Cow<'input, str>) = if self
2696 .input
2697 .nth_char_is(1, '<')
2698 {
2699 let suffix = self.scan_verbatim_tag(&start_mark)?;
2701 (Cow::Owned(String::new()), Cow::Owned(suffix))
2702 } else {
2703 let handle = self.scan_tag_handle_cow(&start_mark)?;
2705 if handle.len() >= 2 && handle.starts_with('!') && handle.ends_with('!') {
2707 let suffix = self.scan_tag_shorthand_suffix_cow(&start_mark, true)?;
2709 (handle, suffix)
2710 } else {
2711 let remaining_suffix = self.scan_tag_shorthand_suffix_cow(&start_mark, false)?;
2716
2717 let suffix = self.combine_local_tag_suffix(&start_mark, handle, remaining_suffix);
2718
2719 if suffix.is_empty() {
2722 (Cow::Borrowed(""), Cow::Borrowed("!"))
2723 } else {
2724 (Cow::Borrowed("!"), suffix)
2725 }
2726 }
2727 };
2728
2729 if is_blank_or_breakz(self.input.look_ch())
2730 || (self.flow_level > 0 && matches!(self.input.peek(), ',' | ']' | '}'))
2731 {
2732 Ok(Token(
2735 Span::new(start_mark, self.mark),
2736 TokenType::Tag(handle, suffix),
2737 ))
2738 } else {
2739 Err(ScanError::from_kind(
2740 start_mark,
2741 ErrorKind::InvalidTagTerminator,
2742 ))
2743 }
2744 }
2745
2746 fn combine_local_tag_suffix(
2747 &self,
2748 start_mark: &Marker,
2749 handle: Cow<'input, str>,
2750 remaining: Cow<'input, str>,
2751 ) -> Cow<'input, str> {
2752 if handle.len() == 1 {
2753 return remaining;
2754 }
2755
2756 match (handle, remaining) {
2757 (Cow::Borrowed(handle), Cow::Borrowed(remaining)) => {
2758 if remaining.is_empty() {
2759 return Cow::Borrowed(&handle[1..]);
2760 }
2761
2762 let borrowed = start_mark
2763 .byte_offset()
2764 .and_then(|start| start.checked_add(1))
2765 .zip(self.input.byte_offset())
2766 .and_then(|(start, end)| self.try_borrow_slice(start, end));
2767 borrowed.map_or_else(
2768 || {
2769 let mut combined =
2770 String::with_capacity(handle.len() - 1 + remaining.len());
2771 combined.push_str(&handle[1..]);
2772 combined.push_str(remaining);
2773 Cow::Owned(combined)
2774 },
2775 Cow::Borrowed,
2776 )
2777 }
2778 (Cow::Borrowed(handle), Cow::Owned(mut remaining)) => {
2779 remaining.reserve(handle.len() - 1);
2780 remaining.insert_str(0, &handle[1..]);
2781 Cow::Owned(remaining)
2782 }
2783 (Cow::Owned(mut handle), remaining) => {
2784 handle.remove(0);
2785 handle.push_str(&remaining);
2786 Cow::Owned(handle)
2787 }
2788 }
2789 }
2790
2791 fn scan_tag_owned(&mut self, start_mark: &Marker) -> Result<Token<'input>, ScanError> {
2793 let mut handle = String::new();
2794 let mut suffix;
2795
2796 if self.input.nth_char_is(1, '<') {
2797 suffix = self.scan_verbatim_tag(start_mark)?;
2798 } else {
2799 handle = self.scan_tag_handle(false, start_mark)?;
2801 if handle.len() >= 2 && handle.starts_with('!') && handle.ends_with('!') {
2803 let is_secondary_handle = handle == "!!";
2805 suffix =
2806 self.scan_tag_shorthand_suffix(false, is_secondary_handle, "", start_mark)?;
2807 } else {
2808 suffix = self.scan_tag_shorthand_suffix(false, false, &handle, start_mark)?;
2809 "!".clone_into(&mut handle);
2810 if suffix.is_empty() {
2813 handle.clear();
2814 "!".clone_into(&mut suffix);
2815 }
2816 }
2817 }
2818
2819 if is_blank_or_breakz(self.input.look_ch())
2820 || (self.flow_level > 0 && matches!(self.input.peek(), ',' | ']' | '}'))
2821 {
2822 Ok(Token(
2825 Span::new(*start_mark, self.mark),
2826 TokenType::Tag(handle.into(), suffix.into()),
2827 ))
2828 } else {
2829 Err(ScanError::from_kind(
2830 *start_mark,
2831 ErrorKind::InvalidTagTerminator,
2832 ))
2833 }
2834 }
2835
2836 fn scan_tag_handle_cow(&mut self, mark: &Marker) -> Result<Cow<'input, str>, ScanError> {
2841 let Some(start) = self.input.byte_offset() else {
2842 return Ok(Cow::Owned(self.scan_tag_handle(false, mark)?));
2843 };
2844
2845 if self.input.look_ch() != '!' {
2846 return Err(ScanError::from_kind(*mark, ErrorKind::ExpectedTagBang));
2847 }
2848
2849 self.skip_non_blank();
2851
2852 self.input.lookahead(1);
2854 while self.input.next_is_alpha() {
2855 self.skip_non_blank();
2856 self.input.lookahead(1);
2857 }
2858
2859 if self.input.peek() == '!' {
2861 self.skip_non_blank();
2862 }
2863
2864 let Some(end) = self.input.byte_offset() else {
2865 return Ok(Cow::Owned(self.scan_tag_handle(false, mark)?));
2866 };
2867
2868 if let Some(slice) = self.try_borrow_slice(start, end) {
2869 Ok(Cow::Borrowed(slice))
2870 } else {
2871 let slice = self
2872 .input
2873 .slice_bytes(start, end)
2874 .ok_or_else(|| ScanError::from_kind(*mark, ErrorKind::InputSlicingUnavailable))?;
2875 Ok(Cow::Owned(slice.to_owned()))
2876 }
2877 }
2878
2879 fn scan_tag_shorthand_suffix_cow(
2883 &mut self,
2884 mark: &Marker,
2885 require_non_empty: bool,
2886 ) -> Result<Cow<'input, str>, ScanError> {
2887 let Some(start) = self.input.byte_offset() else {
2888 return Ok(Cow::Owned(
2889 self.scan_tag_shorthand_suffix(false, false, "", mark)?,
2890 ));
2891 };
2892
2893 while is_tag_char(self.input.look_ch()) {
2895 if self.input.peek() == '%' {
2896 let current = self
2898 .input
2899 .byte_offset()
2900 .expect("byte_offset() must remain available once enabled");
2901 let mut out = if let Some(slice) = self.input.slice_bytes(start, current) {
2902 slice.to_owned()
2903 } else {
2904 String::new()
2905 };
2906
2907 while is_tag_char(self.input.look_ch()) {
2909 if self.input.peek() == '%' {
2910 out.push(self.scan_uri_escapes(mark)?);
2911 } else {
2912 out.push(self.input.peek());
2913 self.skip_non_blank();
2914 }
2915 }
2916 return Ok(Cow::Owned(out));
2917 }
2918 self.skip_non_blank();
2919 }
2920
2921 let Some(end) = self.input.byte_offset() else {
2922 return Ok(Cow::Owned(
2923 self.scan_tag_shorthand_suffix(false, false, "", mark)?,
2924 ));
2925 };
2926
2927 if require_non_empty && start == end {
2928 return Err(ScanError::from_kind(*mark, ErrorKind::MissingTagUri));
2929 }
2930
2931 if let Some(slice) = self.try_borrow_slice(start, end) {
2932 Ok(Cow::Borrowed(slice))
2933 } else {
2934 let slice = self
2935 .input
2936 .slice_bytes(start, end)
2937 .ok_or_else(|| ScanError::from_kind(*mark, ErrorKind::InputSlicingUnavailable))?;
2938 Ok(Cow::Owned(slice.to_owned()))
2939 }
2940 }
2941
2942 fn scan_tag_handle(&mut self, directive: bool, mark: &Marker) -> Result<String, ScanError> {
2943 let mut string = String::new();
2944 if self.input.look_ch() != '!' {
2945 return Err(ScanError::from_kind(*mark, ErrorKind::ExpectedTagBang));
2946 }
2947
2948 string.push(self.input.peek());
2949 self.skip_non_blank();
2950
2951 let n_chars = self.input.fetch_while_is_alpha(&mut string);
2952 self.mark.offsets.chars += n_chars;
2953 self.mark.col += n_chars;
2954 self.mark.offsets.bytes = self.input.byte_offset();
2955
2956 if self.input.peek() == '!' {
2958 string.push(self.input.peek());
2959 self.skip_non_blank();
2960 } else if directive && string != "!" {
2961 return Err(ScanError::from_kind(
2965 *mark,
2966 ErrorKind::ExpectedTagDirectiveBang,
2967 ));
2968 }
2969 Ok(string)
2970 }
2971
2972 fn scan_verbatim_tag(&mut self, start_mark: &Marker) -> Result<String, ScanError> {
2976 self.skip_non_blank();
2978 self.skip_non_blank();
2979
2980 let mut string = String::new();
2981 while is_uri_char(self.input.look_ch()) {
2982 if self.input.peek() == '%' {
2983 string.push(self.scan_uri_escapes(start_mark)?);
2984 } else {
2985 string.push(self.input.peek());
2986 self.skip_non_blank();
2987 }
2988 }
2989
2990 if string.is_empty() {
2991 return Err(ScanError::from_kind(*start_mark, ErrorKind::MissingTagUri));
2992 }
2993
2994 if self.input.peek() != '>' {
2995 return Err(ScanError::from_kind(
2996 *start_mark,
2997 ErrorKind::UnclosedVerbatimTag,
2998 ));
2999 }
3000 self.skip_non_blank();
3001
3002 Ok(string)
3003 }
3004
3005 fn scan_tag_shorthand_suffix(
3006 &mut self,
3007 _directive: bool,
3008 _is_secondary: bool,
3009 head: &str,
3010 mark: &Marker,
3011 ) -> Result<String, ScanError> {
3012 let mut length = head.len();
3013 let mut string = String::new();
3014
3015 if length > 1 {
3018 string.extend(head.chars().skip(1));
3019 }
3020
3021 while is_tag_char(self.input.look_ch()) {
3022 if self.input.peek() == '%' {
3024 string.push(self.scan_uri_escapes(mark)?);
3025 } else {
3026 string.push(self.input.peek());
3027 self.skip_non_blank();
3028 }
3029
3030 length += 1;
3031 }
3032
3033 if length == 0 {
3034 return Err(ScanError::from_kind(*mark, ErrorKind::MissingTagUri));
3035 }
3036
3037 Ok(string)
3038 }
3039
3040 fn scan_uri_escapes(&mut self, mark: &Marker) -> Result<char, ScanError> {
3041 self.scan_uri_escapes_with_budget(mark, None)
3042 }
3043
3044 fn scan_uri_escapes_with_budget(
3045 &mut self,
3046 mark: &Marker,
3047 mut directive_budget: Option<&mut usize>,
3048 ) -> Result<char, ScanError> {
3049 let mut width = 0usize;
3050 let mut bytes = [0u8; 4];
3051 let mut bytes_len = 0usize;
3052 loop {
3053 self.input.lookahead(3);
3054
3055 let c = self.input.peek_nth(1);
3056 let nc = self.input.peek_nth(2);
3057
3058 if !(self.input.peek() == '%' && is_hex(c) && is_hex(nc)) {
3059 return Err(ScanError::from_kind(*mark, ErrorKind::InvalidTagEscape));
3060 }
3061
3062 if let Some(budget) = directive_budget.as_deref_mut() {
3063 self.spend_directive_bytes(budget, 3, *mark)?;
3064 }
3065
3066 let byte = u8::try_from((as_hex(c) << 4) + as_hex(nc))
3067 .expect("two hex nibbles always fit in a byte");
3068 if width == 0 {
3069 width = match byte {
3070 _ if byte & 0x80 == 0x00 => 1,
3071 _ if byte & 0xE0 == 0xC0 => 2,
3072 _ if byte & 0xF0 == 0xE0 => 3,
3073 _ if byte & 0xF8 == 0xF0 => 4,
3074 _ => {
3075 return Err(ScanError::from_kind(
3076 *mark,
3077 ErrorKind::InvalidTagUtf8LeadingByte,
3078 ));
3079 }
3080 };
3081 } else if byte & 0xc0 != 0x80 {
3082 return Err(ScanError::from_kind(
3083 *mark,
3084 ErrorKind::InvalidTagUtf8TrailingByte,
3085 ));
3086 }
3087
3088 bytes[bytes_len] = byte;
3089 bytes_len += 1;
3090
3091 self.skip_n_non_blank(3);
3092
3093 width -= 1;
3094 if width == 0 {
3095 break;
3096 }
3097 }
3098
3099 let s = core::str::from_utf8(&bytes[..bytes_len])
3100 .map_err(|_| ScanError::from_kind(*mark, ErrorKind::InvalidTagUtf8))?;
3101
3102 let Some(ch) = s.chars().next() else {
3103 unreachable!("a validated URI escape cannot decode to an empty string")
3104 };
3105 Ok(ch)
3106 }
3107
3108 fn fetch_anchor(&mut self, alias: bool) -> ScanResult {
3109 self.save_simple_key();
3110 self.disallow_simple_key();
3111
3112 let tok = self.scan_anchor(alias)?;
3113
3114 self.tokens.push_back(tok.into());
3115
3116 Ok(())
3117 }
3118
3119 fn scan_anchor(&mut self, alias: bool) -> Result<Token<'input>, ScanError> {
3120 let start_mark = self.mark;
3121
3122 self.skip_non_blank();
3124
3125 if let Some(start) = self.input.byte_offset() {
3127 while is_anchor_char(self.input.look_ch()) {
3128 self.skip_non_blank();
3129 }
3130
3131 let end = self
3132 .input
3133 .byte_offset()
3134 .expect("byte_offset() must remain available once enabled");
3135
3136 if start == end {
3137 return Err(ScanError::from_kind(
3138 start_mark,
3139 ErrorKind::MissingAnchorOrAliasName,
3140 ));
3141 }
3142
3143 let cow = if let Some(slice) = self.try_borrow_slice(start, end) {
3144 Cow::Borrowed(slice)
3145 } else if let Some(slice) = self.input.slice_bytes(start, end) {
3146 Cow::Owned(slice.to_owned())
3147 } else {
3148 return Err(ScanError::from_kind(
3149 start_mark,
3150 ErrorKind::InputSlicingUnavailable,
3151 ));
3152 };
3153
3154 let tok = if alias {
3155 TokenType::Alias(cow)
3156 } else {
3157 TokenType::Anchor(cow)
3158 };
3159 return Ok(Token(Span::new(start_mark, self.mark), tok));
3160 }
3161
3162 let mut string = String::new();
3163 while is_anchor_char(self.input.look_ch()) {
3164 string.push(self.input.peek());
3165 self.skip_non_blank();
3166 }
3167
3168 if string.is_empty() {
3169 return Err(ScanError::from_kind(
3170 start_mark,
3171 ErrorKind::MissingAnchorOrAliasName,
3172 ));
3173 }
3174
3175 let tok = if alias {
3176 TokenType::Alias(string.into())
3177 } else {
3178 TokenType::Anchor(string.into())
3179 };
3180 Ok(Token(Span::new(start_mark, self.mark), tok))
3181 }
3182
3183 fn fetch_flow_collection_start(&mut self, tok: TokenType<'input>) -> ScanResult {
3184 self.save_simple_key();
3186
3187 let start_mark = self.mark;
3188 let indicator = self.input.peek();
3189 self.flow_markers.push((start_mark, indicator));
3190
3191 self.roll_one_col_indent();
3192 self.increase_flow_level()?;
3193
3194 self.allow_simple_key();
3195
3196 self.skip_non_blank();
3197 let end_mark = self.mark;
3198
3199 if tok == TokenType::FlowMappingStart {
3200 self.flow_mapping_started.push(true);
3201 } else {
3202 self.flow_mapping_started.push(false);
3203 self.implicit_flow_mapping_states
3204 .push(ImplicitMappingState::Possible);
3205 }
3206
3207 let token_index = self.tokens.len();
3208 self.skip_ws_to_eol(SkipTabs::Yes)?;
3209
3210 self.insert_token(token_index, Token(Span::new(start_mark, end_mark), tok));
3211 Ok(())
3212 }
3213
3214 fn fetch_flow_collection_end(
3215 &mut self,
3216 tok: TokenType<'input>,
3217 expected_open: char,
3218 actual_close: char,
3219 ) -> ScanResult {
3220 if self.flow_level == 0 {
3222 return Err(self.scan_error(ErrorKind::MisplacedFlowCollectionEnd));
3223 }
3224
3225 let Some((open_mark, open_ch)) = self.flow_markers.pop() else {
3226 return Err(self.scan_error(ErrorKind::MisplacedFlowCollectionEnd));
3227 };
3228
3229 if open_ch != expected_open {
3230 return Err(ScanError::from_kind(
3231 open_mark,
3232 ErrorKind::MismatchedFlowCollectionEnd {
3233 open: open_ch,
3234 close: actual_close,
3235 },
3236 ));
3237 }
3238
3239 let flow_level = self.flow_level;
3240
3241 self.remove_simple_key()?;
3242
3243 if matches!(tok, TokenType::FlowSequenceEnd) {
3244 self.end_implicit_mapping(self.mark, flow_level);
3245 self.implicit_flow_mapping_states.pop();
3247 }
3248 self.flow_mapping_started.pop();
3249
3250 self.decrease_flow_level();
3251
3252 self.disallow_simple_key();
3253
3254 let start_mark = self.mark;
3255 self.skip_non_blank();
3256 let end_mark = self.mark;
3257 let token_index = self.tokens.len();
3258 self.skip_ws_to_eol(SkipTabs::Yes)?;
3259
3260 if self.flow_level > 0 {
3266 self.adjacent_value_allowed_at = self.mark.index();
3267 }
3268
3269 self.insert_token(token_index, Token(Span::new(start_mark, end_mark), tok));
3270 Ok(())
3271 }
3272
3273 fn fetch_flow_entry(&mut self) -> ScanResult {
3275 self.remove_simple_key()?;
3276 self.allow_simple_key();
3277
3278 self.end_implicit_mapping(self.mark, self.flow_level);
3279 if self.current_flow_collection_is_sequence() {
3280 self.set_current_flow_mapping_started(false);
3281 }
3282
3283 let start_mark = self.mark;
3284 self.skip_non_blank();
3285 let end_mark = self.mark;
3286 let token_index = self.tokens.len();
3287 self.skip_ws_to_eol(SkipTabs::Yes)?;
3288
3289 self.insert_token(
3290 token_index,
3291 Token(Span::new(start_mark, end_mark), TokenType::FlowEntry),
3292 );
3293 Ok(())
3294 }
3295
3296 fn increase_flow_level(&mut self) -> ScanResult {
3297 if self.flow_level >= self.options.flow_nesting_limit {
3298 return Err(self.scan_error(ErrorKind::RecursionLimitExceeded));
3299 }
3300
3301 self.simple_keys.push(SimpleKey::new(Marker::new(0, 0, 0)));
3302 self.flow_level += 1;
3303 Ok(())
3304 }
3305
3306 fn decrease_flow_level(&mut self) {
3307 if self.flow_level > 0 {
3308 debug_assert!(!self.simple_keys.last().unwrap().possible);
3310 debug_assert_ne!(self.first_simple_key, Some(self.flow_level));
3311 self.flow_level -= 1;
3312 self.simple_keys.pop().unwrap();
3313 }
3314 }
3315
3316 fn fetch_block_entry(&mut self) -> ScanResult {
3322 if self.flow_level > 0 {
3323 return Err(self.scan_error(ErrorKind::BlockEntryInFlowCollection));
3325 }
3326 if !self.simple_key_allowed {
3328 return Err(self.scan_error(ErrorKind::BlockSequenceEntryNotAllowed));
3329 }
3330
3331 let mark = self.mark;
3333 self.skip_non_blank();
3334
3335 self.roll_indent(mark.col, None, TokenType::BlockSequenceStart, mark)?;
3337 let token_index = self.tokens.len();
3338 let found_tabs = self.skip_ws_to_eol(SkipTabs::Yes)?.found_tabs();
3339 self.input.lookahead(2);
3340 if found_tabs && self.input.next_char_is('-') && is_blank_or_breakz(self.input.peek_nth(1))
3341 {
3342 return Err(self.scan_error(ErrorKind::InvalidBlockEntryWhitespace));
3343 }
3344
3345 self.skip_ws_to_eol(SkipTabs::No)?;
3346 self.input.lookahead(1);
3347 if self.input.next_is_break() || self.input.next_is_flow() {
3348 self.roll_one_col_indent();
3349 }
3350
3351 self.remove_simple_key()?;
3352 self.allow_simple_key();
3353
3354 self.insert_token(
3355 token_index,
3356 Token(Span::empty(self.mark), TokenType::BlockEntry),
3357 );
3358
3359 Ok(())
3360 }
3361
3362 fn fetch_document_indicator(&mut self, t: TokenType<'input>) -> ScanResult {
3363 self.in_directive_prefix = false;
3364 if let Some((mark, bracket)) = self.flow_markers.pop() {
3365 return Err(ScanError::from_kind(
3366 mark,
3367 ErrorKind::UnclosedFlowCollection { open: bracket },
3368 ));
3369 }
3370
3371 self.unroll_indent(-1);
3372 self.remove_simple_key()?;
3373 self.disallow_simple_key();
3374
3375 let mark = self.mark;
3376
3377 self.skip_n_non_blank(3);
3378
3379 self.document_prefix_allowed = matches!(t, TokenType::DocumentEnd);
3380 self.tokens
3381 .push_back(Token(Span::new(mark, self.mark), t).into());
3382 Ok(())
3383 }
3384
3385 fn fetch_block_scalar(&mut self, literal: bool) -> ScanResult {
3386 self.save_simple_key();
3387 self.allow_simple_key();
3388 let token_index = self.tokens.len();
3389 let tok = self.scan_block_scalar(literal)?;
3390
3391 self.insert_token(token_index, tok);
3392 Ok(())
3393 }
3394
3395 #[allow(clippy::too_many_lines)]
3396 fn scan_block_scalar(&mut self, literal: bool) -> Result<Token<'input>, ScanError> {
3397 let start_mark = self.mark;
3398 let mut chomping = Chomping::Clip;
3399 let mut increment: usize = 0;
3400 let mut indent: usize = 0;
3401 let mut trailing_blank: bool;
3402 let mut leading_blank: bool = false;
3403 let style = if literal {
3404 ScalarStyle::Literal
3405 } else {
3406 ScalarStyle::Folded
3407 };
3408
3409 let mut string = String::new();
3410 let mut leading_break = false;
3411 let mut trailing_breaks = 0;
3412 let mut chomping_break = false;
3413
3414 self.skip_non_blank();
3416 self.unroll_non_block_indents();
3417
3418 if self.input.look_ch() == '+' || self.input.peek() == '-' {
3419 if self.input.peek() == '+' {
3420 chomping = Chomping::Keep;
3421 } else {
3422 chomping = Chomping::Strip;
3423 }
3424 self.skip_non_blank();
3425 self.input.lookahead(1);
3426 if self.input.next_is_digit() {
3427 if self.input.peek() == '0' {
3428 return Err(ScanError::from_kind(
3429 start_mark,
3430 ErrorKind::ZeroBlockScalarIndent,
3431 ));
3432 }
3433 increment = (self.input.peek() as usize) - ('0' as usize);
3434 self.skip_non_blank();
3435 }
3436 } else if self.input.next_is_digit() {
3437 if self.input.peek() == '0' {
3438 return Err(ScanError::from_kind(
3439 start_mark,
3440 ErrorKind::ZeroBlockScalarIndent,
3441 ));
3442 }
3443
3444 increment = (self.input.peek() as usize) - ('0' as usize);
3445 self.skip_non_blank();
3446 self.input.lookahead(1);
3447 if self.input.peek() == '+' || self.input.peek() == '-' {
3448 if self.input.peek() == '+' {
3449 chomping = Chomping::Keep;
3450 } else {
3451 chomping = Chomping::Strip;
3452 }
3453 self.skip_non_blank();
3454 }
3455 }
3456
3457 self.skip_ws_to_eol(SkipTabs::Yes)?;
3458
3459 self.input.lookahead(1);
3461 self.ensure_current_char_is_printable()?;
3462 if !self.input.next_is_breakz() {
3463 return Err(ScanError::from_kind(
3464 start_mark,
3465 ErrorKind::InvalidBlockScalarHeader,
3466 ));
3467 }
3468
3469 if self.input.next_is_break() {
3470 self.input.lookahead(2);
3471 self.skip_break();
3472 chomping_break = true;
3473 }
3474
3475 self.ensure_current_char_is_printable()?;
3476
3477 if self.input.look_ch() == '\t' {
3478 return Err(ScanError::from_kind(
3479 start_mark,
3480 ErrorKind::TabAtBlockScalarStart,
3481 ));
3482 }
3483
3484 if increment > 0 {
3485 indent = if self.indent >= 0 {
3486 (self.indent + increment as isize) as usize
3487 } else {
3488 increment
3489 }
3490 }
3491
3492 if indent == 0 {
3494 self.skip_block_scalar_first_line_indent(&mut indent, &mut trailing_breaks);
3495 } else {
3496 self.skip_block_scalar_indent(indent, &mut trailing_breaks);
3497 }
3498
3499 self.ensure_current_char_is_printable()?;
3500
3501 if self.input.next_is_z() {
3506 let contents = match chomping {
3507 Chomping::Strip => String::new(),
3509 _ if self.mark.line == start_mark.line() => String::new(),
3511 Chomping::Clip => String::new(),
3513 Chomping::Keep if trailing_breaks == 0 && self.mark.col > 0 => {
3516 if chomping_break && !self.options.block_scalar_eof_without_line_feed {
3517 "\n".into()
3518 } else {
3519 String::new()
3520 }
3521 }
3522 Chomping::Keep => "\n".repeat(trailing_breaks),
3524 };
3525
3526 return Ok(Token(
3527 Span::new(start_mark, self.mark),
3528 TokenType::Scalar(style, contents.into()),
3529 ));
3530 }
3531
3532 if self.mark.col < indent && (self.mark.col as isize) > self.indent {
3533 if self.indent < 0 && self.mark.col == 0 {
3534 self.input.lookahead(4);
3535 if self.input.next_is_document_start()
3536 || self.input.next_is_document_end()
3537 || self.input.peek() == '#'
3538 {
3539 } else {
3543 return Err(self.scan_error(ErrorKind::InvalidBlockScalarIndent));
3544 }
3545 } else {
3546 return Err(self.scan_error(ErrorKind::InvalidBlockScalarIndent));
3547 }
3548 }
3549
3550 let start_mark = self.mark;
3551 while self.mark.col == indent && !self.input.next_is_z() {
3552 self.ensure_current_char_is_printable()?;
3553
3554 if indent == 0 {
3555 self.input.lookahead(4);
3556 if self.input.next_is_document_indicator() {
3557 break;
3558 }
3559 }
3560
3561 trailing_blank = self.input.next_is_blank();
3563 if !literal && leading_break && !leading_blank && !trailing_blank {
3564 string.extend(core::iter::repeat('\n').take(trailing_breaks));
3565 if trailing_breaks == 0 {
3566 string.push(' ');
3567 }
3568 } else {
3569 if leading_break {
3570 string.push('\n');
3571 }
3572 string.extend(core::iter::repeat('\n').take(trailing_breaks));
3573 }
3574
3575 leading_break = false;
3576 trailing_breaks = 0;
3577
3578 leading_blank = self.input.next_is_blank();
3579
3580 self.scan_block_scalar_content_line(&mut string);
3581
3582 self.input.lookahead(2);
3584 if self.input.next_is_z() {
3585 break;
3586 }
3587
3588 self.ensure_current_char_is_printable()?;
3589
3590 self.skip_break();
3591 leading_break = true;
3592
3593 self.skip_block_scalar_indent(indent, &mut trailing_breaks);
3595 }
3596
3597 self.ensure_current_char_is_printable()?;
3598
3599 if chomping != Chomping::Strip {
3601 if !leading_break
3608 && !self.options.block_scalar_eof_without_line_feed
3609 && self.input.next_is_z()
3610 && self.mark.col >= indent.max(1)
3611 {
3612 string.push('\n');
3613 }
3614 if leading_break {
3615 string.push('\n');
3616 }
3617 }
3618
3619 if chomping == Chomping::Keep {
3620 string.extend(core::iter::repeat('\n').take(trailing_breaks));
3621 }
3622
3623 if let Some(character) = find_non_printable(&string) {
3624 return Err(ScanError::from_kind(
3625 start_mark,
3626 ErrorKind::UnexpectedCharacter { character },
3627 ));
3628 }
3629
3630 let span = if string.trim().is_empty() {
3631 Span::new(start_mark, self.mark)
3632 } else {
3633 Span::new(start_mark, self.mark).with_indent(Some(indent))
3634 };
3635
3636 Ok(Token(span, TokenType::Scalar(style, string.into())))
3637 }
3638
3639 fn scan_block_scalar_content_line(&mut self, string: &mut String) {
3644 let chars_consumed = self.input.fetch_block_scalar_line(string);
3645 self.mark.col += chars_consumed;
3646 self.mark.offsets.chars += chars_consumed;
3647 self.mark.offsets.bytes = self.input.byte_offset();
3648 }
3651
3652 fn skip_block_scalar_indent(&mut self, indent: usize, breaks: &mut usize) {
3654 loop {
3655 if indent < self.input.bufmaxlen().saturating_sub(2) {
3657 self.input.lookahead(self.input.bufmaxlen());
3658 while self.mark.col < indent && self.input.peek() == ' ' {
3659 self.skip_blank();
3660 }
3661 } else {
3662 loop {
3663 self.input.lookahead(self.input.bufmaxlen());
3664 while !self.input.buf_is_empty()
3665 && self.mark.col < indent
3666 && self.input.peek() == ' '
3667 {
3668 self.skip_blank();
3669 }
3670 if self.mark.col == indent
3674 || (!self.input.buf_is_empty() && self.input.peek() != ' ')
3675 {
3676 break;
3677 }
3678 }
3679 self.input.lookahead(2);
3680 }
3681
3682 if self.input.next_is_break() {
3684 self.skip_break();
3685 *breaks += 1;
3686 } else {
3687 break;
3689 }
3690 }
3691 }
3692
3693 fn skip_block_scalar_first_line_indent(&mut self, indent: &mut usize, breaks: &mut usize) {
3698 let mut max_indent = 0;
3699 loop {
3700 while self.input.look_ch() == ' ' {
3702 self.skip_blank();
3703 }
3704
3705 if self.mark.col > max_indent {
3706 max_indent = self.mark.col;
3707 }
3708
3709 if self.input.next_is_break() {
3710 self.input.lookahead(2);
3712 self.skip_break();
3713 *breaks += 1;
3714 } else {
3715 break;
3717 }
3718 }
3719
3720 *indent = max_indent.max((self.indent + 1) as usize);
3729 }
3730
3731 fn fetch_flow_scalar(&mut self, single: bool) -> ScanResult {
3732 self.save_simple_key();
3733 self.disallow_simple_key();
3734
3735 let token_index = self.tokens.len();
3736 let tok = self.scan_flow_scalar(single)?;
3737
3738 if self.skip_to_next_token()?.saw_comment {
3741 self.adjacent_value_allowed_at = usize::MAX;
3742 } else {
3743 self.adjacent_value_allowed_at = self.mark.index();
3744 }
3745
3746 self.insert_token(token_index, tok);
3747 Ok(())
3748 }
3749
3750 #[allow(clippy::too_many_lines)]
3751 fn scan_flow_scalar(&mut self, single: bool) -> Result<Token<'input>, ScanError> {
3752 let start_mark = self.mark;
3753
3754 let mut buf = match self.input.byte_offset() {
3756 Some(off) => FlowScalarBuf::new_borrowed(off + self.input.peek().len_utf8()),
3757 None => FlowScalarBuf::new_owned(),
3758 };
3759
3760 self.skip_non_blank();
3762
3763 loop {
3764 self.input.lookahead(4);
3766
3767 if self.mark.col == 0 && self.input.next_is_document_indicator() {
3768 return Err(ScanError::from_kind(
3769 start_mark,
3770 ErrorKind::DocumentIndicatorInQuotedScalar,
3771 ));
3772 }
3773
3774 if self.input.next_is_z() {
3775 return Err(ScanError::from_kind(
3776 start_mark,
3777 ErrorKind::UnclosedQuotedScalar,
3778 ));
3779 }
3780
3781 self.ensure_current_char_is_printable()?;
3782
3783 let mut leading_blanks = false;
3785 self.consume_flow_scalar_non_whitespace_chars(
3786 single,
3787 &mut buf,
3788 &mut leading_blanks,
3789 &start_mark,
3790 )?;
3791
3792 match self.input.look_ch() {
3793 '\'' if single && !leading_blanks => break,
3794 '"' if !single && !leading_blanks => break,
3795 _ => {}
3796 }
3797
3798 let mut trailing_ws_start: Option<usize> = None;
3814 let mut has_leading_break = false;
3815 let mut has_trailing_breaks = false;
3816
3817 let mut pending_ws_start: Option<usize> = None;
3819
3820 while self.input.next_is_blank() || self.input.next_is_break() {
3822 if self.input.next_is_blank() {
3823 if leading_blanks {
3825 if self.options.strict_indentation && self.input.peek() == '\t' {
3828 let indent = if self.flow_level > 0 {
3829 self.flow_block_indent() + 1
3830 } else {
3831 self.indent
3832 };
3833 if (self.mark.col as isize) < indent {
3834 return Err(self.scan_error(ErrorKind::TabInIndentation));
3835 }
3836 }
3837 self.skip_blank();
3838 } else {
3839 match buf {
3841 FlowScalarBuf::Owned(ref mut string) => {
3842 if trailing_ws_start.is_none() {
3843 trailing_ws_start = Some(string.len());
3844 }
3845 string.push(self.input.peek());
3846 }
3847 FlowScalarBuf::Borrowed { .. } => {
3848 if pending_ws_start.is_none() {
3849 pending_ws_start = self.input.byte_offset();
3850 }
3851 }
3852 }
3853 self.skip_blank();
3854
3855 if let (FlowScalarBuf::Borrowed { .. }, Some(ws_start), Some(ws_end)) =
3856 (&mut buf, pending_ws_start, self.input.byte_offset())
3857 {
3858 buf.note_pending_ws(ws_start, ws_end);
3859 }
3860 }
3861 } else {
3862 self.input.lookahead(2);
3863
3864 if leading_blanks {
3866 match buf {
3868 FlowScalarBuf::Owned(ref mut string) => self.read_break(string),
3869 FlowScalarBuf::Borrowed { .. } => {
3870 self.promote_flow_scalar_buf_to_owned(&start_mark, &mut buf)?;
3871 let Some(string) = buf.as_owned_mut() else {
3872 unreachable!()
3873 };
3874 self.read_break(string);
3875 }
3876 }
3877 has_trailing_breaks = true;
3878 } else {
3879 if let Some(pos) = trailing_ws_start.take() {
3881 if let FlowScalarBuf::Owned(ref mut string) = buf {
3882 string.truncate(pos);
3883 }
3884 }
3885
3886 if pending_ws_start.take().is_some() {
3887 if matches!(buf, FlowScalarBuf::Borrowed { .. }) {
3889 self.promote_flow_scalar_buf_to_owned(&start_mark, &mut buf)?;
3890 }
3891 buf.discard_pending_ws();
3892 } else {
3893 buf.commit_pending_ws();
3894 }
3895
3896 self.skip_break();
3897
3898 has_leading_break = true;
3899 leading_blanks = true;
3900 }
3901 }
3902
3903 self.input.lookahead(1);
3904 }
3905
3906 if leading_blanks
3910 && self.options.strict_indentation
3911 && (self.mark.col as isize) <= self.flow_block_indent()
3912 {
3913 let kind = if has_leading_break && self.flow_level == 0 {
3914 ErrorKind::InvalidQuotedScalarIndent
3915 } else {
3916 ErrorKind::InvalidIndentation
3917 };
3918 return Err(self.scan_error(kind));
3919 }
3920
3921 if leading_blanks {
3923 if has_leading_break && !has_trailing_breaks {
3928 match buf {
3929 FlowScalarBuf::Owned(ref mut string) => string.push(' '),
3930 FlowScalarBuf::Borrowed { .. } => {
3931 self.promote_flow_scalar_buf_to_owned(&start_mark, &mut buf)?;
3932 let Some(string) = buf.as_owned_mut() else {
3933 unreachable!()
3934 };
3935 string.push(' ');
3936 }
3937 }
3938 }
3939 }
3940 } self.skip_non_blank();
3945 let end_mark = self.mark;
3946
3947 self.skip_ws_to_eol(SkipTabs::Yes)?;
3949 self.ensure_current_char_is_printable()?;
3950 match self.input.peek() {
3951 ',' | '}' | ']' if self.flow_level > 0 => {}
3953 c if is_breakz(c) => {}
3955 ':' if self.flow_level == 0 && start_mark.line == self.mark.line => {}
3958 ':' if self.flow_level > 0 => {}
3960 _ => {
3961 let kind = if single {
3962 ErrorKind::InvalidTrailingSingleQuotedScalar
3963 } else {
3964 ErrorKind::InvalidTrailingDoubleQuotedScalar
3965 };
3966 return Err(self.scan_error(kind));
3967 }
3968 }
3969
3970 let style = if single {
3971 ScalarStyle::SingleQuoted
3972 } else {
3973 ScalarStyle::DoubleQuoted
3974 };
3975
3976 let contents = match buf {
3977 FlowScalarBuf::Owned(string) => Cow::Owned(string),
3978 FlowScalarBuf::Borrowed {
3979 start,
3980 mut end,
3981 pending_ws_start,
3982 pending_ws_end,
3983 } => {
3984 if pending_ws_start.is_some() {
3986 end = pending_ws_end;
3987 }
3988 if let Some(slice) = self.try_borrow_slice(start, end) {
3989 Cow::Borrowed(slice)
3990 } else {
3991 let slice = self.input.slice_bytes(start, end).ok_or_else(|| {
3992 ScanError::from_kind(start_mark, ErrorKind::InputOffsetsWithoutSlice)
3993 })?;
3994 Cow::Owned(slice.to_owned())
3995 }
3996 }
3997 };
3998
3999 Ok(Token(
4000 Span::new(start_mark, end_mark),
4001 TokenType::Scalar(style, contents),
4002 ))
4003 }
4004
4005 fn consume_flow_scalar_chunk(&mut self, single: bool, buf: &mut FlowScalarBuf) -> bool {
4007 let (chunk, consumed) = self.input.take_quoted_scalar_chunk(single);
4008 if consumed == 0 {
4009 return false;
4010 }
4011
4012 match buf {
4013 FlowScalarBuf::Owned(string) => string.push_str(chunk),
4014 FlowScalarBuf::Borrowed { .. } => buf.commit_pending_ws(),
4015 }
4016
4017 self.mark.offsets.chars += consumed;
4019 self.mark.col += consumed;
4020 self.mark.offsets.bytes = self.input.byte_offset();
4021 self.leading_whitespace = false;
4022 if let (Some(new_end), FlowScalarBuf::Borrowed { end, .. }) = (self.mark.offsets.bytes, buf)
4023 {
4024 *end = new_end;
4025 }
4026 true
4027 }
4028
4029 fn consume_flow_scalar_non_whitespace_chars(
4038 &mut self,
4039 single: bool,
4040 buf: &mut FlowScalarBuf,
4041 leading_blanks: &mut bool,
4042 start_mark: &Marker,
4043 ) -> Result<(), ScanError> {
4044 self.input.lookahead(2);
4045 loop {
4046 let character = self.input.peek();
4047 if is_blank_or_breakz(character) || !is_printable(character) {
4048 break;
4049 }
4050 match character {
4051 '\'' if self.input.peek_nth(1) == '\'' && single => {
4053 if matches!(buf, FlowScalarBuf::Borrowed { .. }) {
4054 buf.commit_pending_ws();
4055 self.promote_flow_scalar_buf_to_owned(start_mark, buf)?;
4056 }
4057 let Some(string) = buf.as_owned_mut() else {
4058 unreachable!()
4059 };
4060 string.push('\'');
4061 self.skip_n_non_blank(2);
4062 }
4063 '\'' if single => break,
4065 '"' if !single => break,
4066 '\\' if !single && is_break(self.input.peek_nth(1)) => {
4068 self.input.lookahead(3);
4069 if matches!(buf, FlowScalarBuf::Borrowed { .. }) {
4070 buf.commit_pending_ws();
4071 self.promote_flow_scalar_buf_to_owned(start_mark, buf)?;
4072 }
4073 self.skip_non_blank();
4074 self.skip_linebreak();
4075 *leading_blanks = true;
4076 break;
4077 }
4078 '\\' if !single => {
4080 if matches!(buf, FlowScalarBuf::Borrowed { .. }) {
4081 buf.commit_pending_ws();
4082 self.promote_flow_scalar_buf_to_owned(start_mark, buf)?;
4083 }
4084 let Some(string) = buf.as_owned_mut() else {
4085 unreachable!()
4086 };
4087 string.push(self.resolve_flow_scalar_escape_sequence(start_mark)?);
4088 }
4089 c => {
4090 if self.consume_flow_scalar_chunk(single, buf) {
4091 self.input.lookahead(2);
4092 continue;
4093 }
4094 match buf {
4095 FlowScalarBuf::Owned(ref mut string) => {
4096 string.push(c);
4097 }
4098 FlowScalarBuf::Borrowed { .. } => {
4099 buf.commit_pending_ws();
4100 }
4101 }
4102 self.skip_non_blank();
4103
4104 if let Some(new_end) = self.input.byte_offset() {
4105 if let FlowScalarBuf::Borrowed { end, .. } = buf {
4106 *end = new_end;
4107 }
4108 }
4109 }
4110 }
4111 self.input.lookahead(2);
4112 }
4113 Ok(())
4114 }
4115
4116 fn resolve_flow_scalar_escape_sequence(
4123 &mut self,
4124 start_mark: &Marker,
4125 ) -> Result<char, ScanError> {
4126 let mut code_length = 0usize;
4127 let mut ret = '\0';
4128
4129 match self.input.peek_nth(1) {
4130 '0' => ret = '\0',
4131 'a' => ret = '\x07',
4132 'b' => ret = '\x08',
4133 't' | '\t' => ret = '\t',
4134 'n' => ret = '\n',
4135 'v' => ret = '\x0b',
4136 'f' => ret = '\x0c',
4137 'r' => ret = '\x0d',
4138 'e' => ret = '\x1b',
4139 ' ' => ret = '\x20',
4140 '"' => ret = '"',
4141 '/' => ret = '/',
4142 '\\' => ret = '\\',
4143 'N' => ret = char::from_u32(0x85).unwrap(),
4145 '_' => ret = char::from_u32(0xA0).unwrap(),
4147 'L' => ret = char::from_u32(0x2028).unwrap(),
4149 'P' => ret = char::from_u32(0x2029).unwrap(),
4151 'x' => code_length = 2,
4152 'u' => code_length = 4,
4153 'U' => code_length = 8,
4154 _ => {
4155 return Err(ScanError::from_kind(
4156 *start_mark,
4157 ErrorKind::UnknownQuotedScalarEscape,
4158 ))
4159 }
4160 }
4161 self.skip_n_non_blank(2);
4162
4163 if code_length > 0 {
4165 self.input.lookahead(code_length);
4166 let mut value = 0u32;
4167 for i in 0..code_length {
4168 let c = self.input.peek_nth(i);
4169 if !is_hex(c) {
4170 return Err(ScanError::from_kind(
4171 *start_mark,
4172 ErrorKind::InvalidQuotedScalarHexEscape,
4173 ));
4174 }
4175 value = (value << 4) + as_hex(c);
4176 }
4177
4178 self.skip_n_non_blank(code_length);
4179
4180 if code_length == 4 && (0xD800..=0xDBFF).contains(&value) {
4182 self.input.lookahead(2);
4183 if self.input.peek() == '\\' && self.input.peek_nth(1) == 'u' {
4184 self.skip_n_non_blank(2);
4185 self.input.lookahead(4);
4186 let mut low_value = 0u32;
4187 for i in 0..4 {
4188 let c = self.input.peek_nth(i);
4189 if !is_hex(c) {
4190 return Err(ScanError::from_kind(
4191 *start_mark,
4192 ErrorKind::InvalidLowSurrogateHexEscape,
4193 ));
4194 }
4195 low_value = (low_value << 4) + as_hex(c);
4196 }
4197 if (0xDC00..=0xDFFF).contains(&low_value) {
4198 value = 0x10000 + (((value - 0xD800) << 10) | (low_value - 0xDC00));
4199 self.skip_n_non_blank(4);
4200 } else {
4201 return Err(ScanError::from_kind(
4202 *start_mark,
4203 ErrorKind::InvalidLowSurrogate,
4204 ));
4205 }
4206 } else {
4207 return Err(ScanError::from_kind(
4208 *start_mark,
4209 ErrorKind::MissingLowSurrogate,
4210 ));
4211 }
4212 } else if code_length == 4 && (0xDC00..=0xDFFF).contains(&value) {
4213 return Err(ScanError::from_kind(
4214 *start_mark,
4215 ErrorKind::UnpairedLowSurrogate,
4216 ));
4217 }
4218
4219 let Some(ch) = char::from_u32(value) else {
4220 return Err(ScanError::from_kind(
4221 *start_mark,
4222 ErrorKind::InvalidUnicodeEscape,
4223 ));
4224 };
4225 ret = ch;
4226 }
4227 Ok(ret)
4228 }
4229
4230 fn fetch_plain_scalar(&mut self) -> ScanResult {
4231 self.save_simple_key();
4232 self.disallow_simple_key();
4233
4234 let token_index = self.tokens.len();
4235 let tok = self.scan_plain_scalar()?;
4236
4237 self.insert_token(token_index, tok);
4238 Ok(())
4239 }
4240
4241 #[allow(clippy::too_many_lines)]
4246 fn scan_plain_scalar(&mut self) -> Result<Token<'input>, ScanError> {
4247 self.unroll_non_block_indents();
4248 let indent = self.indent + 1;
4249 let start_mark = self.mark;
4250
4251 let borrow_start = start_mark
4252 .byte_offset()
4253 .filter(|start| self.try_borrow_slice(*start, *start).is_some());
4254 let mut string = borrow_start.is_none().then(|| String::with_capacity(32));
4255 let mut has_content = false;
4256 self.buf_whitespaces.clear();
4257 self.buf_leading_break.clear();
4258 self.buf_trailing_breaks.clear();
4259 let mut end_mark = self.mark;
4260
4261 loop {
4262 self.input.lookahead(4);
4263 if (self.mark.col == 0 && self.input.next_is_document_indicator())
4264 || self.input.peek() == '#'
4265 {
4266 if self.input.peek() == '#'
4271 && has_content
4272 && !self.buf_whitespaces.is_empty()
4273 && self.flow_level == 0
4274 {
4275 self.interrupted_plain_by_comment = Some(self.mark);
4276 }
4277 break;
4278 }
4279
4280 if !has_content
4282 && self.flow_level > 0
4283 && self.input.peek() == '-'
4284 && is_flow(self.input.peek_nth(1))
4285 {
4286 return Err(self.scan_error(ErrorKind::PlainScalarStartsWithDashFlowIndicator));
4287 }
4288
4289 if !self.input.next_is_blank_or_breakz()
4290 && self.input.next_can_be_plain_scalar(self.flow_level > 0)
4291 {
4292 if self.leading_whitespace {
4293 if has_content && string.is_none() {
4294 let start = borrow_start.expect("borrowed scalar has a start offset");
4295 let end = end_mark.byte_offset().ok_or_else(|| {
4296 ScanError::from_kind(start_mark, ErrorKind::InputOffsetsWithoutSlice)
4297 })?;
4298 let prefix = self.try_borrow_slice(start, end).ok_or_else(|| {
4299 ScanError::from_kind(start_mark, ErrorKind::InputOffsetsWithoutSlice)
4300 })?;
4301 string = Some(prefix.to_owned());
4302 }
4303 if self.buf_leading_break.is_empty() {
4304 if let Some(output) = string.as_mut() {
4305 output.push_str(&self.buf_leading_break);
4306 output.push_str(&self.buf_trailing_breaks);
4307 }
4308 self.buf_trailing_breaks.clear();
4309 self.buf_leading_break.clear();
4310 } else {
4311 if self.buf_trailing_breaks.is_empty() {
4312 if let Some(output) = string.as_mut() {
4313 output.push(' ');
4314 }
4315 } else {
4316 if let Some(output) = string.as_mut() {
4317 output.push_str(&self.buf_trailing_breaks);
4318 }
4319 self.buf_trailing_breaks.clear();
4320 }
4321 self.buf_leading_break.clear();
4322 }
4323 self.leading_whitespace = false;
4324 } else if !self.buf_whitespaces.is_empty() {
4325 if let Some(output) = string.as_mut() {
4326 output.push_str(&self.buf_whitespaces);
4327 }
4328 self.buf_whitespaces.clear();
4329 }
4330
4331 has_content = true;
4333 if let Some(output) = string.as_mut() {
4334 output.push(self.input.peek());
4335 }
4336 self.skip_non_blank();
4337 if let Some(output) = string.as_mut() {
4338 output.reserve(self.input.bufmaxlen());
4339 }
4340
4341 let mut end = false;
4343 while !end {
4344 self.input.lookahead(self.input.bufmaxlen());
4349 let chunk_len = self.input.bufmaxlen().saturating_sub(1).max(1);
4350 let (stop, chars_consumed) = if let Some(output) = string.as_mut() {
4351 self.input
4352 .fetch_plain_scalar_chunk(output, chunk_len, self.flow_level > 0)
4353 } else {
4354 self.input
4355 .skip_plain_scalar_chunk(chunk_len, self.flow_level > 0)
4356 };
4357 end = stop;
4358 self.mark.offsets.chars += chars_consumed;
4359 self.mark.col += chars_consumed;
4360 self.mark.offsets.bytes = self.input.byte_offset();
4361 }
4362 end_mark = self.mark;
4363 }
4364
4365 if !(self.input.next_is_blank() || self.input.next_is_break()) {
4370 break;
4371 }
4372
4373 self.input.lookahead(2);
4375 while self.input.next_is_blank_or_break() {
4376 if self.input.next_is_blank() {
4377 if !self.leading_whitespace {
4378 self.buf_whitespaces.push(self.input.peek());
4379 self.skip_blank();
4380 } else if (self.mark.col as isize) < indent && self.input.peek() == '\t' {
4381 self.skip_ws_to_eol(SkipTabs::Yes)?;
4384 if !self.input.next_is_breakz() {
4385 return Err(ScanError::from_kind(
4386 start_mark,
4387 ErrorKind::TabInPlainScalar,
4388 ));
4389 }
4390 } else {
4391 self.skip_blank();
4392 }
4393 } else {
4394 if self.leading_whitespace {
4396 self.skip_break();
4397 self.buf_trailing_breaks.push('\n');
4398 } else {
4399 self.buf_whitespaces.clear();
4400 self.skip_break();
4401 self.buf_leading_break.push('\n');
4402 self.leading_whitespace = true;
4403 }
4404 }
4405 self.input.lookahead(2);
4406 }
4407
4408 if (self.flow_level == 0 || self.options.strict_indentation)
4411 && (self.mark.col as isize) < indent
4412 {
4413 break;
4414 }
4415 }
4416
4417 if self.leading_whitespace {
4418 self.allow_simple_key();
4419 }
4420
4421 let borrowed_contents = if string.is_none() {
4422 let start = borrow_start.expect("borrowed scalar has a start offset");
4423 let end = end_mark.byte_offset().ok_or_else(|| {
4424 ScanError::from_kind(start_mark, ErrorKind::InputOffsetsWithoutSlice)
4425 })?;
4426 Some(self.try_borrow_slice(start, end).ok_or_else(|| {
4427 ScanError::from_kind(start_mark, ErrorKind::InputOffsetsWithoutSlice)
4428 })?)
4429 } else {
4430 None
4431 };
4432 let scalar_text = borrowed_contents.unwrap_or_else(|| {
4433 string
4434 .as_deref()
4435 .expect("owned plain scalar has an output buffer")
4436 });
4437 if let Some(character) = find_non_printable(scalar_text) {
4438 return Err(ScanError::from_kind(
4439 start_mark,
4440 ErrorKind::UnexpectedCharacter { character },
4441 ));
4442 }
4443 self.ensure_current_char_is_printable()?;
4444
4445 if has_content {
4446 let contents = if let Some(slice) = borrowed_contents {
4447 Cow::Borrowed(slice)
4448 } else {
4449 Cow::Owned(string.expect("owned plain scalar has an output buffer"))
4450 };
4451
4452 Ok(Token(
4453 Span::new(start_mark, end_mark),
4454 TokenType::Scalar(ScalarStyle::Plain, contents),
4455 ))
4456 } else {
4457 Err(ScanError::from_kind(
4461 start_mark,
4462 ErrorKind::UnexpectedEndOfPlainScalar,
4463 ))
4464 }
4465 }
4466
4467 fn fetch_key(&mut self) -> ScanResult {
4468 let start_mark = self.mark;
4469 if self.flow_level == 0 {
4470 if !self.simple_key_allowed {
4472 return Err(self.scan_error(ErrorKind::MappingKeyNotAllowed));
4473 }
4474 self.roll_indent(
4475 start_mark.col,
4476 None,
4477 TokenType::BlockMappingStart,
4478 start_mark,
4479 )?;
4480 } else {
4481 self.set_current_flow_mapping_started(true);
4483 }
4484
4485 self.remove_simple_key()?;
4486
4487 if self.flow_level == 0 {
4488 self.allow_simple_key();
4489 } else {
4490 self.disallow_simple_key();
4491 }
4492
4493 self.skip_non_blank();
4494 let end_mark = self.mark;
4495 let token_index = self.tokens.len();
4496 self.explicit_key_tab_check_pending = false;
4497 if self.flow_level == 0 {
4502 let stopped_after_comment = self.skip_yaml_whitespace()?;
4503 self.explicit_key_tab_check_pending = stopped_after_comment
4504 || (self.options.strict_indentation && matches!(self.input.peek(), '&' | '!'));
4505 }
4506 self.insert_token(
4507 token_index,
4508 Token(Span::new(start_mark, end_mark), TokenType::Key),
4509 );
4510 Ok(())
4511 }
4512
4513 fn fetch_flow_value(&mut self) -> ScanResult {
4521 let nc = self.input.peek_nth(1);
4522
4523 if self.mark.index() != self.adjacent_value_allowed_at && (nc == '[' || nc == '{') {
4535 return Err(self.scan_error(ErrorKind::FlowMappingValueAdjacentCollection));
4536 }
4537
4538 self.fetch_value()
4539 }
4540
4541 fn fetch_value(&mut self) -> ScanResult {
4543 let sk = *self.simple_keys.last().unwrap();
4544 let start_mark = self.mark;
4545 let is_implicit_flow_mapping = self.current_flow_collection_is_sequence()
4546 && !self.current_flow_mapping_started()
4547 && !self.implicit_flow_mapping_states.is_empty();
4548 if is_implicit_flow_mapping {
4549 *self.implicit_flow_mapping_states.last_mut().unwrap() =
4550 ImplicitMappingState::Inside(self.flow_level);
4551 }
4552
4553 self.skip_non_blank();
4555 let mut trailing_comment = None;
4558 let mut found_tabs = false;
4559 if matches!(self.input.look_ch(), ' ' | '\t') {
4560 let trailing_token_index = self.tokens.len();
4561 found_tabs = self.skip_ws_to_eol(SkipTabs::Yes)?.found_tabs();
4562 debug_assert!(self.tokens.len() <= trailing_token_index + 1);
4564 if self.tokens.len() > trailing_token_index {
4565 trailing_comment = self.tokens.pop_back();
4566 }
4567 }
4568
4569 if sk.possible {
4570 let block_indent = self.flow_block_indent();
4574 if self.flow_level > 0
4575 && sk.mark.line < start_mark.line
4576 && (sk.mark.col as isize) <= block_indent
4577 {
4578 return Err(ScanError::from_kind(
4579 start_mark,
4580 ErrorKind::InvalidColonPlacement,
4581 ));
4582 }
4583 let token_index = self.simple_key_token_index(&sk, start_mark)?;
4584 self.validate_flow_key_indentation(&sk, token_index, start_mark)?;
4585 let tok = Token(Span::empty(sk.mark), TokenType::Key);
4587 self.insert_token(token_index, tok);
4588 if is_implicit_flow_mapping {
4589 if sk.mark.line < start_mark.line {
4590 return Err(ScanError::from_kind(
4591 start_mark,
4592 ErrorKind::InvalidColonPlacement,
4593 ));
4594 }
4595 self.insert_token(
4596 token_index,
4597 Token(Span::empty(sk.mark), TokenType::FlowMappingStart),
4598 );
4599 }
4600
4601 self.roll_indent(
4603 sk.mark.col,
4604 Some(sk.token_number),
4605 TokenType::BlockMappingStart,
4606 sk.mark,
4607 )?;
4608 self.roll_one_col_indent();
4609
4610 self.clear_simple_key();
4611 self.disallow_simple_key();
4612 } else {
4613 if is_implicit_flow_mapping {
4614 self.tokens
4615 .push_back(Token(Span::empty(start_mark), TokenType::FlowMappingStart).into());
4616 }
4617 if self.flow_level == 0 {
4619 if !self.simple_key_allowed {
4620 return Err(ScanError::from_kind(
4621 start_mark,
4622 ErrorKind::MappingValueNotAllowed,
4623 ));
4624 }
4625
4626 self.roll_indent(
4627 start_mark.col,
4628 None,
4629 TokenType::BlockMappingStart,
4630 start_mark,
4631 )?;
4632 }
4633 self.roll_one_col_indent();
4634
4635 if self.flow_level == 0 && !found_tabs {
4638 self.allow_simple_key();
4639 } else {
4640 self.disallow_simple_key();
4641 }
4642 }
4643 self.tokens
4644 .push_back(Token(Span::empty(start_mark), TokenType::Value).into());
4645 if let Some(comment) = trailing_comment {
4646 self.tokens.push_back(comment);
4647 }
4648
4649 Ok(())
4650 }
4651
4652 fn validate_flow_key_indentation(
4654 &self,
4655 key: &SimpleKey,
4656 token_index: usize,
4657 colon: Marker,
4658 ) -> ScanResult {
4659 if self.flow_level == 0 || key.mark.line == colon.line {
4660 return Ok(());
4661 }
4662
4663 let block_indent = self.flow_block_indent();
4664 let mut under_indented = [key.mark.col, colon.col]
4668 .iter()
4669 .any(|&col| (col as isize) <= block_indent);
4670 for token in self.tokens.iter().skip(token_index) {
4671 #[cfg(feature = "comments")]
4672 if matches!(token.1, QueuedTokenType::Comment(_)) {
4673 continue;
4674 }
4675 under_indented |= (token.0.start.col as isize) <= block_indent;
4676 if !matches!(
4677 token.1,
4678 QueuedTokenType::Anchor(_) | QueuedTokenType::Tag(..)
4679 ) {
4680 break;
4681 }
4682 }
4683 if under_indented {
4684 return Err(ScanError::from_kind(
4685 colon,
4686 ErrorKind::InvalidColonPlacement,
4687 ));
4688 }
4689 Ok(())
4690 }
4691
4692 fn flow_block_indent(&self) -> isize {
4694 self.indents
4695 .last()
4696 .filter(|indent| !indent.needs_block_end)
4697 .map_or(self.indent, |indent| indent.indent)
4698 }
4699
4700 fn roll_indent(
4706 &mut self,
4707 col: usize,
4708 number: Option<usize>,
4709 tok: TokenType<'input>,
4710 mark: Marker,
4711 ) -> ScanResult {
4712 if self.flow_level > 0 {
4713 return Ok(());
4714 }
4715
4716 if self.indent <= col as isize {
4720 if let Some(indent) = self.indents.last() {
4721 if !indent.needs_block_end {
4722 self.indent = indent.indent;
4723 self.indents.pop();
4724 }
4725 }
4726 }
4727
4728 if self.indent < col as isize {
4729 if self.block_level >= self.options.block_nesting_limit {
4730 return Err(ScanError::from_kind(
4731 mark,
4732 ErrorKind::RecursionLimitExceeded,
4733 ));
4734 }
4735 self.indents.push(Indent {
4736 indent: self.indent,
4737 needs_block_end: true,
4738 });
4739 self.block_level += 1;
4740 self.indent = col as isize;
4741 let tokens_parsed = self.tokens_parsed;
4742 match number {
4743 Some(n) => self.insert_token(n - tokens_parsed, Token(Span::empty(mark), tok)),
4744 None => self.tokens.push_back(Token(Span::empty(mark), tok).into()),
4745 }
4746 }
4747 Ok(())
4748 }
4749
4750 fn unroll_indent(&mut self, col: isize) {
4756 if self.flow_level > 0 {
4757 return;
4758 }
4759 while self.indent > col {
4760 let indent = self.indents.pop().unwrap();
4761 self.indent = indent.indent;
4762 if indent.needs_block_end {
4763 debug_assert!(self.block_level > 0);
4764 self.block_level -= 1;
4765 self.tokens
4766 .push_back(Token(Span::empty(self.mark), TokenType::BlockEnd).into());
4767 }
4768 }
4769 }
4770
4771 fn roll_one_col_indent(&mut self) {
4777 if self.flow_level == 0 && self.indents.last().is_some_and(|x| x.needs_block_end) {
4778 self.indents.push(Indent {
4779 indent: self.indent,
4780 needs_block_end: false,
4781 });
4782 self.indent += 1;
4783 }
4784 }
4785
4786 fn unroll_non_block_indents(&mut self) {
4788 while let Some(indent) = self.indents.last() {
4789 if indent.needs_block_end {
4790 break;
4791 }
4792 self.indent = indent.indent;
4793 self.indents.pop();
4794 }
4795 }
4796
4797 fn save_simple_key(&mut self) {
4799 if self.simple_key_allowed {
4800 let required = self.flow_level == 0
4801 && self.indent == (self.mark.col as isize)
4802 && self.indents.last().unwrap().needs_block_end;
4803
4804 if let Some(last) = self.simple_keys.last_mut() {
4805 *last = SimpleKey {
4806 mark: self.mark,
4807 possible: true,
4808 required,
4809 token_number: self.tokens_parsed + self.tokens.len(),
4810 };
4811 self.first_simple_key.get_or_insert(self.flow_level);
4812 }
4813 }
4814 }
4815
4816 fn remove_simple_key(&mut self) -> ScanResult {
4817 let last = self.simple_keys.last().unwrap();
4818 if last.possible && last.required {
4819 return Err(Self::simple_key_expected(last.mark));
4820 }
4821
4822 self.clear_simple_key();
4823 Ok(())
4824 }
4825
4826 fn clear_simple_key(&mut self) {
4828 self.simple_keys.last_mut().unwrap().possible = false;
4829 if self.first_simple_key == Some(self.flow_level) {
4830 self.first_simple_key = None;
4832 }
4833 }
4834
4835 fn is_within_block(&self) -> bool {
4837 !self.indents.is_empty()
4838 }
4839
4840 fn end_implicit_mapping(&mut self, mark: Marker, flow_level: usize) {
4846 if self
4847 .implicit_flow_mapping_states
4848 .last()
4849 .is_some_and(|state| *state == ImplicitMappingState::Inside(flow_level))
4850 {
4851 *self.implicit_flow_mapping_states.last_mut().unwrap() = ImplicitMappingState::Possible;
4852 self.set_current_flow_mapping_started(false);
4853 self.tokens
4854 .push_back(Token(Span::empty(mark), TokenType::FlowMappingEnd).into());
4855 }
4856 }
4857
4858 fn current_flow_collection_is_sequence(&self) -> bool {
4859 self.flow_markers
4860 .last()
4861 .is_some_and(|(_, bracket)| *bracket == '[')
4862 }
4863
4864 fn current_flow_mapping_started(&self) -> bool {
4865 self.flow_mapping_started.last().copied().unwrap_or(false)
4866 }
4867
4868 fn set_current_flow_mapping_started(&mut self, started: bool) {
4869 if let Some(current) = self.flow_mapping_started.last_mut() {
4870 *current = started;
4871 }
4872 }
4873}
4874
4875#[derive(PartialEq, Eq)]
4879enum Chomping {
4880 Strip,
4882 Clip,
4884 Keep,
4886}
4887
4888#[cfg(test)]
4889mod test {
4890 use alloc::{
4891 borrow::{Cow, ToOwned},
4892 rc::Rc,
4893 string::String,
4894 vec,
4895 vec::Vec,
4896 };
4897 use core::cell::Cell;
4898
4899 use crate::error::{ErrorKind, ScanError};
4900 #[cfg(feature = "comments")]
4901 use crate::scanner::{Comment, Placement};
4902 use crate::{
4903 input::{str::StrInput, BorrowedInput, BufferedInput, Input},
4904 scanner::{
4905 Marker, QueuedToken, QueuedTokenType, ScalarStyle, Scanner, Span, Token, TokenType,
4906 },
4907 };
4908
4909 #[test]
4910 fn tag_span_supports_the_full_u32_length_without_allocating() {
4911 let start = Marker::new(0, 1, 0).with_byte_offset(Some(0));
4912 let span = Span::empty(start).with_tag_span(Some((start, u32::MAX)));
4913 let tag_span = span.tag_span().unwrap();
4914 let length = usize::try_from(u32::MAX).unwrap();
4915 assert_eq!(tag_span.start, start);
4916 assert_eq!(tag_span.end.index(), length);
4917 assert_eq!(tag_span.end.col(), length);
4918 assert_eq!(tag_span.end.line(), 1);
4919 assert_eq!(tag_span.end.byte_offset(), Some(length));
4920 }
4921
4922 #[test]
4923 fn tag_span_rejects_overflow_in_each_reconstructed_coordinate() {
4924 for start in [
4925 Marker::new(usize::MAX, 1, 0),
4926 Marker::new(0, 1, usize::MAX),
4927 Marker::new(0, 1, 0).with_byte_offset(Some(usize::MAX)),
4928 ] {
4929 let span = Span::empty(start).with_tag_span(Some((start, 1)));
4930 assert_eq!(span.tag_span(), None);
4931 }
4932 }
4933
4934 #[test]
4935 fn recovery_ignores_invalid_document_marker_lookalikes() {
4936 let input = "@bad\n---# comment\n ---\n---\0\n... trailing\n--- healthy\n";
4937 let mut scanner = Scanner::new(StrInput::new(input));
4938 assert!(matches!(
4939 scanner.next_token().unwrap().unwrap().1,
4940 TokenType::StreamStart
4941 ));
4942 assert!(scanner.next_token().is_err());
4943
4944 scanner.proceed_next_document(None).unwrap();
4945 let token = scanner.next_token().unwrap().unwrap();
4946 assert_eq!(token.1, TokenType::DocumentStart);
4947 assert_eq!(token.0.start.line(), 6);
4948 assert!(matches!(
4949 scanner.next_token().unwrap().unwrap().1,
4950 TokenType::Scalar(_, ref value) if value == "healthy"
4951 ));
4952 }
4953
4954 #[test]
4955 fn recovery_rejects_end_marker_queued_before_its_line_failed() {
4956 let mut scanner =
4957 Scanner::new(StrInput::new("... trailing\nnot_a_document\n--- healthy\n"));
4958 scanner.next_token().unwrap();
4959 assert_eq!(
4960 scanner.next_token().unwrap_err().kind(),
4961 &ErrorKind::InvalidDocumentEnd
4962 );
4963 assert!(scanner
4964 .tokens
4965 .iter()
4966 .any(|token| matches!(token.1, QueuedTokenType::DocumentEnd)));
4967
4968 scanner.proceed_next_document(None).unwrap();
4969 let token = scanner.next_token().unwrap().unwrap();
4970 assert_eq!(token.1, TokenType::DocumentStart);
4971 assert_eq!(token.0.start.line(), 3);
4972 }
4973
4974 #[test]
4975 fn recovery_preserves_boundary_already_held_by_parser() {
4976 let mut scanner = Scanner::new(StrInput::new("first\n--- second\n"));
4977 let boundary = loop {
4978 let token = scanner.next_queued_token().unwrap().unwrap();
4979 if matches!(token.1, QueuedTokenType::DocumentStart) {
4980 break token;
4981 }
4982 };
4983 let span = boundary.0;
4984 scanner.proceed_next_document(Some(boundary)).unwrap();
4985 assert_eq!(
4986 scanner.next_token().unwrap().unwrap(),
4987 Token(span, TokenType::DocumentStart)
4988 );
4989 assert!(matches!(
4990 scanner.next_token().unwrap().unwrap().1,
4991 TokenType::Scalar(_, ref value) if value == "second"
4992 ));
4993 }
4994
4995 #[test]
4996 fn recovery_retains_previously_reported_source_error() {
4997 let kind = ErrorKind::InputDecoding {
4998 message: "invalid encoding".into(),
4999 };
5000 let input = crate::FallibleBufferedInput::new(
5001 vec![Ok('['), Err(kind.clone()), Ok('\n')].into_iter(),
5002 );
5003 let mut scanner = Scanner::new(input);
5004 scanner.next_token().unwrap();
5005 let error = scanner.next_token().unwrap_err();
5006 assert_eq!(error.kind(), &kind);
5007 assert_eq!(scanner.proceed_next_document(None), Err(error));
5008 }
5009
5010 #[test]
5011 fn recovery_distinguishes_directive_header_errors_from_document_content() {
5012 for input in ["%YAML bad\n--- body\n", "%TAG invalid\n--- body\n"] {
5013 let mut scanner = Scanner::new(StrInput::new(input));
5014 scanner.next_token().unwrap();
5015 assert!(scanner.next_token().is_err());
5016 assert!(scanner.in_directive_prefix());
5017 scanner.proceed_next_document(None).unwrap();
5018 assert!(!scanner.in_directive_prefix());
5019 }
5020
5021 let mut scanner = Scanner::with_options(
5022 StrInput::new("%YAML 1.2\n--- body\n"),
5023 crate::options! { disallow_directives: true },
5024 );
5025 scanner.next_token().unwrap();
5026 assert!(scanner.next_token().is_err());
5027 assert!(scanner.in_directive_prefix());
5028
5029 for input in ["%YAML 1.2\n--- body\n", "%YAML 1.2\nbare\n"] {
5030 let mut scanner = Scanner::new(StrInput::new(input));
5031 scanner.next_token().unwrap();
5032 scanner.next_token().unwrap();
5033 assert!(scanner.in_directive_prefix());
5034 scanner.next_token().unwrap();
5035 assert!(!scanner.in_directive_prefix());
5036 }
5037 }
5038
5039 fn ignoring_comments_options() -> crate::Options {
5040 #[cfg(feature = "comments")]
5041 {
5042 crate::options! { emit_comments: false }
5043 }
5044 #[cfg(not(feature = "comments"))]
5045 {
5046 crate::Options::default()
5047 }
5048 }
5049
5050 struct CountingChars {
5051 chars: alloc::vec::IntoIter<char>,
5052 read: Rc<Cell<usize>>,
5053 }
5054
5055 impl Iterator for CountingChars {
5056 type Item = char;
5057
5058 fn next(&mut self) -> Option<Self::Item> {
5059 let next = self.chars.next();
5060 if next.is_some() {
5061 self.read.set(self.read.get() + 1);
5062 }
5063 next
5064 }
5065 }
5066
5067 struct SlicingOnlyInput<'input> {
5068 inner: StrInput<'input>,
5069 expose_slice: bool,
5070 }
5071
5072 impl<'input> SlicingOnlyInput<'input> {
5073 fn new(source: &'input str, expose_slice: bool) -> Self {
5074 Self {
5075 inner: StrInput::new(source),
5076 expose_slice,
5077 }
5078 }
5079 }
5080
5081 impl Input for SlicingOnlyInput<'_> {
5082 fn lookahead(&mut self, count: usize) {
5083 self.inner.lookahead(count);
5084 }
5085
5086 fn buflen(&self) -> usize {
5087 self.inner.buflen()
5088 }
5089
5090 fn bufmaxlen(&self) -> usize {
5091 self.inner.bufmaxlen()
5092 }
5093
5094 fn raw_read_ch(&mut self) -> char {
5095 self.inner.raw_read_ch()
5096 }
5097
5098 fn raw_read_non_breakz_ch(&mut self) -> Option<char> {
5099 self.inner.raw_read_non_breakz_ch()
5100 }
5101
5102 fn skip(&mut self) {
5103 self.inner.skip();
5104 }
5105
5106 fn skip_n(&mut self, count: usize) {
5107 self.inner.skip_n(count);
5108 }
5109
5110 fn peek(&self) -> char {
5111 self.inner.peek()
5112 }
5113
5114 fn peek_nth(&self, n: usize) -> char {
5115 self.inner.peek_nth(n)
5116 }
5117
5118 fn byte_offset(&self) -> Option<usize> {
5119 self.inner.byte_offset()
5120 }
5121
5122 fn slice_bytes(&self, start: usize, end: usize) -> Option<&str> {
5123 if self.expose_slice {
5124 self.inner.slice_bytes(start, end)
5125 } else {
5126 None
5127 }
5128 }
5129 }
5130
5131 impl<'input> BorrowedInput<'input> for SlicingOnlyInput<'input> {
5132 fn slice_borrowed(&self, _start: usize, _end: usize) -> Option<&'input str> {
5133 None
5134 }
5135 }
5136
5137 struct SmallReportedBufferInput<'input> {
5138 inner: StrInput<'input>,
5139 reported_bufmaxlen: usize,
5140 }
5141
5142 impl<'input> SmallReportedBufferInput<'input> {
5143 fn new(source: &'input str, reported_bufmaxlen: usize) -> Self {
5144 Self {
5145 inner: StrInput::new(source),
5146 reported_bufmaxlen,
5147 }
5148 }
5149 }
5150
5151 impl Input for SmallReportedBufferInput<'_> {
5152 fn lookahead(&mut self, count: usize) {
5153 self.inner.lookahead(count);
5154 }
5155
5156 fn buflen(&self) -> usize {
5157 self.inner.buflen()
5158 }
5159
5160 fn bufmaxlen(&self) -> usize {
5161 self.reported_bufmaxlen
5162 }
5163
5164 fn raw_read_ch(&mut self) -> char {
5165 self.inner.raw_read_ch()
5166 }
5167
5168 fn raw_read_non_breakz_ch(&mut self) -> Option<char> {
5169 self.inner.raw_read_non_breakz_ch()
5170 }
5171
5172 fn skip(&mut self) {
5173 self.inner.skip();
5174 }
5175
5176 fn skip_n(&mut self, count: usize) {
5177 self.inner.skip_n(count);
5178 }
5179
5180 fn peek(&self) -> char {
5181 self.inner.peek()
5182 }
5183
5184 fn peek_nth(&self, n: usize) -> char {
5185 self.inner.peek_nth(n)
5186 }
5187 }
5188
5189 impl<'input> BorrowedInput<'input> for SmallReportedBufferInput<'input> {
5190 fn slice_borrowed(&self, start: usize, end: usize) -> Option<&'input str> {
5191 self.inner.slice_borrowed(start, end)
5192 }
5193 }
5194
5195 #[test]
5196 fn anchor_character_set_allows_colon_and_rejects_flow_indicators() {
5197 use super::is_anchor_char;
5198
5199 assert!(is_anchor_char('x'));
5200 assert!(is_anchor_char('-'));
5201 assert!(is_anchor_char('_'));
5202 assert!(is_anchor_char(':'));
5203 assert!(is_anchor_char('#'));
5204 assert!(is_anchor_char('/'));
5205 assert!(is_anchor_char('?'));
5206
5207 for c in [',', '[', ']', '{', '}', ' ', '\t', '\n', '\r', '\0'] {
5208 assert!(
5209 !is_anchor_char(c),
5210 "character {c:?} must not be accepted in anchor/alias names"
5211 );
5212 }
5213 }
5214
5215 #[test]
5216 fn flow_simple_key_length_limit_bounds_buffering() {
5217 let mut yaml = String::from("[\n\"start\"\n");
5218 for _ in 0..600 {
5219 yaml.push_str("\"x\"\n");
5220 }
5221 let total_chars = yaml.chars().count();
5222 let read = Rc::new(Cell::new(0));
5223 let chars = yaml.chars().collect::<Vec<_>>().into_iter();
5224 let mut scanner = Scanner::new(BufferedInput::new(CountingChars {
5225 chars,
5226 read: Rc::clone(&read),
5227 }));
5228
5229 assert!(matches!(
5230 scanner.next_token().unwrap().unwrap().1,
5231 TokenType::StreamStart
5232 ));
5233
5234 let token = scanner.next_token().unwrap().unwrap();
5235 assert!(matches!(token.1, TokenType::FlowSequenceStart));
5236
5237 let token = scanner.next_token().unwrap().unwrap();
5238 assert!(matches!(
5239 token.1,
5240 TokenType::Scalar(_, ref value) if value == "start"
5241 ));
5242 assert!(
5243 read.get() < total_chars,
5244 "scanner consumed all {total_chars} chars before yielding the first flow scalar"
5245 );
5246 assert!(
5247 read.get() <= scanner.options.simple_key_max_lookahead + 128,
5248 "scanner read {} chars before yielding the first flow scalar",
5249 read.get()
5250 );
5251 }
5252
5253 #[test]
5254 fn block_scalar_indent_tolerates_small_reported_bufmaxlen() {
5255 let mut scanner = Scanner::new(SmallReportedBufferInput::new("|\n value\n", 0));
5256
5257 let scalar = scanner
5258 .find_map(
5259 |token| match token.expect("valid YAML should scan without errors") {
5260 Token(_, TokenType::Scalar(ScalarStyle::Literal, value)) => {
5261 Some(value.into_owned())
5262 }
5263 _ => None,
5264 },
5265 )
5266 .expect("expected block scalar token");
5267
5268 assert_eq!(scalar, "value\n");
5269 }
5270
5271 #[test]
5272 fn plain_scalar_chunk_tolerates_small_reported_bufmaxlen() {
5273 let mut scanner = Scanner::new(SmallReportedBufferInput::new("plain\n", 0));
5274
5275 let scalar = scanner
5276 .find_map(
5277 |token| match token.expect("valid YAML should scan without errors") {
5278 Token(_, TokenType::Scalar(ScalarStyle::Plain, value)) => {
5279 Some(value.into_owned())
5280 }
5281 _ => None,
5282 },
5283 )
5284 .expect("expected plain scalar token");
5285
5286 assert_eq!(scalar, "plain");
5287 }
5288
5289 fn first_token_slice(
5290 yaml: &str,
5291 matches_token: impl Fn(&TokenType<'_>) -> bool,
5292 ) -> Option<String> {
5293 let mut scanner = Scanner::new(StrInput::new(yaml));
5294
5295 loop {
5296 let token = scanner
5297 .next_token()
5298 .expect("scanner should accept the test YAML")?;
5299 if matches_token(&token.1) {
5300 return token.0.slice(yaml).map(ToOwned::to_owned);
5301 }
5302 }
5303 }
5304
5305 #[test]
5306 fn flow_indicator_token_spans_cover_only_the_indicator() {
5307 assert_eq!(
5308 first_token_slice("[ # c\n a]\n", |token| matches!(
5309 token,
5310 TokenType::FlowSequenceStart
5311 ))
5312 .as_deref(),
5313 Some("[")
5314 );
5315 assert_eq!(
5316 first_token_slice("{ # c\n a: b}\n", |token| matches!(
5317 token,
5318 TokenType::FlowMappingStart
5319 ))
5320 .as_deref(),
5321 Some("{")
5322 );
5323 assert_eq!(
5324 first_token_slice("[a] # c\n", |token| matches!(
5325 token,
5326 TokenType::FlowSequenceEnd
5327 ))
5328 .as_deref(),
5329 Some("]")
5330 );
5331 assert_eq!(
5332 first_token_slice("{a: b} # c\n", |token| matches!(
5333 token,
5334 TokenType::FlowMappingEnd
5335 ))
5336 .as_deref(),
5337 Some("}")
5338 );
5339 assert_eq!(
5340 first_token_slice("[a, # c\nb]\n", |token| matches!(
5341 token,
5342 TokenType::FlowEntry
5343 ))
5344 .as_deref(),
5345 Some(",")
5346 );
5347 }
5348
5349 #[test]
5350 fn explicit_key_token_span_covers_only_the_indicator() {
5351 assert_eq!(
5352 first_token_slice("? # c\n: value\n", |token| matches!(token, TokenType::Key))
5353 .as_deref(),
5354 Some("?")
5355 );
5356 }
5357
5358 #[test]
5359 #[cfg(feature = "comments")]
5360 fn comment_capture_does_not_change_leading_whitespace() {
5361 let mut scanner = Scanner::new(StrInput::new("# comment\n"));
5362
5363 let token = scanner.scan_comment_token().unwrap();
5364
5365 assert!(scanner.leading_whitespace);
5366 assert!(matches!(token.1, TokenType::Comment(ref comment) if comment.text == " comment"));
5367
5368 let mut scanner = Scanner::new(BufferedInput::new("# streaming\n".chars()));
5369 scanner.input.lookahead(1);
5370
5371 let token = scanner.scan_comment_token().unwrap();
5372
5373 assert!(scanner.leading_whitespace);
5374 assert!(matches!(token.1, TokenType::Comment(ref comment) if comment.text == " streaming"));
5375 }
5376
5377 #[test]
5378 #[cfg(feature = "comments")]
5379 fn comment_capture_falls_back_to_owned_slice_when_borrow_unavailable() {
5380 let mut scanner = Scanner::new(SlicingOnlyInput::new("# sliced\n", true));
5381 scanner.input.lookahead(2);
5382 assert_eq!(scanner.input.peek_nth(1), ' ');
5383
5384 let token = scanner.scan_comment_token().unwrap();
5385
5386 assert!(matches!(token.1, TokenType::Comment(ref comment)
5387 if matches!(comment.text, Cow::Owned(ref text) if text == " sliced")));
5388 }
5389
5390 #[test]
5391 #[cfg(feature = "comments")]
5392 fn comment_capture_errors_when_offsets_have_no_slice() {
5393 let mut scanner = Scanner::new(SlicingOnlyInput::new("# broken\n", false));
5394
5395 let error = scanner.scan_comment_token().unwrap_err();
5396
5397 assert_eq!(error.kind(), &ErrorKind::InputOffsetsWithoutSlice);
5398 }
5399
5400 #[test]
5401 fn disabled_comments_do_not_require_input_slicing() {
5402 let options = ignoring_comments_options();
5403 let scanner = Scanner::with_options(
5404 SlicingOnlyInput::new("# ignored\nkey: value\n", false),
5405 options,
5406 );
5407
5408 let tokens = scanner
5409 .collect::<Result<Vec<_>, _>>()
5410 .expect("ignored comments should not capture their payload");
5411
5412 #[cfg(feature = "comments")]
5413 assert!(tokens
5414 .iter()
5415 .all(|token| !matches!(token.1, TokenType::Comment(_))));
5416 assert!(tokens.iter().any(|token| matches!(
5417 token.1,
5418 TokenType::Scalar(ScalarStyle::Plain, ref text) if text == "value"
5419 )));
5420 }
5421
5422 #[test]
5423 fn queued_token_roundtrips_public_token_variants() {
5424 let span = Span::new(Marker::new(0, 1, 0), Marker::new(7, 1, 7));
5425 let tokens = [
5426 Token(span, TokenType::StreamStart),
5427 Token(span, TokenType::StreamEnd),
5428 Token(span, TokenType::VersionDirective(1, 2)),
5429 Token(
5430 span,
5431 TokenType::TagDirective(Cow::Borrowed("!app!"), Cow::Borrowed("tag:app.example,")),
5432 ),
5433 Token(span, TokenType::DocumentStart),
5434 Token(span, TokenType::DocumentEnd),
5435 Token(span, TokenType::BlockSequenceStart),
5436 Token(span, TokenType::BlockMappingStart),
5437 Token(span, TokenType::BlockEnd),
5438 Token(span, TokenType::FlowSequenceStart),
5439 Token(span, TokenType::FlowSequenceEnd),
5440 Token(span, TokenType::FlowMappingStart),
5441 Token(span, TokenType::FlowMappingEnd),
5442 Token(span, TokenType::BlockEntry),
5443 Token(span, TokenType::FlowEntry),
5444 Token(span, TokenType::Key),
5445 Token(span, TokenType::Value),
5446 Token(span, TokenType::Alias(Cow::Borrowed("alias"))),
5447 Token(span, TokenType::Anchor(Cow::Borrowed("anchor"))),
5448 Token(
5449 span,
5450 TokenType::Tag(Cow::Borrowed("!"), Cow::Borrowed("tag")),
5451 ),
5452 Token(
5453 span,
5454 TokenType::Scalar(ScalarStyle::Literal, Cow::Borrowed("scalar")),
5455 ),
5456 #[cfg(feature = "comments")]
5457 Token(
5458 span,
5459 TokenType::Comment(
5460 Comment::new(Cow::Borrowed(" comment")).with_placement(Placement::Right),
5461 ),
5462 ),
5463 Token(
5464 span,
5465 TokenType::ReservedDirective(
5466 "reserved".to_owned(),
5467 vec!["one".to_owned(), "two".to_owned()],
5468 ),
5469 ),
5470 ];
5471
5472 for token in tokens {
5473 let queued: QueuedToken = token.clone().into();
5474
5475 assert_eq!(queued.into_public(), token);
5476 }
5477 }
5478
5479 #[test]
5480 fn comment_skipping_path_consumes_comment_without_tokenizing_it() {
5481 let mut scanner = Scanner::new(StrInput::new("# skipped\nnext: value\n"));
5482
5483 scanner.skip_yaml_whitespace().unwrap();
5484
5485 assert!(scanner.tokens.is_empty());
5486 assert_eq!(scanner.mark.line(), 2);
5487 assert_eq!(scanner.mark.col(), 0);
5488 }
5489
5490 #[test]
5491 #[cfg(feature = "comments")]
5492 fn yaml_whitespace_can_stop_after_queued_comment() {
5493 let mut scanner = Scanner::new(StrInput::new(" # queued\n# later\n"));
5494
5495 assert!(scanner.skip_yaml_whitespace().unwrap());
5496
5497 assert_eq!(scanner.tokens.len(), 1);
5498 assert!(matches!(
5499 scanner.tokens.front().unwrap().1,
5500 QueuedTokenType::Comment(ref comment) if comment.text == " queued"
5501 ));
5502 assert_eq!(scanner.mark.line(), 1);
5503 assert_eq!(scanner.mark.col(), 9);
5504 }
5505
5506 #[test]
5507 #[cfg(feature = "comments")]
5508 fn token_skip_can_stop_after_queued_comment() {
5509 let mut scanner = Scanner::new(StrInput::new("# first\n# second\n"));
5510
5511 assert!(scanner.skip_to_next_token().unwrap().queued_comment);
5512
5513 assert_eq!(scanner.tokens.len(), 1);
5514 assert!(matches!(
5515 scanner.tokens.front().unwrap().1,
5516 QueuedTokenType::Comment(ref comment) if comment.text == " first"
5517 ));
5518 assert_eq!(scanner.mark.line(), 2);
5519 assert_eq!(scanner.mark.col(), 0);
5520 }
5521
5522 #[test]
5523 fn token_skip_stops_after_one_ignored_comment_without_queuing_it() {
5524 let options = ignoring_comments_options();
5525 let mut scanner =
5526 Scanner::with_options(StrInput::new("# first\n# second\nvalue\n"), options);
5527
5528 let outcome = scanner.skip_to_next_token().unwrap();
5529
5530 assert!(outcome.saw_comment);
5531 #[cfg(feature = "comments")]
5532 assert!(!outcome.queued_comment);
5533 assert!(scanner.tokens.is_empty());
5534 assert_eq!((scanner.mark.line(), scanner.mark.col()), (2, 0));
5535 assert_eq!(scanner.input.look_ch(), '#');
5536 }
5537
5538 #[test]
5539 fn yaml_whitespace_stops_after_one_separated_ignored_comment() {
5540 let options = ignoring_comments_options();
5541 let mut scanner =
5542 Scanner::with_options(StrInput::new(" # first\n# second\nvalue\n"), options);
5543
5544 assert!(scanner.skip_yaml_whitespace().unwrap());
5545
5546 assert!(scanner.tokens.is_empty());
5547 assert_eq!((scanner.mark.line(), scanner.mark.col()), (1, 8));
5548 assert_eq!(scanner.input.look_ch(), '\n');
5549 }
5550
5551 #[test]
5552 fn scanner_skips_consecutive_leading_ignored_comments_before_next_token() {
5553 let options = ignoring_comments_options();
5554 let mut scanner =
5555 Scanner::with_options(StrInput::new("# first\n# second\nvalue\n"), options);
5556
5557 assert!(matches!(
5558 scanner.next_token().unwrap().unwrap().1,
5559 TokenType::StreamStart
5560 ));
5561 assert!(matches!(
5562 scanner.next_token().unwrap().unwrap().1,
5563 TokenType::Scalar(ScalarStyle::Plain, ref value) if value == "value"
5564 ));
5565 #[cfg(feature = "comments")]
5566 assert!(scanner
5567 .tokens
5568 .iter()
5569 .all(|QueuedToken(_, token)| !matches!(token, QueuedTokenType::Comment(_))));
5570 }
5571
5572 #[test]
5573 #[cfg(feature = "comments")]
5574 fn scanner_emits_first_leading_comment_before_scanning_next_comment() {
5575 let mut scanner = Scanner::new(StrInput::new("# first\n# second\nkey: value\n"));
5576
5577 assert!(matches!(
5578 scanner.next_token().unwrap().unwrap().1,
5579 TokenType::StreamStart
5580 ));
5581 assert!(matches!(
5582 scanner.next_token().unwrap().unwrap().1,
5583 TokenType::Comment(ref comment) if comment.text == " first"
5584 ));
5585 assert!(scanner.tokens.is_empty());
5586 assert!(matches!(
5587 scanner.next_token().unwrap().unwrap().1,
5588 TokenType::Comment(ref comment) if comment.text == " second"
5589 ));
5590 }
5591
5592 #[test]
5593 #[cfg(feature = "comments")]
5594 fn scanner_emits_quoted_scalar_comment_before_scanning_following_value() {
5595 let mut scanner = Scanner::new(StrInput::new("\"key\" # quoted\n: value\n"));
5596
5597 assert!(matches!(
5598 scanner.next_token().unwrap().unwrap().1,
5599 TokenType::StreamStart
5600 ));
5601 assert!(matches!(
5602 scanner.next_token().unwrap().unwrap().1,
5603 TokenType::Scalar(ScalarStyle::DoubleQuoted, ref value) if value == "key"
5604 ));
5605 assert!(matches!(
5606 scanner.next_token().unwrap().unwrap().1,
5607 TokenType::Comment(ref comment) if comment.text == " quoted"
5608 ));
5609 }
5610
5611 #[test]
5612 #[cfg(feature = "comments")]
5613 fn flow_scalar_comment_disables_adjacent_value_lookahead() {
5614 let mut scanner = Scanner::new(StrInput::new("\"key\"\n# quoted\n: value\n"));
5615
5616 scanner.fetch_flow_scalar(false).unwrap();
5617
5618 assert_eq!(scanner.adjacent_value_allowed_at, usize::MAX);
5619 assert!(matches!(
5620 scanner.tokens.front().unwrap().1,
5621 QueuedTokenType::Scalar(ScalarStyle::DoubleQuoted, ref value) if value == "key"
5622 ));
5623 assert!(scanner.tokens.iter().any(|QueuedToken(_, token)| matches!(
5624 token,
5625 QueuedTokenType::Comment(comment) if comment.text == " quoted"
5626 )));
5627 }
5628
5629 #[test]
5630 fn ignored_flow_scalar_comment_still_disables_adjacent_value_lookahead() {
5631 let options = ignoring_comments_options();
5632 let mut scanner =
5633 Scanner::with_options(StrInput::new("\"key\"\n# ignored\n: value\n"), options);
5634
5635 scanner.fetch_flow_scalar(false).unwrap();
5636
5637 assert_eq!(scanner.adjacent_value_allowed_at, usize::MAX);
5638 assert_eq!(scanner.tokens.len(), 1);
5639 assert!(matches!(
5640 scanner.tokens.front().unwrap().1,
5641 QueuedTokenType::Scalar(ScalarStyle::DoubleQuoted, ref value) if value == "key"
5642 ));
5643 }
5644
5645 #[test]
5646 #[cfg(feature = "comments")]
5647 fn deferred_error_waits_for_all_comment_tokens() {
5648 let mut scanner = Scanner::new(StrInput::new("# first\n# second\n@\n"));
5649
5650 assert!(matches!(
5651 scanner.next_token().unwrap().unwrap().1,
5652 TokenType::StreamStart
5653 ));
5654 assert!(matches!(
5655 scanner.next_token().unwrap().unwrap().1,
5656 TokenType::Comment(ref comment) if comment.text == " first"
5657 ));
5658 assert!(matches!(
5659 scanner.next_token().unwrap().unwrap().1,
5660 TokenType::Comment(ref comment) if comment.text == " second"
5661 ));
5662
5663 let error = scanner.next_token().unwrap_err();
5664
5665 assert_eq!(
5666 error.kind(),
5667 &ErrorKind::UnexpectedCharacter { character: '@' }
5668 );
5669 }
5670
5671 #[test]
5673 fn anchor_name_is_borrowed_for_str_input() {
5674 let mut scanner = Scanner::new(StrInput::new("&anch\n"));
5675
5676 loop {
5677 let tok = scanner
5678 .next_token()
5679 .expect("valid YAML must scan without errors")
5680 .expect("scanner must eventually produce a token");
5681 if let TokenType::Anchor(name) = tok.1 {
5682 assert!(matches!(name, Cow::Borrowed("anch")));
5683 break;
5684 }
5685 }
5686 }
5687
5688 #[test]
5689 fn anchor_name_rejects_non_printable_control_chars() {
5690 let mut scanner = Scanner::new(StrInput::new("&foo\u{0001}\n"));
5691
5692 scanner.next_token().unwrap();
5693 assert_eq!(
5694 scanner.next_token().unwrap_err().kind(),
5695 &ErrorKind::UnexpectedCharacter {
5696 character: '\u{0001}'
5697 }
5698 );
5699 }
5700
5701 #[test]
5702 fn alias_name_rejects_non_printable_control_chars() {
5703 let mut scanner = Scanner::new(StrInput::new("*foo\u{0001}\n"));
5704
5705 scanner.next_token().unwrap();
5706 assert_eq!(
5707 scanner.next_token().unwrap_err().kind(),
5708 &ErrorKind::UnexpectedCharacter {
5709 character: '\u{0001}'
5710 }
5711 );
5712 }
5713
5714 #[test]
5715 fn alias_name_is_borrowed_for_str_input() {
5716 let mut scanner = Scanner::new(StrInput::new("*anch\n"));
5717
5718 loop {
5719 let tok = scanner
5720 .next_token()
5721 .expect("valid YAML must scan without errors")
5722 .expect("scanner must eventually produce a token");
5723 if let TokenType::Alias(name) = tok.1 {
5724 assert!(matches!(name, Cow::Borrowed("anch")));
5725 break;
5726 }
5727 }
5728 }
5729
5730 #[test]
5731 fn alias_name_scans_colon_as_part_of_name() {
5732 let mut scanner = Scanner::new(StrInput::new("*foo: bar\n"));
5733
5734 loop {
5735 let tok = scanner
5736 .next_token()
5737 .expect("scanner must not fail before alias token")
5738 .expect("scanner must eventually emit an alias token");
5739
5740 if let TokenType::Alias(name) = tok.1 {
5741 assert_eq!(name.as_ref(), "foo:");
5742 break;
5743 }
5744 }
5745 }
5746
5747 #[test]
5748 fn anchor_name_scans_colon_as_part_of_name() {
5749 let mut scanner = Scanner::new(StrInput::new("&foo: bar\n"));
5750
5751 loop {
5752 let tok = scanner
5753 .next_token()
5754 .expect("scanner must not fail before anchor token")
5755 .expect("scanner must eventually emit an anchor token");
5756
5757 if let TokenType::Anchor(name) = tok.1 {
5758 assert_eq!(name.as_ref(), "foo:");
5759 break;
5760 }
5761 }
5762 }
5763
5764 #[test]
5766 fn tag_directive_parts_are_borrowed_for_str_input() {
5767 let mut scanner = Scanner::new(StrInput::new("%TAG !e! tag:example.com,2000:app/\n"));
5768
5769 loop {
5770 let tok = scanner
5771 .next_token()
5772 .expect("valid YAML must scan without errors")
5773 .expect("scanner must eventually produce a token");
5774 if let TokenType::TagDirective(handle, prefix) = tok.1 {
5775 assert!(matches!(handle, Cow::Borrowed("!e!")));
5776 assert!(matches!(prefix, Cow::Borrowed("tag:example.com,2000:app/")));
5777 break;
5778 }
5779 }
5780 }
5781
5782 #[test]
5783 fn tag_directive_parts_are_owned_for_buffered_input() {
5784 let mut scanner = Scanner::new(BufferedInput::new(
5785 "%TAG !e! tag:example.com,2000:app/\n".chars(),
5786 ));
5787
5788 loop {
5789 let tok = scanner
5790 .next_token()
5791 .expect("valid YAML must scan without errors")
5792 .expect("scanner must eventually produce a token");
5793 if let TokenType::TagDirective(handle, prefix) = tok.1 {
5794 assert!(matches!(handle, Cow::Owned(_)));
5795 assert_eq!(&*handle, "!e!");
5796 assert!(matches!(prefix, Cow::Owned(_)));
5797 assert_eq!(&*prefix, "tag:example.com,2000:app/");
5798 break;
5799 }
5800 }
5801 }
5802
5803 #[test]
5804 fn buffered_tag_directive_decodes_prefix_escape() {
5805 let mut scanner = Scanner::new(BufferedInput::new(
5806 "%TAG !e! %74ag:example.com,2000:app/\n".chars(),
5807 ));
5808
5809 loop {
5810 let tok = scanner
5811 .next_token()
5812 .expect("valid YAML must scan without errors")
5813 .expect("scanner must eventually produce a token");
5814 if let TokenType::TagDirective(handle, prefix) = tok.1 {
5815 assert_eq!(&*handle, "!e!");
5816 assert!(matches!(prefix, Cow::Owned(_)));
5817 assert_eq!(&*prefix, "tag:example.com,2000:app/");
5818 break;
5819 }
5820 }
5821 }
5822
5823 #[test]
5824 fn local_tag_combines_handle_text_with_escaped_suffix() {
5825 let mut scanner = Scanner::new(StrInput::new("!foo%20bar value\n"));
5826
5827 loop {
5828 let tok = scanner
5829 .next_token()
5830 .expect("valid YAML must scan without errors")
5831 .expect("scanner must eventually produce a token");
5832 if let TokenType::Tag(handle, suffix) = tok.1 {
5833 assert!(matches!(handle, Cow::Borrowed("!")));
5834 assert!(matches!(suffix, Cow::Owned(_)));
5835 assert_eq!(&*suffix, "foo bar");
5836 break;
5837 }
5838 }
5839 }
5840
5841 #[test]
5842 fn secondary_tag_requires_suffix_in_borrowed_and_buffered_paths() {
5843 assert_eq!(
5844 first_scanner_error_kind("!! value\n"),
5845 ErrorKind::MissingTagUri
5846 );
5847 assert_eq!(
5848 first_buffered_scanner_error_kind("!! value\n"),
5849 ErrorKind::MissingTagUri
5850 );
5851 }
5852
5853 #[test]
5854 fn plain_scalar_is_borrowed_when_whitespace_free_for_str_input() {
5855 let mut scanner = Scanner::new(StrInput::new("foo\n"));
5856
5857 loop {
5858 let tok = scanner
5859 .next_token()
5860 .expect("valid YAML must scan without errors")
5861 .expect("scanner must eventually produce a token");
5862 if let TokenType::Scalar(_, value) = tok.1 {
5863 assert!(matches!(value, Cow::Borrowed("foo")));
5864 break;
5865 }
5866 }
5867 }
5868
5869 #[test]
5870 fn plain_scalar_is_borrowed_when_whitespace_present_for_str_input() {
5871 let mut scanner = Scanner::new(StrInput::new("foo bar\n"));
5872
5873 loop {
5874 let tok = scanner
5875 .next_token()
5876 .expect("valid YAML must scan without errors")
5877 .expect("scanner must eventually produce a token");
5878 if let TokenType::Scalar(_, value) = tok.1 {
5879 assert!(matches!(value, Cow::Borrowed("foo bar")));
5880 break;
5881 }
5882 }
5883 }
5884
5885 #[test]
5886 fn single_quoted_scalar_is_borrowed_when_verbatim_for_str_input() {
5887 let mut scanner = Scanner::new(StrInput::new("'foo bar'\n"));
5888
5889 loop {
5890 let tok = scanner
5891 .next_token()
5892 .expect("valid YAML must scan without errors")
5893 .expect("scanner must eventually produce a token");
5894 if let TokenType::Scalar(_, value) = tok.1 {
5895 assert!(matches!(value, Cow::Borrowed("foo bar")));
5896 break;
5897 }
5898 }
5899 }
5900
5901 #[test]
5902 fn single_quoted_scalar_is_owned_when_quote_is_escaped_for_str_input() {
5903 let mut scanner = Scanner::new(StrInput::new("'foo''bar'\n"));
5904
5905 loop {
5906 let tok = scanner
5907 .next_token()
5908 .expect("valid YAML must scan without errors")
5909 .expect("scanner must eventually produce a token");
5910 if let TokenType::Scalar(_, value) = tok.1 {
5911 assert!(matches!(value, Cow::Owned(_)));
5912 assert_eq!(&*value, "foo'bar");
5913 break;
5914 }
5915 }
5916 }
5917
5918 #[test]
5919 fn double_quoted_scalar_is_borrowed_when_verbatim_for_str_input() {
5920 let mut scanner = Scanner::new(StrInput::new("\"foo bar\"\n"));
5921
5922 loop {
5923 let tok = scanner
5924 .next_token()
5925 .expect("valid YAML must scan without errors")
5926 .expect("scanner must eventually produce a token");
5927 if let TokenType::Scalar(_, value) = tok.1 {
5928 assert!(matches!(value, Cow::Borrowed("foo bar")));
5929 break;
5930 }
5931 }
5932 }
5933
5934 #[test]
5935 fn double_quoted_scalar_is_owned_when_escape_sequence_present_for_str_input() {
5936 let mut scanner = Scanner::new(StrInput::new("\"foo\\nbar\"\n"));
5937
5938 loop {
5939 let tok = scanner
5940 .next_token()
5941 .expect("valid YAML must scan without errors")
5942 .expect("scanner must eventually produce a token");
5943 if let TokenType::Scalar(_, value) = tok.1 {
5944 assert!(matches!(value, Cow::Owned(_)));
5945 assert_eq!(&*value, "foo\nbar");
5946 break;
5947 }
5948 }
5949 }
5950
5951 #[test]
5952 fn plain_key_is_borrowed_for_str_input() {
5953 let mut scanner = Scanner::new(StrInput::new("mykey: value\n"));
5955
5956 let mut found_key = false;
5957 let mut key_value: Option<Cow<'_, str>> = None;
5958
5959 loop {
5960 let tok = scanner
5961 .next_token()
5962 .expect("valid YAML must scan without errors");
5963 let Some(tok) = tok else { break };
5964
5965 if matches!(tok.1, TokenType::Key) {
5966 found_key = true;
5967 } else if found_key {
5968 if let TokenType::Scalar(_, value) = tok.1 {
5969 key_value = Some(value);
5970 break;
5971 }
5972 }
5973 }
5974
5975 assert!(found_key, "expected to find a Key token");
5976 let key_value = key_value.expect("expected to find a scalar after Key token");
5977 assert!(
5978 matches!(key_value, Cow::Borrowed("mykey")),
5979 "key should be borrowed, got: {key_value:?}"
5980 );
5981 }
5982
5983 #[test]
5984 fn quoted_key_is_borrowed_when_verbatim_for_str_input() {
5985 let mut scanner = Scanner::new(StrInput::new("\"mykey\": value\n"));
5986
5987 let mut found_key = false;
5988 let mut key_value: Option<Cow<'_, str>> = None;
5989
5990 loop {
5991 let tok = scanner
5992 .next_token()
5993 .expect("valid YAML must scan without errors");
5994 let Some(tok) = tok else { break };
5995
5996 if matches!(tok.1, TokenType::Key) {
5997 found_key = true;
5998 } else if found_key {
5999 if let TokenType::Scalar(_, value) = tok.1 {
6000 key_value = Some(value);
6001 break;
6002 }
6003 }
6004 }
6005
6006 assert!(found_key, "expected to find a Key token");
6007 let key_value = key_value.expect("expected to find a scalar after Key token");
6008 assert!(
6009 matches!(key_value, Cow::Borrowed("mykey")),
6010 "quoted key should be borrowed when verbatim, got: {key_value:?}"
6011 );
6012 }
6013
6014 #[test]
6015 fn tag_handle_and_suffix_are_borrowed_for_str_input() {
6016 let mut scanner = Scanner::new(StrInput::new("!!str foo\n"));
6018
6019 loop {
6020 let tok = scanner
6021 .next_token()
6022 .expect("valid YAML must scan without errors")
6023 .expect("scanner must eventually produce a token");
6024 if let TokenType::Tag(handle, suffix) = tok.1 {
6025 assert!(
6026 matches!(handle, Cow::Borrowed("!!")),
6027 "tag handle should be borrowed, got: {handle:?}"
6028 );
6029 assert!(
6030 matches!(suffix, Cow::Borrowed("str")),
6031 "tag suffix should be borrowed, got: {suffix:?}"
6032 );
6033 break;
6034 }
6035 }
6036 }
6037
6038 #[test]
6039 fn local_tag_suffix_is_borrowed_for_str_input() {
6040 let mut scanner = Scanner::new(StrInput::new("!mytag foo\n"));
6042
6043 loop {
6044 let tok = scanner
6045 .next_token()
6046 .expect("valid YAML must scan without errors")
6047 .expect("scanner must eventually produce a token");
6048 if let TokenType::Tag(handle, suffix) = tok.1 {
6049 assert!(
6050 matches!(handle, Cow::Borrowed("!")),
6051 "local tag handle should be '!', got: {handle:?}"
6052 );
6053 assert!(
6054 matches!(suffix, Cow::Borrowed("mytag")),
6055 "local tag suffix should be borrowed, got: {suffix:?}"
6056 );
6057 break;
6058 }
6059 }
6060 }
6061
6062 #[test]
6063 fn local_tag_suffix_with_punctuation_is_borrowed_for_str_input() {
6064 let mut scanner = Scanner::new(StrInput::new("!mytag/part foo\n"));
6065
6066 loop {
6067 let tok = scanner
6068 .next_token()
6069 .expect("valid YAML must scan without errors")
6070 .expect("scanner must eventually produce a token");
6071 if let TokenType::Tag(handle, suffix) = tok.1 {
6072 assert!(matches!(handle, Cow::Borrowed("!")));
6073 assert!(matches!(suffix, Cow::Borrowed("mytag/part")));
6074 break;
6075 }
6076 }
6077 }
6078
6079 #[test]
6080 fn tag_with_uri_escape_is_owned_for_str_input() {
6081 let mut scanner = Scanner::new(StrInput::new("!!my%20tag foo\n"));
6083
6084 loop {
6085 let tok = scanner
6086 .next_token()
6087 .expect("valid YAML must scan without errors")
6088 .expect("scanner must eventually produce a token");
6089 if let TokenType::Tag(handle, suffix) = tok.1 {
6090 assert!(
6091 matches!(handle, Cow::Borrowed("!!")),
6092 "tag handle should still be borrowed, got: {handle:?}"
6093 );
6094 assert!(
6095 matches!(suffix, Cow::Owned(_)),
6096 "tag suffix with URI escape should be owned, got: {suffix:?}"
6097 );
6098 assert_eq!(&*suffix, "my tag");
6099 break;
6100 }
6101 }
6102 }
6103
6104 #[test]
6105 fn flow_scalar_buffer_tracks_pending_whitespace() {
6106 let mut borrowed = super::FlowScalarBuf::new_borrowed(2);
6107
6108 borrowed.note_pending_ws(5, 8);
6109 borrowed.commit_pending_ws();
6110 assert!(matches!(
6111 borrowed,
6112 super::FlowScalarBuf::Borrowed {
6113 end: 8,
6114 pending_ws_start: None,
6115 pending_ws_end: 8,
6116 ..
6117 }
6118 ));
6119
6120 borrowed.note_pending_ws(9, 11);
6121 borrowed.discard_pending_ws();
6122 assert!(matches!(
6123 borrowed,
6124 super::FlowScalarBuf::Borrowed {
6125 end: 8,
6126 pending_ws_start: None,
6127 pending_ws_end: 8,
6128 ..
6129 }
6130 ));
6131 assert!(borrowed.as_owned_mut().is_none());
6132
6133 let mut owned = super::FlowScalarBuf::new_owned();
6134 owned.as_owned_mut().unwrap().push_str("owned");
6135 assert!(matches!(owned, super::FlowScalarBuf::Owned(ref s) if s == "owned"));
6136 }
6137
6138 fn first_scanner_error_kind(input: &str) -> ErrorKind {
6139 first_scanner_error(input).kind().clone()
6140 }
6141
6142 fn first_buffered_scanner_error_kind(input: &str) -> ErrorKind {
6143 let mut scanner = Scanner::new(BufferedInput::new(input.chars()));
6144 loop {
6145 match scanner.next_token() {
6146 Ok(Some(_)) => {}
6147 Ok(None) => panic!("expected scanner error"),
6148 Err(error) => return error.kind().clone(),
6149 }
6150 }
6151 }
6152
6153 fn first_scanner_error(input: &str) -> ScanError {
6154 let mut scanner = Scanner::new(StrInput::new(input));
6155 loop {
6156 match scanner.next_token() {
6157 Ok(Some(_)) => {}
6158 Ok(None) => panic!("expected scanner error"),
6159 Err(error) => return error,
6160 }
6161 }
6162 }
6163
6164 fn first_scalar_value(input: &str) -> String {
6165 let mut scanner = Scanner::new(StrInput::new(input));
6166 loop {
6167 match scanner.next_token().expect("scanner should not error") {
6168 Some(Token(_, TokenType::Scalar(_, value))) => return value.into_owned(),
6169 Some(_) => {}
6170 None => panic!("expected scalar token"),
6171 }
6172 }
6173 }
6174
6175 fn first_buffered_scalar_value(input: &str) -> String {
6176 let mut scanner = Scanner::new(BufferedInput::new(input.chars()));
6177 loop {
6178 match scanner.next_token().expect("scanner should not error") {
6179 Some(Token(_, TokenType::Scalar(_, value))) => return value.into_owned(),
6180 Some(_) => {}
6181 None => panic!("expected scalar token"),
6182 }
6183 }
6184 }
6185
6186 #[test]
6187 fn iterator_next_emits_error_and_then_stays_empty() {
6188 let mut scanner = Scanner::new(StrInput::new("\"unterminated"));
6189
6190 let error = scanner
6191 .by_ref()
6192 .find_map(Result::err)
6193 .expect("scanner should emit the error");
6194 assert_eq!(error.kind(), &ErrorKind::UnclosedQuotedScalar);
6195 assert!(scanner.next().is_none());
6196 }
6197
6198 #[test]
6199 fn next_token_returns_none_after_stream_end() {
6200 let mut scanner = Scanner::new(StrInput::new(""));
6201
6202 while let Some(token) = scanner.next_token().unwrap() {
6203 if matches!(token.1, TokenType::StreamEnd) {
6204 break;
6205 }
6206 }
6207
6208 assert!(scanner.stream_started());
6209 assert!(scanner.stream_ended());
6210 assert!(scanner.next_token().unwrap().is_none());
6211 }
6212
6213 #[test]
6214 fn directive_name_must_be_present() {
6215 assert_eq!(
6216 first_scanner_error_kind("%\n"),
6217 ErrorKind::MissingDirectiveName
6218 );
6219 }
6220
6221 #[test]
6222 fn yaml_directive_requires_dot_between_version_numbers() {
6223 assert_eq!(
6224 first_scanner_error_kind("%YAML 1\n"),
6225 ErrorKind::MissingYamlVersionSeparator
6226 );
6227 }
6228
6229 #[test]
6230 fn yaml_directive_requires_major_version_number() {
6231 assert_eq!(
6232 first_scanner_error_kind("%YAML .2\n"),
6233 ErrorKind::MissingYamlVersion
6234 );
6235 }
6236
6237 #[test]
6238 fn yaml_directive_rejects_extremely_long_version_number() {
6239 assert_eq!(
6240 first_scanner_error_kind("%YAML 1234567890.2\n"),
6241 ErrorKind::YamlVersionTooLong
6242 );
6243 }
6244
6245 #[test]
6246 fn tag_directive_handle_must_end_with_bang() {
6247 assert_eq!(
6248 first_scanner_error_kind("%TAG !bad tag:example.com,2024:\n"),
6249 ErrorKind::ExpectedTagDirectiveBang
6250 );
6251 }
6252
6253 #[test]
6254 fn tag_directive_handle_must_start_with_bang() {
6255 assert_eq!(
6256 first_scanner_error_kind("%TAG bad! tag:example.com,2024:\n"),
6257 ErrorKind::ExpectedTagBang
6258 );
6259 assert_eq!(
6260 first_buffered_scanner_error_kind("%TAG bad! tag:example.com,2024:\n"),
6261 ErrorKind::ExpectedTagBang
6262 );
6263 }
6264
6265 #[test]
6266 fn tag_directive_prefix_must_start_with_tag_character() {
6267 assert_eq!(
6268 first_scanner_error_kind("%TAG !e! `bad\n"),
6269 ErrorKind::InvalidGlobalTagCharacter
6270 );
6271 }
6272
6273 #[test]
6274 fn tag_directive_prefix_must_end_before_invalid_content() {
6275 assert_eq!(
6276 first_scanner_error_kind("%TAG !e! tag:example.com^suffix\n"),
6277 ErrorKind::InvalidTagDirectiveTerminator
6278 );
6279 }
6280
6281 #[test]
6282 fn tag_directive_prefix_with_uri_escape_is_owned_and_decoded() {
6283 let mut scanner =
6284 Scanner::new(StrInput::new("%TAG !e! tag:example.com,2024:some%20app/\n"));
6285
6286 loop {
6287 let token = scanner
6288 .next_token()
6289 .expect("valid directive should scan")
6290 .expect("scanner must produce a directive token");
6291 if let TokenType::TagDirective(handle, prefix) = token.1 {
6292 assert!(matches!(handle, Cow::Borrowed("!e!")));
6293 assert!(matches!(prefix, Cow::Owned(_)));
6294 assert_eq!(&*prefix, "tag:example.com,2024:some app/");
6295 break;
6296 }
6297 }
6298 }
6299
6300 #[test]
6301 fn bare_bang_tag_scans_as_non_specific_tag() {
6302 let mut scanner = Scanner::new(StrInput::new("! foo\n"));
6303
6304 loop {
6305 let token = scanner
6306 .next_token()
6307 .expect("valid tag should scan")
6308 .expect("scanner must produce a tag token");
6309 if let TokenType::Tag(handle, suffix) = token.1 {
6310 assert_eq!(&*handle, "");
6311 assert_eq!(&*suffix, "!");
6312 break;
6313 }
6314 }
6315 }
6316
6317 #[test]
6318 fn tag_requires_separation_after_suffix() {
6319 assert_eq!(
6320 first_scanner_error_kind("!foo,bar\n"),
6321 ErrorKind::InvalidTagTerminator
6322 );
6323 }
6324
6325 #[test]
6326 fn verbatim_tag_requires_uri() {
6327 assert_eq!(
6328 first_scanner_error_kind("!<> foo\n"),
6329 ErrorKind::MissingTagUri
6330 );
6331 }
6332
6333 #[test]
6334 fn verbatim_tag_requires_closing_angle_bracket() {
6335 assert_eq!(
6336 first_scanner_error_kind("!<tag:yaml.org,2002:str foo\n"),
6337 ErrorKind::UnclosedVerbatimTag
6338 );
6339 }
6340
6341 #[test]
6342 fn tag_uri_escape_requires_hex_digits() {
6343 assert_eq!(
6344 first_scanner_error_kind("!!bad%zz foo\n"),
6345 ErrorKind::InvalidTagEscape
6346 );
6347 }
6348
6349 #[test]
6350 fn tag_uri_escape_rejects_bad_leading_utf8_byte() {
6351 assert_eq!(
6352 first_scanner_error_kind("!!bad%80 foo\n"),
6353 ErrorKind::InvalidTagUtf8LeadingByte
6354 );
6355 }
6356
6357 #[test]
6358 fn tag_uri_escape_rejects_bad_trailing_utf8_byte() {
6359 assert_eq!(
6360 first_scanner_error_kind("!!bad%C2%41 foo\n"),
6361 ErrorKind::InvalidTagUtf8TrailingByte
6362 );
6363 }
6364
6365 #[test]
6366 fn tag_uri_escape_rejects_invalid_utf8_codepoint() {
6367 assert_eq!(
6368 first_scanner_error_kind("!!bad%F4%90%80%80 foo\n"),
6369 ErrorKind::InvalidTagUtf8
6370 );
6371 }
6372
6373 #[test]
6374 fn anchors_and_aliases_require_names() {
6375 assert_eq!(
6376 first_scanner_error_kind("& \n"),
6377 ErrorKind::MissingAnchorOrAliasName
6378 );
6379 assert_eq!(
6380 first_scanner_error_kind("* \n"),
6381 ErrorKind::MissingAnchorOrAliasName
6382 );
6383 }
6384
6385 #[test]
6386 fn document_end_marker_rejects_trailing_content() {
6387 assert_eq!(
6388 first_scanner_error_kind("... trailing\n"),
6389 ErrorKind::InvalidDocumentEnd
6390 );
6391 }
6392
6393 #[test]
6394 fn reserved_indicators_are_rejected_outside_directives() {
6395 let error = first_scanner_error(" @\n");
6396
6397 assert_eq!(
6398 error.kind(),
6399 &ErrorKind::UnexpectedCharacter { character: '@' }
6400 );
6401 }
6402
6403 #[test]
6404 fn flow_block_entry_indicator_is_rejected() {
6405 assert_eq!(
6406 first_scanner_error_kind("[- ]\n"),
6407 ErrorKind::BlockEntryInFlowCollection
6408 );
6409 }
6410
6411 #[test]
6412 fn block_entry_after_tabbed_separator_reports_specific_error() {
6413 assert_eq!(
6414 first_scanner_error_kind("-\t- value\n"),
6415 ErrorKind::InvalidBlockEntryWhitespace
6416 );
6417 }
6418
6419 #[test]
6420 fn document_indicator_reports_unclosed_flow_collection() {
6421 let error = first_scanner_error("[\n---\n");
6422
6423 assert_eq!(
6424 error.kind(),
6425 &ErrorKind::UnclosedFlowCollection { open: '[' }
6426 );
6427 }
6428
6429 #[test]
6430 fn block_scalar_header_rejects_trailing_content() {
6431 assert_eq!(
6432 first_scanner_error_kind("|+ trailing\n"),
6433 ErrorKind::InvalidBlockScalarHeader
6434 );
6435 }
6436
6437 #[test]
6438 fn block_scalar_rejects_zero_indent_indicator() {
6439 assert_eq!(
6440 first_scanner_error_kind("|0\n"),
6441 ErrorKind::ZeroBlockScalarIndent
6442 );
6443 assert_eq!(
6444 first_scanner_error_kind("|+0\n"),
6445 ErrorKind::ZeroBlockScalarIndent
6446 );
6447 }
6448
6449 #[test]
6450 fn empty_block_scalar_at_eof_honors_chomping() {
6451 assert_eq!(first_scalar_value("|\n"), "");
6452 assert_eq!(first_scalar_value("|-\n"), "");
6453 assert_eq!(first_scalar_value("|+\n"), "");
6454 assert_eq!(first_scalar_value("|+\n\n"), "\n");
6455 assert_eq!(first_scalar_value("|+\n "), "\n");
6456 }
6457
6458 #[test]
6459 fn buffered_block_scalar_reads_content_past_lookahead_window() {
6460 assert_eq!(
6461 first_buffered_scalar_value("|\n abcdefghijklmnopqrstuvwxyz\n"),
6462 "abcdefghijklmnopqrstuvwxyz\n"
6463 );
6464 }
6465
6466 #[test]
6467 fn explicit_indent_block_scalar_can_end_at_document_marker() {
6468 assert_eq!(first_scalar_value("|1\n...\n"), "");
6469 }
6470
6471 #[test]
6472 fn root_explicit_indent_block_scalar_rejects_underindented_content() {
6473 assert_eq!(
6474 first_scanner_error_kind("|2\nx\n"),
6475 ErrorKind::InvalidBlockScalarIndent
6476 );
6477 }
6478
6479 #[test]
6480 fn quoted_scalar_rejects_document_indicator_at_line_start() {
6481 assert_eq!(
6482 first_scanner_error_kind("\"one\n---\ntwo\"\n"),
6483 ErrorKind::DocumentIndicatorInQuotedScalar
6484 );
6485 }
6486
6487 #[test]
6488 fn strict_quoted_scalar_rejects_tab_indentation_after_line_break() {
6489 let error = Scanner::with_options(
6490 StrInput::new("a: \"one\n\tbad\"\n"),
6491 crate::options! { strict_indentation: true },
6492 )
6493 .find_map(Result::err)
6494 .expect("strict mode must reject a tab indenting a quoted continuation");
6495 assert_eq!(error.kind(), &ErrorKind::TabInIndentation);
6496 }
6497
6498 #[test]
6499 fn strict_quoted_scalar_rejects_underindented_continuation() {
6500 for input in ["a: \"one\nbad\"\n", "a:\n b: 'one\n bad'\n"] {
6501 let error = Scanner::with_options(
6502 StrInput::new(input),
6503 crate::options! { strict_indentation: true },
6504 )
6505 .find_map(Result::err)
6506 .expect("strict mode must reject underindented quoted continuations");
6507 assert_eq!(error.kind(), &ErrorKind::InvalidQuotedScalarIndent);
6508 }
6509 }
6510
6511 #[test]
6512 fn quoted_scalar_continuation_one_column_past_block_indent() {
6513 for input in [
6516 "a: \"one\n two\"\n",
6517 "a: 'one\n two'\n",
6518 "a:\n b: \"one\n two\"\n",
6519 "- a: \"one\n two\"\n",
6520 "? k\n: \"one\n two\"\n",
6521 ] {
6522 let mut scanner = Scanner::new(StrInput::new(input));
6523 loop {
6524 match scanner.next_token() {
6525 Ok(Some(_)) => {}
6526 Ok(None) => break,
6527 Err(error) => panic!("{input:?}: {error}"),
6528 }
6529 }
6530 }
6531 }
6532
6533 #[test]
6534 fn quoted_scalar_trailing_content_error_names_quote_style() {
6535 assert_eq!(
6536 first_scanner_error_kind("'foo' trailing\n"),
6537 ErrorKind::InvalidTrailingSingleQuotedScalar
6538 );
6539 assert_eq!(
6540 first_scanner_error_kind("\"foo\" trailing\n"),
6541 ErrorKind::InvalidTrailingDoubleQuotedScalar
6542 );
6543 }
6544
6545 #[test]
6546 fn quoted_scalar_escape_errors_cover_hex_and_surrogate_edges() {
6547 assert_eq!(
6548 first_scanner_error_kind("\"\\xG0\"\n"),
6549 ErrorKind::InvalidQuotedScalarHexEscape
6550 );
6551 assert_eq!(
6552 first_scanner_error_kind("\"\\uD800\\uGGGG\"\n"),
6553 ErrorKind::InvalidLowSurrogateHexEscape
6554 );
6555 assert_eq!(
6556 first_scanner_error_kind("\"\\uD800\\u0041\"\n"),
6557 ErrorKind::InvalidLowSurrogate
6558 );
6559 assert_eq!(
6560 first_scanner_error_kind("\"\\U00110000\"\n"),
6561 ErrorKind::InvalidUnicodeEscape
6562 );
6563 }
6564
6565 #[test]
6566 fn under_indented_flow_scalar_is_accepted() {
6567 let tokens: Vec<_> = Scanner::new(StrInput::new("a:\n [\nfoo]\n"))
6568 .map(|result| result.expect("under-indented flow entry should scan").1)
6569 .collect();
6570 assert_eq!(
6571 tokens,
6572 [
6573 TokenType::StreamStart,
6574 TokenType::BlockMappingStart,
6575 TokenType::Key,
6576 TokenType::Scalar(ScalarStyle::Plain, "a".into()),
6577 TokenType::Value,
6578 TokenType::FlowSequenceStart,
6579 TokenType::Scalar(ScalarStyle::Plain, "foo".into()),
6580 TokenType::FlowSequenceEnd,
6581 TokenType::BlockEnd,
6582 TokenType::StreamEnd,
6583 ]
6584 );
6585 }
6586
6587 #[test]
6588 fn required_simple_key_requires_value_at_stream_end() {
6589 let error = first_scanner_error("a:\n&b\n- c\n");
6590
6591 assert_eq!(error.kind(), &ErrorKind::SimpleKeyExpected);
6592 assert_eq!(error.marker().index(), 3);
6593 assert_eq!(error.marker().line(), 2);
6594 assert_eq!(error.marker().col(), 0);
6595 }
6596
6597 #[test]
6598 fn first_simple_key_tracks_ordered_possible_candidates() {
6599 let deep = alloc::format!(
6600 "{}{}{{[é, z]: v}}{}\n",
6601 "[".repeat(240),
6602 "a, ".repeat(400),
6603 "]".repeat(240)
6604 );
6605 for source in [
6606 "",
6607 "a: b\nmissing",
6608 "a: b\nmissing\n# after\nnext: value\n",
6609 "{[a, {b: c}]: [d, e], []: f}\n",
6610 "[&a !tag [x, y], *a, {z: []}]\n",
6611 "key: {\n&anchor\nname: value}\n",
6612 "---\n{[a, b]: c} # end\n...\n# next\n---\nx: y\n",
6613 "a: b\n[unterminated",
6614 &deep,
6615 ] {
6616 for limit in [0, 4, 1024, usize::MAX] {
6617 #[cfg(feature = "comments")]
6618 let emission_modes = [false, true].as_slice();
6619 #[cfg(not(feature = "comments"))]
6620 let emission_modes = [false].as_slice();
6621 for &emit_comments in emission_modes {
6622 let options = crate::options! { simple_key_max_lookahead: limit };
6623 #[cfg(feature = "comments")]
6624 let options = {
6625 let mut options = options;
6626 options.emit_comments = emit_comments;
6627 options
6628 };
6629 let mut scanner = Scanner::with_options(StrInput::new(source), options);
6630 loop {
6631 let result = scanner.next();
6632 assert_eq!(
6633 scanner.first_simple_key,
6634 scanner.simple_keys.iter().position(|key| key.possible),
6635 "source: {source:?}, limit: {limit}, comments: {emit_comments}"
6636 );
6637 let mut previous = None;
6638 for key in scanner.simple_keys.iter().filter(|key| key.possible) {
6639 assert!(key.token_number >= scanner.tokens_parsed);
6640 if let Some((index, token_number)) = previous {
6641 assert!(key.mark.index() >= index);
6642 assert!(key.token_number >= token_number);
6643 }
6644 previous = Some((key.mark.index(), key.token_number));
6645 }
6646 if result.is_none() {
6647 break;
6648 }
6649 }
6650 }
6651 }
6652 }
6653 }
6654
6655 #[test]
6656 fn plain_scalar_rejects_dash_before_flow_indicator() {
6657 assert_eq!(
6658 first_scanner_error_kind("[-]\n"),
6659 ErrorKind::PlainScalarStartsWithDashFlowIndicator
6660 );
6661 }
6662
6663 #[test]
6664 fn explicit_key_rejects_tab_used_as_indentation() {
6665 assert_eq!(
6666 first_scanner_error_kind("?\n\tfoo\n"),
6667 ErrorKind::TabNotAllowed
6668 );
6669 }
6670
6671 #[test]
6672 fn flow_mapping_rejects_adjacent_collection_value_after_plain_key() {
6673 assert_eq!(
6674 first_scanner_error_kind("[a:[]]\n"),
6675 ErrorKind::FlowMappingValueAdjacentCollection
6676 );
6677 }
6678
6679 #[test]
6680 fn implicit_flow_mapping_colon_cannot_move_to_next_line() {
6681 assert_eq!(
6682 first_scanner_error_kind("[foo\n: bar]\n"),
6683 ErrorKind::InvalidColonPlacement
6684 );
6685 }
6686
6687 #[test]
6688 fn invalid_simple_key_token_positions_are_scan_errors() {
6689 for (tokens_parsed, token_number) in [(1, 0), (0, 1)] {
6690 let mut scanner = Scanner::new(StrInput::new(": value\n"));
6691 scanner.fetch_stream_start();
6692 scanner.tokens.clear();
6693 scanner.tokens_parsed = tokens_parsed;
6694
6695 let simple_key = scanner
6696 .simple_keys
6697 .last_mut()
6698 .expect("stream start should create a simple key slot");
6699 simple_key.possible = true;
6700 simple_key.token_number = token_number;
6701
6702 let error = scanner
6703 .fetch_value()
6704 .expect_err("invalid simple key position should be reported as a scan error");
6705 assert_eq!(error.kind(), &ErrorKind::InvalidSimpleKey);
6706 assert_eq!(error.marker(), &Marker::new(0, 1, 0));
6707 }
6708 }
6709
6710 #[test]
6711 fn issue14_alias_scanner_consumes_colon_as_name_character() {
6712 let mut scanner = Scanner::new(StrInput::new("*foo: bar\n"));
6713
6714 assert!(matches!(
6715 scanner.next_token().unwrap().unwrap().1,
6716 TokenType::StreamStart
6717 ));
6718
6719 let token = scanner.next_token().unwrap().unwrap();
6720
6721 assert!(
6722 matches!(token.1, TokenType::Alias(ref name) if name.as_ref() == "foo:"),
6723 "expected `*foo: bar` to start with Alias(\"foo:\"), got {token:?}"
6724 );
6725 }
6726
6727 #[test]
6728 fn issue14_anchor_scanner_consumes_colon_as_name_character() {
6729 let mut scanner = Scanner::new(StrInput::new("&foo: bar\n"));
6730
6731 assert!(matches!(
6732 scanner.next_token().unwrap().unwrap().1,
6733 TokenType::StreamStart
6734 ));
6735
6736 let token = scanner.next_token().unwrap().unwrap();
6737
6738 assert!(
6739 matches!(token.1, TokenType::Anchor(ref name) if name.as_ref() == "foo:"),
6740 "expected `&foo: bar` to start with Anchor(\"foo:\"), got {token:?}"
6741 );
6742 }
6743}