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#[cfg(feature = "extended_details")]
32use crate::scalar_style::BlockScalarSyntax;
33use crate::scalar_style::Chomping;
34pub use crate::scalar_style::ScalarStyle;
35
36#[derive(Clone, Copy, Debug, Default)]
43struct MarkerOffsets {
44 chars: usize,
46 bytes: Option<usize>,
48}
49
50impl PartialEq for MarkerOffsets {
51 fn eq(&self, other: &Self) -> bool {
52 self.chars == other.chars
56 }
57}
58
59impl Eq for MarkerOffsets {}
60
61#[derive(Clone, Copy, PartialEq, Debug, Eq, Default)]
63pub struct Marker {
64 offsets: MarkerOffsets,
66 line: usize,
68 col: usize,
70}
71
72impl Marker {
73 #[must_use]
75 pub fn new(index: usize, line: usize, col: usize) -> Marker {
76 Marker {
77 offsets: MarkerOffsets {
78 chars: index,
79 bytes: None,
80 },
81 line,
82 col,
83 }
84 }
85
86 #[must_use]
88 pub fn with_byte_offset(mut self, byte_offset: Option<usize>) -> Marker {
89 self.offsets.bytes = byte_offset;
90 self
91 }
92
93 #[must_use]
95 pub fn index(&self) -> usize {
96 self.offsets.chars
97 }
98
99 #[must_use]
101 pub fn byte_offset(&self) -> Option<usize> {
102 self.offsets.bytes
103 }
104
105 #[must_use]
107 pub fn line(&self) -> usize {
108 self.line
109 }
110
111 #[must_use]
113 pub fn col(&self) -> usize {
114 self.col
115 }
116}
117
118#[non_exhaustive]
154#[derive(Clone, Copy, PartialEq, Debug, Eq, Default)]
155pub struct Span {
156 pub start: Marker,
158 pub end: Marker,
160
161 pub indent: Option<usize>,
166
167 pub tag_start: Option<Marker>,
176
177 tag_length: u32,
180}
181
182impl Span {
183 #[must_use]
185 pub fn new(start: Marker, end: Marker) -> Span {
186 Span {
187 start,
188 end,
189 indent: None,
190 tag_start: None,
191 tag_length: 0,
192 }
193 }
194
195 #[must_use]
202 pub fn empty(mark: Marker) -> Span {
203 Span {
204 start: mark,
205 end: mark,
206 indent: None,
207 tag_start: None,
208 tag_length: 0,
209 }
210 }
211
212 #[must_use]
214 pub fn with_indent(mut self, indent: Option<usize>) -> Span {
215 self.indent = indent;
216 self
217 }
218
219 #[deprecated(
225 since = "2.1.0",
226 note = "Only sets a tag start (.tag_span() then returns None). Use with_tag_span."
227 )]
228 #[must_use]
229 pub fn with_tag_start(mut self, tag_start: Option<Marker>) -> Span {
230 self.tag_start = tag_start;
231 self.tag_length = 0;
232 self
233 }
234
235 #[must_use]
237 pub fn with_tag_span(mut self, tag_span: Option<(Marker, u32)>) -> Span {
238 let (start, length) = tag_span.map_or((None, 0), |(start, length)| (Some(start), length));
239 self.tag_start = start;
240 self.tag_length = length;
241 self
242 }
243
244 #[must_use]
250 pub fn tag_start(&self) -> Option<Marker> {
251 self.tag_start
252 }
253
254 #[must_use]
276 pub fn tag_span(&self) -> Option<Span> {
277 let start = self.tag_start?;
278 if self.tag_length == 0 {
279 return None;
280 }
281 let length = usize::try_from(self.tag_length).ok()?;
282 let end = Marker::new(
285 start.index().checked_add(length)?,
286 start.line(),
287 start.col().checked_add(length)?,
288 )
289 .with_byte_offset(match start.byte_offset() {
290 Some(byte_offset) => Some(byte_offset.checked_add(length)?),
291 None => None,
292 });
293 Some(Span::new(start, end))
294 }
295
296 #[track_caller]
301 #[must_use]
302 pub fn len(&self) -> usize {
303 self.end.index() - self.start.index()
304 }
305
306 #[track_caller]
311 #[must_use]
312 pub fn is_empty(&self) -> bool {
313 self.len() == 0
314 }
315
316 #[must_use]
327 pub fn byte_range(&self) -> Option<core::ops::Range<usize>> {
328 Some(self.start.byte_offset()?..self.end.byte_offset()?)
329 }
330
331 #[must_use]
338 pub fn slice<'source>(&self, source: &'source str) -> Option<&'source str> {
339 source.get(self.byte_range()?)
340 }
341}
342
343#[non_exhaustive]
358#[derive(Clone, Copy, Default, PartialEq, Debug, Eq)]
359#[cfg(feature = "comments")]
360pub enum Placement {
361 Above,
367 Right,
370 #[default]
376 Free,
377 Last,
382}
383
384#[derive(Clone, PartialEq, Debug, Eq)]
389#[cfg(feature = "comments")]
390pub struct Comment<'input> {
391 text: Cow<'input, str>,
395 placement: Placement,
397}
398
399#[cfg(feature = "comments")]
400impl<'input> Comment<'input> {
401 #[must_use]
406 pub fn new(text: impl Into<Cow<'input, str>>) -> Self {
407 Self {
408 text: text.into(),
409 placement: Placement::Free,
410 }
411 }
412
413 #[must_use]
415 pub fn with_placement(mut self, placement: Placement) -> Self {
416 self.placement = placement;
417 self
418 }
419
420 #[must_use]
422 pub fn text(&self) -> &str {
423 self.text.as_ref()
424 }
425
426 #[must_use]
428 pub const fn placement(&self) -> Placement {
429 self.placement
430 }
431
432 #[must_use]
434 pub fn into_text(self) -> Cow<'input, str> {
435 self.text
436 }
437
438 #[must_use]
442 pub fn trimmed_text(&self) -> &str {
443 self.text.trim()
444 }
445}
446
447#[cfg(feature = "comments")]
448impl AsRef<str> for Comment<'_> {
449 fn as_ref(&self) -> &str {
450 self.text.as_ref()
451 }
452}
453
454#[cfg_attr(
473 not(feature = "test_equality"),
474 doc = r"
475```compile_fail,E0369
476use granit_parser::TokenType;
477fn equal_tokens(left: TokenType<'_>, right: TokenType<'_>) -> bool {
478 left == right
479}
480```
481"
482)]
483#[non_exhaustive]
490#[derive(Clone, Debug)]
491#[cfg_attr(feature = "test_equality", derive(PartialEq, Eq))]
492pub enum TokenType<'input> {
493 #[non_exhaustive]
495 StreamStart,
496 #[non_exhaustive]
498 StreamEnd,
499 #[non_exhaustive]
501 VersionDirective {
502 major: u32,
504 minor: u32,
506 },
507 #[non_exhaustive]
509 TagDirective {
510 handle: Cow<'input, str>,
512 prefix: Cow<'input, str>,
514 },
515 #[non_exhaustive]
517 DocumentStart,
518 #[non_exhaustive]
520 DocumentEnd,
521 #[non_exhaustive]
523 BlockSequenceStart,
524 #[non_exhaustive]
526 BlockMappingStart,
527 #[non_exhaustive]
529 BlockEnd,
530 #[non_exhaustive]
532 FlowSequenceStart,
533 #[non_exhaustive]
535 FlowSequenceEnd,
536 #[non_exhaustive]
538 FlowMappingStart,
539 #[non_exhaustive]
541 FlowMappingEnd,
542 #[non_exhaustive]
544 BlockEntry,
545 #[non_exhaustive]
547 FlowEntry,
548 #[non_exhaustive]
550 Key,
551 #[non_exhaustive]
553 Value,
554 #[non_exhaustive]
556 Alias {
557 name: Cow<'input, str>,
559 },
560 #[non_exhaustive]
562 Anchor {
563 name: Cow<'input, str>,
565 },
566 #[non_exhaustive]
568 Tag {
569 handle: Cow<'input, str>,
571 suffix: Cow<'input, str>,
573 },
574 #[non_exhaustive]
576 Scalar {
577 style: ScalarStyle,
579 value: Cow<'input, str>,
581 },
582 #[cfg(feature = "comments")]
584 #[non_exhaustive]
585 Comment {
586 comment: Comment<'input>,
588 },
589 #[non_exhaustive]
591 ReservedDirective {
592 name: String,
594 parameters: Vec<String>,
596 },
597}
598
599impl<'input> TokenType<'input> {
600 #[must_use]
602 pub const fn stream_start() -> Self {
603 Self::StreamStart
604 }
605
606 #[must_use]
608 pub const fn stream_end() -> Self {
609 Self::StreamEnd
610 }
611
612 #[must_use]
614 pub const fn document_start() -> Self {
615 Self::DocumentStart
616 }
617
618 #[must_use]
620 pub const fn document_end() -> Self {
621 Self::DocumentEnd
622 }
623
624 #[must_use]
626 pub const fn block_sequence_start() -> Self {
627 Self::BlockSequenceStart
628 }
629
630 #[must_use]
632 pub const fn block_mapping_start() -> Self {
633 Self::BlockMappingStart
634 }
635
636 #[must_use]
638 pub const fn block_end() -> Self {
639 Self::BlockEnd
640 }
641
642 #[must_use]
644 pub const fn flow_sequence_start() -> Self {
645 Self::FlowSequenceStart
646 }
647
648 #[must_use]
650 pub const fn flow_sequence_end() -> Self {
651 Self::FlowSequenceEnd
652 }
653
654 #[must_use]
656 pub const fn flow_mapping_start() -> Self {
657 Self::FlowMappingStart
658 }
659
660 #[must_use]
662 pub const fn flow_mapping_end() -> Self {
663 Self::FlowMappingEnd
664 }
665
666 #[must_use]
668 pub const fn block_entry() -> Self {
669 Self::BlockEntry
670 }
671
672 #[must_use]
674 pub const fn flow_entry() -> Self {
675 Self::FlowEntry
676 }
677
678 #[must_use]
680 pub const fn key() -> Self {
681 Self::Key
682 }
683
684 #[must_use]
686 pub const fn value() -> Self {
687 Self::Value
688 }
689
690 #[must_use]
695 pub fn version_directive(major: u32, minor: u32) -> Self {
696 Self::VersionDirective { major, minor }
697 }
698
699 #[must_use]
704 pub fn tag_directive(handle: Cow<'input, str>, prefix: Cow<'input, str>) -> Self {
705 Self::TagDirective { handle, prefix }
706 }
707
708 #[must_use]
712 pub fn alias(name: Cow<'input, str>) -> Self {
713 Self::Alias { name }
714 }
715
716 #[must_use]
720 pub fn anchor(name: Cow<'input, str>) -> Self {
721 Self::Anchor { name }
722 }
723
724 #[must_use]
729 pub fn tag(handle: Cow<'input, str>, suffix: Cow<'input, str>) -> Self {
730 Self::Tag { handle, suffix }
731 }
732
733 #[must_use]
738 pub fn scalar(style: ScalarStyle, value: Cow<'input, str>) -> Self {
739 Self::Scalar { style, value }
740 }
741
742 #[cfg(feature = "comments")]
746 #[must_use]
747 pub fn comment(comment: Comment<'input>) -> Self {
748 Self::Comment { comment }
749 }
750
751 #[must_use]
756 pub fn reserved_directive(name: String, parameters: Vec<String>) -> Self {
757 Self::ReservedDirective { name, parameters }
758 }
759}
760
761#[derive(Clone, Debug)]
767#[cfg_attr(feature = "test_equality", derive(PartialEq, Eq))]
768pub struct Token<'input>(Span, TokenType<'input>);
769
770impl<'input> Token<'input> {
771 #[must_use]
773 pub const fn new(span: Span, token_type: TokenType<'input>) -> Self {
774 Self(span, token_type)
775 }
776
777 #[must_use]
779 pub const fn span(&self) -> Span {
780 self.0
781 }
782
783 #[must_use]
785 pub const fn token_type(&self) -> &TokenType<'input> {
786 &self.1
787 }
788
789 #[must_use]
791 pub fn into_parts(self) -> (Span, TokenType<'input>) {
792 (self.0, self.1)
793 }
794}
795
796#[derive(Clone, Debug)]
800#[cfg_attr(feature = "test_equality", derive(PartialEq, Eq))]
801pub(crate) enum QueuedTokenType<'input> {
802 StreamStart,
803 StreamEnd,
804 VersionDirective(u32, u32),
805 TagDirective(Cow<'input, str>, Cow<'input, str>),
806 DocumentStart,
807 DocumentEnd,
808 BlockSequenceStart,
809 BlockMappingStart,
810 BlockEnd,
811 FlowSequenceStart,
812 FlowSequenceEnd,
813 FlowMappingStart,
814 FlowMappingEnd,
815 BlockEntry,
816 FlowEntry,
817 Key,
818 Value,
819 Alias(Cow<'input, str>),
820 Anchor(Cow<'input, str>),
821 Tag(Cow<'input, str>, Cow<'input, str>),
822 Scalar(ScalarStyle, Cow<'input, str>),
823 #[cfg(feature = "comments")]
824 Comment(Comment<'input>),
825 ReservedDirective(String, Vec<String>),
826}
827
828impl<'input> QueuedTokenType<'input> {
829 fn into_public(self) -> TokenType<'input> {
830 match self {
831 Self::StreamStart => TokenType::StreamStart,
832 Self::StreamEnd => TokenType::StreamEnd,
833 Self::VersionDirective(major, minor) => TokenType::VersionDirective { major, minor },
834 Self::TagDirective(handle, prefix) => TokenType::TagDirective { handle, prefix },
835 Self::DocumentStart => TokenType::DocumentStart,
836 Self::DocumentEnd => TokenType::DocumentEnd,
837 Self::BlockSequenceStart => TokenType::BlockSequenceStart,
838 Self::BlockMappingStart => TokenType::BlockMappingStart,
839 Self::BlockEnd => TokenType::BlockEnd,
840 Self::FlowSequenceStart => TokenType::FlowSequenceStart,
841 Self::FlowSequenceEnd => TokenType::FlowSequenceEnd,
842 Self::FlowMappingStart => TokenType::FlowMappingStart,
843 Self::FlowMappingEnd => TokenType::FlowMappingEnd,
844 Self::BlockEntry => TokenType::BlockEntry,
845 Self::FlowEntry => TokenType::FlowEntry,
846 Self::Key => TokenType::Key,
847 Self::Value => TokenType::Value,
848 Self::Alias(name) => TokenType::Alias { name },
849 Self::Anchor(name) => TokenType::Anchor { name },
850 Self::Tag(handle, suffix) => TokenType::Tag { handle, suffix },
851 Self::Scalar(style, value) => TokenType::Scalar { style, value },
852 #[cfg(feature = "comments")]
853 Self::Comment(comment) => TokenType::Comment { comment },
854 Self::ReservedDirective(name, params) => TokenType::ReservedDirective {
855 name,
856 parameters: params,
857 },
858 }
859 }
860}
861
862impl<'input> From<TokenType<'input>> for QueuedTokenType<'input> {
863 fn from(token: TokenType<'input>) -> Self {
864 match token {
865 TokenType::StreamStart => Self::StreamStart,
866 TokenType::StreamEnd => Self::StreamEnd,
867 TokenType::VersionDirective { major, minor } => Self::VersionDirective(major, minor),
868 TokenType::TagDirective { handle, prefix } => Self::TagDirective(handle, prefix),
869 TokenType::DocumentStart => Self::DocumentStart,
870 TokenType::DocumentEnd => Self::DocumentEnd,
871 TokenType::BlockSequenceStart => Self::BlockSequenceStart,
872 TokenType::BlockMappingStart => Self::BlockMappingStart,
873 TokenType::BlockEnd => Self::BlockEnd,
874 TokenType::FlowSequenceStart => Self::FlowSequenceStart,
875 TokenType::FlowSequenceEnd => Self::FlowSequenceEnd,
876 TokenType::FlowMappingStart => Self::FlowMappingStart,
877 TokenType::FlowMappingEnd => Self::FlowMappingEnd,
878 TokenType::BlockEntry => Self::BlockEntry,
879 TokenType::FlowEntry => Self::FlowEntry,
880 TokenType::Key => Self::Key,
881 TokenType::Value => Self::Value,
882 TokenType::Alias { name } => Self::Alias(name),
883 TokenType::Anchor { name } => Self::Anchor(name),
884 TokenType::Tag { handle, suffix } => Self::Tag(handle, suffix),
885 TokenType::Scalar { style, value } => Self::Scalar(style, value),
886 #[cfg(feature = "comments")]
887 TokenType::Comment { comment } => Self::Comment(comment),
888 TokenType::ReservedDirective {
889 name,
890 parameters: params,
891 } => Self::ReservedDirective(name, params),
892 }
893 }
894}
895
896#[derive(Clone, Debug)]
898#[cfg_attr(feature = "test_equality", derive(PartialEq, Eq))]
899pub(crate) struct QueuedToken<'input>(pub(crate) Span, pub(crate) QueuedTokenType<'input>);
900
901impl<'input> QueuedToken<'input> {
902 fn into_public(self) -> Token<'input> {
903 Token(self.0, self.1.into_public())
904 }
905}
906
907impl<'input> From<Token<'input>> for QueuedToken<'input> {
908 fn from(token: Token<'input>) -> Self {
909 Self(token.0, token.1.into())
910 }
911}
912
913#[derive(Clone, Copy, PartialEq, Debug, Eq)]
948struct SimpleKey {
949 possible: bool,
962 required: bool,
971 token_number: usize,
977 mark: Marker,
979}
980
981impl SimpleKey {
982 fn new(mark: Marker) -> SimpleKey {
984 SimpleKey {
985 possible: false,
986 required: false,
987 token_number: 0,
988 mark,
989 }
990 }
991}
992
993#[derive(Clone, Debug, Default)]
995struct Indent {
996 indent: isize,
998 needs_block_end: bool,
1016}
1017
1018#[derive(Debug, PartialEq)]
1040enum ImplicitMappingState {
1041 Possible,
1046 Inside(usize),
1050}
1051
1052#[derive(Debug)]
1065#[allow(clippy::struct_excessive_bools)]
1066pub struct Scanner<'input, T> {
1067 input: T,
1071 options: Options,
1073 mark: Marker,
1075 tokens: VecDeque<QueuedToken<'input>>,
1082 failed: bool,
1084 source_error: Option<ScanError>,
1086 #[cfg(feature = "comments")]
1088 deferred_error: Option<ScanError>,
1089 #[cfg(feature = "comments")]
1095 comments_possible: bool,
1096
1097 stream_start_produced: bool,
1099 stream_end_produced: bool,
1101 document_prefix_allowed: bool,
1107 in_directive_prefix: bool,
1109 adjacent_value_allowed_at: usize,
1112 simple_key_allowed: bool,
1116 simple_keys: smallvec::SmallVec<[SimpleKey; 8]>,
1121 first_simple_key: Option<usize>,
1127 indent: isize,
1129 indents: smallvec::SmallVec<[Indent; 8]>,
1131 flow_level: usize,
1133 block_level: usize,
1135 tokens_parsed: usize,
1139 token_available: bool,
1141 leading_whitespace: bool,
1143 flow_mapping_started: smallvec::SmallVec<[bool; 8]>,
1150 implicit_flow_mapping_states: smallvec::SmallVec<[ImplicitMappingState; 8]>,
1163 interrupted_plain_by_comment: Option<Marker>,
1166 explicit_key_tab_check_pending: bool,
1172 flow_markers: smallvec::SmallVec<[(Marker, char); 8]>,
1174 buf_leading_break: String,
1175 buf_trailing_breaks: String,
1176 buf_whitespaces: String,
1177}
1178
1179impl<'input, T: BorrowedInput<'input>> Iterator for Scanner<'input, T> {
1180 type Item = Result<Token<'input>, ScanError>;
1181
1182 fn next(&mut self) -> Option<Self::Item> {
1183 if self.failed {
1184 return None;
1185 }
1186 match self.next_token() {
1187 Ok(Some(tok)) => {
1188 debug_print!(
1189 " \x1B[;32m\u{21B3} {:?} \x1B[;36m{:?}\x1B[;m",
1190 tok.1,
1191 tok.0
1192 );
1193 Some(Ok(tok))
1194 }
1195 Ok(None) => None,
1196 Err(error) => {
1197 self.failed = true;
1198 Some(Err(error))
1199 }
1200 }
1201 }
1202}
1203
1204impl<'input, T: BorrowedInput<'input>> core::iter::FusedIterator for Scanner<'input, T> {}
1205
1206type ScanResult = Result<(), ScanError>;
1208
1209#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
1214struct SkipToNextTokenOutcome {
1215 saw_comment: bool,
1216 #[cfg(feature = "comments")]
1217 queued_comment: bool,
1218}
1219
1220#[derive(Debug)]
1221enum FlowScalarBuf {
1222 Borrowed {
1228 start: usize,
1229 end: usize,
1230 pending_ws_start: Option<usize>,
1231 pending_ws_end: usize,
1232 },
1233 Owned(String),
1234}
1235
1236impl FlowScalarBuf {
1237 #[inline]
1238 fn new_borrowed(start: usize) -> Self {
1239 Self::Borrowed {
1240 start,
1241 end: start,
1242 pending_ws_start: None,
1243 pending_ws_end: start,
1244 }
1245 }
1246
1247 #[inline]
1248 fn new_owned() -> Self {
1249 Self::Owned(String::new())
1250 }
1251
1252 #[inline]
1253 fn as_owned_mut(&mut self) -> Option<&mut String> {
1254 match self {
1255 Self::Owned(s) => Some(s),
1256 Self::Borrowed { .. } => None,
1257 }
1258 }
1259
1260 #[inline]
1261 fn commit_pending_ws(&mut self) {
1262 if let Self::Borrowed {
1263 end,
1264 pending_ws_start,
1265 pending_ws_end,
1266 ..
1267 } = self
1268 {
1269 if pending_ws_start.is_some() {
1270 *end = *pending_ws_end;
1271 *pending_ws_start = None;
1272 }
1273 }
1274 }
1275
1276 #[inline]
1277 fn note_pending_ws(&mut self, ws_start: usize, ws_end: usize) {
1278 if let Self::Borrowed {
1279 pending_ws_start,
1280 pending_ws_end,
1281 ..
1282 } = self
1283 {
1284 if pending_ws_start.is_none() {
1285 *pending_ws_start = Some(ws_start);
1286 }
1287 *pending_ws_end = ws_end;
1288 }
1289 }
1290
1291 #[inline]
1292 fn discard_pending_ws(&mut self) {
1293 if let Self::Borrowed {
1294 pending_ws_start,
1295 pending_ws_end,
1296 end,
1297 ..
1298 } = self
1299 {
1300 *pending_ws_start = None;
1301 *pending_ws_end = *end;
1302 }
1303 }
1304}
1305
1306impl<'input, T: BorrowedInput<'input>> Scanner<'input, T> {
1307 #[inline]
1308 fn promote_flow_scalar_buf_to_owned(
1309 &self,
1310 start_mark: &Marker,
1311 buf: &mut FlowScalarBuf,
1312 ) -> Result<(), ScanError> {
1313 let FlowScalarBuf::Borrowed {
1314 start,
1315 end,
1316 pending_ws_start: _,
1317 pending_ws_end: _,
1318 } = *buf
1319 else {
1320 return Ok(());
1321 };
1322
1323 let slice = self.input.slice_bytes(start, end).ok_or_else(|| {
1324 ScanError::from_kind(*start_mark, ErrorKind::InputOffsetsWithoutSlice)
1325 })?;
1326 *buf = FlowScalarBuf::Owned(slice.to_owned());
1327 Ok(())
1328 }
1329 #[inline]
1335 fn try_borrow_slice(&self, start: usize, end: usize) -> Option<&'input str> {
1336 self.input.slice_borrowed(start, end)
1337 }
1338
1339 fn scan_tag_handle_directive_cow(
1344 &mut self,
1345 mark: &Marker,
1346 budget: &mut usize,
1347 ) -> Result<Cow<'input, str>, ScanError> {
1348 let Some(start) = self.input.byte_offset() else {
1349 return Ok(Cow::Owned(
1350 self.scan_tag_handle_directive_owned(mark, budget)?,
1351 ));
1352 };
1353
1354 if self.input.look_ch() != '!' {
1355 return Err(ScanError::from_kind(*mark, ErrorKind::ExpectedTagBang));
1356 }
1357
1358 self.spend_directive_bytes(budget, 1, *mark)?;
1360 self.skip_non_blank();
1361
1362 self.input.lookahead(1);
1365 while self.input.next_is_alpha() {
1366 self.spend_directive_bytes(budget, 1, *mark)?;
1367 self.skip_non_blank();
1368 self.input.lookahead(1);
1369 }
1370
1371 if self.input.peek() == '!' {
1373 self.spend_directive_bytes(budget, 1, *mark)?;
1374 self.skip_non_blank();
1375 }
1376
1377 let Some(end) = self.input.byte_offset() else {
1378 return Err(ScanError::from_kind(
1379 *mark,
1380 ErrorKind::InputSlicingUnavailable,
1381 ));
1382 };
1383
1384 let Some(slice) = self.try_borrow_slice(start, end) else {
1385 let slice = self
1387 .input
1388 .slice_bytes(start, end)
1389 .ok_or_else(|| ScanError::from_kind(*mark, ErrorKind::InputSlicingUnavailable))?;
1390 if !slice.ends_with('!') && slice != "!" {
1391 return Err(ScanError::from_kind(
1392 *mark,
1393 ErrorKind::ExpectedTagDirectiveBang,
1394 ));
1395 }
1396 return Ok(Cow::Owned(slice.to_owned()));
1397 };
1398
1399 if !slice.ends_with('!') && slice != "!" {
1400 return Err(ScanError::from_kind(
1401 *mark,
1402 ErrorKind::ExpectedTagDirectiveBang,
1403 ));
1404 }
1405
1406 Ok(Cow::Borrowed(slice))
1407 }
1408
1409 fn scan_tag_handle_directive_owned(
1411 &mut self,
1412 mark: &Marker,
1413 budget: &mut usize,
1414 ) -> Result<String, ScanError> {
1415 let mut string = String::new();
1416 if self.input.look_ch() != '!' {
1417 return Err(ScanError::from_kind(*mark, ErrorKind::ExpectedTagBang));
1418 }
1419
1420 self.spend_directive_bytes(budget, 1, *mark)?;
1421 string.push('!');
1422 self.skip_non_blank();
1423
1424 self.input.lookahead(1);
1425 while self.input.next_is_alpha() {
1426 self.spend_directive_bytes(budget, 1, *mark)?;
1427 string.push(self.input.peek());
1428 self.skip_non_blank();
1429 self.input.lookahead(1);
1430 }
1431
1432 if self.input.peek() == '!' {
1433 self.spend_directive_bytes(budget, 1, *mark)?;
1434 string.push('!');
1435 self.skip_non_blank();
1436 } else if string != "!" {
1437 return Err(ScanError::from_kind(
1438 *mark,
1439 ErrorKind::ExpectedTagDirectiveBang,
1440 ));
1441 }
1442
1443 Ok(string)
1444 }
1445
1446 fn scan_tag_prefix_directive_cow(
1451 &mut self,
1452 start_mark: &Marker,
1453 budget: &mut usize,
1454 ) -> Result<Cow<'input, str>, ScanError> {
1455 let Some(start) = self.input.byte_offset() else {
1456 return Ok(Cow::Owned(
1457 self.scan_tag_prefix_directive_owned(start_mark, budget)?,
1458 ));
1459 };
1460
1461 if self.input.look_ch() == '!' {
1463 self.spend_directive_bytes(budget, 1, *start_mark)?;
1464 self.skip_non_blank();
1465 } else if !is_tag_char(self.input.peek()) {
1466 return Err(ScanError::from_kind(
1467 *start_mark,
1468 ErrorKind::InvalidGlobalTagCharacter,
1469 ));
1470 } else if self.input.peek() == '%' {
1471 } else {
1473 self.spend_directive_bytes(budget, 1, *start_mark)?;
1474 self.skip_non_blank();
1475 }
1476
1477 while is_uri_char(self.input.look_ch()) {
1479 if self.input.peek() == '%' {
1480 break;
1481 }
1482 self.spend_directive_bytes(budget, 1, *start_mark)?;
1483 self.skip_non_blank();
1484 }
1485
1486 if self.input.peek() == '%' {
1488 let current = self
1489 .input
1490 .byte_offset()
1491 .expect("byte_offset() must remain available once enabled");
1492 let mut out = if let Some(slice) = self.input.slice_bytes(start, current) {
1493 slice.to_owned()
1494 } else {
1495 String::new()
1496 };
1497
1498 while is_uri_char(self.input.look_ch()) {
1499 if self.input.peek() == '%' {
1500 out.push(self.scan_uri_escapes_with_budget(start_mark, Some(budget))?);
1501 } else {
1502 self.spend_directive_bytes(budget, 1, *start_mark)?;
1503 out.push(self.input.peek());
1504 self.skip_non_blank();
1505 }
1506 }
1507 return Ok(Cow::Owned(out));
1508 }
1509
1510 let Some(end) = self.input.byte_offset() else {
1511 return Err(ScanError::from_kind(
1512 *start_mark,
1513 ErrorKind::InputSlicingUnavailable,
1514 ));
1515 };
1516
1517 let Some(slice) = self.try_borrow_slice(start, end) else {
1518 let slice = self.input.slice_bytes(start, end).ok_or_else(|| {
1520 ScanError::from_kind(*start_mark, ErrorKind::InputSlicingUnavailable)
1521 })?;
1522 return Ok(Cow::Owned(slice.to_owned()));
1523 };
1524
1525 Ok(Cow::Borrowed(slice))
1526 }
1527
1528 fn scan_tag_prefix_directive_owned(
1530 &mut self,
1531 start_mark: &Marker,
1532 budget: &mut usize,
1533 ) -> Result<String, ScanError> {
1534 let mut string = String::new();
1535
1536 if self.input.look_ch() == '!' {
1537 self.spend_directive_bytes(budget, 1, *start_mark)?;
1538 string.push('!');
1539 self.skip_non_blank();
1540 } else if !is_tag_char(self.input.peek()) {
1541 return Err(ScanError::from_kind(
1542 *start_mark,
1543 ErrorKind::InvalidGlobalTagCharacter,
1544 ));
1545 } else if self.input.peek() == '%' {
1546 string.push(self.scan_uri_escapes_with_budget(start_mark, Some(budget))?);
1547 } else {
1548 self.spend_directive_bytes(budget, 1, *start_mark)?;
1549 string.push(self.input.peek());
1550 self.skip_non_blank();
1551 }
1552
1553 while is_uri_char(self.input.look_ch()) {
1554 if self.input.peek() == '%' {
1555 string.push(self.scan_uri_escapes_with_budget(start_mark, Some(budget))?);
1556 } else {
1557 self.spend_directive_bytes(budget, 1, *start_mark)?;
1558 string.push(self.input.peek());
1559 self.skip_non_blank();
1560 }
1561 }
1562
1563 Ok(string)
1564 }
1565 #[must_use]
1567 pub fn new(input: T) -> Self {
1568 Self::with_options(input, Options::default())
1569 }
1570
1571 #[cfg_attr(
1573 feature = "comments",
1574 doc = "\n[`Options::emit_comments`] controls comment emission. \
1575 [`Options::max_buffered_comment_events`] has no effect when using a scanner \
1576 directly, because comment-event buffering is performed by [`crate::Parser`]."
1577 )]
1578 #[must_use]
1579 pub fn with_options(input: T, options: Options) -> Self {
1580 let initial_byte_offset = input.byte_offset();
1581 #[cfg(feature = "comments")]
1584 let comments_possible = !options.emit_comments || input.may_contain_comments();
1585 Scanner {
1586 input,
1587 options,
1588 mark: Marker::new(0, 1, 0).with_byte_offset(initial_byte_offset),
1589 tokens: VecDeque::with_capacity(64),
1590 failed: false,
1591 source_error: None,
1592 #[cfg(feature = "comments")]
1593 deferred_error: None,
1594 #[cfg(feature = "comments")]
1595 comments_possible,
1596
1597 stream_start_produced: false,
1598 stream_end_produced: false,
1599 document_prefix_allowed: true,
1600 in_directive_prefix: false,
1601 adjacent_value_allowed_at: 0,
1602 simple_key_allowed: true,
1603 simple_keys: smallvec::SmallVec::new(),
1604 first_simple_key: None,
1605 indent: -1,
1606 indents: smallvec::SmallVec::new(),
1607 flow_level: 0,
1608 block_level: 0,
1609 tokens_parsed: 0,
1610 token_available: false,
1611 leading_whitespace: true,
1612 flow_mapping_started: smallvec::SmallVec::new(),
1613 implicit_flow_mapping_states: smallvec::SmallVec::new(),
1614 flow_markers: smallvec::SmallVec::new(),
1615 interrupted_plain_by_comment: None,
1616 explicit_key_tab_check_pending: false,
1617
1618 buf_leading_break: String::with_capacity(128),
1619 buf_trailing_breaks: String::with_capacity(128),
1620 buf_whitespaces: String::with_capacity(128),
1621 }
1622 }
1623
1624 #[cold]
1625 fn scan_error(&self, kind: ErrorKind) -> ScanError {
1626 ScanError::from_kind(self.mark, kind)
1627 }
1628
1629 #[inline]
1630 fn ensure_current_char_is_printable(&self) -> ScanResult {
1631 let character = self.input.peek();
1632 if self.input.next_is_z() || is_printable(character) {
1633 Ok(())
1634 } else {
1635 Err(self.scan_error(ErrorKind::UnexpectedCharacter { character }))
1636 }
1637 }
1638
1639 #[cold]
1640 fn simple_key_expected(mark: Marker) -> ScanError {
1641 ScanError::from_kind(mark, ErrorKind::SimpleKeyExpected)
1642 }
1643
1644 #[cold]
1645 fn unclosed_bracket(mark: Marker, bracket: char) -> ScanError {
1646 ScanError::from_kind(mark, ErrorKind::UnclosedFlowCollection { open: bracket })
1647 }
1648
1649 #[inline]
1651 fn skip_blank(&mut self) {
1652 self.input.skip();
1653
1654 self.mark.offsets.chars += 1;
1655 self.mark.col += 1;
1656 self.mark.offsets.bytes = self.input.byte_offset();
1657 }
1658
1659 #[inline]
1661 fn skip_non_blank(&mut self) {
1662 self.input.skip();
1663
1664 self.mark.offsets.chars += 1;
1665 self.mark.col += 1;
1666 self.mark.offsets.bytes = self.input.byte_offset();
1667 self.leading_whitespace = false;
1668 }
1669
1670 #[inline]
1675 fn skip_bom(&mut self) {
1676 self.input.skip();
1677
1678 self.mark.offsets.chars += 1;
1679 self.mark.offsets.bytes = self.input.byte_offset();
1680 }
1681
1682 #[inline]
1688 fn skip_comment_char(&mut self) {
1689 self.input.skip();
1690
1691 self.mark.offsets.chars += 1;
1692 self.mark.col += 1;
1693 self.mark.offsets.bytes = self.input.byte_offset();
1694 }
1695
1696 #[inline]
1698 fn skip_n_non_blank(&mut self, count: usize) {
1699 for _ in 0..count {
1700 self.input.skip();
1701 self.mark.offsets.chars += 1;
1702 self.mark.col += 1;
1703 }
1704 self.mark.offsets.bytes = self.input.byte_offset();
1705 self.leading_whitespace = false;
1706 }
1707
1708 #[inline]
1710 fn skip_nl(&mut self) {
1711 self.input.skip();
1712
1713 self.mark.offsets.chars += 1;
1714 self.mark.col = 0;
1715 self.mark.line += 1;
1716 self.mark.offsets.bytes = self.input.byte_offset();
1717 self.leading_whitespace = true;
1718 }
1719
1720 #[inline]
1722 fn skip_linebreak(&mut self) {
1723 if self.input.next_2_are('\r', '\n') {
1724 self.skip_blank();
1727 self.skip_nl();
1728 } else if self.input.next_is_break() {
1729 self.skip_nl();
1730 }
1731 }
1732
1733 #[cfg(all(test, feature = "comments"))]
1734 fn scan_comment_token(&mut self) -> Result<Token<'input>, ScanError> {
1735 Ok(self.scan_comment_queued_token()?.into_public())
1736 }
1737
1738 #[cfg(feature = "comments")]
1739 fn scan_comment_queued_token(&mut self) -> Result<QueuedToken<'input>, ScanError> {
1740 let start_mark = self.mark;
1741 debug_assert_eq!(self.input.peek(), '#');
1742 let placement = if self.leading_whitespace {
1743 Placement::Free
1744 } else {
1745 Placement::Right
1746 };
1747
1748 self.skip_comment_char();
1749
1750 let text = if let Some(start) = self.input.byte_offset() {
1751 let n = self.input.skip_while_non_breakz();
1753 self.mark.offsets.chars += n;
1754 self.mark.col += n;
1755 let byte_offset = self.input.byte_offset();
1756 self.mark.offsets.bytes = byte_offset;
1757 let end = byte_offset.expect("byte_offset must remain available once enabled");
1758
1759 if let Some(slice) = self.try_borrow_slice(start, end) {
1760 Cow::Borrowed(slice)
1761 } else if let Some(slice) = self.input.slice_bytes(start, end) {
1762 Cow::Owned(slice.to_owned())
1764 } else {
1765 return Err(ScanError::from_kind(
1766 start_mark,
1767 ErrorKind::InputOffsetsWithoutSlice,
1768 ));
1769 }
1770 } else {
1771 let mut owned = String::new();
1773 while {
1774 let character = self.input.look_ch();
1775 !is_breakz(character) && is_printable(character)
1776 } {
1777 owned.push(self.input.peek());
1778 self.skip_comment_char();
1779 }
1780 Cow::Owned(owned)
1781 };
1782
1783 self.ensure_current_char_is_printable()?;
1784
1785 let end_mark = self.mark;
1786 let span = Span::new(start_mark, end_mark);
1787 Ok(QueuedToken(
1788 span,
1789 QueuedTokenType::Comment(Comment { text, placement }),
1790 ))
1791 }
1792
1793 #[cfg(feature = "comments")]
1794 fn push_comment_token(&mut self) -> ScanResult {
1795 let token = self.scan_comment_queued_token()?;
1796 self.tokens.push_back(token);
1797 Ok(())
1798 }
1799
1800 fn consume_comment(&mut self) -> Result<bool, ScanError> {
1802 #[cfg(feature = "comments")]
1803 if self.options.emit_comments {
1804 self.push_comment_token()?;
1805 return Ok(true);
1806 }
1807 self.skip_comment()?;
1808 Ok(false)
1809 }
1810
1811 fn skip_comment(&mut self) -> ScanResult {
1812 debug_assert_eq!(self.input.peek(), '#');
1813
1814 self.skip_comment_char();
1815 let n = self.input.skip_while_non_breakz();
1816 self.mark.offsets.chars += n;
1817 self.mark.col += n;
1818 self.mark.offsets.bytes = self.input.byte_offset();
1819 self.ensure_current_char_is_printable()
1820 }
1821
1822 #[inline]
1824 #[must_use]
1825 pub fn stream_started(&self) -> bool {
1826 self.stream_start_produced
1827 }
1828
1829 #[inline]
1831 #[must_use]
1832 pub fn stream_ended(&self) -> bool {
1833 self.stream_end_produced
1834 }
1835
1836 #[inline]
1838 #[must_use]
1839 pub fn mark(&self) -> Marker {
1840 self.mark
1841 }
1842
1843 pub(crate) fn in_directive_prefix(&self) -> bool {
1845 self.in_directive_prefix
1846 }
1847
1848 pub(crate) fn proceed_next_document(
1853 &mut self,
1854 token: Option<QueuedToken<'input>>,
1855 ) -> ScanResult {
1856 self.check_source_error()?;
1857 self.input.lookahead(4);
1858 self.check_source_error()?;
1859
1860 let cursor = self.mark;
1861 let at_line_end = self.input.next_is_z() || self.input.next_is_break();
1862 let at_real_nul = !self.input.next_is_z() && self.input.peek() == '\0';
1863 let boundary = token
1864 .into_iter()
1865 .chain(self.tokens.drain(..))
1866 .find(|token| {
1867 match token.1 {
1868 QueuedTokenType::DocumentStart => {
1869 cursor != token.0.end || !at_real_nul
1871 }
1872 QueuedTokenType::DocumentEnd => {
1873 cursor.line > token.0.end.line || at_line_end
1876 }
1877 QueuedTokenType::StreamEnd => true,
1878 _ => false,
1879 }
1880 });
1881 self.reset_document_state();
1882 if let Some(boundary) = boundary {
1883 self.queue_recovery_boundary(boundary);
1884 return Ok(());
1885 }
1886
1887 loop {
1888 self.input.lookahead(4);
1889 self.check_source_error()?;
1890 if self.input.next_is_z() {
1891 self.queue_recovery_boundary(QueuedToken(
1892 Span::empty(self.mark),
1893 QueuedTokenType::StreamEnd,
1894 ));
1895 return Ok(());
1896 }
1897
1898 if self.mark.col == 0 {
1899 if is_bom(self.input.peek()) {
1900 self.skip_bom();
1901 continue;
1902 }
1903 let start = self.input.next_is_document_start();
1904 if start || self.input.next_is_document_end() {
1905 let mark = self.mark;
1906 self.skip_n_non_blank(3);
1907 let span = Span::new(mark, self.mark);
1908 self.input.lookahead(1);
1909 self.check_source_error()?;
1910 if self.input.next_is_z()
1913 || matches!(self.input.peek(), ' ' | '\t' | '\r' | '\n')
1914 {
1915 if start {
1916 self.queue_recovery_boundary(QueuedToken(
1917 span,
1918 QueuedTokenType::DocumentStart,
1919 ));
1920 return Ok(());
1921 }
1922 if self.skip_recovery_document_end_line()? {
1923 self.queue_recovery_boundary(QueuedToken(
1924 span,
1925 QueuedTokenType::DocumentEnd,
1926 ));
1927 return Ok(());
1928 }
1929 }
1930 }
1931 }
1932
1933 self.input.lookahead(2);
1934 self.check_source_error()?;
1935 if self.input.next_is_break() {
1936 self.skip_linebreak();
1937 } else if !self.input.next_is_z() {
1938 self.skip_non_blank();
1939 }
1940 }
1941 }
1942
1943 fn skip_recovery_document_end_line(&mut self) -> Result<bool, ScanError> {
1945 let mut comment = false;
1946 loop {
1947 self.input.lookahead(2);
1948 self.check_source_error()?;
1949 if self.input.next_is_z() || self.input.next_is_break() {
1950 return Ok(true);
1951 }
1952 let ch = self.input.peek();
1953 if !is_printable(ch) {
1954 return Ok(false);
1955 }
1956 if comment || matches!(ch, ' ' | '\t') {
1957 self.skip_non_blank();
1958 } else if ch == '#' {
1959 comment = true;
1960 self.skip_non_blank();
1961 } else {
1962 return Ok(false);
1963 }
1964 }
1965 }
1966
1967 fn reset_document_state(&mut self) {
1969 self.tokens.clear();
1970 self.failed = false;
1971 #[cfg(feature = "comments")]
1972 {
1973 self.deferred_error = None;
1974 }
1975 self.stream_start_produced = true;
1976 self.stream_end_produced = false;
1977 self.document_prefix_allowed = true;
1978 self.in_directive_prefix = false;
1979 self.adjacent_value_allowed_at = 0;
1980 self.simple_key_allowed = true;
1981 self.simple_keys.clear();
1982 self.simple_keys.push(SimpleKey::new(self.mark));
1983 self.first_simple_key = None;
1984 self.indent = -1;
1985 self.indents.clear();
1986 self.flow_level = 0;
1987 self.block_level = 0;
1988 self.tokens_parsed = 0;
1989 self.token_available = false;
1990 self.leading_whitespace = self.mark.col == 0;
1991 self.flow_mapping_started.clear();
1992 self.implicit_flow_mapping_states.clear();
1993 self.flow_markers.clear();
1994 self.interrupted_plain_by_comment = None;
1995 self.explicit_key_tab_check_pending = false;
1996 self.buf_leading_break.clear();
1997 self.buf_trailing_breaks.clear();
1998 self.buf_whitespaces.clear();
1999 }
2000
2001 fn queue_recovery_boundary(&mut self, token: QueuedToken<'input>) {
2002 self.document_prefix_allowed = matches!(token.1, QueuedTokenType::DocumentEnd);
2003 self.disallow_simple_key();
2004 self.tokens.push_back(token);
2005 self.token_available = true;
2006 }
2007
2008 pub(crate) fn check_source_error(&mut self) -> ScanResult {
2010 if let Some(kind) = self.input.take_source_error() {
2011 self.source_error
2012 .get_or_insert_with(|| ScanError::from_kind(self.mark, kind));
2013 }
2014 match &self.source_error {
2015 Some(error) => Err(error.clone()),
2016 None => Ok(()),
2017 }
2018 }
2019
2020 #[cfg(feature = "comments")]
2022 #[inline]
2023 pub(crate) fn comments_possible(&self) -> bool {
2024 self.options.emit_comments && self.comments_possible
2025 }
2026
2027 #[track_caller]
2034 #[inline]
2035 fn read_break(&mut self, s: &mut String) {
2036 self.skip_break();
2037 s.push('\n');
2038 }
2039
2040 #[track_caller]
2045 #[inline]
2046 fn skip_break(&mut self) {
2047 let c = self.input.peek();
2048 let nc = self.input.peek_nth(1);
2049 debug_assert!(is_break(c));
2050 if c == '\r' && nc == '\n' {
2051 self.skip_blank();
2052 }
2053 self.skip_nl();
2054 }
2055
2056 #[track_caller]
2061 fn insert_token(&mut self, pos: usize, tok: Token<'input>) {
2062 let old_len = self.tokens.len();
2063 assert!(pos <= old_len);
2064 self.tokens.insert(pos, tok.into());
2065 }
2066
2067 fn simple_key_token_index(&self, sk: &SimpleKey, mark: Marker) -> Result<usize, ScanError> {
2068 let Some(index) = sk.token_number.checked_sub(self.tokens_parsed) else {
2069 return Err(ScanError::from_kind(mark, ErrorKind::InvalidSimpleKey));
2070 };
2071 if index > self.tokens.len() {
2072 return Err(ScanError::from_kind(mark, ErrorKind::InvalidSimpleKey));
2073 }
2074 Ok(index)
2075 }
2076
2077 #[inline]
2078 fn allow_simple_key(&mut self) {
2079 self.simple_key_allowed = true;
2080 }
2081
2082 #[inline]
2083 fn disallow_simple_key(&mut self) {
2084 self.simple_key_allowed = false;
2085 }
2086
2087 fn fetch_next_token(&mut self) -> ScanResult {
2092 let result = self.fetch_next_token_impl();
2093 self.check_source_error()?;
2094 result
2095 }
2096
2097 fn fetch_next_token_impl(&mut self) -> ScanResult {
2098 self.input.lookahead(1);
2099
2100 if !self.stream_start_produced {
2101 self.fetch_stream_start();
2102 return Ok(());
2103 }
2104 loop {
2105 let outcome = self.skip_to_next_token()?;
2106 #[cfg(feature = "comments")]
2107 if outcome.queued_comment {
2108 return Ok(());
2109 }
2110 if outcome.saw_comment && !self.tokens.is_empty() {
2111 return Ok(());
2112 }
2113 if !outcome.saw_comment {
2114 break;
2115 }
2116 }
2119
2120 debug_print!(
2121 " \x1B[38;5;244m\u{2192} fetch_next_token after whitespace {:?} {:?}\x1B[m",
2122 self.mark,
2123 self.input.peek()
2124 );
2125
2126 self.stale_simple_keys()?;
2127
2128 let mark = self.mark;
2129 self.unroll_indent(mark.col as isize);
2130
2131 self.input.lookahead(4);
2132
2133 if self.input.next_is_z() {
2134 self.fetch_stream_end()?;
2135 return Ok(());
2136 }
2137
2138 self.ensure_current_char_is_printable()?;
2139
2140 if self.mark.col == 0 {
2141 if self.input.next_char_is('%') {
2142 self.in_directive_prefix = true;
2143 return self.fetch_directive();
2144 } else if self.input.next_is_document_start() {
2145 return self.fetch_document_indicator(TokenType::DocumentStart);
2146 } else if self.input.next_is_document_end() {
2147 self.fetch_document_indicator(TokenType::DocumentEnd)?;
2148 self.skip_ws_to_eol(SkipTabs::Yes)?;
2149 if !self.input.next_is_breakz() {
2150 return Err(self.scan_error(ErrorKind::InvalidDocumentEnd));
2151 }
2152 return Ok(());
2153 }
2154 }
2155
2156 self.in_directive_prefix = false;
2157 if self.document_prefix_allowed {
2158 self.document_prefix_allowed = false;
2159 }
2160
2161 if self.options.strict_indentation
2164 && self.flow_level > 0
2165 && (self.mark.col as isize) <= self.flow_block_indent()
2166 {
2167 return Err(self.scan_error(ErrorKind::InvalidIndentation));
2168 }
2169
2170 let c = self.input.peek();
2171 let nc = self.input.peek_nth(1);
2172 match c {
2173 '[' => self.fetch_flow_collection_start(TokenType::FlowSequenceStart),
2174 '{' => self.fetch_flow_collection_start(TokenType::FlowMappingStart),
2175 ']' => self.fetch_flow_collection_end(TokenType::FlowSequenceEnd, '[', ']'),
2176 '}' => self.fetch_flow_collection_end(TokenType::FlowMappingEnd, '{', '}'),
2177 ',' => self.fetch_flow_entry(),
2178 '-' if is_blank_or_breakz(nc) => self.fetch_block_entry(),
2179 '?' if is_blank_or_breakz(nc) => self.fetch_key(),
2180 ':' if is_blank_or_breakz(nc) => self.fetch_value(),
2181 ':' if self.flow_level > 0
2182 && (is_flow(nc) || self.mark.index() == self.adjacent_value_allowed_at) =>
2183 {
2184 self.fetch_flow_value()
2185 }
2186 '*' => self.fetch_anchor(true),
2188 '&' => self.fetch_anchor(false),
2190 '!' => self.fetch_tag(),
2191 '|' if self.flow_level == 0 => self.fetch_block_scalar(true),
2193 '>' if self.flow_level == 0 => self.fetch_block_scalar(false),
2195 '\'' => self.fetch_flow_scalar(true),
2196 '"' => self.fetch_flow_scalar(false),
2197 '-' if !is_blank_or_breakz(nc) => self.fetch_plain_scalar(),
2199 ':' | '?' if !is_blank_or_breakz(nc) && self.flow_level == 0 => {
2200 self.fetch_plain_scalar()
2201 }
2202 c if is_bom(c) && !self.options.bom_inside_document_as_content => {
2204 Err(self.scan_error(ErrorKind::BomInsideDocument))
2205 }
2206 '|' | '>' | '%' | '@' | '`' => {
2207 Err(self.scan_error(ErrorKind::UnexpectedCharacter { character: c }))
2208 }
2209 _ => self.fetch_plain_scalar(),
2210 }
2211 }
2212
2213 pub(crate) fn next_queued_token(&mut self) -> Result<Option<QueuedToken<'input>>, ScanError> {
2218 #[cfg(feature = "comments")]
2219 if self.deferred_error.is_some() {
2220 if !matches!(
2221 self.tokens.front().map(|token| &token.1),
2222 Some(QueuedTokenType::Comment(_))
2223 ) {
2224 if let Some(error) = self.deferred_error.take() {
2225 return error.into_result();
2226 }
2227 }
2228 self.token_available = true;
2229 }
2230
2231 if self.stream_end_produced {
2232 return Ok(None);
2233 }
2234
2235 if !self.token_available {
2236 #[cfg(feature = "comments")]
2237 if let Err(error) = self.fetch_more_tokens() {
2238 if matches!(
2239 self.tokens.front().map(|token| &token.1),
2240 Some(QueuedTokenType::Comment(_))
2241 ) {
2242 self.deferred_error = Some(error);
2243 } else {
2244 return Err(error);
2245 }
2246 }
2247 #[cfg(not(feature = "comments"))]
2248 self.fetch_more_tokens()?;
2249 }
2250 let Some(t) = self.tokens.pop_front() else {
2251 unreachable!("fetch_more_tokens succeeded without producing a token")
2252 };
2253 self.token_available = false;
2254 self.tokens_parsed += 1;
2255
2256 let is_stream_end = matches!(t.1, QueuedTokenType::StreamEnd);
2257 if is_stream_end {
2258 self.stream_end_produced = true;
2259 }
2260 Ok(Some(t))
2261 }
2262
2263 fn next_token(&mut self) -> Result<Option<Token<'input>>, ScanError> {
2268 Ok(self.next_queued_token()?.map(QueuedToken::into_public))
2269 }
2270
2271 fn fetch_more_tokens(&mut self) -> ScanResult {
2276 let mut need_more;
2277 loop {
2278 if self.tokens.is_empty() {
2279 need_more = true;
2280 } else {
2281 #[cfg(feature = "comments")]
2282 {
2283 need_more = false;
2284 }
2285 self.stale_simple_keys()?;
2287 #[cfg(feature = "comments")]
2288 if !matches!(
2289 self.tokens.front().map(|token| &token.1),
2290 Some(QueuedTokenType::Comment(_))
2291 ) {
2292 need_more = self.first_simple_key.is_some_and(|index| {
2294 self.simple_keys[index].token_number == self.tokens_parsed
2295 });
2296 }
2297 #[cfg(not(feature = "comments"))]
2298 {
2299 need_more = self.first_simple_key.is_some_and(|index| {
2300 self.simple_keys[index].token_number == self.tokens_parsed
2301 });
2302 }
2303 }
2304
2305 if let Some(token) = self.tokens.back() {
2308 if matches!(
2309 token.1,
2310 QueuedTokenType::DocumentEnd | QueuedTokenType::DocumentStart
2311 ) {
2312 break;
2313 }
2314 }
2315
2316 if !need_more {
2317 break;
2318 }
2319 self.fetch_next_token()?;
2320 }
2321 self.token_available = true;
2322
2323 Ok(())
2324 }
2325
2326 fn stale_simple_keys(&mut self) -> ScanResult {
2335 while let Some(index) = self.first_simple_key {
2336 let sk = &mut self.simple_keys[index];
2337 debug_assert!(sk.possible);
2338 let is_line_stale = self.flow_level == 0 && sk.mark.line < self.mark.line;
2339 let is_length_stale = self.mark.index().saturating_sub(sk.mark.index())
2342 > self.options.simple_key_max_lookahead;
2343
2344 if !is_line_stale && !is_length_stale {
2345 break;
2347 }
2348 if sk.required {
2349 return Err(Self::simple_key_expected(sk.mark));
2350 }
2351 sk.possible = false;
2352 self.first_simple_key = self.simple_keys[index + 1..]
2355 .iter()
2356 .position(|key| key.possible)
2357 .map(|offset| index + 1 + offset);
2358 }
2359 Ok(())
2360 }
2361
2362 #[cfg_attr(
2367 feature = "comments",
2368 doc = "\nWhen comment emission is enabled, encountered comments are queued as \
2369 [`TokenType::Comment`] tokens so the parser can emit presentation events."
2370 )]
2371 fn skip_to_next_token(&mut self) -> Result<SkipToNextTokenOutcome, ScanError> {
2376 let consume_linebreak = |this: &mut Self| {
2379 this.input.lookahead(2);
2380 this.skip_linebreak();
2381 if this.flow_level == 0 {
2382 this.allow_simple_key();
2383 }
2384 };
2385
2386 let mut outcome = SkipToNextTokenOutcome::default();
2387 loop {
2388 let ch = self.input.look_ch();
2389 if self.explicit_key_tab_check_pending {
2390 match ch {
2391 '\t' => {
2392 self.skip_explicit_key_tab()?;
2393 continue;
2394 }
2395 ' ' | '\n' | '\r' | '#' => {}
2396 '&' | '!' if self.options.strict_indentation => {}
2397 _ => self.explicit_key_tab_check_pending = false,
2398 }
2399 }
2400
2401 match ch {
2402 '\t' => {
2404 let indent = if self.options.strict_indentation && self.flow_level > 0 {
2405 self.flow_block_indent() + 1
2406 } else {
2407 self.indent
2408 };
2409 if self.is_within_block()
2410 && self.leading_whitespace
2411 && (self.mark.col as isize) < indent
2412 {
2413 let (chars_consumed, _) = self.input.skip_ws_to_eol_blanks(SkipTabs::Yes);
2414 self.mark.col += chars_consumed;
2415 self.mark.offsets.chars += chars_consumed;
2416 self.mark.offsets.bytes = self.input.byte_offset();
2417
2418 if self.input.look_ch() == '#' {
2420 continue;
2421 }
2422
2423 if !self.input.next_is_breakz() {
2425 return Err(self.scan_error(ErrorKind::TabInBlockIndentation));
2426 }
2427
2428 if matches!(self.input.look_ch(), '\n' | '\r') {
2430 consume_linebreak(self);
2431 }
2432 } else {
2433 self.skip_blank();
2435 }
2436 }
2437
2438 ' ' => self.skip_blank(),
2439
2440 '\n' | '\r' => consume_linebreak(self),
2441
2442 c if is_bom(c)
2443 && self.document_prefix_allowed
2444 && self.flow_level == 0
2445 && self.mark.col == 0 =>
2446 {
2447 self.skip_bom();
2448 }
2449
2450 '#' => {
2451 outcome.saw_comment = true;
2452 #[cfg(feature = "comments")]
2453 {
2454 outcome.queued_comment |= self.consume_comment()?;
2455 }
2456 #[cfg(not(feature = "comments"))]
2457 self.skip_comment()?;
2458
2459 if matches!(self.input.look_ch(), '\n' | '\r') {
2461 consume_linebreak(self);
2462 }
2463 return Ok(outcome);
2464 }
2465
2466 _ => break,
2467 }
2468 }
2469
2470 if let Some(err_mark) = self.interrupted_plain_by_comment.take() {
2473 let is_immediate_next_line = self.mark.line == err_mark.line + 1;
2477
2478 if self.flow_level == 0
2480 && is_immediate_next_line
2481 && (self.mark.col as isize) > self.indent
2482 {
2483 self.input.lookahead(4);
2487
2488 if !self.input.next_is_z()
2489 && !self.input.next_is_document_indicator()
2490 && self.input.next_can_be_plain_scalar(false)
2491 {
2492 return Err(ScanError::from_kind(
2493 err_mark,
2494 ErrorKind::CommentInterceptedScalar,
2495 ));
2496 }
2497 }
2498 }
2499
2500 Ok(outcome)
2501 }
2502
2503 fn skip_explicit_key_tab(&mut self) -> ScanResult {
2505 if self.leading_whitespace && (self.mark.col as isize) <= self.indent {
2506 let tab_mark = self.mark;
2507 let (chars_consumed, _) = self.input.skip_ws_to_eol_blanks(SkipTabs::Yes);
2508 self.mark.col += chars_consumed;
2509 self.mark.offsets.chars += chars_consumed;
2510 self.mark.offsets.bytes = self.input.byte_offset();
2511 if self.input.look_ch() != '#' && !self.input.next_is_breakz() {
2513 return Err(ScanError::from_kind(tab_mark, ErrorKind::TabNotAllowed));
2514 }
2515 } else {
2516 self.skip_blank();
2517 }
2518 self.disallow_simple_key();
2521 Ok(())
2522 }
2523
2524 fn skip_yaml_whitespace(&mut self) -> Result<bool, ScanError> {
2533 let mut need_whitespace = true;
2534 loop {
2535 match self.input.look_ch() {
2536 ' ' => {
2537 self.skip_blank();
2538
2539 need_whitespace = false;
2540 }
2541 '\t' => {
2542 self.skip_explicit_key_tab()?;
2543 need_whitespace = false;
2544 }
2545 '\n' | '\r' => {
2546 self.input.lookahead(2);
2547 self.skip_linebreak();
2548 if self.flow_level == 0 {
2549 self.allow_simple_key();
2550 }
2551 need_whitespace = false;
2552 }
2553 '#' => {
2554 if need_whitespace {
2555 self.skip_comment()?;
2556 } else {
2557 self.consume_comment()?;
2558 return Ok(true);
2559 }
2560 }
2561 _ => break,
2562 }
2563 }
2564
2565 if need_whitespace && !self.input.next_is_z() {
2569 Err(self.scan_error(ErrorKind::ExpectedWhitespace))
2570 } else {
2571 Ok(false)
2572 }
2573 }
2574
2575 fn skip_ws_to_eol(&mut self, skip_tabs: SkipTabs) -> Result<WhitespaceResult, ScanError> {
2577 #[cfg(feature = "comments")]
2578 if !self.comments_possible {
2579 let (chars_consumed, result) = self.input.skip_ws_to_eol(skip_tabs);
2580 self.mark.col += chars_consumed;
2581 self.mark.offsets.chars += chars_consumed;
2582 self.mark.offsets.bytes = self.input.byte_offset();
2583 return result.map_err(|kind| self.scan_error(kind));
2584 }
2585
2586 let (chars_consumed, whitespace) = self.input.skip_ws_to_eol_blanks(skip_tabs);
2587 self.mark.col += chars_consumed;
2588 self.mark.offsets.chars += chars_consumed;
2589 self.mark.offsets.bytes = self.input.byte_offset();
2590
2591 if self.input.look_ch() != '#' {
2592 return Ok(whitespace);
2593 }
2594
2595 if !whitespace.found_tabs() && !whitespace.has_valid_yaml_ws() {
2596 return Err(self.scan_error(ErrorKind::CommentNotSeparated));
2597 }
2598
2599 self.consume_comment()?;
2600 Ok(whitespace)
2601 }
2602
2603 fn fetch_stream_start(&mut self) {
2604 let mark = self.mark;
2605 self.indent = -1;
2606 self.stream_start_produced = true;
2607 self.allow_simple_key();
2608 self.tokens
2609 .push_back(Token(Span::empty(mark), TokenType::StreamStart).into());
2610 self.simple_keys.push(SimpleKey::new(Marker::new(0, 0, 0)));
2611 }
2612
2613 fn fetch_stream_end(&mut self) -> ScanResult {
2614 if let Some((mark, bracket)) = self.flow_markers.pop() {
2617 return Err(Self::unclosed_bracket(mark, bracket));
2618 }
2619
2620 for sk in &mut self.simple_keys {
2623 if sk.required && sk.possible {
2624 return Err(Self::simple_key_expected(sk.mark));
2625 }
2626 sk.possible = false;
2627 }
2628 self.first_simple_key = None;
2629
2630 self.unroll_indent(-1);
2631 self.remove_simple_key()?;
2632 self.disallow_simple_key();
2633
2634 self.tokens
2635 .push_back(Token(Span::empty(self.mark), TokenType::StreamEnd).into());
2636 Ok(())
2637 }
2638
2639 fn fetch_directive(&mut self) -> ScanResult {
2640 if self.options.disallow_directives {
2641 return Err(self.scan_error(ErrorKind::DirectiveDisallowed));
2642 }
2643
2644 self.unroll_indent(-1);
2645 self.remove_simple_key()?;
2646
2647 self.disallow_simple_key();
2648
2649 let token_index = self.tokens.len();
2650 let tok = self.scan_directive()?;
2651 self.insert_token(token_index, tok);
2652
2653 Ok(())
2654 }
2655
2656 fn scan_directive(&mut self) -> Result<Token<'input>, ScanError> {
2657 let start_mark = self.mark;
2658 self.skip_non_blank();
2659
2660 let mut budget = self.options.max_directive_bytes;
2663
2664 let name = self.scan_directive_name(&mut budget)?;
2665 let mut separated_comment = false;
2666 let tok = match name.as_ref() {
2667 "YAML" => self.scan_version_directive_value(&start_mark)?,
2668 "TAG" => self.scan_tag_directive_value(&start_mark, &mut budget)?,
2669 _ => {
2670 let mut params = Vec::new();
2671 while self.input.next_is_blank() {
2672 let n_blanks = self.input.skip_while_blank();
2673 self.mark.offsets.chars += n_blanks;
2674 self.mark.col += n_blanks;
2675 self.mark.offsets.bytes = self.input.byte_offset();
2676
2677 if self.input.peek() == '#' {
2678 separated_comment = true;
2679 break;
2680 }
2681
2682 if !is_blank_or_breakz(self.input.peek()) {
2683 self.spend_directive_bytes(&mut budget, n_blanks, start_mark)?;
2684 if params.len() >= self.options.max_reserved_directive_params {
2685 return Err(ScanError::from_kind(
2686 start_mark,
2687 ErrorKind::TooManyReservedDirectiveParams {
2688 limit: self.options.max_reserved_directive_params,
2689 },
2690 ));
2691 }
2692
2693 let mut param = String::new();
2694 let Some(n_chars) = self.fetch_directive_word(&mut param, &mut budget)
2695 else {
2696 return Err(self.directive_byte_limit(start_mark));
2697 };
2698 self.mark.offsets.chars += n_chars;
2699 self.mark.col += n_chars;
2700 self.mark.offsets.bytes = self.input.byte_offset();
2701 params.push(param);
2702 }
2703 }
2704
2705 Token(
2706 Span::new(start_mark, self.mark),
2707 TokenType::ReservedDirective {
2708 name,
2709 parameters: params,
2710 },
2711 )
2712 }
2713 };
2714
2715 if separated_comment {
2716 self.consume_comment()?;
2718 } else {
2719 self.skip_ws_to_eol(SkipTabs::Yes)?;
2720 }
2721
2722 if self.input.next_is_breakz() {
2723 self.input.lookahead(2);
2724 self.skip_linebreak();
2725 Ok(tok)
2726 } else {
2727 Err(ScanError::from_kind(
2728 start_mark,
2729 ErrorKind::InvalidDirectiveTerminator,
2730 ))
2731 }
2732 }
2733
2734 fn scan_version_directive_value(&mut self, mark: &Marker) -> Result<Token<'input>, ScanError> {
2735 let n_blanks = self.input.skip_while_blank();
2736 self.mark.offsets.chars += n_blanks;
2737 self.mark.col += n_blanks;
2738 self.mark.offsets.bytes = self.input.byte_offset();
2739
2740 let major = self.scan_version_directive_number(mark)?;
2741
2742 if self.input.peek() != '.' {
2743 return Err(ScanError::from_kind(
2744 *mark,
2745 ErrorKind::MissingYamlVersionSeparator,
2746 ));
2747 }
2748 self.skip_non_blank();
2749
2750 let minor = self.scan_version_directive_number(mark)?;
2751
2752 Ok(Token(
2753 Span::new(*mark, self.mark),
2754 TokenType::VersionDirective { major, minor },
2755 ))
2756 }
2757
2758 fn directive_byte_limit(&self, start_mark: Marker) -> ScanError {
2760 ScanError::from_kind(
2761 start_mark,
2762 ErrorKind::DirectiveByteLimitExceeded {
2763 limit: self.options.max_directive_bytes,
2764 },
2765 )
2766 }
2767
2768 fn spend_directive_bytes(
2770 &self,
2771 budget: &mut usize,
2772 bytes: usize,
2773 start_mark: Marker,
2774 ) -> ScanResult {
2775 let Some(remaining) = budget.checked_sub(bytes) else {
2776 return Err(self.directive_byte_limit(start_mark));
2777 };
2778 *budget = remaining;
2779 Ok(())
2780 }
2781
2782 fn fetch_directive_word(&mut self, out: &mut String, budget: &mut usize) -> Option<usize> {
2789 let mut n_chars = 0;
2790
2791 loop {
2792 let c = self.input.look_ch();
2793 if !is_yaml_non_space(c) || is_z(c) {
2794 break;
2795 }
2796
2797 let len = c.len_utf8();
2798 if len > *budget {
2799 return None;
2800 }
2801 *budget -= len;
2802
2803 out.push(c);
2804 self.input.skip();
2805 n_chars += 1;
2806 }
2807
2808 Some(n_chars)
2809 }
2810
2811 fn scan_directive_name(&mut self, budget: &mut usize) -> Result<String, ScanError> {
2812 let start_mark = self.mark;
2813 let mut string = String::new();
2814
2815 let Some(n_chars) = self.fetch_directive_word(&mut string, budget) else {
2816 return Err(self.directive_byte_limit(start_mark));
2817 };
2818 self.mark.offsets.chars += n_chars;
2819 self.mark.col += n_chars;
2820 self.mark.offsets.bytes = self.input.byte_offset();
2821
2822 if string.is_empty() {
2823 return Err(ScanError::from_kind(
2824 start_mark,
2825 ErrorKind::MissingDirectiveName,
2826 ));
2827 }
2828
2829 if !is_blank_or_breakz(self.input.peek()) {
2830 return Err(ScanError::from_kind(
2831 start_mark,
2832 ErrorKind::InvalidDirectiveName,
2833 ));
2834 }
2835
2836 Ok(string)
2837 }
2838
2839 fn scan_version_directive_number(&mut self, mark: &Marker) -> Result<u32, ScanError> {
2840 let mut val = 0u32;
2841 let mut length = 0usize;
2842 while let Some(digit) = self.input.look_ch().to_digit(10) {
2843 if length + 1 > 9 {
2844 return Err(ScanError::from_kind(*mark, ErrorKind::YamlVersionTooLong));
2845 }
2846 length += 1;
2847 val = val * 10 + digit;
2848 self.skip_non_blank();
2849 }
2850
2851 if length == 0 {
2852 return Err(ScanError::from_kind(*mark, ErrorKind::MissingYamlVersion));
2853 }
2854
2855 Ok(val)
2856 }
2857
2858 fn scan_tag_directive_value(
2859 &mut self,
2860 mark: &Marker,
2861 budget: &mut usize,
2862 ) -> Result<Token<'input>, ScanError> {
2863 let n_blanks = self.input.skip_while_blank();
2864 self.mark.offsets.chars += n_blanks;
2865 self.mark.col += n_blanks;
2866 self.mark.offsets.bytes = self.input.byte_offset();
2867 self.spend_directive_bytes(budget, n_blanks, *mark)?;
2868
2869 let handle = self.scan_tag_handle_directive_cow(mark, budget)?;
2870
2871 let n_blanks = self.input.skip_while_blank();
2872 self.mark.offsets.chars += n_blanks;
2873 self.mark.col += n_blanks;
2874 self.mark.offsets.bytes = self.input.byte_offset();
2875 self.spend_directive_bytes(budget, n_blanks, *mark)?;
2876
2877 let prefix = self.scan_tag_prefix_directive_cow(mark, budget)?;
2878
2879 self.input.lookahead(1);
2880
2881 if self.input.next_is_blank_or_breakz() {
2882 Ok(Token(
2883 Span::new(*mark, self.mark),
2884 TokenType::TagDirective { handle, prefix },
2885 ))
2886 } else {
2887 Err(ScanError::from_kind(
2888 *mark,
2889 ErrorKind::InvalidTagDirectiveTerminator,
2890 ))
2891 }
2892 }
2893
2894 fn fetch_tag(&mut self) -> ScanResult {
2895 self.save_simple_key();
2896 self.disallow_simple_key();
2897
2898 let tok = self.scan_tag()?;
2899 self.tokens.push_back(tok.into());
2900 Ok(())
2901 }
2902
2903 fn scan_tag(&mut self) -> Result<Token<'input>, ScanError> {
2904 let start_mark = self.mark;
2905
2906 self.input.lookahead(2);
2908
2909 if self.input.byte_offset().is_none() {
2911 return self.scan_tag_owned(&start_mark);
2912 }
2913
2914 let (handle, suffix): (Cow<'input, str>, Cow<'input, str>) = if self
2915 .input
2916 .nth_char_is(1, '<')
2917 {
2918 let suffix = self.scan_verbatim_tag(&start_mark)?;
2920 (Cow::Owned(String::new()), Cow::Owned(suffix))
2921 } else {
2922 let handle = self.scan_tag_handle_cow(&start_mark)?;
2924 if handle.len() >= 2 && handle.starts_with('!') && handle.ends_with('!') {
2926 let suffix = self.scan_tag_shorthand_suffix_cow(&start_mark, true)?;
2928 (handle, suffix)
2929 } else {
2930 let remaining_suffix = self.scan_tag_shorthand_suffix_cow(&start_mark, false)?;
2935
2936 let suffix = self.combine_local_tag_suffix(&start_mark, handle, remaining_suffix);
2937
2938 if suffix.is_empty() {
2941 (Cow::Borrowed(""), Cow::Borrowed("!"))
2942 } else {
2943 (Cow::Borrowed("!"), suffix)
2944 }
2945 }
2946 };
2947
2948 if is_blank_or_breakz(self.input.look_ch())
2949 || (self.flow_level > 0 && matches!(self.input.peek(), ',' | ']' | '}'))
2950 {
2951 Ok(Token(
2954 Span::new(start_mark, self.mark),
2955 TokenType::Tag { handle, suffix },
2956 ))
2957 } else {
2958 Err(ScanError::from_kind(
2959 start_mark,
2960 ErrorKind::InvalidTagTerminator,
2961 ))
2962 }
2963 }
2964
2965 fn combine_local_tag_suffix(
2966 &self,
2967 start_mark: &Marker,
2968 handle: Cow<'input, str>,
2969 remaining: Cow<'input, str>,
2970 ) -> Cow<'input, str> {
2971 if handle.len() == 1 {
2972 return remaining;
2973 }
2974
2975 match (handle, remaining) {
2976 (Cow::Borrowed(handle), Cow::Borrowed(remaining)) => {
2977 if remaining.is_empty() {
2978 return Cow::Borrowed(&handle[1..]);
2979 }
2980
2981 let borrowed = start_mark
2982 .byte_offset()
2983 .and_then(|start| start.checked_add(1))
2984 .zip(self.input.byte_offset())
2985 .and_then(|(start, end)| self.try_borrow_slice(start, end));
2986 borrowed.map_or_else(
2987 || {
2988 let mut combined =
2989 String::with_capacity(handle.len() - 1 + remaining.len());
2990 combined.push_str(&handle[1..]);
2991 combined.push_str(remaining);
2992 Cow::Owned(combined)
2993 },
2994 Cow::Borrowed,
2995 )
2996 }
2997 (Cow::Borrowed(handle), Cow::Owned(mut remaining)) => {
2998 remaining.reserve(handle.len() - 1);
2999 remaining.insert_str(0, &handle[1..]);
3000 Cow::Owned(remaining)
3001 }
3002 (Cow::Owned(mut handle), remaining) => {
3003 handle.remove(0);
3004 handle.push_str(&remaining);
3005 Cow::Owned(handle)
3006 }
3007 }
3008 }
3009
3010 fn scan_tag_owned(&mut self, start_mark: &Marker) -> Result<Token<'input>, ScanError> {
3012 let mut handle = String::new();
3013 let mut suffix;
3014
3015 if self.input.nth_char_is(1, '<') {
3016 suffix = self.scan_verbatim_tag(start_mark)?;
3017 } else {
3018 handle = self.scan_tag_handle(false, start_mark)?;
3020 if handle.len() >= 2 && handle.starts_with('!') && handle.ends_with('!') {
3022 let is_secondary_handle = handle == "!!";
3024 suffix =
3025 self.scan_tag_shorthand_suffix(false, is_secondary_handle, "", start_mark)?;
3026 } else {
3027 suffix = self.scan_tag_shorthand_suffix(false, false, &handle, start_mark)?;
3028 "!".clone_into(&mut handle);
3029 if suffix.is_empty() {
3032 handle.clear();
3033 "!".clone_into(&mut suffix);
3034 }
3035 }
3036 }
3037
3038 if is_blank_or_breakz(self.input.look_ch())
3039 || (self.flow_level > 0 && matches!(self.input.peek(), ',' | ']' | '}'))
3040 {
3041 Ok(Token(
3044 Span::new(*start_mark, self.mark),
3045 TokenType::Tag {
3046 handle: handle.into(),
3047 suffix: suffix.into(),
3048 },
3049 ))
3050 } else {
3051 Err(ScanError::from_kind(
3052 *start_mark,
3053 ErrorKind::InvalidTagTerminator,
3054 ))
3055 }
3056 }
3057
3058 fn scan_tag_handle_cow(&mut self, mark: &Marker) -> Result<Cow<'input, str>, ScanError> {
3063 let Some(start) = self.input.byte_offset() else {
3064 return Ok(Cow::Owned(self.scan_tag_handle(false, mark)?));
3065 };
3066
3067 if self.input.look_ch() != '!' {
3068 return Err(ScanError::from_kind(*mark, ErrorKind::ExpectedTagBang));
3069 }
3070
3071 self.skip_non_blank();
3073
3074 self.input.lookahead(1);
3076 while self.input.next_is_alpha() {
3077 self.skip_non_blank();
3078 self.input.lookahead(1);
3079 }
3080
3081 if self.input.peek() == '!' {
3083 self.skip_non_blank();
3084 }
3085
3086 let Some(end) = self.input.byte_offset() else {
3087 return Ok(Cow::Owned(self.scan_tag_handle(false, mark)?));
3088 };
3089
3090 if let Some(slice) = self.try_borrow_slice(start, end) {
3091 Ok(Cow::Borrowed(slice))
3092 } else {
3093 let slice = self
3094 .input
3095 .slice_bytes(start, end)
3096 .ok_or_else(|| ScanError::from_kind(*mark, ErrorKind::InputSlicingUnavailable))?;
3097 Ok(Cow::Owned(slice.to_owned()))
3098 }
3099 }
3100
3101 fn scan_tag_shorthand_suffix_cow(
3105 &mut self,
3106 mark: &Marker,
3107 require_non_empty: bool,
3108 ) -> Result<Cow<'input, str>, ScanError> {
3109 let Some(start) = self.input.byte_offset() else {
3110 return Ok(Cow::Owned(
3111 self.scan_tag_shorthand_suffix(false, false, "", mark)?,
3112 ));
3113 };
3114
3115 while is_tag_char(self.input.look_ch()) {
3117 if self.input.peek() == '%' {
3118 let current = self
3120 .input
3121 .byte_offset()
3122 .expect("byte_offset() must remain available once enabled");
3123 let mut out = if let Some(slice) = self.input.slice_bytes(start, current) {
3124 slice.to_owned()
3125 } else {
3126 String::new()
3127 };
3128
3129 while is_tag_char(self.input.look_ch()) {
3131 if self.input.peek() == '%' {
3132 out.push(self.scan_uri_escapes(mark)?);
3133 } else {
3134 out.push(self.input.peek());
3135 self.skip_non_blank();
3136 }
3137 }
3138 return Ok(Cow::Owned(out));
3139 }
3140 self.skip_non_blank();
3141 }
3142
3143 let Some(end) = self.input.byte_offset() else {
3144 return Ok(Cow::Owned(
3145 self.scan_tag_shorthand_suffix(false, false, "", mark)?,
3146 ));
3147 };
3148
3149 if require_non_empty && start == end {
3150 return Err(ScanError::from_kind(*mark, ErrorKind::MissingTagUri));
3151 }
3152
3153 if let Some(slice) = self.try_borrow_slice(start, end) {
3154 Ok(Cow::Borrowed(slice))
3155 } else {
3156 let slice = self
3157 .input
3158 .slice_bytes(start, end)
3159 .ok_or_else(|| ScanError::from_kind(*mark, ErrorKind::InputSlicingUnavailable))?;
3160 Ok(Cow::Owned(slice.to_owned()))
3161 }
3162 }
3163
3164 fn scan_tag_handle(&mut self, directive: bool, mark: &Marker) -> Result<String, ScanError> {
3165 let mut string = String::new();
3166 if self.input.look_ch() != '!' {
3167 return Err(ScanError::from_kind(*mark, ErrorKind::ExpectedTagBang));
3168 }
3169
3170 string.push(self.input.peek());
3171 self.skip_non_blank();
3172
3173 let n_chars = self.input.fetch_while_is_alpha(&mut string);
3174 self.mark.offsets.chars += n_chars;
3175 self.mark.col += n_chars;
3176 self.mark.offsets.bytes = self.input.byte_offset();
3177
3178 if self.input.peek() == '!' {
3180 string.push(self.input.peek());
3181 self.skip_non_blank();
3182 } else if directive && string != "!" {
3183 return Err(ScanError::from_kind(
3187 *mark,
3188 ErrorKind::ExpectedTagDirectiveBang,
3189 ));
3190 }
3191 Ok(string)
3192 }
3193
3194 fn scan_verbatim_tag(&mut self, start_mark: &Marker) -> Result<String, ScanError> {
3198 self.skip_non_blank();
3200 self.skip_non_blank();
3201
3202 let mut string = String::new();
3203 while is_uri_char(self.input.look_ch()) {
3204 if self.input.peek() == '%' {
3205 string.push(self.scan_uri_escapes(start_mark)?);
3206 } else {
3207 string.push(self.input.peek());
3208 self.skip_non_blank();
3209 }
3210 }
3211
3212 if string.is_empty() {
3213 return Err(ScanError::from_kind(*start_mark, ErrorKind::MissingTagUri));
3214 }
3215
3216 if self.input.peek() != '>' {
3217 return Err(ScanError::from_kind(
3218 *start_mark,
3219 ErrorKind::UnclosedVerbatimTag,
3220 ));
3221 }
3222 self.skip_non_blank();
3223
3224 Ok(string)
3225 }
3226
3227 fn scan_tag_shorthand_suffix(
3228 &mut self,
3229 _directive: bool,
3230 _is_secondary: bool,
3231 head: &str,
3232 mark: &Marker,
3233 ) -> Result<String, ScanError> {
3234 let mut length = head.len();
3235 let mut string = String::new();
3236
3237 if length > 1 {
3240 string.extend(head.chars().skip(1));
3241 }
3242
3243 while is_tag_char(self.input.look_ch()) {
3244 if self.input.peek() == '%' {
3246 string.push(self.scan_uri_escapes(mark)?);
3247 } else {
3248 string.push(self.input.peek());
3249 self.skip_non_blank();
3250 }
3251
3252 length += 1;
3253 }
3254
3255 if length == 0 {
3256 return Err(ScanError::from_kind(*mark, ErrorKind::MissingTagUri));
3257 }
3258
3259 Ok(string)
3260 }
3261
3262 fn scan_uri_escapes(&mut self, mark: &Marker) -> Result<char, ScanError> {
3263 self.scan_uri_escapes_with_budget(mark, None)
3264 }
3265
3266 fn scan_uri_escapes_with_budget(
3267 &mut self,
3268 mark: &Marker,
3269 mut directive_budget: Option<&mut usize>,
3270 ) -> Result<char, ScanError> {
3271 let mut width = 0usize;
3272 let mut bytes = [0u8; 4];
3273 let mut bytes_len = 0usize;
3274 loop {
3275 self.input.lookahead(3);
3276
3277 let c = self.input.peek_nth(1);
3278 let nc = self.input.peek_nth(2);
3279
3280 if !(self.input.peek() == '%' && is_hex(c) && is_hex(nc)) {
3281 return Err(ScanError::from_kind(*mark, ErrorKind::InvalidTagEscape));
3282 }
3283
3284 if let Some(budget) = directive_budget.as_deref_mut() {
3285 self.spend_directive_bytes(budget, 3, *mark)?;
3286 }
3287
3288 let byte = u8::try_from((as_hex(c) << 4) + as_hex(nc))
3289 .expect("two hex nibbles always fit in a byte");
3290 if width == 0 {
3291 width = match byte {
3292 _ if byte & 0x80 == 0x00 => 1,
3293 _ if byte & 0xE0 == 0xC0 => 2,
3294 _ if byte & 0xF0 == 0xE0 => 3,
3295 _ if byte & 0xF8 == 0xF0 => 4,
3296 _ => {
3297 return Err(ScanError::from_kind(
3298 *mark,
3299 ErrorKind::InvalidTagUtf8LeadingByte,
3300 ));
3301 }
3302 };
3303 } else if byte & 0xc0 != 0x80 {
3304 return Err(ScanError::from_kind(
3305 *mark,
3306 ErrorKind::InvalidTagUtf8TrailingByte,
3307 ));
3308 }
3309
3310 bytes[bytes_len] = byte;
3311 bytes_len += 1;
3312
3313 self.skip_n_non_blank(3);
3314
3315 width -= 1;
3316 if width == 0 {
3317 break;
3318 }
3319 }
3320
3321 let s = core::str::from_utf8(&bytes[..bytes_len])
3322 .map_err(|_| ScanError::from_kind(*mark, ErrorKind::InvalidTagUtf8))?;
3323
3324 let Some(ch) = s.chars().next() else {
3325 unreachable!("a validated URI escape cannot decode to an empty string")
3326 };
3327 Ok(ch)
3328 }
3329
3330 fn fetch_anchor(&mut self, alias: bool) -> ScanResult {
3331 self.save_simple_key();
3332 self.disallow_simple_key();
3333
3334 let tok = self.scan_anchor(alias)?;
3335
3336 self.tokens.push_back(tok.into());
3337
3338 Ok(())
3339 }
3340
3341 fn scan_anchor(&mut self, alias: bool) -> Result<Token<'input>, ScanError> {
3342 let start_mark = self.mark;
3343
3344 self.skip_non_blank();
3346
3347 if let Some(start) = self.input.byte_offset() {
3349 while is_anchor_char(self.input.look_ch()) {
3350 self.skip_non_blank();
3351 }
3352
3353 let end = self
3354 .input
3355 .byte_offset()
3356 .expect("byte_offset() must remain available once enabled");
3357
3358 if start == end {
3359 return Err(ScanError::from_kind(
3360 start_mark,
3361 ErrorKind::MissingAnchorOrAliasName,
3362 ));
3363 }
3364
3365 let cow = if let Some(slice) = self.try_borrow_slice(start, end) {
3366 Cow::Borrowed(slice)
3367 } else if let Some(slice) = self.input.slice_bytes(start, end) {
3368 Cow::Owned(slice.to_owned())
3369 } else {
3370 return Err(ScanError::from_kind(
3371 start_mark,
3372 ErrorKind::InputSlicingUnavailable,
3373 ));
3374 };
3375
3376 let tok = if alias {
3377 TokenType::Alias { name: cow }
3378 } else {
3379 TokenType::Anchor { name: cow }
3380 };
3381 return Ok(Token(Span::new(start_mark, self.mark), tok));
3382 }
3383
3384 let mut string = String::new();
3385 while is_anchor_char(self.input.look_ch()) {
3386 string.push(self.input.peek());
3387 self.skip_non_blank();
3388 }
3389
3390 if string.is_empty() {
3391 return Err(ScanError::from_kind(
3392 start_mark,
3393 ErrorKind::MissingAnchorOrAliasName,
3394 ));
3395 }
3396
3397 let tok = if alias {
3398 TokenType::Alias {
3399 name: string.into(),
3400 }
3401 } else {
3402 TokenType::Anchor {
3403 name: string.into(),
3404 }
3405 };
3406 Ok(Token(Span::new(start_mark, self.mark), tok))
3407 }
3408
3409 fn fetch_flow_collection_start(&mut self, tok: TokenType<'input>) -> ScanResult {
3410 self.save_simple_key();
3412
3413 let start_mark = self.mark;
3414 let indicator = self.input.peek();
3415 self.flow_markers.push((start_mark, indicator));
3416
3417 self.roll_one_col_indent();
3418 self.increase_flow_level()?;
3419
3420 self.allow_simple_key();
3421
3422 self.skip_non_blank();
3423 let end_mark = self.mark;
3424
3425 if matches!(tok, TokenType::FlowMappingStart) {
3426 self.flow_mapping_started.push(true);
3427 } else {
3428 self.flow_mapping_started.push(false);
3429 self.implicit_flow_mapping_states
3430 .push(ImplicitMappingState::Possible);
3431 }
3432
3433 let token_index = self.tokens.len();
3434 self.skip_ws_to_eol(SkipTabs::Yes)?;
3435
3436 self.insert_token(token_index, Token(Span::new(start_mark, end_mark), tok));
3437 Ok(())
3438 }
3439
3440 fn fetch_flow_collection_end(
3441 &mut self,
3442 tok: TokenType<'input>,
3443 expected_open: char,
3444 actual_close: char,
3445 ) -> ScanResult {
3446 if self.flow_level == 0 {
3448 return Err(self.scan_error(ErrorKind::MisplacedFlowCollectionEnd));
3449 }
3450
3451 let Some((open_mark, open_ch)) = self.flow_markers.pop() else {
3452 return Err(self.scan_error(ErrorKind::MisplacedFlowCollectionEnd));
3453 };
3454
3455 if open_ch != expected_open {
3456 return Err(ScanError::from_kind(
3457 open_mark,
3458 ErrorKind::MismatchedFlowCollectionEnd {
3459 open: open_ch,
3460 close: actual_close,
3461 },
3462 ));
3463 }
3464
3465 let flow_level = self.flow_level;
3466
3467 self.remove_simple_key()?;
3468
3469 if matches!(tok, TokenType::FlowSequenceEnd) {
3470 self.end_implicit_mapping(self.mark, flow_level);
3471 self.implicit_flow_mapping_states.pop();
3473 }
3474 self.flow_mapping_started.pop();
3475
3476 self.decrease_flow_level();
3477
3478 self.disallow_simple_key();
3479
3480 let start_mark = self.mark;
3481 self.skip_non_blank();
3482 let end_mark = self.mark;
3483 let token_index = self.tokens.len();
3484 self.skip_ws_to_eol(SkipTabs::Yes)?;
3485
3486 if self.flow_level > 0 {
3492 self.adjacent_value_allowed_at = self.mark.index();
3493 }
3494
3495 self.insert_token(token_index, Token(Span::new(start_mark, end_mark), tok));
3496 Ok(())
3497 }
3498
3499 fn fetch_flow_entry(&mut self) -> ScanResult {
3501 self.remove_simple_key()?;
3502 self.allow_simple_key();
3503
3504 self.end_implicit_mapping(self.mark, self.flow_level);
3505 if self.current_flow_collection_is_sequence() {
3506 self.set_current_flow_mapping_started(false);
3507 }
3508
3509 let start_mark = self.mark;
3510 self.skip_non_blank();
3511 let end_mark = self.mark;
3512 let token_index = self.tokens.len();
3513 self.skip_ws_to_eol(SkipTabs::Yes)?;
3514
3515 self.insert_token(
3516 token_index,
3517 Token(Span::new(start_mark, end_mark), TokenType::FlowEntry),
3518 );
3519 Ok(())
3520 }
3521
3522 fn increase_flow_level(&mut self) -> ScanResult {
3523 if self.flow_level >= self.options.flow_nesting_limit {
3524 return Err(self.scan_error(ErrorKind::RecursionLimitExceeded));
3525 }
3526
3527 self.simple_keys.push(SimpleKey::new(Marker::new(0, 0, 0)));
3528 self.flow_level += 1;
3529 Ok(())
3530 }
3531
3532 fn decrease_flow_level(&mut self) {
3533 if self.flow_level > 0 {
3534 debug_assert!(!self.simple_keys.last().unwrap().possible);
3536 debug_assert_ne!(self.first_simple_key, Some(self.flow_level));
3537 self.flow_level -= 1;
3538 self.simple_keys.pop().unwrap();
3539 }
3540 }
3541
3542 fn fetch_block_entry(&mut self) -> ScanResult {
3548 if self.flow_level > 0 {
3549 return Err(self.scan_error(ErrorKind::BlockEntryInFlowCollection));
3551 }
3552 if !self.simple_key_allowed {
3554 return Err(self.scan_error(ErrorKind::BlockSequenceEntryNotAllowed));
3555 }
3556
3557 let mark = self.mark;
3559 self.skip_non_blank();
3560
3561 self.roll_indent(mark.col, None, TokenType::BlockSequenceStart, mark)?;
3563 let token_index = self.tokens.len();
3564 let found_tabs = self.skip_ws_to_eol(SkipTabs::Yes)?.found_tabs();
3565 self.input.lookahead(2);
3566 if found_tabs && self.input.next_char_is('-') && is_blank_or_breakz(self.input.peek_nth(1))
3567 {
3568 return Err(self.scan_error(ErrorKind::InvalidBlockEntryWhitespace));
3569 }
3570
3571 self.skip_ws_to_eol(SkipTabs::No)?;
3572 self.input.lookahead(1);
3573 if self.input.next_is_break() || self.input.next_is_flow() {
3574 self.roll_one_col_indent();
3575 }
3576
3577 self.remove_simple_key()?;
3578 self.allow_simple_key();
3579
3580 self.insert_token(
3581 token_index,
3582 Token(Span::empty(self.mark), TokenType::BlockEntry),
3583 );
3584
3585 Ok(())
3586 }
3587
3588 fn fetch_document_indicator(&mut self, t: TokenType<'input>) -> ScanResult {
3589 self.in_directive_prefix = false;
3590 if let Some((mark, bracket)) = self.flow_markers.pop() {
3591 return Err(ScanError::from_kind(
3592 mark,
3593 ErrorKind::UnclosedFlowCollection { open: bracket },
3594 ));
3595 }
3596
3597 self.unroll_indent(-1);
3598 self.remove_simple_key()?;
3599 self.disallow_simple_key();
3600
3601 let mark = self.mark;
3602
3603 self.skip_n_non_blank(3);
3604
3605 self.document_prefix_allowed = matches!(t, TokenType::DocumentEnd);
3606 self.tokens
3607 .push_back(Token(Span::new(mark, self.mark), t).into());
3608 Ok(())
3609 }
3610
3611 fn fetch_block_scalar(&mut self, literal: bool) -> ScanResult {
3612 self.save_simple_key();
3613 self.allow_simple_key();
3614 let token_index = self.tokens.len();
3615 let tok = self.scan_block_scalar(literal)?;
3616
3617 self.insert_token(token_index, tok);
3618 Ok(())
3619 }
3620
3621 #[allow(clippy::too_many_lines)]
3622 fn scan_block_scalar(&mut self, literal: bool) -> Result<Token<'input>, ScanError> {
3623 let start_mark = self.mark;
3624 #[cfg(feature = "extended_details")]
3625 let header_start = start_mark;
3626 #[cfg(feature = "extended_details")]
3627 let mut digit_first = false;
3628 let mut chomping = Chomping::Clip;
3629 let mut increment: u8 = 0;
3630 let mut indent: usize = 0;
3631 let mut trailing_blank: bool;
3632 let mut leading_blank: bool = false;
3633
3634 let mut string = String::new();
3635 let mut leading_break = false;
3636 let mut trailing_breaks = 0;
3637 let mut chomping_break = false;
3638
3639 self.skip_non_blank();
3641 self.unroll_non_block_indents();
3642
3643 if self.input.look_ch() == '+' || self.input.peek() == '-' {
3644 if self.input.peek() == '+' {
3645 chomping = Chomping::Keep;
3646 } else {
3647 chomping = Chomping::Strip;
3648 }
3649 self.skip_non_blank();
3650 self.input.lookahead(1);
3651 if self.input.next_is_digit() {
3652 if self.input.peek() == '0' {
3653 return Err(ScanError::from_kind(
3654 start_mark,
3655 ErrorKind::ZeroBlockScalarIndent,
3656 ));
3657 }
3658 increment = (self.input.peek() as u8) - b'0';
3659 self.skip_non_blank();
3660 }
3661 } else if self.input.next_is_digit() {
3662 if self.input.peek() == '0' {
3663 return Err(ScanError::from_kind(
3664 start_mark,
3665 ErrorKind::ZeroBlockScalarIndent,
3666 ));
3667 }
3668
3669 increment = (self.input.peek() as u8) - b'0';
3670 self.skip_non_blank();
3671 self.input.lookahead(1);
3672 if self.input.peek() == '+' || self.input.peek() == '-' {
3673 #[cfg(feature = "extended_details")]
3674 {
3675 digit_first = true;
3676 }
3677 if self.input.peek() == '+' {
3678 chomping = Chomping::Keep;
3679 } else {
3680 chomping = Chomping::Strip;
3681 }
3682 self.skip_non_blank();
3683 }
3684 }
3685
3686 self.skip_ws_to_eol(SkipTabs::Yes)?;
3687
3688 self.input.lookahead(1);
3690 self.ensure_current_char_is_printable()?;
3691 if !self.input.next_is_breakz() {
3692 return Err(ScanError::from_kind(
3693 start_mark,
3694 ErrorKind::InvalidBlockScalarHeader,
3695 ));
3696 }
3697
3698 if self.input.next_is_break() {
3699 self.input.lookahead(2);
3700 self.skip_break();
3701 chomping_break = true;
3702 }
3703
3704 self.ensure_current_char_is_printable()?;
3705
3706 if self.input.look_ch() == '\t' {
3707 return Err(ScanError::from_kind(
3708 start_mark,
3709 ErrorKind::TabAtBlockScalarStart,
3710 ));
3711 }
3712
3713 if increment > 0 {
3714 indent = if self.indent >= 0 {
3715 (self.indent + isize::from(increment)) as usize
3716 } else {
3717 usize::from(increment)
3718 }
3719 }
3720
3721 if indent == 0 {
3723 self.skip_block_scalar_first_line_indent(&mut indent, &mut trailing_breaks);
3724 } else {
3725 self.skip_block_scalar_indent(indent, &mut trailing_breaks);
3726 }
3727
3728 let indent_floor_applied = self.options.block_scalar_indent_at_least_one && indent == 0;
3731 if indent_floor_applied {
3732 indent = 1;
3733 }
3734
3735 #[cfg(feature = "extended_details")]
3739 let syntax = {
3740 let content_indent = if increment == 0 && self.mark.line() == header_start.line() {
3741 (self.indent + 1).max(0) as usize
3742 } else {
3743 indent
3744 };
3745 BlockScalarSyntax::new(
3746 chomping,
3747 (increment > 0).then_some(increment),
3748 content_indent,
3749 )
3750 .map(|mut syntax| {
3751 syntax.digit_first = digit_first;
3752 syntax
3753 })
3754 };
3755 self.ensure_current_char_is_printable()?;
3756
3757 if self.input.next_is_z() {
3762 let contents = match chomping {
3763 Chomping::Strip => String::new(),
3765 _ if self.mark.line == start_mark.line() => String::new(),
3767 Chomping::Clip => String::new(),
3769 Chomping::Keep if trailing_breaks == 0 && self.mark.col > 0 => {
3772 if chomping_break && !self.options.block_scalar_eof_without_line_feed {
3773 "\n".into()
3774 } else {
3775 String::new()
3776 }
3777 }
3778 Chomping::Keep => "\n".repeat(trailing_breaks),
3780 };
3781
3782 let style = if literal {
3783 ScalarStyle::literal()
3784 } else {
3785 ScalarStyle::folded()
3786 };
3787 #[cfg(feature = "extended_details")]
3788 let style = syntax.map_or(style, |syntax| style.with_block_syntax(syntax));
3789 return Ok(Token(
3790 Span::new(start_mark, self.mark),
3791 TokenType::Scalar {
3792 style,
3793 value: contents.into(),
3794 },
3795 ));
3796 }
3797
3798 if !indent_floor_applied && self.mark.col < indent && (self.mark.col as isize) > self.indent
3799 {
3800 if self.indent < 0 && self.mark.col == 0 {
3801 self.input.lookahead(4);
3802 if self.input.next_is_document_start()
3803 || self.input.next_is_document_end()
3804 || self.input.peek() == '#'
3805 {
3806 } else {
3810 return Err(self.scan_error(ErrorKind::InvalidBlockScalarIndent));
3811 }
3812 } else {
3813 return Err(self.scan_error(ErrorKind::InvalidBlockScalarIndent));
3814 }
3815 }
3816
3817 let start_mark = self.mark;
3818 #[cfg(feature = "extended_details")]
3819 let syntax = syntax.and_then(|syntax| {
3820 let header_chars_before_span = start_mark.index() - header_start.index();
3821 let header_bytes_before_span = start_mark
3822 .byte_offset()
3823 .zip(header_start.byte_offset())
3824 .map_or(0, |(body, header)| body - header);
3825 syntax.with_header_offsets(header_chars_before_span, header_bytes_before_span)
3826 });
3827 while self.mark.col == indent && !self.input.next_is_z() {
3828 self.ensure_current_char_is_printable()?;
3829
3830 if indent == 0 {
3831 self.input.lookahead(4);
3832 if self.input.next_is_document_indicator() {
3833 break;
3834 }
3835 }
3836
3837 trailing_blank = self.input.next_is_blank();
3839 if !literal && leading_break && !leading_blank && !trailing_blank {
3840 string.extend(core::iter::repeat('\n').take(trailing_breaks));
3841 if trailing_breaks == 0 {
3842 string.push(' ');
3843 }
3844 } else {
3845 if leading_break {
3846 string.push('\n');
3847 }
3848 string.extend(core::iter::repeat('\n').take(trailing_breaks));
3849 }
3850
3851 leading_break = false;
3852 trailing_breaks = 0;
3853
3854 leading_blank = self.input.next_is_blank();
3855
3856 self.scan_block_scalar_content_line(&mut string);
3857
3858 self.input.lookahead(2);
3860 if self.input.next_is_z() {
3861 break;
3862 }
3863
3864 self.ensure_current_char_is_printable()?;
3865
3866 self.skip_break();
3867 leading_break = true;
3868
3869 self.skip_block_scalar_indent(indent, &mut trailing_breaks);
3871 }
3872
3873 self.ensure_current_char_is_printable()?;
3874
3875 if chomping != Chomping::Strip {
3877 if !leading_break
3884 && !self.options.block_scalar_eof_without_line_feed
3885 && self.input.next_is_z()
3886 && self.mark.col >= indent.max(1)
3887 {
3888 string.push('\n');
3889 }
3890 if leading_break {
3891 string.push('\n');
3892 }
3893 }
3894
3895 if chomping == Chomping::Keep {
3896 string.extend(core::iter::repeat('\n').take(trailing_breaks));
3897 }
3898
3899 if let Some(character) = find_non_printable(&string) {
3900 return Err(ScanError::from_kind(
3901 start_mark,
3902 ErrorKind::UnexpectedCharacter { character },
3903 ));
3904 }
3905
3906 let span = if string.trim().is_empty() {
3907 Span::new(start_mark, self.mark)
3908 } else {
3909 Span::new(start_mark, self.mark).with_indent(Some(indent))
3910 };
3911
3912 let style = if literal {
3913 ScalarStyle::literal()
3914 } else {
3915 ScalarStyle::folded()
3916 };
3917 #[cfg(feature = "extended_details")]
3918 let style = syntax.map_or(style, |syntax| style.with_block_syntax(syntax));
3919 Ok(Token(
3920 span,
3921 TokenType::Scalar {
3922 style,
3923 value: string.into(),
3924 },
3925 ))
3926 }
3927
3928 fn scan_block_scalar_content_line(&mut self, string: &mut String) {
3933 let chars_consumed = self.input.fetch_block_scalar_line(string);
3934 self.mark.col += chars_consumed;
3935 self.mark.offsets.chars += chars_consumed;
3936 self.mark.offsets.bytes = self.input.byte_offset();
3937 }
3940
3941 fn skip_block_scalar_indent(&mut self, indent: usize, breaks: &mut usize) {
3943 loop {
3944 if indent < self.input.bufmaxlen().saturating_sub(2) {
3946 self.input.lookahead(self.input.bufmaxlen());
3947 while self.mark.col < indent && self.input.peek() == ' ' {
3948 self.skip_blank();
3949 }
3950 } else {
3951 loop {
3952 self.input.lookahead(self.input.bufmaxlen());
3953 while !self.input.buf_is_empty()
3954 && self.mark.col < indent
3955 && self.input.peek() == ' '
3956 {
3957 self.skip_blank();
3958 }
3959 if self.mark.col == indent
3963 || (!self.input.buf_is_empty() && self.input.peek() != ' ')
3964 {
3965 break;
3966 }
3967 }
3968 self.input.lookahead(2);
3969 }
3970
3971 if self.input.next_is_break() {
3973 self.skip_break();
3974 *breaks += 1;
3975 } else {
3976 break;
3978 }
3979 }
3980 }
3981
3982 fn skip_block_scalar_first_line_indent(&mut self, indent: &mut usize, breaks: &mut usize) {
3987 let mut max_indent = 0;
3988 loop {
3989 while self.input.look_ch() == ' ' {
3991 self.skip_blank();
3992 }
3993
3994 if self.mark.col > max_indent {
3995 max_indent = self.mark.col;
3996 }
3997
3998 if self.input.next_is_break() {
3999 self.input.lookahead(2);
4001 self.skip_break();
4002 *breaks += 1;
4003 } else {
4004 break;
4006 }
4007 }
4008
4009 *indent = max_indent.max((self.indent + 1) as usize);
4018 }
4019
4020 fn fetch_flow_scalar(&mut self, single: bool) -> ScanResult {
4021 self.save_simple_key();
4022 self.disallow_simple_key();
4023
4024 let token_index = self.tokens.len();
4025 let tok = self.scan_flow_scalar(single)?;
4026
4027 if self.skip_to_next_token()?.saw_comment {
4030 self.adjacent_value_allowed_at = usize::MAX;
4031 } else {
4032 self.adjacent_value_allowed_at = self.mark.index();
4033 }
4034
4035 self.insert_token(token_index, tok);
4036 Ok(())
4037 }
4038
4039 #[allow(clippy::too_many_lines)]
4040 fn scan_flow_scalar(&mut self, single: bool) -> Result<Token<'input>, ScanError> {
4041 let start_mark = self.mark;
4042
4043 let mut buf = match self.input.byte_offset() {
4045 Some(off) => FlowScalarBuf::new_borrowed(off + self.input.peek().len_utf8()),
4046 None => FlowScalarBuf::new_owned(),
4047 };
4048
4049 self.skip_non_blank();
4051
4052 loop {
4053 self.input.lookahead(4);
4055
4056 if self.mark.col == 0 && self.input.next_is_document_indicator() {
4057 return Err(ScanError::from_kind(
4058 start_mark,
4059 ErrorKind::DocumentIndicatorInQuotedScalar,
4060 ));
4061 }
4062
4063 if self.input.next_is_z() {
4064 return Err(ScanError::from_kind(
4065 start_mark,
4066 ErrorKind::UnclosedQuotedScalar,
4067 ));
4068 }
4069
4070 self.ensure_current_char_is_printable()?;
4071
4072 let mut leading_blanks = false;
4074 self.consume_flow_scalar_non_whitespace_chars(
4075 single,
4076 &mut buf,
4077 &mut leading_blanks,
4078 &start_mark,
4079 )?;
4080
4081 match self.input.look_ch() {
4082 '\'' if single && !leading_blanks => break,
4083 '"' if !single && !leading_blanks => break,
4084 _ => {}
4085 }
4086
4087 let mut trailing_ws_start: Option<usize> = None;
4103 let mut has_leading_break = false;
4104 let mut has_trailing_breaks = false;
4105
4106 let mut pending_ws_start: Option<usize> = None;
4108
4109 while self.input.next_is_blank() || self.input.next_is_break() {
4111 if self.input.next_is_blank() {
4112 if leading_blanks {
4114 if self.options.strict_indentation && self.input.peek() == '\t' {
4117 let indent = if self.flow_level > 0 {
4118 self.flow_block_indent() + 1
4119 } else {
4120 self.indent
4121 };
4122 if (self.mark.col as isize) < indent {
4123 return Err(self.scan_error(ErrorKind::TabInIndentation));
4124 }
4125 }
4126 self.skip_blank();
4127 } else {
4128 match buf {
4130 FlowScalarBuf::Owned(ref mut string) => {
4131 if trailing_ws_start.is_none() {
4132 trailing_ws_start = Some(string.len());
4133 }
4134 string.push(self.input.peek());
4135 }
4136 FlowScalarBuf::Borrowed { .. } => {
4137 if pending_ws_start.is_none() {
4138 pending_ws_start = self.input.byte_offset();
4139 }
4140 }
4141 }
4142 self.skip_blank();
4143
4144 if let (FlowScalarBuf::Borrowed { .. }, Some(ws_start), Some(ws_end)) =
4145 (&mut buf, pending_ws_start, self.input.byte_offset())
4146 {
4147 buf.note_pending_ws(ws_start, ws_end);
4148 }
4149 }
4150 } else {
4151 self.input.lookahead(2);
4152
4153 if leading_blanks {
4155 match buf {
4157 FlowScalarBuf::Owned(ref mut string) => self.read_break(string),
4158 FlowScalarBuf::Borrowed { .. } => {
4159 self.promote_flow_scalar_buf_to_owned(&start_mark, &mut buf)?;
4160 let Some(string) = buf.as_owned_mut() else {
4161 unreachable!()
4162 };
4163 self.read_break(string);
4164 }
4165 }
4166 has_trailing_breaks = true;
4167 } else {
4168 if let Some(pos) = trailing_ws_start.take() {
4170 if let FlowScalarBuf::Owned(ref mut string) = buf {
4171 string.truncate(pos);
4172 }
4173 }
4174
4175 if pending_ws_start.take().is_some() {
4176 if matches!(buf, FlowScalarBuf::Borrowed { .. }) {
4178 self.promote_flow_scalar_buf_to_owned(&start_mark, &mut buf)?;
4179 }
4180 buf.discard_pending_ws();
4181 } else {
4182 buf.commit_pending_ws();
4183 }
4184
4185 self.skip_break();
4186
4187 has_leading_break = true;
4188 leading_blanks = true;
4189 }
4190 }
4191
4192 self.input.lookahead(1);
4193 }
4194
4195 if leading_blanks
4199 && self.options.strict_indentation
4200 && (self.mark.col as isize) <= self.flow_block_indent()
4201 {
4202 let kind = if has_leading_break && self.flow_level == 0 {
4203 ErrorKind::InvalidQuotedScalarIndent
4204 } else {
4205 ErrorKind::InvalidIndentation
4206 };
4207 return Err(self.scan_error(kind));
4208 }
4209
4210 if leading_blanks {
4212 if has_leading_break && !has_trailing_breaks {
4217 match buf {
4218 FlowScalarBuf::Owned(ref mut string) => string.push(' '),
4219 FlowScalarBuf::Borrowed { .. } => {
4220 self.promote_flow_scalar_buf_to_owned(&start_mark, &mut buf)?;
4221 let Some(string) = buf.as_owned_mut() else {
4222 unreachable!()
4223 };
4224 string.push(' ');
4225 }
4226 }
4227 }
4228 }
4229 } self.skip_non_blank();
4234 let end_mark = self.mark;
4235
4236 self.skip_ws_to_eol(SkipTabs::Yes)?;
4238 self.ensure_current_char_is_printable()?;
4239 match self.input.peek() {
4240 ',' | '}' | ']' if self.flow_level > 0 => {}
4242 c if is_breakz(c) => {}
4244 ':' if self.flow_level == 0 && start_mark.line == self.mark.line => {}
4247 ':' if self.flow_level > 0 => {}
4249 _ => {
4250 let kind = if single {
4251 ErrorKind::InvalidTrailingSingleQuotedScalar
4252 } else {
4253 ErrorKind::InvalidTrailingDoubleQuotedScalar
4254 };
4255 return Err(self.scan_error(kind));
4256 }
4257 }
4258
4259 let style = if single {
4260 ScalarStyle::SingleQuoted
4261 } else {
4262 ScalarStyle::DoubleQuoted
4263 };
4264
4265 let contents = match buf {
4266 FlowScalarBuf::Owned(string) => Cow::Owned(string),
4267 FlowScalarBuf::Borrowed {
4268 start,
4269 mut end,
4270 pending_ws_start,
4271 pending_ws_end,
4272 } => {
4273 if pending_ws_start.is_some() {
4275 end = pending_ws_end;
4276 }
4277 if let Some(slice) = self.try_borrow_slice(start, end) {
4278 Cow::Borrowed(slice)
4279 } else {
4280 let slice = self.input.slice_bytes(start, end).ok_or_else(|| {
4281 ScanError::from_kind(start_mark, ErrorKind::InputOffsetsWithoutSlice)
4282 })?;
4283 Cow::Owned(slice.to_owned())
4284 }
4285 }
4286 };
4287
4288 Ok(Token(
4289 Span::new(start_mark, end_mark),
4290 TokenType::Scalar {
4291 style,
4292 value: contents,
4293 },
4294 ))
4295 }
4296
4297 fn consume_flow_scalar_chunk(&mut self, single: bool, buf: &mut FlowScalarBuf) -> bool {
4299 let (chunk, consumed) = self.input.take_quoted_scalar_chunk(single);
4300 if consumed == 0 {
4301 return false;
4302 }
4303
4304 match buf {
4305 FlowScalarBuf::Owned(string) => string.push_str(chunk),
4306 FlowScalarBuf::Borrowed { .. } => buf.commit_pending_ws(),
4307 }
4308
4309 self.mark.offsets.chars += consumed;
4311 self.mark.col += consumed;
4312 self.mark.offsets.bytes = self.input.byte_offset();
4313 self.leading_whitespace = false;
4314 if let (Some(new_end), FlowScalarBuf::Borrowed { end, .. }) = (self.mark.offsets.bytes, buf)
4315 {
4316 *end = new_end;
4317 }
4318 true
4319 }
4320
4321 fn consume_flow_scalar_non_whitespace_chars(
4330 &mut self,
4331 single: bool,
4332 buf: &mut FlowScalarBuf,
4333 leading_blanks: &mut bool,
4334 start_mark: &Marker,
4335 ) -> Result<(), ScanError> {
4336 self.input.lookahead(2);
4337 loop {
4338 let character = self.input.peek();
4339 if is_blank_or_breakz(character) || !is_printable(character) {
4340 break;
4341 }
4342 match character {
4343 '\'' if self.input.peek_nth(1) == '\'' && single => {
4345 if matches!(buf, FlowScalarBuf::Borrowed { .. }) {
4346 buf.commit_pending_ws();
4347 self.promote_flow_scalar_buf_to_owned(start_mark, buf)?;
4348 }
4349 let Some(string) = buf.as_owned_mut() else {
4350 unreachable!()
4351 };
4352 string.push('\'');
4353 self.skip_n_non_blank(2);
4354 }
4355 '\'' if single => break,
4357 '"' if !single => break,
4358 '\\' if !single && is_break(self.input.peek_nth(1)) => {
4360 self.input.lookahead(3);
4361 if matches!(buf, FlowScalarBuf::Borrowed { .. }) {
4362 buf.commit_pending_ws();
4363 self.promote_flow_scalar_buf_to_owned(start_mark, buf)?;
4364 }
4365 self.skip_non_blank();
4366 self.skip_linebreak();
4367 *leading_blanks = true;
4368 break;
4369 }
4370 '\\' if !single => {
4372 if matches!(buf, FlowScalarBuf::Borrowed { .. }) {
4373 buf.commit_pending_ws();
4374 self.promote_flow_scalar_buf_to_owned(start_mark, buf)?;
4375 }
4376 let Some(string) = buf.as_owned_mut() else {
4377 unreachable!()
4378 };
4379 string.push(self.resolve_flow_scalar_escape_sequence(start_mark)?);
4380 }
4381 c => {
4382 if self.consume_flow_scalar_chunk(single, buf) {
4383 self.input.lookahead(2);
4384 continue;
4385 }
4386 match buf {
4387 FlowScalarBuf::Owned(ref mut string) => {
4388 string.push(c);
4389 }
4390 FlowScalarBuf::Borrowed { .. } => {
4391 buf.commit_pending_ws();
4392 }
4393 }
4394 self.skip_non_blank();
4395
4396 if let Some(new_end) = self.input.byte_offset() {
4397 if let FlowScalarBuf::Borrowed { end, .. } = buf {
4398 *end = new_end;
4399 }
4400 }
4401 }
4402 }
4403 self.input.lookahead(2);
4404 }
4405 Ok(())
4406 }
4407
4408 fn resolve_flow_scalar_escape_sequence(
4415 &mut self,
4416 start_mark: &Marker,
4417 ) -> Result<char, ScanError> {
4418 let mut code_length = 0usize;
4419 let mut ret = '\0';
4420
4421 match self.input.peek_nth(1) {
4422 '0' => ret = '\0',
4423 'a' => ret = '\x07',
4424 'b' => ret = '\x08',
4425 't' | '\t' => ret = '\t',
4426 'n' => ret = '\n',
4427 'v' => ret = '\x0b',
4428 'f' => ret = '\x0c',
4429 'r' => ret = '\x0d',
4430 'e' => ret = '\x1b',
4431 ' ' => ret = '\x20',
4432 '"' => ret = '"',
4433 '/' => ret = '/',
4434 '\\' => ret = '\\',
4435 'N' => ret = char::from_u32(0x85).unwrap(),
4437 '_' => ret = char::from_u32(0xA0).unwrap(),
4439 'L' => ret = char::from_u32(0x2028).unwrap(),
4441 'P' => ret = char::from_u32(0x2029).unwrap(),
4443 'x' => code_length = 2,
4444 'u' => code_length = 4,
4445 'U' => code_length = 8,
4446 _ => {
4447 return Err(ScanError::from_kind(
4448 *start_mark,
4449 ErrorKind::UnknownQuotedScalarEscape,
4450 ))
4451 }
4452 }
4453 self.skip_n_non_blank(2);
4454
4455 if code_length > 0 {
4457 self.input.lookahead(code_length);
4458 let mut value = 0u32;
4459 for i in 0..code_length {
4460 let c = self.input.peek_nth(i);
4461 if !is_hex(c) {
4462 return Err(ScanError::from_kind(
4463 *start_mark,
4464 ErrorKind::InvalidQuotedScalarHexEscape,
4465 ));
4466 }
4467 value = (value << 4) + as_hex(c);
4468 }
4469
4470 self.skip_n_non_blank(code_length);
4471
4472 if code_length == 4 && (0xD800..=0xDBFF).contains(&value) {
4474 self.input.lookahead(2);
4475 if self.input.peek() == '\\' && self.input.peek_nth(1) == 'u' {
4476 self.skip_n_non_blank(2);
4477 self.input.lookahead(4);
4478 let mut low_value = 0u32;
4479 for i in 0..4 {
4480 let c = self.input.peek_nth(i);
4481 if !is_hex(c) {
4482 return Err(ScanError::from_kind(
4483 *start_mark,
4484 ErrorKind::InvalidLowSurrogateHexEscape,
4485 ));
4486 }
4487 low_value = (low_value << 4) + as_hex(c);
4488 }
4489 if (0xDC00..=0xDFFF).contains(&low_value) {
4490 value = 0x10000 + (((value - 0xD800) << 10) | (low_value - 0xDC00));
4491 self.skip_n_non_blank(4);
4492 } else {
4493 return Err(ScanError::from_kind(
4494 *start_mark,
4495 ErrorKind::InvalidLowSurrogate,
4496 ));
4497 }
4498 } else {
4499 return Err(ScanError::from_kind(
4500 *start_mark,
4501 ErrorKind::MissingLowSurrogate,
4502 ));
4503 }
4504 } else if code_length == 4 && (0xDC00..=0xDFFF).contains(&value) {
4505 return Err(ScanError::from_kind(
4506 *start_mark,
4507 ErrorKind::UnpairedLowSurrogate,
4508 ));
4509 }
4510
4511 let Some(ch) = char::from_u32(value) else {
4512 return Err(ScanError::from_kind(
4513 *start_mark,
4514 ErrorKind::InvalidUnicodeEscape,
4515 ));
4516 };
4517 ret = ch;
4518 }
4519 Ok(ret)
4520 }
4521
4522 fn fetch_plain_scalar(&mut self) -> ScanResult {
4523 self.save_simple_key();
4524 self.disallow_simple_key();
4525
4526 let token_index = self.tokens.len();
4527 let tok = self.scan_plain_scalar()?;
4528
4529 self.insert_token(token_index, tok);
4530 Ok(())
4531 }
4532
4533 #[allow(clippy::too_many_lines)]
4538 fn scan_plain_scalar(&mut self) -> Result<Token<'input>, ScanError> {
4539 self.unroll_non_block_indents();
4540 let indent = self.indent + 1;
4541 let start_mark = self.mark;
4542
4543 let borrow_start = start_mark
4544 .byte_offset()
4545 .filter(|start| self.try_borrow_slice(*start, *start).is_some());
4546 let mut string = borrow_start.is_none().then(|| String::with_capacity(32));
4547 let mut has_content = false;
4548 self.buf_whitespaces.clear();
4549 self.buf_leading_break.clear();
4550 self.buf_trailing_breaks.clear();
4551 let mut end_mark = self.mark;
4552
4553 loop {
4554 self.input.lookahead(4);
4555 if (self.mark.col == 0 && self.input.next_is_document_indicator())
4556 || self.input.peek() == '#'
4557 {
4558 if self.input.peek() == '#'
4563 && has_content
4564 && !self.buf_whitespaces.is_empty()
4565 && self.flow_level == 0
4566 {
4567 self.interrupted_plain_by_comment = Some(self.mark);
4568 }
4569 break;
4570 }
4571
4572 if !has_content
4574 && self.flow_level > 0
4575 && self.input.peek() == '-'
4576 && is_flow(self.input.peek_nth(1))
4577 {
4578 return Err(self.scan_error(ErrorKind::PlainScalarStartsWithDashFlowIndicator));
4579 }
4580
4581 if !self.input.next_is_blank_or_breakz()
4582 && self.input.next_can_be_plain_scalar(self.flow_level > 0)
4583 {
4584 if self.leading_whitespace {
4585 if has_content && string.is_none() {
4586 let start = borrow_start.expect("borrowed scalar has a start offset");
4587 let end = end_mark.byte_offset().ok_or_else(|| {
4588 ScanError::from_kind(start_mark, ErrorKind::InputOffsetsWithoutSlice)
4589 })?;
4590 let prefix = self.try_borrow_slice(start, end).ok_or_else(|| {
4591 ScanError::from_kind(start_mark, ErrorKind::InputOffsetsWithoutSlice)
4592 })?;
4593 string = Some(prefix.to_owned());
4594 }
4595 if self.buf_leading_break.is_empty() {
4596 if let Some(output) = string.as_mut() {
4597 output.push_str(&self.buf_leading_break);
4598 output.push_str(&self.buf_trailing_breaks);
4599 }
4600 self.buf_trailing_breaks.clear();
4601 self.buf_leading_break.clear();
4602 } else {
4603 if self.buf_trailing_breaks.is_empty() {
4604 if let Some(output) = string.as_mut() {
4605 output.push(' ');
4606 }
4607 } else {
4608 if let Some(output) = string.as_mut() {
4609 output.push_str(&self.buf_trailing_breaks);
4610 }
4611 self.buf_trailing_breaks.clear();
4612 }
4613 self.buf_leading_break.clear();
4614 }
4615 self.leading_whitespace = false;
4616 } else if !self.buf_whitespaces.is_empty() {
4617 if let Some(output) = string.as_mut() {
4618 output.push_str(&self.buf_whitespaces);
4619 }
4620 self.buf_whitespaces.clear();
4621 }
4622
4623 has_content = true;
4625 if let Some(output) = string.as_mut() {
4626 output.push(self.input.peek());
4627 }
4628 self.skip_non_blank();
4629 if let Some(output) = string.as_mut() {
4630 output.reserve(self.input.bufmaxlen());
4631 }
4632
4633 let mut end = false;
4635 while !end {
4636 self.input.lookahead(self.input.bufmaxlen());
4641 let chunk_len = self.input.bufmaxlen().saturating_sub(1).max(1);
4642 let (stop, chars_consumed) = if let Some(output) = string.as_mut() {
4643 self.input
4644 .fetch_plain_scalar_chunk(output, chunk_len, self.flow_level > 0)
4645 } else {
4646 self.input
4647 .skip_plain_scalar_chunk(chunk_len, self.flow_level > 0)
4648 };
4649 end = stop;
4650 self.mark.offsets.chars += chars_consumed;
4651 self.mark.col += chars_consumed;
4652 self.mark.offsets.bytes = self.input.byte_offset();
4653 }
4654 end_mark = self.mark;
4655 }
4656
4657 if !(self.input.next_is_blank() || self.input.next_is_break()) {
4662 break;
4663 }
4664
4665 self.input.lookahead(2);
4667 while self.input.next_is_blank_or_break() {
4668 if self.input.next_is_blank() {
4669 if !self.leading_whitespace {
4670 self.buf_whitespaces.push(self.input.peek());
4671 self.skip_blank();
4672 } else if (self.mark.col as isize) < indent && self.input.peek() == '\t' {
4673 self.skip_ws_to_eol(SkipTabs::Yes)?;
4676 if !self.input.next_is_breakz() {
4677 return Err(ScanError::from_kind(
4678 start_mark,
4679 ErrorKind::TabInPlainScalar,
4680 ));
4681 }
4682 } else {
4683 self.skip_blank();
4684 }
4685 } else {
4686 if self.leading_whitespace {
4688 self.skip_break();
4689 self.buf_trailing_breaks.push('\n');
4690 } else {
4691 self.buf_whitespaces.clear();
4692 self.skip_break();
4693 self.buf_leading_break.push('\n');
4694 self.leading_whitespace = true;
4695 }
4696 }
4697 self.input.lookahead(2);
4698 }
4699
4700 if (self.flow_level == 0 || self.options.strict_indentation)
4703 && (self.mark.col as isize) < indent
4704 {
4705 break;
4706 }
4707 }
4708
4709 if self.leading_whitespace {
4710 self.allow_simple_key();
4711 }
4712
4713 let borrowed_contents = if string.is_none() {
4714 let start = borrow_start.expect("borrowed scalar has a start offset");
4715 let end = end_mark.byte_offset().ok_or_else(|| {
4716 ScanError::from_kind(start_mark, ErrorKind::InputOffsetsWithoutSlice)
4717 })?;
4718 Some(self.try_borrow_slice(start, end).ok_or_else(|| {
4719 ScanError::from_kind(start_mark, ErrorKind::InputOffsetsWithoutSlice)
4720 })?)
4721 } else {
4722 None
4723 };
4724 let scalar_text = borrowed_contents.unwrap_or_else(|| {
4725 string
4726 .as_deref()
4727 .expect("owned plain scalar has an output buffer")
4728 });
4729 if let Some(character) = find_non_printable(scalar_text) {
4730 return Err(ScanError::from_kind(
4731 start_mark,
4732 ErrorKind::UnexpectedCharacter { character },
4733 ));
4734 }
4735 self.ensure_current_char_is_printable()?;
4736
4737 if has_content {
4738 let contents = if let Some(slice) = borrowed_contents {
4739 Cow::Borrowed(slice)
4740 } else {
4741 Cow::Owned(string.expect("owned plain scalar has an output buffer"))
4742 };
4743
4744 Ok(Token(
4745 Span::new(start_mark, end_mark),
4746 TokenType::Scalar {
4747 style: ScalarStyle::plain(),
4748 value: contents,
4749 },
4750 ))
4751 } else {
4752 Err(ScanError::from_kind(
4756 start_mark,
4757 ErrorKind::UnexpectedEndOfPlainScalar,
4758 ))
4759 }
4760 }
4761
4762 fn fetch_key(&mut self) -> ScanResult {
4763 let start_mark = self.mark;
4764 if self.flow_level == 0 {
4765 if !self.simple_key_allowed {
4767 return Err(self.scan_error(ErrorKind::MappingKeyNotAllowed));
4768 }
4769 self.roll_indent(
4770 start_mark.col,
4771 None,
4772 TokenType::BlockMappingStart,
4773 start_mark,
4774 )?;
4775 } else {
4776 self.set_current_flow_mapping_started(true);
4778 }
4779
4780 self.remove_simple_key()?;
4781
4782 if self.flow_level == 0 {
4783 self.allow_simple_key();
4784 } else {
4785 self.disallow_simple_key();
4786 }
4787
4788 self.skip_non_blank();
4789 let end_mark = self.mark;
4790 let token_index = self.tokens.len();
4791 self.explicit_key_tab_check_pending = false;
4792 if self.flow_level == 0 {
4797 let stopped_after_comment = self.skip_yaml_whitespace()?;
4798 self.explicit_key_tab_check_pending = stopped_after_comment
4799 || (self.options.strict_indentation && matches!(self.input.peek(), '&' | '!'));
4800 }
4801 self.insert_token(
4802 token_index,
4803 Token(Span::new(start_mark, end_mark), TokenType::Key),
4804 );
4805 Ok(())
4806 }
4807
4808 fn fetch_flow_value(&mut self) -> ScanResult {
4816 let nc = self.input.peek_nth(1);
4817
4818 if self.mark.index() != self.adjacent_value_allowed_at && (nc == '[' || nc == '{') {
4830 return Err(self.scan_error(ErrorKind::FlowMappingValueAdjacentCollection));
4831 }
4832
4833 self.fetch_value()
4834 }
4835
4836 fn fetch_value(&mut self) -> ScanResult {
4838 let sk = *self.simple_keys.last().unwrap();
4839 let start_mark = self.mark;
4840 let is_implicit_flow_mapping = self.current_flow_collection_is_sequence()
4841 && !self.current_flow_mapping_started()
4842 && !self.implicit_flow_mapping_states.is_empty();
4843 if is_implicit_flow_mapping {
4844 *self.implicit_flow_mapping_states.last_mut().unwrap() =
4845 ImplicitMappingState::Inside(self.flow_level);
4846 }
4847
4848 self.skip_non_blank();
4850 let mut trailing_comment = None;
4853 let mut found_tabs = false;
4854 if matches!(self.input.look_ch(), ' ' | '\t') {
4855 let trailing_token_index = self.tokens.len();
4856 found_tabs = self.skip_ws_to_eol(SkipTabs::Yes)?.found_tabs();
4857 debug_assert!(self.tokens.len() <= trailing_token_index + 1);
4859 if self.tokens.len() > trailing_token_index {
4860 trailing_comment = self.tokens.pop_back();
4861 }
4862 }
4863
4864 if sk.possible {
4865 let block_indent = self.flow_block_indent();
4869 if self.flow_level > 0
4870 && sk.mark.line < start_mark.line
4871 && (sk.mark.col as isize) <= block_indent
4872 {
4873 return Err(ScanError::from_kind(
4874 start_mark,
4875 ErrorKind::InvalidColonPlacement,
4876 ));
4877 }
4878 let token_index = self.simple_key_token_index(&sk, start_mark)?;
4879 self.validate_flow_key_indentation(&sk, token_index, start_mark)?;
4880 let tok = Token(Span::empty(sk.mark), TokenType::Key);
4882 self.insert_token(token_index, tok);
4883 if is_implicit_flow_mapping {
4884 if sk.mark.line < start_mark.line {
4885 return Err(ScanError::from_kind(
4886 start_mark,
4887 ErrorKind::InvalidColonPlacement,
4888 ));
4889 }
4890 self.insert_token(
4891 token_index,
4892 Token(Span::empty(sk.mark), TokenType::FlowMappingStart),
4893 );
4894 }
4895
4896 self.roll_indent(
4898 sk.mark.col,
4899 Some(sk.token_number),
4900 TokenType::BlockMappingStart,
4901 sk.mark,
4902 )?;
4903 self.roll_one_col_indent();
4904
4905 self.clear_simple_key();
4906 self.disallow_simple_key();
4907 } else {
4908 if is_implicit_flow_mapping {
4909 self.tokens
4910 .push_back(Token(Span::empty(start_mark), TokenType::FlowMappingStart).into());
4911 }
4912 if self.flow_level == 0 {
4914 if !self.simple_key_allowed {
4915 return Err(ScanError::from_kind(
4916 start_mark,
4917 ErrorKind::MappingValueNotAllowed,
4918 ));
4919 }
4920
4921 self.roll_indent(
4922 start_mark.col,
4923 None,
4924 TokenType::BlockMappingStart,
4925 start_mark,
4926 )?;
4927 }
4928 self.roll_one_col_indent();
4929
4930 if self.flow_level == 0 && !found_tabs {
4933 self.allow_simple_key();
4934 } else {
4935 self.disallow_simple_key();
4936 }
4937 }
4938 self.tokens
4939 .push_back(Token(Span::empty(start_mark), TokenType::Value).into());
4940 if let Some(comment) = trailing_comment {
4941 self.tokens.push_back(comment);
4942 }
4943
4944 Ok(())
4945 }
4946
4947 fn validate_flow_key_indentation(
4949 &self,
4950 key: &SimpleKey,
4951 token_index: usize,
4952 colon: Marker,
4953 ) -> ScanResult {
4954 if self.flow_level == 0 || key.mark.line == colon.line {
4955 return Ok(());
4956 }
4957
4958 let block_indent = self.flow_block_indent();
4959 let mut under_indented = [key.mark.col, colon.col]
4963 .iter()
4964 .any(|&col| (col as isize) <= block_indent);
4965 for token in self.tokens.iter().skip(token_index) {
4966 #[cfg(feature = "comments")]
4967 if matches!(token.1, QueuedTokenType::Comment(_)) {
4968 continue;
4969 }
4970 under_indented |= (token.0.start.col as isize) <= block_indent;
4971 if !matches!(
4972 token.1,
4973 QueuedTokenType::Anchor(_) | QueuedTokenType::Tag(..)
4974 ) {
4975 break;
4976 }
4977 }
4978 if under_indented {
4979 return Err(ScanError::from_kind(
4980 colon,
4981 ErrorKind::InvalidColonPlacement,
4982 ));
4983 }
4984 Ok(())
4985 }
4986
4987 fn flow_block_indent(&self) -> isize {
4989 self.indents
4990 .last()
4991 .filter(|indent| !indent.needs_block_end)
4992 .map_or(self.indent, |indent| indent.indent)
4993 }
4994
4995 fn roll_indent(
5001 &mut self,
5002 col: usize,
5003 number: Option<usize>,
5004 tok: TokenType<'input>,
5005 mark: Marker,
5006 ) -> ScanResult {
5007 if self.flow_level > 0 {
5008 return Ok(());
5009 }
5010
5011 if self.indent <= col as isize {
5015 if let Some(indent) = self.indents.last() {
5016 if !indent.needs_block_end {
5017 self.indent = indent.indent;
5018 self.indents.pop();
5019 }
5020 }
5021 }
5022
5023 if self.indent < col as isize {
5024 if self.block_level >= self.options.block_nesting_limit {
5025 return Err(ScanError::from_kind(
5026 mark,
5027 ErrorKind::RecursionLimitExceeded,
5028 ));
5029 }
5030 self.indents.push(Indent {
5031 indent: self.indent,
5032 needs_block_end: true,
5033 });
5034 self.block_level += 1;
5035 self.indent = col as isize;
5036 let tokens_parsed = self.tokens_parsed;
5037 match number {
5038 Some(n) => self.insert_token(n - tokens_parsed, Token(Span::empty(mark), tok)),
5039 None => self.tokens.push_back(Token(Span::empty(mark), tok).into()),
5040 }
5041 }
5042 Ok(())
5043 }
5044
5045 fn unroll_indent(&mut self, col: isize) {
5051 if self.flow_level > 0 {
5052 return;
5053 }
5054 while self.indent > col {
5055 let indent = self.indents.pop().unwrap();
5056 self.indent = indent.indent;
5057 if indent.needs_block_end {
5058 debug_assert!(self.block_level > 0);
5059 self.block_level -= 1;
5060 self.tokens
5061 .push_back(Token(Span::empty(self.mark), TokenType::BlockEnd).into());
5062 }
5063 }
5064 }
5065
5066 fn roll_one_col_indent(&mut self) {
5072 if self.flow_level == 0 && self.indents.last().is_some_and(|x| x.needs_block_end) {
5073 self.indents.push(Indent {
5074 indent: self.indent,
5075 needs_block_end: false,
5076 });
5077 self.indent += 1;
5078 }
5079 }
5080
5081 fn unroll_non_block_indents(&mut self) {
5083 while let Some(indent) = self.indents.last() {
5084 if indent.needs_block_end {
5085 break;
5086 }
5087 self.indent = indent.indent;
5088 self.indents.pop();
5089 }
5090 }
5091
5092 fn save_simple_key(&mut self) {
5094 if self.simple_key_allowed {
5095 let required = self.flow_level == 0
5096 && self.indent == (self.mark.col as isize)
5097 && self.indents.last().unwrap().needs_block_end;
5098
5099 if let Some(last) = self.simple_keys.last_mut() {
5100 *last = SimpleKey {
5101 mark: self.mark,
5102 possible: true,
5103 required,
5104 token_number: self.tokens_parsed + self.tokens.len(),
5105 };
5106 self.first_simple_key.get_or_insert(self.flow_level);
5107 }
5108 }
5109 }
5110
5111 fn remove_simple_key(&mut self) -> ScanResult {
5112 let last = self.simple_keys.last().unwrap();
5113 if last.possible && last.required {
5114 return Err(Self::simple_key_expected(last.mark));
5115 }
5116
5117 self.clear_simple_key();
5118 Ok(())
5119 }
5120
5121 fn clear_simple_key(&mut self) {
5123 self.simple_keys.last_mut().unwrap().possible = false;
5124 if self.first_simple_key == Some(self.flow_level) {
5125 self.first_simple_key = None;
5127 }
5128 }
5129
5130 fn is_within_block(&self) -> bool {
5132 !self.indents.is_empty()
5133 }
5134
5135 fn end_implicit_mapping(&mut self, mark: Marker, flow_level: usize) {
5141 if self
5142 .implicit_flow_mapping_states
5143 .last()
5144 .is_some_and(|state| *state == ImplicitMappingState::Inside(flow_level))
5145 {
5146 *self.implicit_flow_mapping_states.last_mut().unwrap() = ImplicitMappingState::Possible;
5147 self.set_current_flow_mapping_started(false);
5148 self.tokens
5149 .push_back(Token(Span::empty(mark), TokenType::FlowMappingEnd).into());
5150 }
5151 }
5152
5153 fn current_flow_collection_is_sequence(&self) -> bool {
5154 self.flow_markers
5155 .last()
5156 .is_some_and(|(_, bracket)| *bracket == '[')
5157 }
5158
5159 fn current_flow_mapping_started(&self) -> bool {
5160 self.flow_mapping_started.last().copied().unwrap_or(false)
5161 }
5162
5163 fn set_current_flow_mapping_started(&mut self, started: bool) {
5164 if let Some(current) = self.flow_mapping_started.last_mut() {
5165 *current = started;
5166 }
5167 }
5168}
5169
5170#[cfg(test)]
5171mod test {
5172 use alloc::{
5173 borrow::{Cow, ToOwned},
5174 rc::Rc,
5175 string::String,
5176 vec,
5177 vec::Vec,
5178 };
5179 use core::cell::Cell;
5180
5181 use crate::error::{ErrorKind, ScanError};
5182 #[cfg(feature = "comments")]
5183 use crate::scanner::{Comment, Placement};
5184 use crate::{
5185 input::{str::StrInput, BorrowedInput, BufferedInput, Input},
5186 scanner::{
5187 Marker, QueuedToken, QueuedTokenType, ScalarStyle, Scanner, Span, Token, TokenType,
5188 },
5189 };
5190
5191 #[test]
5192 fn tag_span_supports_the_full_u32_length_without_allocating() {
5193 let start = Marker::new(0, 1, 0).with_byte_offset(Some(0));
5194 let span = Span::empty(start).with_tag_span(Some((start, u32::MAX)));
5195 let tag_span = span.tag_span().unwrap();
5196 let length = usize::try_from(u32::MAX).unwrap();
5197 assert_eq!(tag_span.start, start);
5198 assert_eq!(tag_span.end.index(), length);
5199 assert_eq!(tag_span.end.col(), length);
5200 assert_eq!(tag_span.end.line(), 1);
5201 assert_eq!(tag_span.end.byte_offset(), Some(length));
5202 }
5203
5204 #[test]
5205 fn tag_span_rejects_overflow_in_each_reconstructed_coordinate() {
5206 for start in [
5207 Marker::new(usize::MAX, 1, 0),
5208 Marker::new(0, 1, usize::MAX),
5209 Marker::new(0, 1, 0).with_byte_offset(Some(usize::MAX)),
5210 ] {
5211 let span = Span::empty(start).with_tag_span(Some((start, 1)));
5212 assert_eq!(span.tag_span(), None);
5213 }
5214 }
5215
5216 #[test]
5217 fn recovery_ignores_invalid_document_marker_lookalikes() {
5218 let input = "@bad\n---# comment\n ---\n---\0\n... trailing\n--- healthy\n";
5219 let mut scanner = Scanner::new(StrInput::new(input));
5220 assert!(matches!(
5221 scanner.next_token().unwrap().unwrap().1,
5222 TokenType::StreamStart
5223 ));
5224 assert!(scanner.next_token().is_err());
5225
5226 scanner.proceed_next_document(None).unwrap();
5227 let token = scanner.next_token().unwrap().unwrap();
5228 assert_eq!(token.1, TokenType::DocumentStart);
5229 assert_eq!(token.0.start.line(), 6);
5230 assert!(matches!(
5231 scanner.next_token().unwrap().unwrap().1,
5232 TokenType::Scalar { style: _, ref value } if value == "healthy"
5233 ));
5234 }
5235
5236 #[test]
5237 fn recovery_rejects_end_marker_queued_before_its_line_failed() {
5238 let mut scanner =
5239 Scanner::new(StrInput::new("... trailing\nnot_a_document\n--- healthy\n"));
5240 scanner.next_token().unwrap();
5241 assert_eq!(
5242 scanner.next_token().unwrap_err().kind(),
5243 &ErrorKind::InvalidDocumentEnd
5244 );
5245 assert!(scanner
5246 .tokens
5247 .iter()
5248 .any(|token| matches!(token.1, QueuedTokenType::DocumentEnd)));
5249
5250 scanner.proceed_next_document(None).unwrap();
5251 let token = scanner.next_token().unwrap().unwrap();
5252 assert_eq!(token.1, TokenType::DocumentStart);
5253 assert_eq!(token.0.start.line(), 3);
5254 }
5255
5256 #[test]
5257 fn recovery_preserves_boundary_already_held_by_parser() {
5258 let mut scanner = Scanner::new(StrInput::new("first\n--- second\n"));
5259 let boundary = loop {
5260 let token = scanner.next_queued_token().unwrap().unwrap();
5261 if matches!(token.1, QueuedTokenType::DocumentStart) {
5262 break token;
5263 }
5264 };
5265 let span = boundary.0;
5266 scanner.proceed_next_document(Some(boundary)).unwrap();
5267 assert_eq!(
5268 scanner.next_token().unwrap().unwrap(),
5269 Token(span, TokenType::DocumentStart)
5270 );
5271 assert!(matches!(
5272 scanner.next_token().unwrap().unwrap().1,
5273 TokenType::Scalar { style: _, ref value } if value == "second"
5274 ));
5275 }
5276
5277 #[test]
5278 fn recovery_retains_previously_reported_source_error() {
5279 let kind = ErrorKind::InputDecoding {
5280 message: "invalid encoding".into(),
5281 };
5282 let input = crate::FallibleBufferedInput::new(
5283 vec![Ok('['), Err(kind.clone()), Ok('\n')].into_iter(),
5284 );
5285 let mut scanner = Scanner::new(input);
5286 scanner.next_token().unwrap();
5287 let error = scanner.next_token().unwrap_err();
5288 assert_eq!(error.kind(), &kind);
5289 assert_eq!(scanner.proceed_next_document(None), Err(error));
5290 }
5291
5292 #[test]
5293 fn recovery_distinguishes_directive_header_errors_from_document_content() {
5294 for input in ["%YAML bad\n--- body\n", "%TAG invalid\n--- body\n"] {
5295 let mut scanner = Scanner::new(StrInput::new(input));
5296 scanner.next_token().unwrap();
5297 assert!(scanner.next_token().is_err());
5298 assert!(scanner.in_directive_prefix());
5299 scanner.proceed_next_document(None).unwrap();
5300 assert!(!scanner.in_directive_prefix());
5301 }
5302
5303 let mut scanner = Scanner::with_options(
5304 StrInput::new("%YAML 1.2\n--- body\n"),
5305 crate::options! { disallow_directives: true },
5306 );
5307 scanner.next_token().unwrap();
5308 assert!(scanner.next_token().is_err());
5309 assert!(scanner.in_directive_prefix());
5310
5311 for input in ["%YAML 1.2\n--- body\n", "%YAML 1.2\nbare\n"] {
5312 let mut scanner = Scanner::new(StrInput::new(input));
5313 scanner.next_token().unwrap();
5314 scanner.next_token().unwrap();
5315 assert!(scanner.in_directive_prefix());
5316 scanner.next_token().unwrap();
5317 assert!(!scanner.in_directive_prefix());
5318 }
5319 }
5320
5321 fn ignoring_comments_options() -> crate::Options {
5322 #[cfg(feature = "comments")]
5323 {
5324 crate::options! { emit_comments: false }
5325 }
5326 #[cfg(not(feature = "comments"))]
5327 {
5328 crate::Options::default()
5329 }
5330 }
5331
5332 struct CountingChars {
5333 chars: alloc::vec::IntoIter<char>,
5334 read: Rc<Cell<usize>>,
5335 }
5336
5337 impl Iterator for CountingChars {
5338 type Item = char;
5339
5340 fn next(&mut self) -> Option<Self::Item> {
5341 let next = self.chars.next();
5342 if next.is_some() {
5343 self.read.set(self.read.get() + 1);
5344 }
5345 next
5346 }
5347 }
5348
5349 struct SlicingOnlyInput<'input> {
5350 inner: StrInput<'input>,
5351 expose_slice: bool,
5352 }
5353
5354 impl<'input> SlicingOnlyInput<'input> {
5355 fn new(source: &'input str, expose_slice: bool) -> Self {
5356 Self {
5357 inner: StrInput::new(source),
5358 expose_slice,
5359 }
5360 }
5361 }
5362
5363 impl Input for SlicingOnlyInput<'_> {
5364 fn lookahead(&mut self, count: usize) {
5365 self.inner.lookahead(count);
5366 }
5367
5368 fn buflen(&self) -> usize {
5369 self.inner.buflen()
5370 }
5371
5372 fn bufmaxlen(&self) -> usize {
5373 self.inner.bufmaxlen()
5374 }
5375
5376 fn raw_read_ch(&mut self) -> char {
5377 self.inner.raw_read_ch()
5378 }
5379
5380 fn raw_read_non_breakz_ch(&mut self) -> Option<char> {
5381 self.inner.raw_read_non_breakz_ch()
5382 }
5383
5384 fn skip(&mut self) {
5385 self.inner.skip();
5386 }
5387
5388 fn skip_n(&mut self, count: usize) {
5389 self.inner.skip_n(count);
5390 }
5391
5392 fn peek(&self) -> char {
5393 self.inner.peek()
5394 }
5395
5396 fn peek_nth(&self, n: usize) -> char {
5397 self.inner.peek_nth(n)
5398 }
5399
5400 fn byte_offset(&self) -> Option<usize> {
5401 self.inner.byte_offset()
5402 }
5403
5404 fn slice_bytes(&self, start: usize, end: usize) -> Option<&str> {
5405 if self.expose_slice {
5406 self.inner.slice_bytes(start, end)
5407 } else {
5408 None
5409 }
5410 }
5411 }
5412
5413 impl<'input> BorrowedInput<'input> for SlicingOnlyInput<'input> {
5414 fn slice_borrowed(&self, _start: usize, _end: usize) -> Option<&'input str> {
5415 None
5416 }
5417 }
5418
5419 struct SmallReportedBufferInput<'input> {
5420 inner: StrInput<'input>,
5421 reported_bufmaxlen: usize,
5422 }
5423
5424 impl<'input> SmallReportedBufferInput<'input> {
5425 fn new(source: &'input str, reported_bufmaxlen: usize) -> Self {
5426 Self {
5427 inner: StrInput::new(source),
5428 reported_bufmaxlen,
5429 }
5430 }
5431 }
5432
5433 impl Input for SmallReportedBufferInput<'_> {
5434 fn lookahead(&mut self, count: usize) {
5435 self.inner.lookahead(count);
5436 }
5437
5438 fn buflen(&self) -> usize {
5439 self.inner.buflen()
5440 }
5441
5442 fn bufmaxlen(&self) -> usize {
5443 self.reported_bufmaxlen
5444 }
5445
5446 fn raw_read_ch(&mut self) -> char {
5447 self.inner.raw_read_ch()
5448 }
5449
5450 fn raw_read_non_breakz_ch(&mut self) -> Option<char> {
5451 self.inner.raw_read_non_breakz_ch()
5452 }
5453
5454 fn skip(&mut self) {
5455 self.inner.skip();
5456 }
5457
5458 fn skip_n(&mut self, count: usize) {
5459 self.inner.skip_n(count);
5460 }
5461
5462 fn peek(&self) -> char {
5463 self.inner.peek()
5464 }
5465
5466 fn peek_nth(&self, n: usize) -> char {
5467 self.inner.peek_nth(n)
5468 }
5469 }
5470
5471 impl<'input> BorrowedInput<'input> for SmallReportedBufferInput<'input> {
5472 fn slice_borrowed(&self, start: usize, end: usize) -> Option<&'input str> {
5473 self.inner.slice_borrowed(start, end)
5474 }
5475 }
5476
5477 #[test]
5478 fn anchor_character_set_allows_colon_and_rejects_flow_indicators() {
5479 use super::is_anchor_char;
5480
5481 assert!(is_anchor_char('x'));
5482 assert!(is_anchor_char('-'));
5483 assert!(is_anchor_char('_'));
5484 assert!(is_anchor_char(':'));
5485 assert!(is_anchor_char('#'));
5486 assert!(is_anchor_char('/'));
5487 assert!(is_anchor_char('?'));
5488
5489 for c in [',', '[', ']', '{', '}', ' ', '\t', '\n', '\r', '\0'] {
5490 assert!(
5491 !is_anchor_char(c),
5492 "character {c:?} must not be accepted in anchor/alias names"
5493 );
5494 }
5495 }
5496
5497 #[test]
5498 fn flow_simple_key_length_limit_bounds_buffering() {
5499 let mut yaml = String::from("[\n\"start\"\n");
5500 for _ in 0..600 {
5501 yaml.push_str("\"x\"\n");
5502 }
5503 let total_chars = yaml.chars().count();
5504 let read = Rc::new(Cell::new(0));
5505 let chars = yaml.chars().collect::<Vec<_>>().into_iter();
5506 let mut scanner = Scanner::new(BufferedInput::new(CountingChars {
5507 chars,
5508 read: Rc::clone(&read),
5509 }));
5510
5511 assert!(matches!(
5512 scanner.next_token().unwrap().unwrap().1,
5513 TokenType::StreamStart
5514 ));
5515
5516 let token = scanner.next_token().unwrap().unwrap();
5517 assert!(matches!(token.1, TokenType::FlowSequenceStart));
5518
5519 let token = scanner.next_token().unwrap().unwrap();
5520 assert!(matches!(
5521 token.1,
5522 TokenType::Scalar { style: _, ref value } if value == "start"
5523 ));
5524 assert!(
5525 read.get() < total_chars,
5526 "scanner consumed all {total_chars} chars before yielding the first flow scalar"
5527 );
5528 assert!(
5529 read.get() <= scanner.options.simple_key_max_lookahead + 128,
5530 "scanner read {} chars before yielding the first flow scalar",
5531 read.get()
5532 );
5533 }
5534
5535 #[test]
5536 fn block_scalar_indent_tolerates_small_reported_bufmaxlen() {
5537 let mut scanner = Scanner::new(SmallReportedBufferInput::new("|\n value\n", 0));
5538
5539 let scalar = scanner
5540 .find_map(
5541 |token| match token.expect("valid YAML should scan without errors") {
5542 Token(
5543 _,
5544 TokenType::Scalar {
5545 style: ScalarStyle::Literal { .. },
5546 value,
5547 },
5548 ) => Some(value.into_owned()),
5549 _ => None,
5550 },
5551 )
5552 .expect("expected block scalar token");
5553
5554 assert_eq!(scalar, "value\n");
5555 }
5556
5557 #[test]
5558 fn plain_scalar_chunk_tolerates_small_reported_bufmaxlen() {
5559 let mut scanner = Scanner::new(SmallReportedBufferInput::new("plain\n", 0));
5560
5561 let scalar = scanner
5562 .find_map(
5563 |token| match token.expect("valid YAML should scan without errors") {
5564 Token(
5565 _,
5566 TokenType::Scalar {
5567 style: ScalarStyle::Plain { .. },
5568 value,
5569 },
5570 ) => Some(value.into_owned()),
5571 _ => None,
5572 },
5573 )
5574 .expect("expected plain scalar token");
5575
5576 assert_eq!(scalar, "plain");
5577 }
5578
5579 fn first_token_slice(
5580 yaml: &str,
5581 matches_token: impl Fn(&TokenType<'_>) -> bool,
5582 ) -> Option<String> {
5583 let mut scanner = Scanner::new(StrInput::new(yaml));
5584
5585 loop {
5586 let token = scanner
5587 .next_token()
5588 .expect("scanner should accept the test YAML")?;
5589 if matches_token(&token.1) {
5590 return token.0.slice(yaml).map(ToOwned::to_owned);
5591 }
5592 }
5593 }
5594
5595 #[test]
5596 fn flow_indicator_token_spans_cover_only_the_indicator() {
5597 assert_eq!(
5598 first_token_slice("[ # c\n a]\n", |token| matches!(
5599 token,
5600 TokenType::FlowSequenceStart
5601 ))
5602 .as_deref(),
5603 Some("[")
5604 );
5605 assert_eq!(
5606 first_token_slice("{ # c\n a: b}\n", |token| matches!(
5607 token,
5608 TokenType::FlowMappingStart
5609 ))
5610 .as_deref(),
5611 Some("{")
5612 );
5613 assert_eq!(
5614 first_token_slice("[a] # c\n", |token| matches!(
5615 token,
5616 TokenType::FlowSequenceEnd
5617 ))
5618 .as_deref(),
5619 Some("]")
5620 );
5621 assert_eq!(
5622 first_token_slice("{a: b} # c\n", |token| matches!(
5623 token,
5624 TokenType::FlowMappingEnd
5625 ))
5626 .as_deref(),
5627 Some("}")
5628 );
5629 assert_eq!(
5630 first_token_slice("[a, # c\nb]\n", |token| matches!(
5631 token,
5632 TokenType::FlowEntry
5633 ))
5634 .as_deref(),
5635 Some(",")
5636 );
5637 }
5638
5639 #[test]
5640 fn explicit_key_token_span_covers_only_the_indicator() {
5641 assert_eq!(
5642 first_token_slice("? # c\n: value\n", |token| matches!(token, TokenType::Key))
5643 .as_deref(),
5644 Some("?")
5645 );
5646 }
5647
5648 #[test]
5649 #[cfg(feature = "comments")]
5650 fn comment_capture_does_not_change_leading_whitespace() {
5651 let mut scanner = Scanner::new(StrInput::new("# comment\n"));
5652
5653 let token = scanner.scan_comment_token().unwrap();
5654
5655 assert!(scanner.leading_whitespace);
5656 assert!(
5657 matches!(token.1, TokenType::Comment { ref comment } if comment.text == " comment")
5658 );
5659
5660 let mut scanner = Scanner::new(BufferedInput::new("# streaming\n".chars()));
5661 scanner.input.lookahead(1);
5662
5663 let token = scanner.scan_comment_token().unwrap();
5664
5665 assert!(scanner.leading_whitespace);
5666 assert!(
5667 matches!(token.1, TokenType::Comment { ref comment } if comment.text == " streaming")
5668 );
5669 }
5670
5671 #[test]
5672 #[cfg(feature = "comments")]
5673 fn comment_capture_falls_back_to_owned_slice_when_borrow_unavailable() {
5674 let mut scanner = Scanner::new(SlicingOnlyInput::new("# sliced\n", true));
5675 scanner.input.lookahead(2);
5676 assert_eq!(scanner.input.peek_nth(1), ' ');
5677
5678 let token = scanner.scan_comment_token().unwrap();
5679
5680 assert!(matches!(token.1, TokenType::Comment { ref comment }
5681 if matches!(comment.text, Cow::Owned(ref text) if text == " sliced")));
5682 }
5683
5684 #[test]
5685 #[cfg(feature = "comments")]
5686 fn comment_capture_errors_when_offsets_have_no_slice() {
5687 let mut scanner = Scanner::new(SlicingOnlyInput::new("# broken\n", false));
5688
5689 let error = scanner.scan_comment_token().unwrap_err();
5690
5691 assert_eq!(error.kind(), &ErrorKind::InputOffsetsWithoutSlice);
5692 }
5693
5694 #[test]
5695 fn disabled_comments_do_not_require_input_slicing() {
5696 let options = ignoring_comments_options();
5697 let scanner = Scanner::with_options(
5698 SlicingOnlyInput::new("# ignored\nkey: value\n", false),
5699 options,
5700 );
5701
5702 let tokens = scanner
5703 .collect::<Result<Vec<_>, _>>()
5704 .expect("ignored comments should not capture their payload");
5705
5706 #[cfg(feature = "comments")]
5707 assert!(tokens
5708 .iter()
5709 .all(|token| !matches!(token.1, TokenType::Comment { comment: _ })));
5710 assert!(tokens.iter().any(|token| matches!(
5711 token.1,
5712 TokenType::Scalar { style: ScalarStyle::Plain { .. }, value: ref text } if text == "value"
5713 )));
5714 }
5715
5716 #[test]
5717 fn queued_token_roundtrips_public_token_variants() {
5718 let span = Span::new(Marker::new(0, 1, 0), Marker::new(7, 1, 7));
5719 let tokens = [
5720 Token(span, TokenType::StreamStart),
5721 Token(span, TokenType::StreamEnd),
5722 Token(span, TokenType::VersionDirective { major: 1, minor: 2 }),
5723 Token(
5724 span,
5725 TokenType::TagDirective {
5726 handle: Cow::Borrowed("!app!"),
5727 prefix: Cow::Borrowed("tag:app.example,"),
5728 },
5729 ),
5730 Token(span, TokenType::DocumentStart),
5731 Token(span, TokenType::DocumentEnd),
5732 Token(span, TokenType::BlockSequenceStart),
5733 Token(span, TokenType::BlockMappingStart),
5734 Token(span, TokenType::BlockEnd),
5735 Token(span, TokenType::FlowSequenceStart),
5736 Token(span, TokenType::FlowSequenceEnd),
5737 Token(span, TokenType::FlowMappingStart),
5738 Token(span, TokenType::FlowMappingEnd),
5739 Token(span, TokenType::BlockEntry),
5740 Token(span, TokenType::FlowEntry),
5741 Token(span, TokenType::Key),
5742 Token(span, TokenType::Value),
5743 Token(
5744 span,
5745 TokenType::Alias {
5746 name: Cow::Borrowed("alias"),
5747 },
5748 ),
5749 Token(
5750 span,
5751 TokenType::Anchor {
5752 name: Cow::Borrowed("anchor"),
5753 },
5754 ),
5755 Token(
5756 span,
5757 TokenType::Tag {
5758 handle: Cow::Borrowed("!"),
5759 suffix: Cow::Borrowed("tag"),
5760 },
5761 ),
5762 Token(
5763 span,
5764 TokenType::Scalar {
5765 style: ScalarStyle::literal(),
5766 value: Cow::Borrowed("scalar"),
5767 },
5768 ),
5769 #[cfg(feature = "comments")]
5770 Token(
5771 span,
5772 TokenType::Comment {
5773 comment: Comment::new(Cow::Borrowed(" comment"))
5774 .with_placement(Placement::Right),
5775 },
5776 ),
5777 Token(
5778 span,
5779 TokenType::ReservedDirective {
5780 name: "reserved".to_owned(),
5781 parameters: vec!["one".to_owned(), "two".to_owned()],
5782 },
5783 ),
5784 ];
5785
5786 for token in tokens {
5787 let queued: QueuedToken = token.clone().into();
5788
5789 assert_eq!(queued.into_public(), token);
5790 }
5791 }
5792
5793 #[test]
5794 fn comment_skipping_path_consumes_comment_without_tokenizing_it() {
5795 let mut scanner = Scanner::new(StrInput::new("# skipped\nnext: value\n"));
5796
5797 scanner.skip_yaml_whitespace().unwrap();
5798
5799 assert!(scanner.tokens.is_empty());
5800 assert_eq!(scanner.mark.line(), 2);
5801 assert_eq!(scanner.mark.col(), 0);
5802 }
5803
5804 #[test]
5805 #[cfg(feature = "comments")]
5806 fn yaml_whitespace_can_stop_after_queued_comment() {
5807 let mut scanner = Scanner::new(StrInput::new(" # queued\n# later\n"));
5808
5809 assert!(scanner.skip_yaml_whitespace().unwrap());
5810
5811 assert_eq!(scanner.tokens.len(), 1);
5812 assert!(matches!(
5813 scanner.tokens.front().unwrap().1,
5814 QueuedTokenType::Comment(ref comment) if comment.text == " queued"
5815 ));
5816 assert_eq!(scanner.mark.line(), 1);
5817 assert_eq!(scanner.mark.col(), 9);
5818 }
5819
5820 #[test]
5821 #[cfg(feature = "comments")]
5822 fn token_skip_can_stop_after_queued_comment() {
5823 let mut scanner = Scanner::new(StrInput::new("# first\n# second\n"));
5824
5825 assert!(scanner.skip_to_next_token().unwrap().queued_comment);
5826
5827 assert_eq!(scanner.tokens.len(), 1);
5828 assert!(matches!(
5829 scanner.tokens.front().unwrap().1,
5830 QueuedTokenType::Comment(ref comment) if comment.text == " first"
5831 ));
5832 assert_eq!(scanner.mark.line(), 2);
5833 assert_eq!(scanner.mark.col(), 0);
5834 }
5835
5836 #[test]
5837 fn token_skip_stops_after_one_ignored_comment_without_queuing_it() {
5838 let options = ignoring_comments_options();
5839 let mut scanner =
5840 Scanner::with_options(StrInput::new("# first\n# second\nvalue\n"), options);
5841
5842 let outcome = scanner.skip_to_next_token().unwrap();
5843
5844 assert!(outcome.saw_comment);
5845 #[cfg(feature = "comments")]
5846 assert!(!outcome.queued_comment);
5847 assert!(scanner.tokens.is_empty());
5848 assert_eq!((scanner.mark.line(), scanner.mark.col()), (2, 0));
5849 assert_eq!(scanner.input.look_ch(), '#');
5850 }
5851
5852 #[test]
5853 fn yaml_whitespace_stops_after_one_separated_ignored_comment() {
5854 let options = ignoring_comments_options();
5855 let mut scanner =
5856 Scanner::with_options(StrInput::new(" # first\n# second\nvalue\n"), options);
5857
5858 assert!(scanner.skip_yaml_whitespace().unwrap());
5859
5860 assert!(scanner.tokens.is_empty());
5861 assert_eq!((scanner.mark.line(), scanner.mark.col()), (1, 8));
5862 assert_eq!(scanner.input.look_ch(), '\n');
5863 }
5864
5865 #[test]
5866 fn scanner_skips_consecutive_leading_ignored_comments_before_next_token() {
5867 let options = ignoring_comments_options();
5868 let mut scanner =
5869 Scanner::with_options(StrInput::new("# first\n# second\nvalue\n"), options);
5870
5871 assert!(matches!(
5872 scanner.next_token().unwrap().unwrap().1,
5873 TokenType::StreamStart
5874 ));
5875 assert!(matches!(
5876 scanner.next_token().unwrap().unwrap().1,
5877 TokenType::Scalar { style: ScalarStyle::Plain { .. }, ref value } if value == "value"
5878 ));
5879 #[cfg(feature = "comments")]
5880 assert!(scanner
5881 .tokens
5882 .iter()
5883 .all(|QueuedToken(_, token)| !matches!(token, QueuedTokenType::Comment(_))));
5884 }
5885
5886 #[test]
5887 #[cfg(feature = "comments")]
5888 fn scanner_emits_first_leading_comment_before_scanning_next_comment() {
5889 let mut scanner = Scanner::new(StrInput::new("# first\n# second\nkey: value\n"));
5890
5891 assert!(matches!(
5892 scanner.next_token().unwrap().unwrap().1,
5893 TokenType::StreamStart
5894 ));
5895 assert!(matches!(
5896 scanner.next_token().unwrap().unwrap().1,
5897 TokenType::Comment { ref comment } if comment.text == " first"
5898 ));
5899 assert!(scanner.tokens.is_empty());
5900 assert!(matches!(
5901 scanner.next_token().unwrap().unwrap().1,
5902 TokenType::Comment { ref comment } if comment.text == " second"
5903 ));
5904 }
5905
5906 #[test]
5907 #[cfg(feature = "comments")]
5908 fn scanner_emits_quoted_scalar_comment_before_scanning_following_value() {
5909 let mut scanner = Scanner::new(StrInput::new("\"key\" # quoted\n: value\n"));
5910
5911 assert!(matches!(
5912 scanner.next_token().unwrap().unwrap().1,
5913 TokenType::StreamStart
5914 ));
5915 assert!(matches!(
5916 scanner.next_token().unwrap().unwrap().1,
5917 TokenType::Scalar { style: ScalarStyle::DoubleQuoted, ref value } if value == "key"
5918 ));
5919 assert!(matches!(
5920 scanner.next_token().unwrap().unwrap().1,
5921 TokenType::Comment { ref comment } if comment.text == " quoted"
5922 ));
5923 }
5924
5925 #[test]
5926 #[cfg(feature = "comments")]
5927 fn flow_scalar_comment_disables_adjacent_value_lookahead() {
5928 let mut scanner = Scanner::new(StrInput::new("\"key\"\n# quoted\n: value\n"));
5929
5930 scanner.fetch_flow_scalar(false).unwrap();
5931
5932 assert_eq!(scanner.adjacent_value_allowed_at, usize::MAX);
5933 assert!(matches!(
5934 scanner.tokens.front().unwrap().1,
5935 QueuedTokenType::Scalar(ScalarStyle::DoubleQuoted, ref value) if value == "key"
5936 ));
5937 assert!(scanner.tokens.iter().any(|QueuedToken(_, token)| matches!(
5938 token,
5939 QueuedTokenType::Comment(comment) if comment.text == " quoted"
5940 )));
5941 }
5942
5943 #[test]
5944 fn ignored_flow_scalar_comment_still_disables_adjacent_value_lookahead() {
5945 let options = ignoring_comments_options();
5946 let mut scanner =
5947 Scanner::with_options(StrInput::new("\"key\"\n# ignored\n: value\n"), options);
5948
5949 scanner.fetch_flow_scalar(false).unwrap();
5950
5951 assert_eq!(scanner.adjacent_value_allowed_at, usize::MAX);
5952 assert_eq!(scanner.tokens.len(), 1);
5953 assert!(matches!(
5954 scanner.tokens.front().unwrap().1,
5955 QueuedTokenType::Scalar(ScalarStyle::DoubleQuoted, ref value) if value == "key"
5956 ));
5957 }
5958
5959 #[test]
5960 #[cfg(feature = "comments")]
5961 fn deferred_error_waits_for_all_comment_tokens() {
5962 let mut scanner = Scanner::new(StrInput::new("# first\n# second\n@\n"));
5963
5964 assert!(matches!(
5965 scanner.next_token().unwrap().unwrap().1,
5966 TokenType::StreamStart
5967 ));
5968 assert!(matches!(
5969 scanner.next_token().unwrap().unwrap().1,
5970 TokenType::Comment { ref comment } if comment.text == " first"
5971 ));
5972 assert!(matches!(
5973 scanner.next_token().unwrap().unwrap().1,
5974 TokenType::Comment { ref comment } if comment.text == " second"
5975 ));
5976
5977 let error = scanner.next_token().unwrap_err();
5978
5979 assert_eq!(
5980 error.kind(),
5981 &ErrorKind::UnexpectedCharacter { character: '@' }
5982 );
5983 }
5984
5985 #[test]
5987 fn anchor_name_is_borrowed_for_str_input() {
5988 let mut scanner = Scanner::new(StrInput::new("&anch\n"));
5989
5990 loop {
5991 let tok = scanner
5992 .next_token()
5993 .expect("valid YAML must scan without errors")
5994 .expect("scanner must eventually produce a token");
5995 if let TokenType::Anchor { name } = tok.1 {
5996 assert!(matches!(name, Cow::Borrowed("anch")));
5997 break;
5998 }
5999 }
6000 }
6001
6002 #[test]
6003 fn anchor_name_rejects_non_printable_control_chars() {
6004 let mut scanner = Scanner::new(StrInput::new("&foo\u{0001}\n"));
6005
6006 scanner.next_token().unwrap();
6007 assert_eq!(
6008 scanner.next_token().unwrap_err().kind(),
6009 &ErrorKind::UnexpectedCharacter {
6010 character: '\u{0001}'
6011 }
6012 );
6013 }
6014
6015 #[test]
6016 fn alias_name_rejects_non_printable_control_chars() {
6017 let mut scanner = Scanner::new(StrInput::new("*foo\u{0001}\n"));
6018
6019 scanner.next_token().unwrap();
6020 assert_eq!(
6021 scanner.next_token().unwrap_err().kind(),
6022 &ErrorKind::UnexpectedCharacter {
6023 character: '\u{0001}'
6024 }
6025 );
6026 }
6027
6028 #[test]
6029 fn alias_name_is_borrowed_for_str_input() {
6030 let mut scanner = Scanner::new(StrInput::new("*anch\n"));
6031
6032 loop {
6033 let tok = scanner
6034 .next_token()
6035 .expect("valid YAML must scan without errors")
6036 .expect("scanner must eventually produce a token");
6037 if let TokenType::Alias { name } = tok.1 {
6038 assert!(matches!(name, Cow::Borrowed("anch")));
6039 break;
6040 }
6041 }
6042 }
6043
6044 #[test]
6045 fn alias_name_scans_colon_as_part_of_name() {
6046 let mut scanner = Scanner::new(StrInput::new("*foo: bar\n"));
6047
6048 loop {
6049 let tok = scanner
6050 .next_token()
6051 .expect("scanner must not fail before alias token")
6052 .expect("scanner must eventually emit an alias token");
6053
6054 if let TokenType::Alias { name } = tok.1 {
6055 assert_eq!(name.as_ref(), "foo:");
6056 break;
6057 }
6058 }
6059 }
6060
6061 #[test]
6062 fn anchor_name_scans_colon_as_part_of_name() {
6063 let mut scanner = Scanner::new(StrInput::new("&foo: bar\n"));
6064
6065 loop {
6066 let tok = scanner
6067 .next_token()
6068 .expect("scanner must not fail before anchor token")
6069 .expect("scanner must eventually emit an anchor token");
6070
6071 if let TokenType::Anchor { name } = tok.1 {
6072 assert_eq!(name.as_ref(), "foo:");
6073 break;
6074 }
6075 }
6076 }
6077
6078 #[test]
6080 fn tag_directive_parts_are_borrowed_for_str_input() {
6081 let mut scanner = Scanner::new(StrInput::new("%TAG !e! tag:example.com,2000:app/\n"));
6082
6083 loop {
6084 let tok = scanner
6085 .next_token()
6086 .expect("valid YAML must scan without errors")
6087 .expect("scanner must eventually produce a token");
6088 if let TokenType::TagDirective { handle, prefix } = tok.1 {
6089 assert!(matches!(handle, Cow::Borrowed("!e!")));
6090 assert!(matches!(prefix, Cow::Borrowed("tag:example.com,2000:app/")));
6091 break;
6092 }
6093 }
6094 }
6095
6096 #[test]
6097 fn tag_directive_parts_are_owned_for_buffered_input() {
6098 let mut scanner = Scanner::new(BufferedInput::new(
6099 "%TAG !e! tag:example.com,2000:app/\n".chars(),
6100 ));
6101
6102 loop {
6103 let tok = scanner
6104 .next_token()
6105 .expect("valid YAML must scan without errors")
6106 .expect("scanner must eventually produce a token");
6107 if let TokenType::TagDirective { handle, prefix } = tok.1 {
6108 assert!(matches!(handle, Cow::Owned(_)));
6109 assert_eq!(&*handle, "!e!");
6110 assert!(matches!(prefix, Cow::Owned(_)));
6111 assert_eq!(&*prefix, "tag:example.com,2000:app/");
6112 break;
6113 }
6114 }
6115 }
6116
6117 #[test]
6118 fn buffered_tag_directive_decodes_prefix_escape() {
6119 let mut scanner = Scanner::new(BufferedInput::new(
6120 "%TAG !e! %74ag:example.com,2000:app/\n".chars(),
6121 ));
6122
6123 loop {
6124 let tok = scanner
6125 .next_token()
6126 .expect("valid YAML must scan without errors")
6127 .expect("scanner must eventually produce a token");
6128 if let TokenType::TagDirective { handle, prefix } = tok.1 {
6129 assert_eq!(&*handle, "!e!");
6130 assert!(matches!(prefix, Cow::Owned(_)));
6131 assert_eq!(&*prefix, "tag:example.com,2000:app/");
6132 break;
6133 }
6134 }
6135 }
6136
6137 #[test]
6138 fn local_tag_combines_handle_text_with_escaped_suffix() {
6139 let mut scanner = Scanner::new(StrInput::new("!foo%20bar value\n"));
6140
6141 loop {
6142 let tok = scanner
6143 .next_token()
6144 .expect("valid YAML must scan without errors")
6145 .expect("scanner must eventually produce a token");
6146 if let TokenType::Tag { handle, suffix } = tok.1 {
6147 assert!(matches!(handle, Cow::Borrowed("!")));
6148 assert!(matches!(suffix, Cow::Owned(_)));
6149 assert_eq!(&*suffix, "foo bar");
6150 break;
6151 }
6152 }
6153 }
6154
6155 #[test]
6156 fn secondary_tag_requires_suffix_in_borrowed_and_buffered_paths() {
6157 assert_eq!(
6158 first_scanner_error_kind("!! value\n"),
6159 ErrorKind::MissingTagUri
6160 );
6161 assert_eq!(
6162 first_buffered_scanner_error_kind("!! value\n"),
6163 ErrorKind::MissingTagUri
6164 );
6165 }
6166
6167 #[test]
6168 fn plain_scalar_is_borrowed_when_whitespace_free_for_str_input() {
6169 let mut scanner = Scanner::new(StrInput::new("foo\n"));
6170
6171 loop {
6172 let tok = scanner
6173 .next_token()
6174 .expect("valid YAML must scan without errors")
6175 .expect("scanner must eventually produce a token");
6176 if let TokenType::Scalar { style: _, value } = tok.1 {
6177 assert!(matches!(value, Cow::Borrowed("foo")));
6178 break;
6179 }
6180 }
6181 }
6182
6183 #[test]
6184 fn plain_scalar_is_borrowed_when_whitespace_present_for_str_input() {
6185 let mut scanner = Scanner::new(StrInput::new("foo bar\n"));
6186
6187 loop {
6188 let tok = scanner
6189 .next_token()
6190 .expect("valid YAML must scan without errors")
6191 .expect("scanner must eventually produce a token");
6192 if let TokenType::Scalar { style: _, value } = tok.1 {
6193 assert!(matches!(value, Cow::Borrowed("foo bar")));
6194 break;
6195 }
6196 }
6197 }
6198
6199 #[test]
6200 fn single_quoted_scalar_is_borrowed_when_verbatim_for_str_input() {
6201 let mut scanner = Scanner::new(StrInput::new("'foo bar'\n"));
6202
6203 loop {
6204 let tok = scanner
6205 .next_token()
6206 .expect("valid YAML must scan without errors")
6207 .expect("scanner must eventually produce a token");
6208 if let TokenType::Scalar { style: _, value } = tok.1 {
6209 assert!(matches!(value, Cow::Borrowed("foo bar")));
6210 break;
6211 }
6212 }
6213 }
6214
6215 #[test]
6216 fn single_quoted_scalar_is_owned_when_quote_is_escaped_for_str_input() {
6217 let mut scanner = Scanner::new(StrInput::new("'foo''bar'\n"));
6218
6219 loop {
6220 let tok = scanner
6221 .next_token()
6222 .expect("valid YAML must scan without errors")
6223 .expect("scanner must eventually produce a token");
6224 if let TokenType::Scalar { style: _, value } = tok.1 {
6225 assert!(matches!(value, Cow::Owned(_)));
6226 assert_eq!(&*value, "foo'bar");
6227 break;
6228 }
6229 }
6230 }
6231
6232 #[test]
6233 fn double_quoted_scalar_is_borrowed_when_verbatim_for_str_input() {
6234 let mut scanner = Scanner::new(StrInput::new("\"foo bar\"\n"));
6235
6236 loop {
6237 let tok = scanner
6238 .next_token()
6239 .expect("valid YAML must scan without errors")
6240 .expect("scanner must eventually produce a token");
6241 if let TokenType::Scalar { style: _, value } = tok.1 {
6242 assert!(matches!(value, Cow::Borrowed("foo bar")));
6243 break;
6244 }
6245 }
6246 }
6247
6248 #[test]
6249 fn double_quoted_scalar_is_owned_when_escape_sequence_present_for_str_input() {
6250 let mut scanner = Scanner::new(StrInput::new("\"foo\\nbar\"\n"));
6251
6252 loop {
6253 let tok = scanner
6254 .next_token()
6255 .expect("valid YAML must scan without errors")
6256 .expect("scanner must eventually produce a token");
6257 if let TokenType::Scalar { style: _, value } = tok.1 {
6258 assert!(matches!(value, Cow::Owned(_)));
6259 assert_eq!(&*value, "foo\nbar");
6260 break;
6261 }
6262 }
6263 }
6264
6265 #[test]
6266 fn plain_key_is_borrowed_for_str_input() {
6267 let mut scanner = Scanner::new(StrInput::new("mykey: value\n"));
6269
6270 let mut found_key = false;
6271 let mut key_value: Option<Cow<'_, str>> = None;
6272
6273 loop {
6274 let tok = scanner
6275 .next_token()
6276 .expect("valid YAML must scan without errors");
6277 let Some(tok) = tok else { break };
6278
6279 if matches!(tok.1, TokenType::Key) {
6280 found_key = true;
6281 } else if found_key {
6282 if let TokenType::Scalar { style: _, value } = tok.1 {
6283 key_value = Some(value);
6284 break;
6285 }
6286 }
6287 }
6288
6289 assert!(found_key, "expected to find a Key token");
6290 let key_value = key_value.expect("expected to find a scalar after Key token");
6291 assert!(
6292 matches!(key_value, Cow::Borrowed("mykey")),
6293 "key should be borrowed, got: {key_value:?}"
6294 );
6295 }
6296
6297 #[test]
6298 fn quoted_key_is_borrowed_when_verbatim_for_str_input() {
6299 let mut scanner = Scanner::new(StrInput::new("\"mykey\": value\n"));
6300
6301 let mut found_key = false;
6302 let mut key_value: Option<Cow<'_, str>> = None;
6303
6304 loop {
6305 let tok = scanner
6306 .next_token()
6307 .expect("valid YAML must scan without errors");
6308 let Some(tok) = tok else { break };
6309
6310 if matches!(tok.1, TokenType::Key) {
6311 found_key = true;
6312 } else if found_key {
6313 if let TokenType::Scalar { style: _, value } = tok.1 {
6314 key_value = Some(value);
6315 break;
6316 }
6317 }
6318 }
6319
6320 assert!(found_key, "expected to find a Key token");
6321 let key_value = key_value.expect("expected to find a scalar after Key token");
6322 assert!(
6323 matches!(key_value, Cow::Borrowed("mykey")),
6324 "quoted key should be borrowed when verbatim, got: {key_value:?}"
6325 );
6326 }
6327
6328 #[test]
6329 fn tag_handle_and_suffix_are_borrowed_for_str_input() {
6330 let mut scanner = Scanner::new(StrInput::new("!!str foo\n"));
6332
6333 loop {
6334 let tok = scanner
6335 .next_token()
6336 .expect("valid YAML must scan without errors")
6337 .expect("scanner must eventually produce a token");
6338 if let TokenType::Tag { handle, suffix } = tok.1 {
6339 assert!(
6340 matches!(handle, Cow::Borrowed("!!")),
6341 "tag handle should be borrowed, got: {handle:?}"
6342 );
6343 assert!(
6344 matches!(suffix, Cow::Borrowed("str")),
6345 "tag suffix should be borrowed, got: {suffix:?}"
6346 );
6347 break;
6348 }
6349 }
6350 }
6351
6352 #[test]
6353 fn local_tag_suffix_is_borrowed_for_str_input() {
6354 let mut scanner = Scanner::new(StrInput::new("!mytag foo\n"));
6356
6357 loop {
6358 let tok = scanner
6359 .next_token()
6360 .expect("valid YAML must scan without errors")
6361 .expect("scanner must eventually produce a token");
6362 if let TokenType::Tag { handle, suffix } = tok.1 {
6363 assert!(
6364 matches!(handle, Cow::Borrowed("!")),
6365 "local tag handle should be '!', got: {handle:?}"
6366 );
6367 assert!(
6368 matches!(suffix, Cow::Borrowed("mytag")),
6369 "local tag suffix should be borrowed, got: {suffix:?}"
6370 );
6371 break;
6372 }
6373 }
6374 }
6375
6376 #[test]
6377 fn local_tag_suffix_with_punctuation_is_borrowed_for_str_input() {
6378 let mut scanner = Scanner::new(StrInput::new("!mytag/part foo\n"));
6379
6380 loop {
6381 let tok = scanner
6382 .next_token()
6383 .expect("valid YAML must scan without errors")
6384 .expect("scanner must eventually produce a token");
6385 if let TokenType::Tag { handle, suffix } = tok.1 {
6386 assert!(matches!(handle, Cow::Borrowed("!")));
6387 assert!(matches!(suffix, Cow::Borrowed("mytag/part")));
6388 break;
6389 }
6390 }
6391 }
6392
6393 #[test]
6394 fn tag_with_uri_escape_is_owned_for_str_input() {
6395 let mut scanner = Scanner::new(StrInput::new("!!my%20tag foo\n"));
6397
6398 loop {
6399 let tok = scanner
6400 .next_token()
6401 .expect("valid YAML must scan without errors")
6402 .expect("scanner must eventually produce a token");
6403 if let TokenType::Tag { handle, suffix } = tok.1 {
6404 assert!(
6405 matches!(handle, Cow::Borrowed("!!")),
6406 "tag handle should still be borrowed, got: {handle:?}"
6407 );
6408 assert!(
6409 matches!(suffix, Cow::Owned(_)),
6410 "tag suffix with URI escape should be owned, got: {suffix:?}"
6411 );
6412 assert_eq!(&*suffix, "my tag");
6413 break;
6414 }
6415 }
6416 }
6417
6418 #[test]
6419 fn flow_scalar_buffer_tracks_pending_whitespace() {
6420 let mut borrowed = super::FlowScalarBuf::new_borrowed(2);
6421
6422 borrowed.note_pending_ws(5, 8);
6423 borrowed.commit_pending_ws();
6424 assert!(matches!(
6425 borrowed,
6426 super::FlowScalarBuf::Borrowed {
6427 end: 8,
6428 pending_ws_start: None,
6429 pending_ws_end: 8,
6430 ..
6431 }
6432 ));
6433
6434 borrowed.note_pending_ws(9, 11);
6435 borrowed.discard_pending_ws();
6436 assert!(matches!(
6437 borrowed,
6438 super::FlowScalarBuf::Borrowed {
6439 end: 8,
6440 pending_ws_start: None,
6441 pending_ws_end: 8,
6442 ..
6443 }
6444 ));
6445 assert!(borrowed.as_owned_mut().is_none());
6446
6447 let mut owned = super::FlowScalarBuf::new_owned();
6448 owned.as_owned_mut().unwrap().push_str("owned");
6449 assert!(matches!(owned, super::FlowScalarBuf::Owned(ref s) if s == "owned"));
6450 }
6451
6452 fn first_scanner_error_kind(input: &str) -> ErrorKind {
6453 first_scanner_error(input).kind().clone()
6454 }
6455
6456 fn first_buffered_scanner_error_kind(input: &str) -> ErrorKind {
6457 let mut scanner = Scanner::new(BufferedInput::new(input.chars()));
6458 loop {
6459 match scanner.next_token() {
6460 Ok(Some(_)) => {}
6461 Ok(None) => panic!("expected scanner error"),
6462 Err(error) => return error.kind().clone(),
6463 }
6464 }
6465 }
6466
6467 fn first_scanner_error(input: &str) -> ScanError {
6468 let mut scanner = Scanner::new(StrInput::new(input));
6469 loop {
6470 match scanner.next_token() {
6471 Ok(Some(_)) => {}
6472 Ok(None) => panic!("expected scanner error"),
6473 Err(error) => return error,
6474 }
6475 }
6476 }
6477
6478 fn first_scalar_value(input: &str) -> String {
6479 let mut scanner = Scanner::new(StrInput::new(input));
6480 loop {
6481 match scanner.next_token().expect("scanner should not error") {
6482 Some(Token(_, TokenType::Scalar { style: _, value })) => return value.into_owned(),
6483 Some(_) => {}
6484 None => panic!("expected scalar token"),
6485 }
6486 }
6487 }
6488
6489 fn first_buffered_scalar_value(input: &str) -> String {
6490 let mut scanner = Scanner::new(BufferedInput::new(input.chars()));
6491 loop {
6492 match scanner.next_token().expect("scanner should not error") {
6493 Some(Token(_, TokenType::Scalar { style: _, value })) => return value.into_owned(),
6494 Some(_) => {}
6495 None => panic!("expected scalar token"),
6496 }
6497 }
6498 }
6499
6500 #[test]
6501 fn iterator_next_emits_error_and_then_stays_empty() {
6502 let mut scanner = Scanner::new(StrInput::new("\"unterminated"));
6503
6504 let error = scanner
6505 .by_ref()
6506 .find_map(Result::err)
6507 .expect("scanner should emit the error");
6508 assert_eq!(error.kind(), &ErrorKind::UnclosedQuotedScalar);
6509 assert!(scanner.next().is_none());
6510 }
6511
6512 #[test]
6513 fn next_token_returns_none_after_stream_end() {
6514 let mut scanner = Scanner::new(StrInput::new(""));
6515
6516 while let Some(token) = scanner.next_token().unwrap() {
6517 if matches!(token.1, TokenType::StreamEnd) {
6518 break;
6519 }
6520 }
6521
6522 assert!(scanner.stream_started());
6523 assert!(scanner.stream_ended());
6524 assert!(scanner.next_token().unwrap().is_none());
6525 }
6526
6527 #[test]
6528 fn directive_name_must_be_present() {
6529 assert_eq!(
6530 first_scanner_error_kind("%\n"),
6531 ErrorKind::MissingDirectiveName
6532 );
6533 }
6534
6535 #[test]
6536 fn yaml_directive_requires_dot_between_version_numbers() {
6537 assert_eq!(
6538 first_scanner_error_kind("%YAML 1\n"),
6539 ErrorKind::MissingYamlVersionSeparator
6540 );
6541 }
6542
6543 #[test]
6544 fn yaml_directive_requires_major_version_number() {
6545 assert_eq!(
6546 first_scanner_error_kind("%YAML .2\n"),
6547 ErrorKind::MissingYamlVersion
6548 );
6549 }
6550
6551 #[test]
6552 fn yaml_directive_rejects_extremely_long_version_number() {
6553 assert_eq!(
6554 first_scanner_error_kind("%YAML 1234567890.2\n"),
6555 ErrorKind::YamlVersionTooLong
6556 );
6557 }
6558
6559 #[test]
6560 fn tag_directive_handle_must_end_with_bang() {
6561 assert_eq!(
6562 first_scanner_error_kind("%TAG !bad tag:example.com,2024:\n"),
6563 ErrorKind::ExpectedTagDirectiveBang
6564 );
6565 }
6566
6567 #[test]
6568 fn tag_directive_handle_must_start_with_bang() {
6569 assert_eq!(
6570 first_scanner_error_kind("%TAG bad! tag:example.com,2024:\n"),
6571 ErrorKind::ExpectedTagBang
6572 );
6573 assert_eq!(
6574 first_buffered_scanner_error_kind("%TAG bad! tag:example.com,2024:\n"),
6575 ErrorKind::ExpectedTagBang
6576 );
6577 }
6578
6579 #[test]
6580 fn tag_directive_prefix_must_start_with_tag_character() {
6581 assert_eq!(
6582 first_scanner_error_kind("%TAG !e! `bad\n"),
6583 ErrorKind::InvalidGlobalTagCharacter
6584 );
6585 }
6586
6587 #[test]
6588 fn tag_directive_prefix_must_end_before_invalid_content() {
6589 assert_eq!(
6590 first_scanner_error_kind("%TAG !e! tag:example.com^suffix\n"),
6591 ErrorKind::InvalidTagDirectiveTerminator
6592 );
6593 }
6594
6595 #[test]
6596 fn tag_directive_prefix_with_uri_escape_is_owned_and_decoded() {
6597 let mut scanner =
6598 Scanner::new(StrInput::new("%TAG !e! tag:example.com,2024:some%20app/\n"));
6599
6600 loop {
6601 let token = scanner
6602 .next_token()
6603 .expect("valid directive should scan")
6604 .expect("scanner must produce a directive token");
6605 if let TokenType::TagDirective { handle, prefix } = token.1 {
6606 assert!(matches!(handle, Cow::Borrowed("!e!")));
6607 assert!(matches!(prefix, Cow::Owned(_)));
6608 assert_eq!(&*prefix, "tag:example.com,2024:some app/");
6609 break;
6610 }
6611 }
6612 }
6613
6614 #[test]
6615 fn bare_bang_tag_scans_as_non_specific_tag() {
6616 let mut scanner = Scanner::new(StrInput::new("! foo\n"));
6617
6618 loop {
6619 let token = scanner
6620 .next_token()
6621 .expect("valid tag should scan")
6622 .expect("scanner must produce a tag token");
6623 if let TokenType::Tag { handle, suffix } = token.1 {
6624 assert_eq!(&*handle, "");
6625 assert_eq!(&*suffix, "!");
6626 break;
6627 }
6628 }
6629 }
6630
6631 #[test]
6632 fn tag_requires_separation_after_suffix() {
6633 assert_eq!(
6634 first_scanner_error_kind("!foo,bar\n"),
6635 ErrorKind::InvalidTagTerminator
6636 );
6637 }
6638
6639 #[test]
6640 fn verbatim_tag_requires_uri() {
6641 assert_eq!(
6642 first_scanner_error_kind("!<> foo\n"),
6643 ErrorKind::MissingTagUri
6644 );
6645 }
6646
6647 #[test]
6648 fn verbatim_tag_requires_closing_angle_bracket() {
6649 assert_eq!(
6650 first_scanner_error_kind("!<tag:yaml.org,2002:str foo\n"),
6651 ErrorKind::UnclosedVerbatimTag
6652 );
6653 }
6654
6655 #[test]
6656 fn tag_uri_escape_requires_hex_digits() {
6657 assert_eq!(
6658 first_scanner_error_kind("!!bad%zz foo\n"),
6659 ErrorKind::InvalidTagEscape
6660 );
6661 }
6662
6663 #[test]
6664 fn tag_uri_escape_rejects_bad_leading_utf8_byte() {
6665 assert_eq!(
6666 first_scanner_error_kind("!!bad%80 foo\n"),
6667 ErrorKind::InvalidTagUtf8LeadingByte
6668 );
6669 }
6670
6671 #[test]
6672 fn tag_uri_escape_rejects_bad_trailing_utf8_byte() {
6673 assert_eq!(
6674 first_scanner_error_kind("!!bad%C2%41 foo\n"),
6675 ErrorKind::InvalidTagUtf8TrailingByte
6676 );
6677 }
6678
6679 #[test]
6680 fn tag_uri_escape_rejects_invalid_utf8_codepoint() {
6681 assert_eq!(
6682 first_scanner_error_kind("!!bad%F4%90%80%80 foo\n"),
6683 ErrorKind::InvalidTagUtf8
6684 );
6685 }
6686
6687 #[test]
6688 fn anchors_and_aliases_require_names() {
6689 assert_eq!(
6690 first_scanner_error_kind("& \n"),
6691 ErrorKind::MissingAnchorOrAliasName
6692 );
6693 assert_eq!(
6694 first_scanner_error_kind("* \n"),
6695 ErrorKind::MissingAnchorOrAliasName
6696 );
6697 }
6698
6699 #[test]
6700 fn document_end_marker_rejects_trailing_content() {
6701 assert_eq!(
6702 first_scanner_error_kind("... trailing\n"),
6703 ErrorKind::InvalidDocumentEnd
6704 );
6705 }
6706
6707 #[test]
6708 fn reserved_indicators_are_rejected_outside_directives() {
6709 let error = first_scanner_error(" @\n");
6710
6711 assert_eq!(
6712 error.kind(),
6713 &ErrorKind::UnexpectedCharacter { character: '@' }
6714 );
6715 }
6716
6717 #[test]
6718 fn flow_block_entry_indicator_is_rejected() {
6719 assert_eq!(
6720 first_scanner_error_kind("[- ]\n"),
6721 ErrorKind::BlockEntryInFlowCollection
6722 );
6723 }
6724
6725 #[test]
6726 fn block_entry_after_tabbed_separator_reports_specific_error() {
6727 assert_eq!(
6728 first_scanner_error_kind("-\t- value\n"),
6729 ErrorKind::InvalidBlockEntryWhitespace
6730 );
6731 }
6732
6733 #[test]
6734 fn document_indicator_reports_unclosed_flow_collection() {
6735 let error = first_scanner_error("[\n---\n");
6736
6737 assert_eq!(
6738 error.kind(),
6739 &ErrorKind::UnclosedFlowCollection { open: '[' }
6740 );
6741 }
6742
6743 #[test]
6744 fn block_scalar_header_rejects_trailing_content() {
6745 assert_eq!(
6746 first_scanner_error_kind("|+ trailing\n"),
6747 ErrorKind::InvalidBlockScalarHeader
6748 );
6749 }
6750
6751 #[test]
6752 fn block_scalar_rejects_zero_indent_indicator() {
6753 assert_eq!(
6754 first_scanner_error_kind("|0\n"),
6755 ErrorKind::ZeroBlockScalarIndent
6756 );
6757 assert_eq!(
6758 first_scanner_error_kind("|+0\n"),
6759 ErrorKind::ZeroBlockScalarIndent
6760 );
6761 }
6762
6763 #[test]
6764 fn empty_block_scalar_at_eof_honors_chomping() {
6765 assert_eq!(first_scalar_value("|\n"), "");
6766 assert_eq!(first_scalar_value("|-\n"), "");
6767 assert_eq!(first_scalar_value("|+\n"), "");
6768 assert_eq!(first_scalar_value("|+\n\n"), "\n");
6769 assert_eq!(first_scalar_value("|+\n "), "\n");
6770 }
6771
6772 #[test]
6773 fn buffered_block_scalar_reads_content_past_lookahead_window() {
6774 assert_eq!(
6775 first_buffered_scalar_value("|\n abcdefghijklmnopqrstuvwxyz\n"),
6776 "abcdefghijklmnopqrstuvwxyz\n"
6777 );
6778 }
6779
6780 #[test]
6781 fn explicit_indent_block_scalar_can_end_at_document_marker() {
6782 assert_eq!(first_scalar_value("|1\n...\n"), "");
6783 }
6784
6785 #[test]
6786 fn root_explicit_indent_block_scalar_rejects_underindented_content() {
6787 assert_eq!(
6788 first_scanner_error_kind("|2\nx\n"),
6789 ErrorKind::InvalidBlockScalarIndent
6790 );
6791 }
6792
6793 #[test]
6794 fn quoted_scalar_rejects_document_indicator_at_line_start() {
6795 assert_eq!(
6796 first_scanner_error_kind("\"one\n---\ntwo\"\n"),
6797 ErrorKind::DocumentIndicatorInQuotedScalar
6798 );
6799 }
6800
6801 #[test]
6802 fn strict_quoted_scalar_rejects_tab_indentation_after_line_break() {
6803 let error = Scanner::with_options(
6804 StrInput::new("a: \"one\n\tbad\"\n"),
6805 crate::options! { strict_indentation: true },
6806 )
6807 .find_map(Result::err)
6808 .expect("strict mode must reject a tab indenting a quoted continuation");
6809 assert_eq!(error.kind(), &ErrorKind::TabInIndentation);
6810 }
6811
6812 #[test]
6813 fn strict_quoted_scalar_rejects_underindented_continuation() {
6814 for input in ["a: \"one\nbad\"\n", "a:\n b: 'one\n bad'\n"] {
6815 let error = Scanner::with_options(
6816 StrInput::new(input),
6817 crate::options! { strict_indentation: true },
6818 )
6819 .find_map(Result::err)
6820 .expect("strict mode must reject underindented quoted continuations");
6821 assert_eq!(error.kind(), &ErrorKind::InvalidQuotedScalarIndent);
6822 }
6823 }
6824
6825 #[test]
6826 fn quoted_scalar_continuation_one_column_past_block_indent() {
6827 for input in [
6830 "a: \"one\n two\"\n",
6831 "a: 'one\n two'\n",
6832 "a:\n b: \"one\n two\"\n",
6833 "- a: \"one\n two\"\n",
6834 "? k\n: \"one\n two\"\n",
6835 ] {
6836 let mut scanner = Scanner::new(StrInput::new(input));
6837 loop {
6838 match scanner.next_token() {
6839 Ok(Some(_)) => {}
6840 Ok(None) => break,
6841 Err(error) => panic!("{input:?}: {error}"),
6842 }
6843 }
6844 }
6845 }
6846
6847 #[test]
6848 fn quoted_scalar_trailing_content_error_names_quote_style() {
6849 assert_eq!(
6850 first_scanner_error_kind("'foo' trailing\n"),
6851 ErrorKind::InvalidTrailingSingleQuotedScalar
6852 );
6853 assert_eq!(
6854 first_scanner_error_kind("\"foo\" trailing\n"),
6855 ErrorKind::InvalidTrailingDoubleQuotedScalar
6856 );
6857 }
6858
6859 #[test]
6860 fn quoted_scalar_escape_errors_cover_hex_and_surrogate_edges() {
6861 assert_eq!(
6862 first_scanner_error_kind("\"\\xG0\"\n"),
6863 ErrorKind::InvalidQuotedScalarHexEscape
6864 );
6865 assert_eq!(
6866 first_scanner_error_kind("\"\\uD800\\uGGGG\"\n"),
6867 ErrorKind::InvalidLowSurrogateHexEscape
6868 );
6869 assert_eq!(
6870 first_scanner_error_kind("\"\\uD800\\u0041\"\n"),
6871 ErrorKind::InvalidLowSurrogate
6872 );
6873 assert_eq!(
6874 first_scanner_error_kind("\"\\U00110000\"\n"),
6875 ErrorKind::InvalidUnicodeEscape
6876 );
6877 }
6878
6879 #[test]
6880 fn under_indented_flow_scalar_is_accepted() {
6881 let tokens: Vec<_> = Scanner::new(StrInput::new("a:\n [\nfoo]\n"))
6882 .map(|result| result.expect("under-indented flow entry should scan").1)
6883 .collect();
6884 assert_eq!(
6885 tokens,
6886 [
6887 TokenType::StreamStart,
6888 TokenType::BlockMappingStart,
6889 TokenType::Key,
6890 TokenType::Scalar {
6891 style: ScalarStyle::plain(),
6892 value: "a".into()
6893 },
6894 TokenType::Value,
6895 TokenType::FlowSequenceStart,
6896 TokenType::Scalar {
6897 style: ScalarStyle::plain(),
6898 value: "foo".into()
6899 },
6900 TokenType::FlowSequenceEnd,
6901 TokenType::BlockEnd,
6902 TokenType::StreamEnd,
6903 ]
6904 );
6905 }
6906
6907 #[test]
6908 fn required_simple_key_requires_value_at_stream_end() {
6909 let error = first_scanner_error("a:\n&b\n- c\n");
6910
6911 assert_eq!(error.kind(), &ErrorKind::SimpleKeyExpected);
6912 assert_eq!(error.marker().index(), 3);
6913 assert_eq!(error.marker().line(), 2);
6914 assert_eq!(error.marker().col(), 0);
6915 }
6916
6917 #[test]
6918 fn first_simple_key_tracks_ordered_possible_candidates() {
6919 let deep = alloc::format!(
6920 "{}{}{{[é, z]: v}}{}\n",
6921 "[".repeat(240),
6922 "a, ".repeat(400),
6923 "]".repeat(240)
6924 );
6925 for source in [
6926 "",
6927 "a: b\nmissing",
6928 "a: b\nmissing\n# after\nnext: value\n",
6929 "{[a, {b: c}]: [d, e], []: f}\n",
6930 "[&a !tag [x, y], *a, {z: []}]\n",
6931 "key: {\n&anchor\nname: value}\n",
6932 "---\n{[a, b]: c} # end\n...\n# next\n---\nx: y\n",
6933 "a: b\n[unterminated",
6934 &deep,
6935 ] {
6936 for limit in [0, 4, 1024, usize::MAX] {
6937 #[cfg(feature = "comments")]
6938 let emission_modes = [false, true].as_slice();
6939 #[cfg(not(feature = "comments"))]
6940 let emission_modes = [false].as_slice();
6941 for &emit_comments in emission_modes {
6942 let options = crate::options! { simple_key_max_lookahead: limit };
6943 #[cfg(feature = "comments")]
6944 let options = {
6945 let mut options = options;
6946 options.emit_comments = emit_comments;
6947 options
6948 };
6949 let mut scanner = Scanner::with_options(StrInput::new(source), options);
6950 loop {
6951 let result = scanner.next();
6952 assert_eq!(
6953 scanner.first_simple_key,
6954 scanner.simple_keys.iter().position(|key| key.possible),
6955 "source: {source:?}, limit: {limit}, comments: {emit_comments}"
6956 );
6957 let mut previous = None;
6958 for key in scanner.simple_keys.iter().filter(|key| key.possible) {
6959 assert!(key.token_number >= scanner.tokens_parsed);
6960 if let Some((index, token_number)) = previous {
6961 assert!(key.mark.index() >= index);
6962 assert!(key.token_number >= token_number);
6963 }
6964 previous = Some((key.mark.index(), key.token_number));
6965 }
6966 if result.is_none() {
6967 break;
6968 }
6969 }
6970 }
6971 }
6972 }
6973 }
6974
6975 #[test]
6976 fn plain_scalar_rejects_dash_before_flow_indicator() {
6977 assert_eq!(
6978 first_scanner_error_kind("[-]\n"),
6979 ErrorKind::PlainScalarStartsWithDashFlowIndicator
6980 );
6981 }
6982
6983 #[test]
6984 fn explicit_key_rejects_tab_used_as_indentation() {
6985 assert_eq!(
6986 first_scanner_error_kind("?\n\tfoo\n"),
6987 ErrorKind::TabNotAllowed
6988 );
6989 }
6990
6991 #[test]
6992 fn flow_mapping_rejects_adjacent_collection_value_after_plain_key() {
6993 assert_eq!(
6994 first_scanner_error_kind("[a:[]]\n"),
6995 ErrorKind::FlowMappingValueAdjacentCollection
6996 );
6997 }
6998
6999 #[test]
7000 fn implicit_flow_mapping_colon_cannot_move_to_next_line() {
7001 assert_eq!(
7002 first_scanner_error_kind("[foo\n: bar]\n"),
7003 ErrorKind::InvalidColonPlacement
7004 );
7005 }
7006
7007 #[test]
7008 fn invalid_simple_key_token_positions_are_scan_errors() {
7009 for (tokens_parsed, token_number) in [(1, 0), (0, 1)] {
7010 let mut scanner = Scanner::new(StrInput::new(": value\n"));
7011 scanner.fetch_stream_start();
7012 scanner.tokens.clear();
7013 scanner.tokens_parsed = tokens_parsed;
7014
7015 let simple_key = scanner
7016 .simple_keys
7017 .last_mut()
7018 .expect("stream start should create a simple key slot");
7019 simple_key.possible = true;
7020 simple_key.token_number = token_number;
7021
7022 let error = scanner
7023 .fetch_value()
7024 .expect_err("invalid simple key position should be reported as a scan error");
7025 assert_eq!(error.kind(), &ErrorKind::InvalidSimpleKey);
7026 assert_eq!(error.marker(), &Marker::new(0, 1, 0));
7027 }
7028 }
7029
7030 #[test]
7031 fn issue14_alias_scanner_consumes_colon_as_name_character() {
7032 let mut scanner = Scanner::new(StrInput::new("*foo: bar\n"));
7033
7034 assert!(matches!(
7035 scanner.next_token().unwrap().unwrap().1,
7036 TokenType::StreamStart
7037 ));
7038
7039 let token = scanner.next_token().unwrap().unwrap();
7040
7041 assert!(
7042 matches!(token.1, TokenType::Alias { ref name } if name.as_ref() == "foo:"),
7043 "expected `*foo: bar` to start with Alias(\"foo:\"), got {token:?}"
7044 );
7045 }
7046
7047 #[test]
7048 fn issue14_anchor_scanner_consumes_colon_as_name_character() {
7049 let mut scanner = Scanner::new(StrInput::new("&foo: bar\n"));
7050
7051 assert!(matches!(
7052 scanner.next_token().unwrap().unwrap().1,
7053 TokenType::StreamStart
7054 ));
7055
7056 let token = scanner.next_token().unwrap().unwrap();
7057
7058 assert!(
7059 matches!(token.1, TokenType::Anchor { ref name } if name.as_ref() == "foo:"),
7060 "expected `&foo: bar` to start with Anchor(\"foo:\"), got {token:?}"
7061 );
7062 }
7063}