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 #[cfg(feature = "extended_details")]
3732 let syntax = {
3733 let content_indent = if increment == 0 && self.mark.line() == header_start.line() {
3734 (self.indent + 1).max(0) as usize
3735 } else {
3736 indent
3737 };
3738 BlockScalarSyntax::new(
3739 chomping,
3740 (increment > 0).then_some(increment),
3741 content_indent,
3742 )
3743 .map(|mut syntax| {
3744 syntax.digit_first = digit_first;
3745 syntax
3746 })
3747 };
3748 self.ensure_current_char_is_printable()?;
3749
3750 if self.input.next_is_z() {
3755 let contents = match chomping {
3756 Chomping::Strip => String::new(),
3758 _ if self.mark.line == start_mark.line() => String::new(),
3760 Chomping::Clip => String::new(),
3762 Chomping::Keep if trailing_breaks == 0 && self.mark.col > 0 => {
3765 if chomping_break && !self.options.block_scalar_eof_without_line_feed {
3766 "\n".into()
3767 } else {
3768 String::new()
3769 }
3770 }
3771 Chomping::Keep => "\n".repeat(trailing_breaks),
3773 };
3774
3775 let style = if literal {
3776 ScalarStyle::literal()
3777 } else {
3778 ScalarStyle::folded()
3779 };
3780 #[cfg(feature = "extended_details")]
3781 let style = syntax.map_or(style, |syntax| style.with_block_syntax(syntax));
3782 return Ok(Token(
3783 Span::new(start_mark, self.mark),
3784 TokenType::Scalar {
3785 style,
3786 value: contents.into(),
3787 },
3788 ));
3789 }
3790
3791 if self.mark.col < indent && (self.mark.col as isize) > self.indent {
3792 if self.indent < 0 && self.mark.col == 0 {
3793 self.input.lookahead(4);
3794 if self.input.next_is_document_start()
3795 || self.input.next_is_document_end()
3796 || self.input.peek() == '#'
3797 {
3798 } else {
3802 return Err(self.scan_error(ErrorKind::InvalidBlockScalarIndent));
3803 }
3804 } else {
3805 return Err(self.scan_error(ErrorKind::InvalidBlockScalarIndent));
3806 }
3807 }
3808
3809 let start_mark = self.mark;
3810 #[cfg(feature = "extended_details")]
3811 let syntax = syntax.and_then(|syntax| {
3812 let header_chars_before_span = start_mark.index() - header_start.index();
3813 let header_bytes_before_span = start_mark
3814 .byte_offset()
3815 .zip(header_start.byte_offset())
3816 .map_or(0, |(body, header)| body - header);
3817 syntax.with_header_offsets(header_chars_before_span, header_bytes_before_span)
3818 });
3819 while self.mark.col == indent && !self.input.next_is_z() {
3820 self.ensure_current_char_is_printable()?;
3821
3822 if indent == 0 {
3823 self.input.lookahead(4);
3824 if self.input.next_is_document_indicator() {
3825 break;
3826 }
3827 }
3828
3829 trailing_blank = self.input.next_is_blank();
3831 if !literal && leading_break && !leading_blank && !trailing_blank {
3832 string.extend(core::iter::repeat('\n').take(trailing_breaks));
3833 if trailing_breaks == 0 {
3834 string.push(' ');
3835 }
3836 } else {
3837 if leading_break {
3838 string.push('\n');
3839 }
3840 string.extend(core::iter::repeat('\n').take(trailing_breaks));
3841 }
3842
3843 leading_break = false;
3844 trailing_breaks = 0;
3845
3846 leading_blank = self.input.next_is_blank();
3847
3848 self.scan_block_scalar_content_line(&mut string);
3849
3850 self.input.lookahead(2);
3852 if self.input.next_is_z() {
3853 break;
3854 }
3855
3856 self.ensure_current_char_is_printable()?;
3857
3858 self.skip_break();
3859 leading_break = true;
3860
3861 self.skip_block_scalar_indent(indent, &mut trailing_breaks);
3863 }
3864
3865 self.ensure_current_char_is_printable()?;
3866
3867 if chomping != Chomping::Strip {
3869 if !leading_break
3876 && !self.options.block_scalar_eof_without_line_feed
3877 && self.input.next_is_z()
3878 && self.mark.col >= indent.max(1)
3879 {
3880 string.push('\n');
3881 }
3882 if leading_break {
3883 string.push('\n');
3884 }
3885 }
3886
3887 if chomping == Chomping::Keep {
3888 string.extend(core::iter::repeat('\n').take(trailing_breaks));
3889 }
3890
3891 if let Some(character) = find_non_printable(&string) {
3892 return Err(ScanError::from_kind(
3893 start_mark,
3894 ErrorKind::UnexpectedCharacter { character },
3895 ));
3896 }
3897
3898 let span = if string.trim().is_empty() {
3899 Span::new(start_mark, self.mark)
3900 } else {
3901 Span::new(start_mark, self.mark).with_indent(Some(indent))
3902 };
3903
3904 let style = if literal {
3905 ScalarStyle::literal()
3906 } else {
3907 ScalarStyle::folded()
3908 };
3909 #[cfg(feature = "extended_details")]
3910 let style = syntax.map_or(style, |syntax| style.with_block_syntax(syntax));
3911 Ok(Token(
3912 span,
3913 TokenType::Scalar {
3914 style,
3915 value: string.into(),
3916 },
3917 ))
3918 }
3919
3920 fn scan_block_scalar_content_line(&mut self, string: &mut String) {
3925 let chars_consumed = self.input.fetch_block_scalar_line(string);
3926 self.mark.col += chars_consumed;
3927 self.mark.offsets.chars += chars_consumed;
3928 self.mark.offsets.bytes = self.input.byte_offset();
3929 }
3932
3933 fn skip_block_scalar_indent(&mut self, indent: usize, breaks: &mut usize) {
3935 loop {
3936 if indent < self.input.bufmaxlen().saturating_sub(2) {
3938 self.input.lookahead(self.input.bufmaxlen());
3939 while self.mark.col < indent && self.input.peek() == ' ' {
3940 self.skip_blank();
3941 }
3942 } else {
3943 loop {
3944 self.input.lookahead(self.input.bufmaxlen());
3945 while !self.input.buf_is_empty()
3946 && self.mark.col < indent
3947 && self.input.peek() == ' '
3948 {
3949 self.skip_blank();
3950 }
3951 if self.mark.col == indent
3955 || (!self.input.buf_is_empty() && self.input.peek() != ' ')
3956 {
3957 break;
3958 }
3959 }
3960 self.input.lookahead(2);
3961 }
3962
3963 if self.input.next_is_break() {
3965 self.skip_break();
3966 *breaks += 1;
3967 } else {
3968 break;
3970 }
3971 }
3972 }
3973
3974 fn skip_block_scalar_first_line_indent(&mut self, indent: &mut usize, breaks: &mut usize) {
3979 let mut max_indent = 0;
3980 loop {
3981 while self.input.look_ch() == ' ' {
3983 self.skip_blank();
3984 }
3985
3986 if self.mark.col > max_indent {
3987 max_indent = self.mark.col;
3988 }
3989
3990 if self.input.next_is_break() {
3991 self.input.lookahead(2);
3993 self.skip_break();
3994 *breaks += 1;
3995 } else {
3996 break;
3998 }
3999 }
4000
4001 *indent = max_indent.max((self.indent + 1) as usize);
4010 }
4011
4012 fn fetch_flow_scalar(&mut self, single: bool) -> ScanResult {
4013 self.save_simple_key();
4014 self.disallow_simple_key();
4015
4016 let token_index = self.tokens.len();
4017 let tok = self.scan_flow_scalar(single)?;
4018
4019 if self.skip_to_next_token()?.saw_comment {
4022 self.adjacent_value_allowed_at = usize::MAX;
4023 } else {
4024 self.adjacent_value_allowed_at = self.mark.index();
4025 }
4026
4027 self.insert_token(token_index, tok);
4028 Ok(())
4029 }
4030
4031 #[allow(clippy::too_many_lines)]
4032 fn scan_flow_scalar(&mut self, single: bool) -> Result<Token<'input>, ScanError> {
4033 let start_mark = self.mark;
4034
4035 let mut buf = match self.input.byte_offset() {
4037 Some(off) => FlowScalarBuf::new_borrowed(off + self.input.peek().len_utf8()),
4038 None => FlowScalarBuf::new_owned(),
4039 };
4040
4041 self.skip_non_blank();
4043
4044 loop {
4045 self.input.lookahead(4);
4047
4048 if self.mark.col == 0 && self.input.next_is_document_indicator() {
4049 return Err(ScanError::from_kind(
4050 start_mark,
4051 ErrorKind::DocumentIndicatorInQuotedScalar,
4052 ));
4053 }
4054
4055 if self.input.next_is_z() {
4056 return Err(ScanError::from_kind(
4057 start_mark,
4058 ErrorKind::UnclosedQuotedScalar,
4059 ));
4060 }
4061
4062 self.ensure_current_char_is_printable()?;
4063
4064 let mut leading_blanks = false;
4066 self.consume_flow_scalar_non_whitespace_chars(
4067 single,
4068 &mut buf,
4069 &mut leading_blanks,
4070 &start_mark,
4071 )?;
4072
4073 match self.input.look_ch() {
4074 '\'' if single && !leading_blanks => break,
4075 '"' if !single && !leading_blanks => break,
4076 _ => {}
4077 }
4078
4079 let mut trailing_ws_start: Option<usize> = None;
4095 let mut has_leading_break = false;
4096 let mut has_trailing_breaks = false;
4097
4098 let mut pending_ws_start: Option<usize> = None;
4100
4101 while self.input.next_is_blank() || self.input.next_is_break() {
4103 if self.input.next_is_blank() {
4104 if leading_blanks {
4106 if self.options.strict_indentation && self.input.peek() == '\t' {
4109 let indent = if self.flow_level > 0 {
4110 self.flow_block_indent() + 1
4111 } else {
4112 self.indent
4113 };
4114 if (self.mark.col as isize) < indent {
4115 return Err(self.scan_error(ErrorKind::TabInIndentation));
4116 }
4117 }
4118 self.skip_blank();
4119 } else {
4120 match buf {
4122 FlowScalarBuf::Owned(ref mut string) => {
4123 if trailing_ws_start.is_none() {
4124 trailing_ws_start = Some(string.len());
4125 }
4126 string.push(self.input.peek());
4127 }
4128 FlowScalarBuf::Borrowed { .. } => {
4129 if pending_ws_start.is_none() {
4130 pending_ws_start = self.input.byte_offset();
4131 }
4132 }
4133 }
4134 self.skip_blank();
4135
4136 if let (FlowScalarBuf::Borrowed { .. }, Some(ws_start), Some(ws_end)) =
4137 (&mut buf, pending_ws_start, self.input.byte_offset())
4138 {
4139 buf.note_pending_ws(ws_start, ws_end);
4140 }
4141 }
4142 } else {
4143 self.input.lookahead(2);
4144
4145 if leading_blanks {
4147 match buf {
4149 FlowScalarBuf::Owned(ref mut string) => self.read_break(string),
4150 FlowScalarBuf::Borrowed { .. } => {
4151 self.promote_flow_scalar_buf_to_owned(&start_mark, &mut buf)?;
4152 let Some(string) = buf.as_owned_mut() else {
4153 unreachable!()
4154 };
4155 self.read_break(string);
4156 }
4157 }
4158 has_trailing_breaks = true;
4159 } else {
4160 if let Some(pos) = trailing_ws_start.take() {
4162 if let FlowScalarBuf::Owned(ref mut string) = buf {
4163 string.truncate(pos);
4164 }
4165 }
4166
4167 if pending_ws_start.take().is_some() {
4168 if matches!(buf, FlowScalarBuf::Borrowed { .. }) {
4170 self.promote_flow_scalar_buf_to_owned(&start_mark, &mut buf)?;
4171 }
4172 buf.discard_pending_ws();
4173 } else {
4174 buf.commit_pending_ws();
4175 }
4176
4177 self.skip_break();
4178
4179 has_leading_break = true;
4180 leading_blanks = true;
4181 }
4182 }
4183
4184 self.input.lookahead(1);
4185 }
4186
4187 if leading_blanks
4191 && self.options.strict_indentation
4192 && (self.mark.col as isize) <= self.flow_block_indent()
4193 {
4194 let kind = if has_leading_break && self.flow_level == 0 {
4195 ErrorKind::InvalidQuotedScalarIndent
4196 } else {
4197 ErrorKind::InvalidIndentation
4198 };
4199 return Err(self.scan_error(kind));
4200 }
4201
4202 if leading_blanks {
4204 if has_leading_break && !has_trailing_breaks {
4209 match buf {
4210 FlowScalarBuf::Owned(ref mut string) => string.push(' '),
4211 FlowScalarBuf::Borrowed { .. } => {
4212 self.promote_flow_scalar_buf_to_owned(&start_mark, &mut buf)?;
4213 let Some(string) = buf.as_owned_mut() else {
4214 unreachable!()
4215 };
4216 string.push(' ');
4217 }
4218 }
4219 }
4220 }
4221 } self.skip_non_blank();
4226 let end_mark = self.mark;
4227
4228 self.skip_ws_to_eol(SkipTabs::Yes)?;
4230 self.ensure_current_char_is_printable()?;
4231 match self.input.peek() {
4232 ',' | '}' | ']' if self.flow_level > 0 => {}
4234 c if is_breakz(c) => {}
4236 ':' if self.flow_level == 0 && start_mark.line == self.mark.line => {}
4239 ':' if self.flow_level > 0 => {}
4241 _ => {
4242 let kind = if single {
4243 ErrorKind::InvalidTrailingSingleQuotedScalar
4244 } else {
4245 ErrorKind::InvalidTrailingDoubleQuotedScalar
4246 };
4247 return Err(self.scan_error(kind));
4248 }
4249 }
4250
4251 let style = if single {
4252 ScalarStyle::SingleQuoted
4253 } else {
4254 ScalarStyle::DoubleQuoted
4255 };
4256
4257 let contents = match buf {
4258 FlowScalarBuf::Owned(string) => Cow::Owned(string),
4259 FlowScalarBuf::Borrowed {
4260 start,
4261 mut end,
4262 pending_ws_start,
4263 pending_ws_end,
4264 } => {
4265 if pending_ws_start.is_some() {
4267 end = pending_ws_end;
4268 }
4269 if let Some(slice) = self.try_borrow_slice(start, end) {
4270 Cow::Borrowed(slice)
4271 } else {
4272 let slice = self.input.slice_bytes(start, end).ok_or_else(|| {
4273 ScanError::from_kind(start_mark, ErrorKind::InputOffsetsWithoutSlice)
4274 })?;
4275 Cow::Owned(slice.to_owned())
4276 }
4277 }
4278 };
4279
4280 Ok(Token(
4281 Span::new(start_mark, end_mark),
4282 TokenType::Scalar {
4283 style,
4284 value: contents,
4285 },
4286 ))
4287 }
4288
4289 fn consume_flow_scalar_chunk(&mut self, single: bool, buf: &mut FlowScalarBuf) -> bool {
4291 let (chunk, consumed) = self.input.take_quoted_scalar_chunk(single);
4292 if consumed == 0 {
4293 return false;
4294 }
4295
4296 match buf {
4297 FlowScalarBuf::Owned(string) => string.push_str(chunk),
4298 FlowScalarBuf::Borrowed { .. } => buf.commit_pending_ws(),
4299 }
4300
4301 self.mark.offsets.chars += consumed;
4303 self.mark.col += consumed;
4304 self.mark.offsets.bytes = self.input.byte_offset();
4305 self.leading_whitespace = false;
4306 if let (Some(new_end), FlowScalarBuf::Borrowed { end, .. }) = (self.mark.offsets.bytes, buf)
4307 {
4308 *end = new_end;
4309 }
4310 true
4311 }
4312
4313 fn consume_flow_scalar_non_whitespace_chars(
4322 &mut self,
4323 single: bool,
4324 buf: &mut FlowScalarBuf,
4325 leading_blanks: &mut bool,
4326 start_mark: &Marker,
4327 ) -> Result<(), ScanError> {
4328 self.input.lookahead(2);
4329 loop {
4330 let character = self.input.peek();
4331 if is_blank_or_breakz(character) || !is_printable(character) {
4332 break;
4333 }
4334 match character {
4335 '\'' if self.input.peek_nth(1) == '\'' && single => {
4337 if matches!(buf, FlowScalarBuf::Borrowed { .. }) {
4338 buf.commit_pending_ws();
4339 self.promote_flow_scalar_buf_to_owned(start_mark, buf)?;
4340 }
4341 let Some(string) = buf.as_owned_mut() else {
4342 unreachable!()
4343 };
4344 string.push('\'');
4345 self.skip_n_non_blank(2);
4346 }
4347 '\'' if single => break,
4349 '"' if !single => break,
4350 '\\' if !single && is_break(self.input.peek_nth(1)) => {
4352 self.input.lookahead(3);
4353 if matches!(buf, FlowScalarBuf::Borrowed { .. }) {
4354 buf.commit_pending_ws();
4355 self.promote_flow_scalar_buf_to_owned(start_mark, buf)?;
4356 }
4357 self.skip_non_blank();
4358 self.skip_linebreak();
4359 *leading_blanks = true;
4360 break;
4361 }
4362 '\\' if !single => {
4364 if matches!(buf, FlowScalarBuf::Borrowed { .. }) {
4365 buf.commit_pending_ws();
4366 self.promote_flow_scalar_buf_to_owned(start_mark, buf)?;
4367 }
4368 let Some(string) = buf.as_owned_mut() else {
4369 unreachable!()
4370 };
4371 string.push(self.resolve_flow_scalar_escape_sequence(start_mark)?);
4372 }
4373 c => {
4374 if self.consume_flow_scalar_chunk(single, buf) {
4375 self.input.lookahead(2);
4376 continue;
4377 }
4378 match buf {
4379 FlowScalarBuf::Owned(ref mut string) => {
4380 string.push(c);
4381 }
4382 FlowScalarBuf::Borrowed { .. } => {
4383 buf.commit_pending_ws();
4384 }
4385 }
4386 self.skip_non_blank();
4387
4388 if let Some(new_end) = self.input.byte_offset() {
4389 if let FlowScalarBuf::Borrowed { end, .. } = buf {
4390 *end = new_end;
4391 }
4392 }
4393 }
4394 }
4395 self.input.lookahead(2);
4396 }
4397 Ok(())
4398 }
4399
4400 fn resolve_flow_scalar_escape_sequence(
4407 &mut self,
4408 start_mark: &Marker,
4409 ) -> Result<char, ScanError> {
4410 let mut code_length = 0usize;
4411 let mut ret = '\0';
4412
4413 match self.input.peek_nth(1) {
4414 '0' => ret = '\0',
4415 'a' => ret = '\x07',
4416 'b' => ret = '\x08',
4417 't' | '\t' => ret = '\t',
4418 'n' => ret = '\n',
4419 'v' => ret = '\x0b',
4420 'f' => ret = '\x0c',
4421 'r' => ret = '\x0d',
4422 'e' => ret = '\x1b',
4423 ' ' => ret = '\x20',
4424 '"' => ret = '"',
4425 '/' => ret = '/',
4426 '\\' => ret = '\\',
4427 'N' => ret = char::from_u32(0x85).unwrap(),
4429 '_' => ret = char::from_u32(0xA0).unwrap(),
4431 'L' => ret = char::from_u32(0x2028).unwrap(),
4433 'P' => ret = char::from_u32(0x2029).unwrap(),
4435 'x' => code_length = 2,
4436 'u' => code_length = 4,
4437 'U' => code_length = 8,
4438 _ => {
4439 return Err(ScanError::from_kind(
4440 *start_mark,
4441 ErrorKind::UnknownQuotedScalarEscape,
4442 ))
4443 }
4444 }
4445 self.skip_n_non_blank(2);
4446
4447 if code_length > 0 {
4449 self.input.lookahead(code_length);
4450 let mut value = 0u32;
4451 for i in 0..code_length {
4452 let c = self.input.peek_nth(i);
4453 if !is_hex(c) {
4454 return Err(ScanError::from_kind(
4455 *start_mark,
4456 ErrorKind::InvalidQuotedScalarHexEscape,
4457 ));
4458 }
4459 value = (value << 4) + as_hex(c);
4460 }
4461
4462 self.skip_n_non_blank(code_length);
4463
4464 if code_length == 4 && (0xD800..=0xDBFF).contains(&value) {
4466 self.input.lookahead(2);
4467 if self.input.peek() == '\\' && self.input.peek_nth(1) == 'u' {
4468 self.skip_n_non_blank(2);
4469 self.input.lookahead(4);
4470 let mut low_value = 0u32;
4471 for i in 0..4 {
4472 let c = self.input.peek_nth(i);
4473 if !is_hex(c) {
4474 return Err(ScanError::from_kind(
4475 *start_mark,
4476 ErrorKind::InvalidLowSurrogateHexEscape,
4477 ));
4478 }
4479 low_value = (low_value << 4) + as_hex(c);
4480 }
4481 if (0xDC00..=0xDFFF).contains(&low_value) {
4482 value = 0x10000 + (((value - 0xD800) << 10) | (low_value - 0xDC00));
4483 self.skip_n_non_blank(4);
4484 } else {
4485 return Err(ScanError::from_kind(
4486 *start_mark,
4487 ErrorKind::InvalidLowSurrogate,
4488 ));
4489 }
4490 } else {
4491 return Err(ScanError::from_kind(
4492 *start_mark,
4493 ErrorKind::MissingLowSurrogate,
4494 ));
4495 }
4496 } else if code_length == 4 && (0xDC00..=0xDFFF).contains(&value) {
4497 return Err(ScanError::from_kind(
4498 *start_mark,
4499 ErrorKind::UnpairedLowSurrogate,
4500 ));
4501 }
4502
4503 let Some(ch) = char::from_u32(value) else {
4504 return Err(ScanError::from_kind(
4505 *start_mark,
4506 ErrorKind::InvalidUnicodeEscape,
4507 ));
4508 };
4509 ret = ch;
4510 }
4511 Ok(ret)
4512 }
4513
4514 fn fetch_plain_scalar(&mut self) -> ScanResult {
4515 self.save_simple_key();
4516 self.disallow_simple_key();
4517
4518 let token_index = self.tokens.len();
4519 let tok = self.scan_plain_scalar()?;
4520
4521 self.insert_token(token_index, tok);
4522 Ok(())
4523 }
4524
4525 #[allow(clippy::too_many_lines)]
4530 fn scan_plain_scalar(&mut self) -> Result<Token<'input>, ScanError> {
4531 self.unroll_non_block_indents();
4532 let indent = self.indent + 1;
4533 let start_mark = self.mark;
4534
4535 let borrow_start = start_mark
4536 .byte_offset()
4537 .filter(|start| self.try_borrow_slice(*start, *start).is_some());
4538 let mut string = borrow_start.is_none().then(|| String::with_capacity(32));
4539 let mut has_content = false;
4540 self.buf_whitespaces.clear();
4541 self.buf_leading_break.clear();
4542 self.buf_trailing_breaks.clear();
4543 let mut end_mark = self.mark;
4544
4545 loop {
4546 self.input.lookahead(4);
4547 if (self.mark.col == 0 && self.input.next_is_document_indicator())
4548 || self.input.peek() == '#'
4549 {
4550 if self.input.peek() == '#'
4555 && has_content
4556 && !self.buf_whitespaces.is_empty()
4557 && self.flow_level == 0
4558 {
4559 self.interrupted_plain_by_comment = Some(self.mark);
4560 }
4561 break;
4562 }
4563
4564 if !has_content
4566 && self.flow_level > 0
4567 && self.input.peek() == '-'
4568 && is_flow(self.input.peek_nth(1))
4569 {
4570 return Err(self.scan_error(ErrorKind::PlainScalarStartsWithDashFlowIndicator));
4571 }
4572
4573 if !self.input.next_is_blank_or_breakz()
4574 && self.input.next_can_be_plain_scalar(self.flow_level > 0)
4575 {
4576 if self.leading_whitespace {
4577 if has_content && string.is_none() {
4578 let start = borrow_start.expect("borrowed scalar has a start offset");
4579 let end = end_mark.byte_offset().ok_or_else(|| {
4580 ScanError::from_kind(start_mark, ErrorKind::InputOffsetsWithoutSlice)
4581 })?;
4582 let prefix = self.try_borrow_slice(start, end).ok_or_else(|| {
4583 ScanError::from_kind(start_mark, ErrorKind::InputOffsetsWithoutSlice)
4584 })?;
4585 string = Some(prefix.to_owned());
4586 }
4587 if self.buf_leading_break.is_empty() {
4588 if let Some(output) = string.as_mut() {
4589 output.push_str(&self.buf_leading_break);
4590 output.push_str(&self.buf_trailing_breaks);
4591 }
4592 self.buf_trailing_breaks.clear();
4593 self.buf_leading_break.clear();
4594 } else {
4595 if self.buf_trailing_breaks.is_empty() {
4596 if let Some(output) = string.as_mut() {
4597 output.push(' ');
4598 }
4599 } else {
4600 if let Some(output) = string.as_mut() {
4601 output.push_str(&self.buf_trailing_breaks);
4602 }
4603 self.buf_trailing_breaks.clear();
4604 }
4605 self.buf_leading_break.clear();
4606 }
4607 self.leading_whitespace = false;
4608 } else if !self.buf_whitespaces.is_empty() {
4609 if let Some(output) = string.as_mut() {
4610 output.push_str(&self.buf_whitespaces);
4611 }
4612 self.buf_whitespaces.clear();
4613 }
4614
4615 has_content = true;
4617 if let Some(output) = string.as_mut() {
4618 output.push(self.input.peek());
4619 }
4620 self.skip_non_blank();
4621 if let Some(output) = string.as_mut() {
4622 output.reserve(self.input.bufmaxlen());
4623 }
4624
4625 let mut end = false;
4627 while !end {
4628 self.input.lookahead(self.input.bufmaxlen());
4633 let chunk_len = self.input.bufmaxlen().saturating_sub(1).max(1);
4634 let (stop, chars_consumed) = if let Some(output) = string.as_mut() {
4635 self.input
4636 .fetch_plain_scalar_chunk(output, chunk_len, self.flow_level > 0)
4637 } else {
4638 self.input
4639 .skip_plain_scalar_chunk(chunk_len, self.flow_level > 0)
4640 };
4641 end = stop;
4642 self.mark.offsets.chars += chars_consumed;
4643 self.mark.col += chars_consumed;
4644 self.mark.offsets.bytes = self.input.byte_offset();
4645 }
4646 end_mark = self.mark;
4647 }
4648
4649 if !(self.input.next_is_blank() || self.input.next_is_break()) {
4654 break;
4655 }
4656
4657 self.input.lookahead(2);
4659 while self.input.next_is_blank_or_break() {
4660 if self.input.next_is_blank() {
4661 if !self.leading_whitespace {
4662 self.buf_whitespaces.push(self.input.peek());
4663 self.skip_blank();
4664 } else if (self.mark.col as isize) < indent && self.input.peek() == '\t' {
4665 self.skip_ws_to_eol(SkipTabs::Yes)?;
4668 if !self.input.next_is_breakz() {
4669 return Err(ScanError::from_kind(
4670 start_mark,
4671 ErrorKind::TabInPlainScalar,
4672 ));
4673 }
4674 } else {
4675 self.skip_blank();
4676 }
4677 } else {
4678 if self.leading_whitespace {
4680 self.skip_break();
4681 self.buf_trailing_breaks.push('\n');
4682 } else {
4683 self.buf_whitespaces.clear();
4684 self.skip_break();
4685 self.buf_leading_break.push('\n');
4686 self.leading_whitespace = true;
4687 }
4688 }
4689 self.input.lookahead(2);
4690 }
4691
4692 if (self.flow_level == 0 || self.options.strict_indentation)
4695 && (self.mark.col as isize) < indent
4696 {
4697 break;
4698 }
4699 }
4700
4701 if self.leading_whitespace {
4702 self.allow_simple_key();
4703 }
4704
4705 let borrowed_contents = if string.is_none() {
4706 let start = borrow_start.expect("borrowed scalar has a start offset");
4707 let end = end_mark.byte_offset().ok_or_else(|| {
4708 ScanError::from_kind(start_mark, ErrorKind::InputOffsetsWithoutSlice)
4709 })?;
4710 Some(self.try_borrow_slice(start, end).ok_or_else(|| {
4711 ScanError::from_kind(start_mark, ErrorKind::InputOffsetsWithoutSlice)
4712 })?)
4713 } else {
4714 None
4715 };
4716 let scalar_text = borrowed_contents.unwrap_or_else(|| {
4717 string
4718 .as_deref()
4719 .expect("owned plain scalar has an output buffer")
4720 });
4721 if let Some(character) = find_non_printable(scalar_text) {
4722 return Err(ScanError::from_kind(
4723 start_mark,
4724 ErrorKind::UnexpectedCharacter { character },
4725 ));
4726 }
4727 self.ensure_current_char_is_printable()?;
4728
4729 if has_content {
4730 let contents = if let Some(slice) = borrowed_contents {
4731 Cow::Borrowed(slice)
4732 } else {
4733 Cow::Owned(string.expect("owned plain scalar has an output buffer"))
4734 };
4735
4736 Ok(Token(
4737 Span::new(start_mark, end_mark),
4738 TokenType::Scalar {
4739 style: ScalarStyle::plain(),
4740 value: contents,
4741 },
4742 ))
4743 } else {
4744 Err(ScanError::from_kind(
4748 start_mark,
4749 ErrorKind::UnexpectedEndOfPlainScalar,
4750 ))
4751 }
4752 }
4753
4754 fn fetch_key(&mut self) -> ScanResult {
4755 let start_mark = self.mark;
4756 if self.flow_level == 0 {
4757 if !self.simple_key_allowed {
4759 return Err(self.scan_error(ErrorKind::MappingKeyNotAllowed));
4760 }
4761 self.roll_indent(
4762 start_mark.col,
4763 None,
4764 TokenType::BlockMappingStart,
4765 start_mark,
4766 )?;
4767 } else {
4768 self.set_current_flow_mapping_started(true);
4770 }
4771
4772 self.remove_simple_key()?;
4773
4774 if self.flow_level == 0 {
4775 self.allow_simple_key();
4776 } else {
4777 self.disallow_simple_key();
4778 }
4779
4780 self.skip_non_blank();
4781 let end_mark = self.mark;
4782 let token_index = self.tokens.len();
4783 self.explicit_key_tab_check_pending = false;
4784 if self.flow_level == 0 {
4789 let stopped_after_comment = self.skip_yaml_whitespace()?;
4790 self.explicit_key_tab_check_pending = stopped_after_comment
4791 || (self.options.strict_indentation && matches!(self.input.peek(), '&' | '!'));
4792 }
4793 self.insert_token(
4794 token_index,
4795 Token(Span::new(start_mark, end_mark), TokenType::Key),
4796 );
4797 Ok(())
4798 }
4799
4800 fn fetch_flow_value(&mut self) -> ScanResult {
4808 let nc = self.input.peek_nth(1);
4809
4810 if self.mark.index() != self.adjacent_value_allowed_at && (nc == '[' || nc == '{') {
4822 return Err(self.scan_error(ErrorKind::FlowMappingValueAdjacentCollection));
4823 }
4824
4825 self.fetch_value()
4826 }
4827
4828 fn fetch_value(&mut self) -> ScanResult {
4830 let sk = *self.simple_keys.last().unwrap();
4831 let start_mark = self.mark;
4832 let is_implicit_flow_mapping = self.current_flow_collection_is_sequence()
4833 && !self.current_flow_mapping_started()
4834 && !self.implicit_flow_mapping_states.is_empty();
4835 if is_implicit_flow_mapping {
4836 *self.implicit_flow_mapping_states.last_mut().unwrap() =
4837 ImplicitMappingState::Inside(self.flow_level);
4838 }
4839
4840 self.skip_non_blank();
4842 let mut trailing_comment = None;
4845 let mut found_tabs = false;
4846 if matches!(self.input.look_ch(), ' ' | '\t') {
4847 let trailing_token_index = self.tokens.len();
4848 found_tabs = self.skip_ws_to_eol(SkipTabs::Yes)?.found_tabs();
4849 debug_assert!(self.tokens.len() <= trailing_token_index + 1);
4851 if self.tokens.len() > trailing_token_index {
4852 trailing_comment = self.tokens.pop_back();
4853 }
4854 }
4855
4856 if sk.possible {
4857 let block_indent = self.flow_block_indent();
4861 if self.flow_level > 0
4862 && sk.mark.line < start_mark.line
4863 && (sk.mark.col as isize) <= block_indent
4864 {
4865 return Err(ScanError::from_kind(
4866 start_mark,
4867 ErrorKind::InvalidColonPlacement,
4868 ));
4869 }
4870 let token_index = self.simple_key_token_index(&sk, start_mark)?;
4871 self.validate_flow_key_indentation(&sk, token_index, start_mark)?;
4872 let tok = Token(Span::empty(sk.mark), TokenType::Key);
4874 self.insert_token(token_index, tok);
4875 if is_implicit_flow_mapping {
4876 if sk.mark.line < start_mark.line {
4877 return Err(ScanError::from_kind(
4878 start_mark,
4879 ErrorKind::InvalidColonPlacement,
4880 ));
4881 }
4882 self.insert_token(
4883 token_index,
4884 Token(Span::empty(sk.mark), TokenType::FlowMappingStart),
4885 );
4886 }
4887
4888 self.roll_indent(
4890 sk.mark.col,
4891 Some(sk.token_number),
4892 TokenType::BlockMappingStart,
4893 sk.mark,
4894 )?;
4895 self.roll_one_col_indent();
4896
4897 self.clear_simple_key();
4898 self.disallow_simple_key();
4899 } else {
4900 if is_implicit_flow_mapping {
4901 self.tokens
4902 .push_back(Token(Span::empty(start_mark), TokenType::FlowMappingStart).into());
4903 }
4904 if self.flow_level == 0 {
4906 if !self.simple_key_allowed {
4907 return Err(ScanError::from_kind(
4908 start_mark,
4909 ErrorKind::MappingValueNotAllowed,
4910 ));
4911 }
4912
4913 self.roll_indent(
4914 start_mark.col,
4915 None,
4916 TokenType::BlockMappingStart,
4917 start_mark,
4918 )?;
4919 }
4920 self.roll_one_col_indent();
4921
4922 if self.flow_level == 0 && !found_tabs {
4925 self.allow_simple_key();
4926 } else {
4927 self.disallow_simple_key();
4928 }
4929 }
4930 self.tokens
4931 .push_back(Token(Span::empty(start_mark), TokenType::Value).into());
4932 if let Some(comment) = trailing_comment {
4933 self.tokens.push_back(comment);
4934 }
4935
4936 Ok(())
4937 }
4938
4939 fn validate_flow_key_indentation(
4941 &self,
4942 key: &SimpleKey,
4943 token_index: usize,
4944 colon: Marker,
4945 ) -> ScanResult {
4946 if self.flow_level == 0 || key.mark.line == colon.line {
4947 return Ok(());
4948 }
4949
4950 let block_indent = self.flow_block_indent();
4951 let mut under_indented = [key.mark.col, colon.col]
4955 .iter()
4956 .any(|&col| (col as isize) <= block_indent);
4957 for token in self.tokens.iter().skip(token_index) {
4958 #[cfg(feature = "comments")]
4959 if matches!(token.1, QueuedTokenType::Comment(_)) {
4960 continue;
4961 }
4962 under_indented |= (token.0.start.col as isize) <= block_indent;
4963 if !matches!(
4964 token.1,
4965 QueuedTokenType::Anchor(_) | QueuedTokenType::Tag(..)
4966 ) {
4967 break;
4968 }
4969 }
4970 if under_indented {
4971 return Err(ScanError::from_kind(
4972 colon,
4973 ErrorKind::InvalidColonPlacement,
4974 ));
4975 }
4976 Ok(())
4977 }
4978
4979 fn flow_block_indent(&self) -> isize {
4981 self.indents
4982 .last()
4983 .filter(|indent| !indent.needs_block_end)
4984 .map_or(self.indent, |indent| indent.indent)
4985 }
4986
4987 fn roll_indent(
4993 &mut self,
4994 col: usize,
4995 number: Option<usize>,
4996 tok: TokenType<'input>,
4997 mark: Marker,
4998 ) -> ScanResult {
4999 if self.flow_level > 0 {
5000 return Ok(());
5001 }
5002
5003 if self.indent <= col as isize {
5007 if let Some(indent) = self.indents.last() {
5008 if !indent.needs_block_end {
5009 self.indent = indent.indent;
5010 self.indents.pop();
5011 }
5012 }
5013 }
5014
5015 if self.indent < col as isize {
5016 if self.block_level >= self.options.block_nesting_limit {
5017 return Err(ScanError::from_kind(
5018 mark,
5019 ErrorKind::RecursionLimitExceeded,
5020 ));
5021 }
5022 self.indents.push(Indent {
5023 indent: self.indent,
5024 needs_block_end: true,
5025 });
5026 self.block_level += 1;
5027 self.indent = col as isize;
5028 let tokens_parsed = self.tokens_parsed;
5029 match number {
5030 Some(n) => self.insert_token(n - tokens_parsed, Token(Span::empty(mark), tok)),
5031 None => self.tokens.push_back(Token(Span::empty(mark), tok).into()),
5032 }
5033 }
5034 Ok(())
5035 }
5036
5037 fn unroll_indent(&mut self, col: isize) {
5043 if self.flow_level > 0 {
5044 return;
5045 }
5046 while self.indent > col {
5047 let indent = self.indents.pop().unwrap();
5048 self.indent = indent.indent;
5049 if indent.needs_block_end {
5050 debug_assert!(self.block_level > 0);
5051 self.block_level -= 1;
5052 self.tokens
5053 .push_back(Token(Span::empty(self.mark), TokenType::BlockEnd).into());
5054 }
5055 }
5056 }
5057
5058 fn roll_one_col_indent(&mut self) {
5064 if self.flow_level == 0 && self.indents.last().is_some_and(|x| x.needs_block_end) {
5065 self.indents.push(Indent {
5066 indent: self.indent,
5067 needs_block_end: false,
5068 });
5069 self.indent += 1;
5070 }
5071 }
5072
5073 fn unroll_non_block_indents(&mut self) {
5075 while let Some(indent) = self.indents.last() {
5076 if indent.needs_block_end {
5077 break;
5078 }
5079 self.indent = indent.indent;
5080 self.indents.pop();
5081 }
5082 }
5083
5084 fn save_simple_key(&mut self) {
5086 if self.simple_key_allowed {
5087 let required = self.flow_level == 0
5088 && self.indent == (self.mark.col as isize)
5089 && self.indents.last().unwrap().needs_block_end;
5090
5091 if let Some(last) = self.simple_keys.last_mut() {
5092 *last = SimpleKey {
5093 mark: self.mark,
5094 possible: true,
5095 required,
5096 token_number: self.tokens_parsed + self.tokens.len(),
5097 };
5098 self.first_simple_key.get_or_insert(self.flow_level);
5099 }
5100 }
5101 }
5102
5103 fn remove_simple_key(&mut self) -> ScanResult {
5104 let last = self.simple_keys.last().unwrap();
5105 if last.possible && last.required {
5106 return Err(Self::simple_key_expected(last.mark));
5107 }
5108
5109 self.clear_simple_key();
5110 Ok(())
5111 }
5112
5113 fn clear_simple_key(&mut self) {
5115 self.simple_keys.last_mut().unwrap().possible = false;
5116 if self.first_simple_key == Some(self.flow_level) {
5117 self.first_simple_key = None;
5119 }
5120 }
5121
5122 fn is_within_block(&self) -> bool {
5124 !self.indents.is_empty()
5125 }
5126
5127 fn end_implicit_mapping(&mut self, mark: Marker, flow_level: usize) {
5133 if self
5134 .implicit_flow_mapping_states
5135 .last()
5136 .is_some_and(|state| *state == ImplicitMappingState::Inside(flow_level))
5137 {
5138 *self.implicit_flow_mapping_states.last_mut().unwrap() = ImplicitMappingState::Possible;
5139 self.set_current_flow_mapping_started(false);
5140 self.tokens
5141 .push_back(Token(Span::empty(mark), TokenType::FlowMappingEnd).into());
5142 }
5143 }
5144
5145 fn current_flow_collection_is_sequence(&self) -> bool {
5146 self.flow_markers
5147 .last()
5148 .is_some_and(|(_, bracket)| *bracket == '[')
5149 }
5150
5151 fn current_flow_mapping_started(&self) -> bool {
5152 self.flow_mapping_started.last().copied().unwrap_or(false)
5153 }
5154
5155 fn set_current_flow_mapping_started(&mut self, started: bool) {
5156 if let Some(current) = self.flow_mapping_started.last_mut() {
5157 *current = started;
5158 }
5159 }
5160}
5161
5162#[cfg(test)]
5163mod test {
5164 use alloc::{
5165 borrow::{Cow, ToOwned},
5166 rc::Rc,
5167 string::String,
5168 vec,
5169 vec::Vec,
5170 };
5171 use core::cell::Cell;
5172
5173 use crate::error::{ErrorKind, ScanError};
5174 #[cfg(feature = "comments")]
5175 use crate::scanner::{Comment, Placement};
5176 use crate::{
5177 input::{str::StrInput, BorrowedInput, BufferedInput, Input},
5178 scanner::{
5179 Marker, QueuedToken, QueuedTokenType, ScalarStyle, Scanner, Span, Token, TokenType,
5180 },
5181 };
5182
5183 #[test]
5184 fn tag_span_supports_the_full_u32_length_without_allocating() {
5185 let start = Marker::new(0, 1, 0).with_byte_offset(Some(0));
5186 let span = Span::empty(start).with_tag_span(Some((start, u32::MAX)));
5187 let tag_span = span.tag_span().unwrap();
5188 let length = usize::try_from(u32::MAX).unwrap();
5189 assert_eq!(tag_span.start, start);
5190 assert_eq!(tag_span.end.index(), length);
5191 assert_eq!(tag_span.end.col(), length);
5192 assert_eq!(tag_span.end.line(), 1);
5193 assert_eq!(tag_span.end.byte_offset(), Some(length));
5194 }
5195
5196 #[test]
5197 fn tag_span_rejects_overflow_in_each_reconstructed_coordinate() {
5198 for start in [
5199 Marker::new(usize::MAX, 1, 0),
5200 Marker::new(0, 1, usize::MAX),
5201 Marker::new(0, 1, 0).with_byte_offset(Some(usize::MAX)),
5202 ] {
5203 let span = Span::empty(start).with_tag_span(Some((start, 1)));
5204 assert_eq!(span.tag_span(), None);
5205 }
5206 }
5207
5208 #[test]
5209 fn recovery_ignores_invalid_document_marker_lookalikes() {
5210 let input = "@bad\n---# comment\n ---\n---\0\n... trailing\n--- healthy\n";
5211 let mut scanner = Scanner::new(StrInput::new(input));
5212 assert!(matches!(
5213 scanner.next_token().unwrap().unwrap().1,
5214 TokenType::StreamStart
5215 ));
5216 assert!(scanner.next_token().is_err());
5217
5218 scanner.proceed_next_document(None).unwrap();
5219 let token = scanner.next_token().unwrap().unwrap();
5220 assert_eq!(token.1, TokenType::DocumentStart);
5221 assert_eq!(token.0.start.line(), 6);
5222 assert!(matches!(
5223 scanner.next_token().unwrap().unwrap().1,
5224 TokenType::Scalar { style: _, ref value } if value == "healthy"
5225 ));
5226 }
5227
5228 #[test]
5229 fn recovery_rejects_end_marker_queued_before_its_line_failed() {
5230 let mut scanner =
5231 Scanner::new(StrInput::new("... trailing\nnot_a_document\n--- healthy\n"));
5232 scanner.next_token().unwrap();
5233 assert_eq!(
5234 scanner.next_token().unwrap_err().kind(),
5235 &ErrorKind::InvalidDocumentEnd
5236 );
5237 assert!(scanner
5238 .tokens
5239 .iter()
5240 .any(|token| matches!(token.1, QueuedTokenType::DocumentEnd)));
5241
5242 scanner.proceed_next_document(None).unwrap();
5243 let token = scanner.next_token().unwrap().unwrap();
5244 assert_eq!(token.1, TokenType::DocumentStart);
5245 assert_eq!(token.0.start.line(), 3);
5246 }
5247
5248 #[test]
5249 fn recovery_preserves_boundary_already_held_by_parser() {
5250 let mut scanner = Scanner::new(StrInput::new("first\n--- second\n"));
5251 let boundary = loop {
5252 let token = scanner.next_queued_token().unwrap().unwrap();
5253 if matches!(token.1, QueuedTokenType::DocumentStart) {
5254 break token;
5255 }
5256 };
5257 let span = boundary.0;
5258 scanner.proceed_next_document(Some(boundary)).unwrap();
5259 assert_eq!(
5260 scanner.next_token().unwrap().unwrap(),
5261 Token(span, TokenType::DocumentStart)
5262 );
5263 assert!(matches!(
5264 scanner.next_token().unwrap().unwrap().1,
5265 TokenType::Scalar { style: _, ref value } if value == "second"
5266 ));
5267 }
5268
5269 #[test]
5270 fn recovery_retains_previously_reported_source_error() {
5271 let kind = ErrorKind::InputDecoding {
5272 message: "invalid encoding".into(),
5273 };
5274 let input = crate::FallibleBufferedInput::new(
5275 vec![Ok('['), Err(kind.clone()), Ok('\n')].into_iter(),
5276 );
5277 let mut scanner = Scanner::new(input);
5278 scanner.next_token().unwrap();
5279 let error = scanner.next_token().unwrap_err();
5280 assert_eq!(error.kind(), &kind);
5281 assert_eq!(scanner.proceed_next_document(None), Err(error));
5282 }
5283
5284 #[test]
5285 fn recovery_distinguishes_directive_header_errors_from_document_content() {
5286 for input in ["%YAML bad\n--- body\n", "%TAG invalid\n--- body\n"] {
5287 let mut scanner = Scanner::new(StrInput::new(input));
5288 scanner.next_token().unwrap();
5289 assert!(scanner.next_token().is_err());
5290 assert!(scanner.in_directive_prefix());
5291 scanner.proceed_next_document(None).unwrap();
5292 assert!(!scanner.in_directive_prefix());
5293 }
5294
5295 let mut scanner = Scanner::with_options(
5296 StrInput::new("%YAML 1.2\n--- body\n"),
5297 crate::options! { disallow_directives: true },
5298 );
5299 scanner.next_token().unwrap();
5300 assert!(scanner.next_token().is_err());
5301 assert!(scanner.in_directive_prefix());
5302
5303 for input in ["%YAML 1.2\n--- body\n", "%YAML 1.2\nbare\n"] {
5304 let mut scanner = Scanner::new(StrInput::new(input));
5305 scanner.next_token().unwrap();
5306 scanner.next_token().unwrap();
5307 assert!(scanner.in_directive_prefix());
5308 scanner.next_token().unwrap();
5309 assert!(!scanner.in_directive_prefix());
5310 }
5311 }
5312
5313 fn ignoring_comments_options() -> crate::Options {
5314 #[cfg(feature = "comments")]
5315 {
5316 crate::options! { emit_comments: false }
5317 }
5318 #[cfg(not(feature = "comments"))]
5319 {
5320 crate::Options::default()
5321 }
5322 }
5323
5324 struct CountingChars {
5325 chars: alloc::vec::IntoIter<char>,
5326 read: Rc<Cell<usize>>,
5327 }
5328
5329 impl Iterator for CountingChars {
5330 type Item = char;
5331
5332 fn next(&mut self) -> Option<Self::Item> {
5333 let next = self.chars.next();
5334 if next.is_some() {
5335 self.read.set(self.read.get() + 1);
5336 }
5337 next
5338 }
5339 }
5340
5341 struct SlicingOnlyInput<'input> {
5342 inner: StrInput<'input>,
5343 expose_slice: bool,
5344 }
5345
5346 impl<'input> SlicingOnlyInput<'input> {
5347 fn new(source: &'input str, expose_slice: bool) -> Self {
5348 Self {
5349 inner: StrInput::new(source),
5350 expose_slice,
5351 }
5352 }
5353 }
5354
5355 impl Input for SlicingOnlyInput<'_> {
5356 fn lookahead(&mut self, count: usize) {
5357 self.inner.lookahead(count);
5358 }
5359
5360 fn buflen(&self) -> usize {
5361 self.inner.buflen()
5362 }
5363
5364 fn bufmaxlen(&self) -> usize {
5365 self.inner.bufmaxlen()
5366 }
5367
5368 fn raw_read_ch(&mut self) -> char {
5369 self.inner.raw_read_ch()
5370 }
5371
5372 fn raw_read_non_breakz_ch(&mut self) -> Option<char> {
5373 self.inner.raw_read_non_breakz_ch()
5374 }
5375
5376 fn skip(&mut self) {
5377 self.inner.skip();
5378 }
5379
5380 fn skip_n(&mut self, count: usize) {
5381 self.inner.skip_n(count);
5382 }
5383
5384 fn peek(&self) -> char {
5385 self.inner.peek()
5386 }
5387
5388 fn peek_nth(&self, n: usize) -> char {
5389 self.inner.peek_nth(n)
5390 }
5391
5392 fn byte_offset(&self) -> Option<usize> {
5393 self.inner.byte_offset()
5394 }
5395
5396 fn slice_bytes(&self, start: usize, end: usize) -> Option<&str> {
5397 if self.expose_slice {
5398 self.inner.slice_bytes(start, end)
5399 } else {
5400 None
5401 }
5402 }
5403 }
5404
5405 impl<'input> BorrowedInput<'input> for SlicingOnlyInput<'input> {
5406 fn slice_borrowed(&self, _start: usize, _end: usize) -> Option<&'input str> {
5407 None
5408 }
5409 }
5410
5411 struct SmallReportedBufferInput<'input> {
5412 inner: StrInput<'input>,
5413 reported_bufmaxlen: usize,
5414 }
5415
5416 impl<'input> SmallReportedBufferInput<'input> {
5417 fn new(source: &'input str, reported_bufmaxlen: usize) -> Self {
5418 Self {
5419 inner: StrInput::new(source),
5420 reported_bufmaxlen,
5421 }
5422 }
5423 }
5424
5425 impl Input for SmallReportedBufferInput<'_> {
5426 fn lookahead(&mut self, count: usize) {
5427 self.inner.lookahead(count);
5428 }
5429
5430 fn buflen(&self) -> usize {
5431 self.inner.buflen()
5432 }
5433
5434 fn bufmaxlen(&self) -> usize {
5435 self.reported_bufmaxlen
5436 }
5437
5438 fn raw_read_ch(&mut self) -> char {
5439 self.inner.raw_read_ch()
5440 }
5441
5442 fn raw_read_non_breakz_ch(&mut self) -> Option<char> {
5443 self.inner.raw_read_non_breakz_ch()
5444 }
5445
5446 fn skip(&mut self) {
5447 self.inner.skip();
5448 }
5449
5450 fn skip_n(&mut self, count: usize) {
5451 self.inner.skip_n(count);
5452 }
5453
5454 fn peek(&self) -> char {
5455 self.inner.peek()
5456 }
5457
5458 fn peek_nth(&self, n: usize) -> char {
5459 self.inner.peek_nth(n)
5460 }
5461 }
5462
5463 impl<'input> BorrowedInput<'input> for SmallReportedBufferInput<'input> {
5464 fn slice_borrowed(&self, start: usize, end: usize) -> Option<&'input str> {
5465 self.inner.slice_borrowed(start, end)
5466 }
5467 }
5468
5469 #[test]
5470 fn anchor_character_set_allows_colon_and_rejects_flow_indicators() {
5471 use super::is_anchor_char;
5472
5473 assert!(is_anchor_char('x'));
5474 assert!(is_anchor_char('-'));
5475 assert!(is_anchor_char('_'));
5476 assert!(is_anchor_char(':'));
5477 assert!(is_anchor_char('#'));
5478 assert!(is_anchor_char('/'));
5479 assert!(is_anchor_char('?'));
5480
5481 for c in [',', '[', ']', '{', '}', ' ', '\t', '\n', '\r', '\0'] {
5482 assert!(
5483 !is_anchor_char(c),
5484 "character {c:?} must not be accepted in anchor/alias names"
5485 );
5486 }
5487 }
5488
5489 #[test]
5490 fn flow_simple_key_length_limit_bounds_buffering() {
5491 let mut yaml = String::from("[\n\"start\"\n");
5492 for _ in 0..600 {
5493 yaml.push_str("\"x\"\n");
5494 }
5495 let total_chars = yaml.chars().count();
5496 let read = Rc::new(Cell::new(0));
5497 let chars = yaml.chars().collect::<Vec<_>>().into_iter();
5498 let mut scanner = Scanner::new(BufferedInput::new(CountingChars {
5499 chars,
5500 read: Rc::clone(&read),
5501 }));
5502
5503 assert!(matches!(
5504 scanner.next_token().unwrap().unwrap().1,
5505 TokenType::StreamStart
5506 ));
5507
5508 let token = scanner.next_token().unwrap().unwrap();
5509 assert!(matches!(token.1, TokenType::FlowSequenceStart));
5510
5511 let token = scanner.next_token().unwrap().unwrap();
5512 assert!(matches!(
5513 token.1,
5514 TokenType::Scalar { style: _, ref value } if value == "start"
5515 ));
5516 assert!(
5517 read.get() < total_chars,
5518 "scanner consumed all {total_chars} chars before yielding the first flow scalar"
5519 );
5520 assert!(
5521 read.get() <= scanner.options.simple_key_max_lookahead + 128,
5522 "scanner read {} chars before yielding the first flow scalar",
5523 read.get()
5524 );
5525 }
5526
5527 #[test]
5528 fn block_scalar_indent_tolerates_small_reported_bufmaxlen() {
5529 let mut scanner = Scanner::new(SmallReportedBufferInput::new("|\n value\n", 0));
5530
5531 let scalar = scanner
5532 .find_map(
5533 |token| match token.expect("valid YAML should scan without errors") {
5534 Token(
5535 _,
5536 TokenType::Scalar {
5537 style: ScalarStyle::Literal { .. },
5538 value,
5539 },
5540 ) => Some(value.into_owned()),
5541 _ => None,
5542 },
5543 )
5544 .expect("expected block scalar token");
5545
5546 assert_eq!(scalar, "value\n");
5547 }
5548
5549 #[test]
5550 fn plain_scalar_chunk_tolerates_small_reported_bufmaxlen() {
5551 let mut scanner = Scanner::new(SmallReportedBufferInput::new("plain\n", 0));
5552
5553 let scalar = scanner
5554 .find_map(
5555 |token| match token.expect("valid YAML should scan without errors") {
5556 Token(
5557 _,
5558 TokenType::Scalar {
5559 style: ScalarStyle::Plain { .. },
5560 value,
5561 },
5562 ) => Some(value.into_owned()),
5563 _ => None,
5564 },
5565 )
5566 .expect("expected plain scalar token");
5567
5568 assert_eq!(scalar, "plain");
5569 }
5570
5571 fn first_token_slice(
5572 yaml: &str,
5573 matches_token: impl Fn(&TokenType<'_>) -> bool,
5574 ) -> Option<String> {
5575 let mut scanner = Scanner::new(StrInput::new(yaml));
5576
5577 loop {
5578 let token = scanner
5579 .next_token()
5580 .expect("scanner should accept the test YAML")?;
5581 if matches_token(&token.1) {
5582 return token.0.slice(yaml).map(ToOwned::to_owned);
5583 }
5584 }
5585 }
5586
5587 #[test]
5588 fn flow_indicator_token_spans_cover_only_the_indicator() {
5589 assert_eq!(
5590 first_token_slice("[ # c\n a]\n", |token| matches!(
5591 token,
5592 TokenType::FlowSequenceStart
5593 ))
5594 .as_deref(),
5595 Some("[")
5596 );
5597 assert_eq!(
5598 first_token_slice("{ # c\n a: b}\n", |token| matches!(
5599 token,
5600 TokenType::FlowMappingStart
5601 ))
5602 .as_deref(),
5603 Some("{")
5604 );
5605 assert_eq!(
5606 first_token_slice("[a] # c\n", |token| matches!(
5607 token,
5608 TokenType::FlowSequenceEnd
5609 ))
5610 .as_deref(),
5611 Some("]")
5612 );
5613 assert_eq!(
5614 first_token_slice("{a: b} # c\n", |token| matches!(
5615 token,
5616 TokenType::FlowMappingEnd
5617 ))
5618 .as_deref(),
5619 Some("}")
5620 );
5621 assert_eq!(
5622 first_token_slice("[a, # c\nb]\n", |token| matches!(
5623 token,
5624 TokenType::FlowEntry
5625 ))
5626 .as_deref(),
5627 Some(",")
5628 );
5629 }
5630
5631 #[test]
5632 fn explicit_key_token_span_covers_only_the_indicator() {
5633 assert_eq!(
5634 first_token_slice("? # c\n: value\n", |token| matches!(token, TokenType::Key))
5635 .as_deref(),
5636 Some("?")
5637 );
5638 }
5639
5640 #[test]
5641 #[cfg(feature = "comments")]
5642 fn comment_capture_does_not_change_leading_whitespace() {
5643 let mut scanner = Scanner::new(StrInput::new("# comment\n"));
5644
5645 let token = scanner.scan_comment_token().unwrap();
5646
5647 assert!(scanner.leading_whitespace);
5648 assert!(
5649 matches!(token.1, TokenType::Comment { ref comment } if comment.text == " comment")
5650 );
5651
5652 let mut scanner = Scanner::new(BufferedInput::new("# streaming\n".chars()));
5653 scanner.input.lookahead(1);
5654
5655 let token = scanner.scan_comment_token().unwrap();
5656
5657 assert!(scanner.leading_whitespace);
5658 assert!(
5659 matches!(token.1, TokenType::Comment { ref comment } if comment.text == " streaming")
5660 );
5661 }
5662
5663 #[test]
5664 #[cfg(feature = "comments")]
5665 fn comment_capture_falls_back_to_owned_slice_when_borrow_unavailable() {
5666 let mut scanner = Scanner::new(SlicingOnlyInput::new("# sliced\n", true));
5667 scanner.input.lookahead(2);
5668 assert_eq!(scanner.input.peek_nth(1), ' ');
5669
5670 let token = scanner.scan_comment_token().unwrap();
5671
5672 assert!(matches!(token.1, TokenType::Comment { ref comment }
5673 if matches!(comment.text, Cow::Owned(ref text) if text == " sliced")));
5674 }
5675
5676 #[test]
5677 #[cfg(feature = "comments")]
5678 fn comment_capture_errors_when_offsets_have_no_slice() {
5679 let mut scanner = Scanner::new(SlicingOnlyInput::new("# broken\n", false));
5680
5681 let error = scanner.scan_comment_token().unwrap_err();
5682
5683 assert_eq!(error.kind(), &ErrorKind::InputOffsetsWithoutSlice);
5684 }
5685
5686 #[test]
5687 fn disabled_comments_do_not_require_input_slicing() {
5688 let options = ignoring_comments_options();
5689 let scanner = Scanner::with_options(
5690 SlicingOnlyInput::new("# ignored\nkey: value\n", false),
5691 options,
5692 );
5693
5694 let tokens = scanner
5695 .collect::<Result<Vec<_>, _>>()
5696 .expect("ignored comments should not capture their payload");
5697
5698 #[cfg(feature = "comments")]
5699 assert!(tokens
5700 .iter()
5701 .all(|token| !matches!(token.1, TokenType::Comment { comment: _ })));
5702 assert!(tokens.iter().any(|token| matches!(
5703 token.1,
5704 TokenType::Scalar { style: ScalarStyle::Plain { .. }, value: ref text } if text == "value"
5705 )));
5706 }
5707
5708 #[test]
5709 fn queued_token_roundtrips_public_token_variants() {
5710 let span = Span::new(Marker::new(0, 1, 0), Marker::new(7, 1, 7));
5711 let tokens = [
5712 Token(span, TokenType::StreamStart),
5713 Token(span, TokenType::StreamEnd),
5714 Token(span, TokenType::VersionDirective { major: 1, minor: 2 }),
5715 Token(
5716 span,
5717 TokenType::TagDirective {
5718 handle: Cow::Borrowed("!app!"),
5719 prefix: Cow::Borrowed("tag:app.example,"),
5720 },
5721 ),
5722 Token(span, TokenType::DocumentStart),
5723 Token(span, TokenType::DocumentEnd),
5724 Token(span, TokenType::BlockSequenceStart),
5725 Token(span, TokenType::BlockMappingStart),
5726 Token(span, TokenType::BlockEnd),
5727 Token(span, TokenType::FlowSequenceStart),
5728 Token(span, TokenType::FlowSequenceEnd),
5729 Token(span, TokenType::FlowMappingStart),
5730 Token(span, TokenType::FlowMappingEnd),
5731 Token(span, TokenType::BlockEntry),
5732 Token(span, TokenType::FlowEntry),
5733 Token(span, TokenType::Key),
5734 Token(span, TokenType::Value),
5735 Token(
5736 span,
5737 TokenType::Alias {
5738 name: Cow::Borrowed("alias"),
5739 },
5740 ),
5741 Token(
5742 span,
5743 TokenType::Anchor {
5744 name: Cow::Borrowed("anchor"),
5745 },
5746 ),
5747 Token(
5748 span,
5749 TokenType::Tag {
5750 handle: Cow::Borrowed("!"),
5751 suffix: Cow::Borrowed("tag"),
5752 },
5753 ),
5754 Token(
5755 span,
5756 TokenType::Scalar {
5757 style: ScalarStyle::literal(),
5758 value: Cow::Borrowed("scalar"),
5759 },
5760 ),
5761 #[cfg(feature = "comments")]
5762 Token(
5763 span,
5764 TokenType::Comment {
5765 comment: Comment::new(Cow::Borrowed(" comment"))
5766 .with_placement(Placement::Right),
5767 },
5768 ),
5769 Token(
5770 span,
5771 TokenType::ReservedDirective {
5772 name: "reserved".to_owned(),
5773 parameters: vec!["one".to_owned(), "two".to_owned()],
5774 },
5775 ),
5776 ];
5777
5778 for token in tokens {
5779 let queued: QueuedToken = token.clone().into();
5780
5781 assert_eq!(queued.into_public(), token);
5782 }
5783 }
5784
5785 #[test]
5786 fn comment_skipping_path_consumes_comment_without_tokenizing_it() {
5787 let mut scanner = Scanner::new(StrInput::new("# skipped\nnext: value\n"));
5788
5789 scanner.skip_yaml_whitespace().unwrap();
5790
5791 assert!(scanner.tokens.is_empty());
5792 assert_eq!(scanner.mark.line(), 2);
5793 assert_eq!(scanner.mark.col(), 0);
5794 }
5795
5796 #[test]
5797 #[cfg(feature = "comments")]
5798 fn yaml_whitespace_can_stop_after_queued_comment() {
5799 let mut scanner = Scanner::new(StrInput::new(" # queued\n# later\n"));
5800
5801 assert!(scanner.skip_yaml_whitespace().unwrap());
5802
5803 assert_eq!(scanner.tokens.len(), 1);
5804 assert!(matches!(
5805 scanner.tokens.front().unwrap().1,
5806 QueuedTokenType::Comment(ref comment) if comment.text == " queued"
5807 ));
5808 assert_eq!(scanner.mark.line(), 1);
5809 assert_eq!(scanner.mark.col(), 9);
5810 }
5811
5812 #[test]
5813 #[cfg(feature = "comments")]
5814 fn token_skip_can_stop_after_queued_comment() {
5815 let mut scanner = Scanner::new(StrInput::new("# first\n# second\n"));
5816
5817 assert!(scanner.skip_to_next_token().unwrap().queued_comment);
5818
5819 assert_eq!(scanner.tokens.len(), 1);
5820 assert!(matches!(
5821 scanner.tokens.front().unwrap().1,
5822 QueuedTokenType::Comment(ref comment) if comment.text == " first"
5823 ));
5824 assert_eq!(scanner.mark.line(), 2);
5825 assert_eq!(scanner.mark.col(), 0);
5826 }
5827
5828 #[test]
5829 fn token_skip_stops_after_one_ignored_comment_without_queuing_it() {
5830 let options = ignoring_comments_options();
5831 let mut scanner =
5832 Scanner::with_options(StrInput::new("# first\n# second\nvalue\n"), options);
5833
5834 let outcome = scanner.skip_to_next_token().unwrap();
5835
5836 assert!(outcome.saw_comment);
5837 #[cfg(feature = "comments")]
5838 assert!(!outcome.queued_comment);
5839 assert!(scanner.tokens.is_empty());
5840 assert_eq!((scanner.mark.line(), scanner.mark.col()), (2, 0));
5841 assert_eq!(scanner.input.look_ch(), '#');
5842 }
5843
5844 #[test]
5845 fn yaml_whitespace_stops_after_one_separated_ignored_comment() {
5846 let options = ignoring_comments_options();
5847 let mut scanner =
5848 Scanner::with_options(StrInput::new(" # first\n# second\nvalue\n"), options);
5849
5850 assert!(scanner.skip_yaml_whitespace().unwrap());
5851
5852 assert!(scanner.tokens.is_empty());
5853 assert_eq!((scanner.mark.line(), scanner.mark.col()), (1, 8));
5854 assert_eq!(scanner.input.look_ch(), '\n');
5855 }
5856
5857 #[test]
5858 fn scanner_skips_consecutive_leading_ignored_comments_before_next_token() {
5859 let options = ignoring_comments_options();
5860 let mut scanner =
5861 Scanner::with_options(StrInput::new("# first\n# second\nvalue\n"), options);
5862
5863 assert!(matches!(
5864 scanner.next_token().unwrap().unwrap().1,
5865 TokenType::StreamStart
5866 ));
5867 assert!(matches!(
5868 scanner.next_token().unwrap().unwrap().1,
5869 TokenType::Scalar { style: ScalarStyle::Plain { .. }, ref value } if value == "value"
5870 ));
5871 #[cfg(feature = "comments")]
5872 assert!(scanner
5873 .tokens
5874 .iter()
5875 .all(|QueuedToken(_, token)| !matches!(token, QueuedTokenType::Comment(_))));
5876 }
5877
5878 #[test]
5879 #[cfg(feature = "comments")]
5880 fn scanner_emits_first_leading_comment_before_scanning_next_comment() {
5881 let mut scanner = Scanner::new(StrInput::new("# first\n# second\nkey: value\n"));
5882
5883 assert!(matches!(
5884 scanner.next_token().unwrap().unwrap().1,
5885 TokenType::StreamStart
5886 ));
5887 assert!(matches!(
5888 scanner.next_token().unwrap().unwrap().1,
5889 TokenType::Comment { ref comment } if comment.text == " first"
5890 ));
5891 assert!(scanner.tokens.is_empty());
5892 assert!(matches!(
5893 scanner.next_token().unwrap().unwrap().1,
5894 TokenType::Comment { ref comment } if comment.text == " second"
5895 ));
5896 }
5897
5898 #[test]
5899 #[cfg(feature = "comments")]
5900 fn scanner_emits_quoted_scalar_comment_before_scanning_following_value() {
5901 let mut scanner = Scanner::new(StrInput::new("\"key\" # quoted\n: value\n"));
5902
5903 assert!(matches!(
5904 scanner.next_token().unwrap().unwrap().1,
5905 TokenType::StreamStart
5906 ));
5907 assert!(matches!(
5908 scanner.next_token().unwrap().unwrap().1,
5909 TokenType::Scalar { style: ScalarStyle::DoubleQuoted, ref value } if value == "key"
5910 ));
5911 assert!(matches!(
5912 scanner.next_token().unwrap().unwrap().1,
5913 TokenType::Comment { ref comment } if comment.text == " quoted"
5914 ));
5915 }
5916
5917 #[test]
5918 #[cfg(feature = "comments")]
5919 fn flow_scalar_comment_disables_adjacent_value_lookahead() {
5920 let mut scanner = Scanner::new(StrInput::new("\"key\"\n# quoted\n: value\n"));
5921
5922 scanner.fetch_flow_scalar(false).unwrap();
5923
5924 assert_eq!(scanner.adjacent_value_allowed_at, usize::MAX);
5925 assert!(matches!(
5926 scanner.tokens.front().unwrap().1,
5927 QueuedTokenType::Scalar(ScalarStyle::DoubleQuoted, ref value) if value == "key"
5928 ));
5929 assert!(scanner.tokens.iter().any(|QueuedToken(_, token)| matches!(
5930 token,
5931 QueuedTokenType::Comment(comment) if comment.text == " quoted"
5932 )));
5933 }
5934
5935 #[test]
5936 fn ignored_flow_scalar_comment_still_disables_adjacent_value_lookahead() {
5937 let options = ignoring_comments_options();
5938 let mut scanner =
5939 Scanner::with_options(StrInput::new("\"key\"\n# ignored\n: value\n"), options);
5940
5941 scanner.fetch_flow_scalar(false).unwrap();
5942
5943 assert_eq!(scanner.adjacent_value_allowed_at, usize::MAX);
5944 assert_eq!(scanner.tokens.len(), 1);
5945 assert!(matches!(
5946 scanner.tokens.front().unwrap().1,
5947 QueuedTokenType::Scalar(ScalarStyle::DoubleQuoted, ref value) if value == "key"
5948 ));
5949 }
5950
5951 #[test]
5952 #[cfg(feature = "comments")]
5953 fn deferred_error_waits_for_all_comment_tokens() {
5954 let mut scanner = Scanner::new(StrInput::new("# first\n# second\n@\n"));
5955
5956 assert!(matches!(
5957 scanner.next_token().unwrap().unwrap().1,
5958 TokenType::StreamStart
5959 ));
5960 assert!(matches!(
5961 scanner.next_token().unwrap().unwrap().1,
5962 TokenType::Comment { ref comment } if comment.text == " first"
5963 ));
5964 assert!(matches!(
5965 scanner.next_token().unwrap().unwrap().1,
5966 TokenType::Comment { ref comment } if comment.text == " second"
5967 ));
5968
5969 let error = scanner.next_token().unwrap_err();
5970
5971 assert_eq!(
5972 error.kind(),
5973 &ErrorKind::UnexpectedCharacter { character: '@' }
5974 );
5975 }
5976
5977 #[test]
5979 fn anchor_name_is_borrowed_for_str_input() {
5980 let mut scanner = Scanner::new(StrInput::new("&anch\n"));
5981
5982 loop {
5983 let tok = scanner
5984 .next_token()
5985 .expect("valid YAML must scan without errors")
5986 .expect("scanner must eventually produce a token");
5987 if let TokenType::Anchor { name } = tok.1 {
5988 assert!(matches!(name, Cow::Borrowed("anch")));
5989 break;
5990 }
5991 }
5992 }
5993
5994 #[test]
5995 fn anchor_name_rejects_non_printable_control_chars() {
5996 let mut scanner = Scanner::new(StrInput::new("&foo\u{0001}\n"));
5997
5998 scanner.next_token().unwrap();
5999 assert_eq!(
6000 scanner.next_token().unwrap_err().kind(),
6001 &ErrorKind::UnexpectedCharacter {
6002 character: '\u{0001}'
6003 }
6004 );
6005 }
6006
6007 #[test]
6008 fn alias_name_rejects_non_printable_control_chars() {
6009 let mut scanner = Scanner::new(StrInput::new("*foo\u{0001}\n"));
6010
6011 scanner.next_token().unwrap();
6012 assert_eq!(
6013 scanner.next_token().unwrap_err().kind(),
6014 &ErrorKind::UnexpectedCharacter {
6015 character: '\u{0001}'
6016 }
6017 );
6018 }
6019
6020 #[test]
6021 fn alias_name_is_borrowed_for_str_input() {
6022 let mut scanner = Scanner::new(StrInput::new("*anch\n"));
6023
6024 loop {
6025 let tok = scanner
6026 .next_token()
6027 .expect("valid YAML must scan without errors")
6028 .expect("scanner must eventually produce a token");
6029 if let TokenType::Alias { name } = tok.1 {
6030 assert!(matches!(name, Cow::Borrowed("anch")));
6031 break;
6032 }
6033 }
6034 }
6035
6036 #[test]
6037 fn alias_name_scans_colon_as_part_of_name() {
6038 let mut scanner = Scanner::new(StrInput::new("*foo: bar\n"));
6039
6040 loop {
6041 let tok = scanner
6042 .next_token()
6043 .expect("scanner must not fail before alias token")
6044 .expect("scanner must eventually emit an alias token");
6045
6046 if let TokenType::Alias { name } = tok.1 {
6047 assert_eq!(name.as_ref(), "foo:");
6048 break;
6049 }
6050 }
6051 }
6052
6053 #[test]
6054 fn anchor_name_scans_colon_as_part_of_name() {
6055 let mut scanner = Scanner::new(StrInput::new("&foo: bar\n"));
6056
6057 loop {
6058 let tok = scanner
6059 .next_token()
6060 .expect("scanner must not fail before anchor token")
6061 .expect("scanner must eventually emit an anchor token");
6062
6063 if let TokenType::Anchor { name } = tok.1 {
6064 assert_eq!(name.as_ref(), "foo:");
6065 break;
6066 }
6067 }
6068 }
6069
6070 #[test]
6072 fn tag_directive_parts_are_borrowed_for_str_input() {
6073 let mut scanner = Scanner::new(StrInput::new("%TAG !e! tag:example.com,2000:app/\n"));
6074
6075 loop {
6076 let tok = scanner
6077 .next_token()
6078 .expect("valid YAML must scan without errors")
6079 .expect("scanner must eventually produce a token");
6080 if let TokenType::TagDirective { handle, prefix } = tok.1 {
6081 assert!(matches!(handle, Cow::Borrowed("!e!")));
6082 assert!(matches!(prefix, Cow::Borrowed("tag:example.com,2000:app/")));
6083 break;
6084 }
6085 }
6086 }
6087
6088 #[test]
6089 fn tag_directive_parts_are_owned_for_buffered_input() {
6090 let mut scanner = Scanner::new(BufferedInput::new(
6091 "%TAG !e! tag:example.com,2000:app/\n".chars(),
6092 ));
6093
6094 loop {
6095 let tok = scanner
6096 .next_token()
6097 .expect("valid YAML must scan without errors")
6098 .expect("scanner must eventually produce a token");
6099 if let TokenType::TagDirective { handle, prefix } = tok.1 {
6100 assert!(matches!(handle, Cow::Owned(_)));
6101 assert_eq!(&*handle, "!e!");
6102 assert!(matches!(prefix, Cow::Owned(_)));
6103 assert_eq!(&*prefix, "tag:example.com,2000:app/");
6104 break;
6105 }
6106 }
6107 }
6108
6109 #[test]
6110 fn buffered_tag_directive_decodes_prefix_escape() {
6111 let mut scanner = Scanner::new(BufferedInput::new(
6112 "%TAG !e! %74ag:example.com,2000:app/\n".chars(),
6113 ));
6114
6115 loop {
6116 let tok = scanner
6117 .next_token()
6118 .expect("valid YAML must scan without errors")
6119 .expect("scanner must eventually produce a token");
6120 if let TokenType::TagDirective { handle, prefix } = tok.1 {
6121 assert_eq!(&*handle, "!e!");
6122 assert!(matches!(prefix, Cow::Owned(_)));
6123 assert_eq!(&*prefix, "tag:example.com,2000:app/");
6124 break;
6125 }
6126 }
6127 }
6128
6129 #[test]
6130 fn local_tag_combines_handle_text_with_escaped_suffix() {
6131 let mut scanner = Scanner::new(StrInput::new("!foo%20bar value\n"));
6132
6133 loop {
6134 let tok = scanner
6135 .next_token()
6136 .expect("valid YAML must scan without errors")
6137 .expect("scanner must eventually produce a token");
6138 if let TokenType::Tag { handle, suffix } = tok.1 {
6139 assert!(matches!(handle, Cow::Borrowed("!")));
6140 assert!(matches!(suffix, Cow::Owned(_)));
6141 assert_eq!(&*suffix, "foo bar");
6142 break;
6143 }
6144 }
6145 }
6146
6147 #[test]
6148 fn secondary_tag_requires_suffix_in_borrowed_and_buffered_paths() {
6149 assert_eq!(
6150 first_scanner_error_kind("!! value\n"),
6151 ErrorKind::MissingTagUri
6152 );
6153 assert_eq!(
6154 first_buffered_scanner_error_kind("!! value\n"),
6155 ErrorKind::MissingTagUri
6156 );
6157 }
6158
6159 #[test]
6160 fn plain_scalar_is_borrowed_when_whitespace_free_for_str_input() {
6161 let mut scanner = Scanner::new(StrInput::new("foo\n"));
6162
6163 loop {
6164 let tok = scanner
6165 .next_token()
6166 .expect("valid YAML must scan without errors")
6167 .expect("scanner must eventually produce a token");
6168 if let TokenType::Scalar { style: _, value } = tok.1 {
6169 assert!(matches!(value, Cow::Borrowed("foo")));
6170 break;
6171 }
6172 }
6173 }
6174
6175 #[test]
6176 fn plain_scalar_is_borrowed_when_whitespace_present_for_str_input() {
6177 let mut scanner = Scanner::new(StrInput::new("foo bar\n"));
6178
6179 loop {
6180 let tok = scanner
6181 .next_token()
6182 .expect("valid YAML must scan without errors")
6183 .expect("scanner must eventually produce a token");
6184 if let TokenType::Scalar { style: _, value } = tok.1 {
6185 assert!(matches!(value, Cow::Borrowed("foo bar")));
6186 break;
6187 }
6188 }
6189 }
6190
6191 #[test]
6192 fn single_quoted_scalar_is_borrowed_when_verbatim_for_str_input() {
6193 let mut scanner = Scanner::new(StrInput::new("'foo bar'\n"));
6194
6195 loop {
6196 let tok = scanner
6197 .next_token()
6198 .expect("valid YAML must scan without errors")
6199 .expect("scanner must eventually produce a token");
6200 if let TokenType::Scalar { style: _, value } = tok.1 {
6201 assert!(matches!(value, Cow::Borrowed("foo bar")));
6202 break;
6203 }
6204 }
6205 }
6206
6207 #[test]
6208 fn single_quoted_scalar_is_owned_when_quote_is_escaped_for_str_input() {
6209 let mut scanner = Scanner::new(StrInput::new("'foo''bar'\n"));
6210
6211 loop {
6212 let tok = scanner
6213 .next_token()
6214 .expect("valid YAML must scan without errors")
6215 .expect("scanner must eventually produce a token");
6216 if let TokenType::Scalar { style: _, value } = tok.1 {
6217 assert!(matches!(value, Cow::Owned(_)));
6218 assert_eq!(&*value, "foo'bar");
6219 break;
6220 }
6221 }
6222 }
6223
6224 #[test]
6225 fn double_quoted_scalar_is_borrowed_when_verbatim_for_str_input() {
6226 let mut scanner = Scanner::new(StrInput::new("\"foo bar\"\n"));
6227
6228 loop {
6229 let tok = scanner
6230 .next_token()
6231 .expect("valid YAML must scan without errors")
6232 .expect("scanner must eventually produce a token");
6233 if let TokenType::Scalar { style: _, value } = tok.1 {
6234 assert!(matches!(value, Cow::Borrowed("foo bar")));
6235 break;
6236 }
6237 }
6238 }
6239
6240 #[test]
6241 fn double_quoted_scalar_is_owned_when_escape_sequence_present_for_str_input() {
6242 let mut scanner = Scanner::new(StrInput::new("\"foo\\nbar\"\n"));
6243
6244 loop {
6245 let tok = scanner
6246 .next_token()
6247 .expect("valid YAML must scan without errors")
6248 .expect("scanner must eventually produce a token");
6249 if let TokenType::Scalar { style: _, value } = tok.1 {
6250 assert!(matches!(value, Cow::Owned(_)));
6251 assert_eq!(&*value, "foo\nbar");
6252 break;
6253 }
6254 }
6255 }
6256
6257 #[test]
6258 fn plain_key_is_borrowed_for_str_input() {
6259 let mut scanner = Scanner::new(StrInput::new("mykey: value\n"));
6261
6262 let mut found_key = false;
6263 let mut key_value: Option<Cow<'_, str>> = None;
6264
6265 loop {
6266 let tok = scanner
6267 .next_token()
6268 .expect("valid YAML must scan without errors");
6269 let Some(tok) = tok else { break };
6270
6271 if matches!(tok.1, TokenType::Key) {
6272 found_key = true;
6273 } else if found_key {
6274 if let TokenType::Scalar { style: _, value } = tok.1 {
6275 key_value = Some(value);
6276 break;
6277 }
6278 }
6279 }
6280
6281 assert!(found_key, "expected to find a Key token");
6282 let key_value = key_value.expect("expected to find a scalar after Key token");
6283 assert!(
6284 matches!(key_value, Cow::Borrowed("mykey")),
6285 "key should be borrowed, got: {key_value:?}"
6286 );
6287 }
6288
6289 #[test]
6290 fn quoted_key_is_borrowed_when_verbatim_for_str_input() {
6291 let mut scanner = Scanner::new(StrInput::new("\"mykey\": value\n"));
6292
6293 let mut found_key = false;
6294 let mut key_value: Option<Cow<'_, str>> = None;
6295
6296 loop {
6297 let tok = scanner
6298 .next_token()
6299 .expect("valid YAML must scan without errors");
6300 let Some(tok) = tok else { break };
6301
6302 if matches!(tok.1, TokenType::Key) {
6303 found_key = true;
6304 } else if found_key {
6305 if let TokenType::Scalar { style: _, value } = tok.1 {
6306 key_value = Some(value);
6307 break;
6308 }
6309 }
6310 }
6311
6312 assert!(found_key, "expected to find a Key token");
6313 let key_value = key_value.expect("expected to find a scalar after Key token");
6314 assert!(
6315 matches!(key_value, Cow::Borrowed("mykey")),
6316 "quoted key should be borrowed when verbatim, got: {key_value:?}"
6317 );
6318 }
6319
6320 #[test]
6321 fn tag_handle_and_suffix_are_borrowed_for_str_input() {
6322 let mut scanner = Scanner::new(StrInput::new("!!str foo\n"));
6324
6325 loop {
6326 let tok = scanner
6327 .next_token()
6328 .expect("valid YAML must scan without errors")
6329 .expect("scanner must eventually produce a token");
6330 if let TokenType::Tag { handle, suffix } = tok.1 {
6331 assert!(
6332 matches!(handle, Cow::Borrowed("!!")),
6333 "tag handle should be borrowed, got: {handle:?}"
6334 );
6335 assert!(
6336 matches!(suffix, Cow::Borrowed("str")),
6337 "tag suffix should be borrowed, got: {suffix:?}"
6338 );
6339 break;
6340 }
6341 }
6342 }
6343
6344 #[test]
6345 fn local_tag_suffix_is_borrowed_for_str_input() {
6346 let mut scanner = Scanner::new(StrInput::new("!mytag foo\n"));
6348
6349 loop {
6350 let tok = scanner
6351 .next_token()
6352 .expect("valid YAML must scan without errors")
6353 .expect("scanner must eventually produce a token");
6354 if let TokenType::Tag { handle, suffix } = tok.1 {
6355 assert!(
6356 matches!(handle, Cow::Borrowed("!")),
6357 "local tag handle should be '!', got: {handle:?}"
6358 );
6359 assert!(
6360 matches!(suffix, Cow::Borrowed("mytag")),
6361 "local tag suffix should be borrowed, got: {suffix:?}"
6362 );
6363 break;
6364 }
6365 }
6366 }
6367
6368 #[test]
6369 fn local_tag_suffix_with_punctuation_is_borrowed_for_str_input() {
6370 let mut scanner = Scanner::new(StrInput::new("!mytag/part foo\n"));
6371
6372 loop {
6373 let tok = scanner
6374 .next_token()
6375 .expect("valid YAML must scan without errors")
6376 .expect("scanner must eventually produce a token");
6377 if let TokenType::Tag { handle, suffix } = tok.1 {
6378 assert!(matches!(handle, Cow::Borrowed("!")));
6379 assert!(matches!(suffix, Cow::Borrowed("mytag/part")));
6380 break;
6381 }
6382 }
6383 }
6384
6385 #[test]
6386 fn tag_with_uri_escape_is_owned_for_str_input() {
6387 let mut scanner = Scanner::new(StrInput::new("!!my%20tag foo\n"));
6389
6390 loop {
6391 let tok = scanner
6392 .next_token()
6393 .expect("valid YAML must scan without errors")
6394 .expect("scanner must eventually produce a token");
6395 if let TokenType::Tag { handle, suffix } = tok.1 {
6396 assert!(
6397 matches!(handle, Cow::Borrowed("!!")),
6398 "tag handle should still be borrowed, got: {handle:?}"
6399 );
6400 assert!(
6401 matches!(suffix, Cow::Owned(_)),
6402 "tag suffix with URI escape should be owned, got: {suffix:?}"
6403 );
6404 assert_eq!(&*suffix, "my tag");
6405 break;
6406 }
6407 }
6408 }
6409
6410 #[test]
6411 fn flow_scalar_buffer_tracks_pending_whitespace() {
6412 let mut borrowed = super::FlowScalarBuf::new_borrowed(2);
6413
6414 borrowed.note_pending_ws(5, 8);
6415 borrowed.commit_pending_ws();
6416 assert!(matches!(
6417 borrowed,
6418 super::FlowScalarBuf::Borrowed {
6419 end: 8,
6420 pending_ws_start: None,
6421 pending_ws_end: 8,
6422 ..
6423 }
6424 ));
6425
6426 borrowed.note_pending_ws(9, 11);
6427 borrowed.discard_pending_ws();
6428 assert!(matches!(
6429 borrowed,
6430 super::FlowScalarBuf::Borrowed {
6431 end: 8,
6432 pending_ws_start: None,
6433 pending_ws_end: 8,
6434 ..
6435 }
6436 ));
6437 assert!(borrowed.as_owned_mut().is_none());
6438
6439 let mut owned = super::FlowScalarBuf::new_owned();
6440 owned.as_owned_mut().unwrap().push_str("owned");
6441 assert!(matches!(owned, super::FlowScalarBuf::Owned(ref s) if s == "owned"));
6442 }
6443
6444 fn first_scanner_error_kind(input: &str) -> ErrorKind {
6445 first_scanner_error(input).kind().clone()
6446 }
6447
6448 fn first_buffered_scanner_error_kind(input: &str) -> ErrorKind {
6449 let mut scanner = Scanner::new(BufferedInput::new(input.chars()));
6450 loop {
6451 match scanner.next_token() {
6452 Ok(Some(_)) => {}
6453 Ok(None) => panic!("expected scanner error"),
6454 Err(error) => return error.kind().clone(),
6455 }
6456 }
6457 }
6458
6459 fn first_scanner_error(input: &str) -> ScanError {
6460 let mut scanner = Scanner::new(StrInput::new(input));
6461 loop {
6462 match scanner.next_token() {
6463 Ok(Some(_)) => {}
6464 Ok(None) => panic!("expected scanner error"),
6465 Err(error) => return error,
6466 }
6467 }
6468 }
6469
6470 fn first_scalar_value(input: &str) -> String {
6471 let mut scanner = Scanner::new(StrInput::new(input));
6472 loop {
6473 match scanner.next_token().expect("scanner should not error") {
6474 Some(Token(_, TokenType::Scalar { style: _, value })) => return value.into_owned(),
6475 Some(_) => {}
6476 None => panic!("expected scalar token"),
6477 }
6478 }
6479 }
6480
6481 fn first_buffered_scalar_value(input: &str) -> String {
6482 let mut scanner = Scanner::new(BufferedInput::new(input.chars()));
6483 loop {
6484 match scanner.next_token().expect("scanner should not error") {
6485 Some(Token(_, TokenType::Scalar { style: _, value })) => return value.into_owned(),
6486 Some(_) => {}
6487 None => panic!("expected scalar token"),
6488 }
6489 }
6490 }
6491
6492 #[test]
6493 fn iterator_next_emits_error_and_then_stays_empty() {
6494 let mut scanner = Scanner::new(StrInput::new("\"unterminated"));
6495
6496 let error = scanner
6497 .by_ref()
6498 .find_map(Result::err)
6499 .expect("scanner should emit the error");
6500 assert_eq!(error.kind(), &ErrorKind::UnclosedQuotedScalar);
6501 assert!(scanner.next().is_none());
6502 }
6503
6504 #[test]
6505 fn next_token_returns_none_after_stream_end() {
6506 let mut scanner = Scanner::new(StrInput::new(""));
6507
6508 while let Some(token) = scanner.next_token().unwrap() {
6509 if matches!(token.1, TokenType::StreamEnd) {
6510 break;
6511 }
6512 }
6513
6514 assert!(scanner.stream_started());
6515 assert!(scanner.stream_ended());
6516 assert!(scanner.next_token().unwrap().is_none());
6517 }
6518
6519 #[test]
6520 fn directive_name_must_be_present() {
6521 assert_eq!(
6522 first_scanner_error_kind("%\n"),
6523 ErrorKind::MissingDirectiveName
6524 );
6525 }
6526
6527 #[test]
6528 fn yaml_directive_requires_dot_between_version_numbers() {
6529 assert_eq!(
6530 first_scanner_error_kind("%YAML 1\n"),
6531 ErrorKind::MissingYamlVersionSeparator
6532 );
6533 }
6534
6535 #[test]
6536 fn yaml_directive_requires_major_version_number() {
6537 assert_eq!(
6538 first_scanner_error_kind("%YAML .2\n"),
6539 ErrorKind::MissingYamlVersion
6540 );
6541 }
6542
6543 #[test]
6544 fn yaml_directive_rejects_extremely_long_version_number() {
6545 assert_eq!(
6546 first_scanner_error_kind("%YAML 1234567890.2\n"),
6547 ErrorKind::YamlVersionTooLong
6548 );
6549 }
6550
6551 #[test]
6552 fn tag_directive_handle_must_end_with_bang() {
6553 assert_eq!(
6554 first_scanner_error_kind("%TAG !bad tag:example.com,2024:\n"),
6555 ErrorKind::ExpectedTagDirectiveBang
6556 );
6557 }
6558
6559 #[test]
6560 fn tag_directive_handle_must_start_with_bang() {
6561 assert_eq!(
6562 first_scanner_error_kind("%TAG bad! tag:example.com,2024:\n"),
6563 ErrorKind::ExpectedTagBang
6564 );
6565 assert_eq!(
6566 first_buffered_scanner_error_kind("%TAG bad! tag:example.com,2024:\n"),
6567 ErrorKind::ExpectedTagBang
6568 );
6569 }
6570
6571 #[test]
6572 fn tag_directive_prefix_must_start_with_tag_character() {
6573 assert_eq!(
6574 first_scanner_error_kind("%TAG !e! `bad\n"),
6575 ErrorKind::InvalidGlobalTagCharacter
6576 );
6577 }
6578
6579 #[test]
6580 fn tag_directive_prefix_must_end_before_invalid_content() {
6581 assert_eq!(
6582 first_scanner_error_kind("%TAG !e! tag:example.com^suffix\n"),
6583 ErrorKind::InvalidTagDirectiveTerminator
6584 );
6585 }
6586
6587 #[test]
6588 fn tag_directive_prefix_with_uri_escape_is_owned_and_decoded() {
6589 let mut scanner =
6590 Scanner::new(StrInput::new("%TAG !e! tag:example.com,2024:some%20app/\n"));
6591
6592 loop {
6593 let token = scanner
6594 .next_token()
6595 .expect("valid directive should scan")
6596 .expect("scanner must produce a directive token");
6597 if let TokenType::TagDirective { handle, prefix } = token.1 {
6598 assert!(matches!(handle, Cow::Borrowed("!e!")));
6599 assert!(matches!(prefix, Cow::Owned(_)));
6600 assert_eq!(&*prefix, "tag:example.com,2024:some app/");
6601 break;
6602 }
6603 }
6604 }
6605
6606 #[test]
6607 fn bare_bang_tag_scans_as_non_specific_tag() {
6608 let mut scanner = Scanner::new(StrInput::new("! foo\n"));
6609
6610 loop {
6611 let token = scanner
6612 .next_token()
6613 .expect("valid tag should scan")
6614 .expect("scanner must produce a tag token");
6615 if let TokenType::Tag { handle, suffix } = token.1 {
6616 assert_eq!(&*handle, "");
6617 assert_eq!(&*suffix, "!");
6618 break;
6619 }
6620 }
6621 }
6622
6623 #[test]
6624 fn tag_requires_separation_after_suffix() {
6625 assert_eq!(
6626 first_scanner_error_kind("!foo,bar\n"),
6627 ErrorKind::InvalidTagTerminator
6628 );
6629 }
6630
6631 #[test]
6632 fn verbatim_tag_requires_uri() {
6633 assert_eq!(
6634 first_scanner_error_kind("!<> foo\n"),
6635 ErrorKind::MissingTagUri
6636 );
6637 }
6638
6639 #[test]
6640 fn verbatim_tag_requires_closing_angle_bracket() {
6641 assert_eq!(
6642 first_scanner_error_kind("!<tag:yaml.org,2002:str foo\n"),
6643 ErrorKind::UnclosedVerbatimTag
6644 );
6645 }
6646
6647 #[test]
6648 fn tag_uri_escape_requires_hex_digits() {
6649 assert_eq!(
6650 first_scanner_error_kind("!!bad%zz foo\n"),
6651 ErrorKind::InvalidTagEscape
6652 );
6653 }
6654
6655 #[test]
6656 fn tag_uri_escape_rejects_bad_leading_utf8_byte() {
6657 assert_eq!(
6658 first_scanner_error_kind("!!bad%80 foo\n"),
6659 ErrorKind::InvalidTagUtf8LeadingByte
6660 );
6661 }
6662
6663 #[test]
6664 fn tag_uri_escape_rejects_bad_trailing_utf8_byte() {
6665 assert_eq!(
6666 first_scanner_error_kind("!!bad%C2%41 foo\n"),
6667 ErrorKind::InvalidTagUtf8TrailingByte
6668 );
6669 }
6670
6671 #[test]
6672 fn tag_uri_escape_rejects_invalid_utf8_codepoint() {
6673 assert_eq!(
6674 first_scanner_error_kind("!!bad%F4%90%80%80 foo\n"),
6675 ErrorKind::InvalidTagUtf8
6676 );
6677 }
6678
6679 #[test]
6680 fn anchors_and_aliases_require_names() {
6681 assert_eq!(
6682 first_scanner_error_kind("& \n"),
6683 ErrorKind::MissingAnchorOrAliasName
6684 );
6685 assert_eq!(
6686 first_scanner_error_kind("* \n"),
6687 ErrorKind::MissingAnchorOrAliasName
6688 );
6689 }
6690
6691 #[test]
6692 fn document_end_marker_rejects_trailing_content() {
6693 assert_eq!(
6694 first_scanner_error_kind("... trailing\n"),
6695 ErrorKind::InvalidDocumentEnd
6696 );
6697 }
6698
6699 #[test]
6700 fn reserved_indicators_are_rejected_outside_directives() {
6701 let error = first_scanner_error(" @\n");
6702
6703 assert_eq!(
6704 error.kind(),
6705 &ErrorKind::UnexpectedCharacter { character: '@' }
6706 );
6707 }
6708
6709 #[test]
6710 fn flow_block_entry_indicator_is_rejected() {
6711 assert_eq!(
6712 first_scanner_error_kind("[- ]\n"),
6713 ErrorKind::BlockEntryInFlowCollection
6714 );
6715 }
6716
6717 #[test]
6718 fn block_entry_after_tabbed_separator_reports_specific_error() {
6719 assert_eq!(
6720 first_scanner_error_kind("-\t- value\n"),
6721 ErrorKind::InvalidBlockEntryWhitespace
6722 );
6723 }
6724
6725 #[test]
6726 fn document_indicator_reports_unclosed_flow_collection() {
6727 let error = first_scanner_error("[\n---\n");
6728
6729 assert_eq!(
6730 error.kind(),
6731 &ErrorKind::UnclosedFlowCollection { open: '[' }
6732 );
6733 }
6734
6735 #[test]
6736 fn block_scalar_header_rejects_trailing_content() {
6737 assert_eq!(
6738 first_scanner_error_kind("|+ trailing\n"),
6739 ErrorKind::InvalidBlockScalarHeader
6740 );
6741 }
6742
6743 #[test]
6744 fn block_scalar_rejects_zero_indent_indicator() {
6745 assert_eq!(
6746 first_scanner_error_kind("|0\n"),
6747 ErrorKind::ZeroBlockScalarIndent
6748 );
6749 assert_eq!(
6750 first_scanner_error_kind("|+0\n"),
6751 ErrorKind::ZeroBlockScalarIndent
6752 );
6753 }
6754
6755 #[test]
6756 fn empty_block_scalar_at_eof_honors_chomping() {
6757 assert_eq!(first_scalar_value("|\n"), "");
6758 assert_eq!(first_scalar_value("|-\n"), "");
6759 assert_eq!(first_scalar_value("|+\n"), "");
6760 assert_eq!(first_scalar_value("|+\n\n"), "\n");
6761 assert_eq!(first_scalar_value("|+\n "), "\n");
6762 }
6763
6764 #[test]
6765 fn buffered_block_scalar_reads_content_past_lookahead_window() {
6766 assert_eq!(
6767 first_buffered_scalar_value("|\n abcdefghijklmnopqrstuvwxyz\n"),
6768 "abcdefghijklmnopqrstuvwxyz\n"
6769 );
6770 }
6771
6772 #[test]
6773 fn explicit_indent_block_scalar_can_end_at_document_marker() {
6774 assert_eq!(first_scalar_value("|1\n...\n"), "");
6775 }
6776
6777 #[test]
6778 fn root_explicit_indent_block_scalar_rejects_underindented_content() {
6779 assert_eq!(
6780 first_scanner_error_kind("|2\nx\n"),
6781 ErrorKind::InvalidBlockScalarIndent
6782 );
6783 }
6784
6785 #[test]
6786 fn quoted_scalar_rejects_document_indicator_at_line_start() {
6787 assert_eq!(
6788 first_scanner_error_kind("\"one\n---\ntwo\"\n"),
6789 ErrorKind::DocumentIndicatorInQuotedScalar
6790 );
6791 }
6792
6793 #[test]
6794 fn strict_quoted_scalar_rejects_tab_indentation_after_line_break() {
6795 let error = Scanner::with_options(
6796 StrInput::new("a: \"one\n\tbad\"\n"),
6797 crate::options! { strict_indentation: true },
6798 )
6799 .find_map(Result::err)
6800 .expect("strict mode must reject a tab indenting a quoted continuation");
6801 assert_eq!(error.kind(), &ErrorKind::TabInIndentation);
6802 }
6803
6804 #[test]
6805 fn strict_quoted_scalar_rejects_underindented_continuation() {
6806 for input in ["a: \"one\nbad\"\n", "a:\n b: 'one\n bad'\n"] {
6807 let error = Scanner::with_options(
6808 StrInput::new(input),
6809 crate::options! { strict_indentation: true },
6810 )
6811 .find_map(Result::err)
6812 .expect("strict mode must reject underindented quoted continuations");
6813 assert_eq!(error.kind(), &ErrorKind::InvalidQuotedScalarIndent);
6814 }
6815 }
6816
6817 #[test]
6818 fn quoted_scalar_continuation_one_column_past_block_indent() {
6819 for input in [
6822 "a: \"one\n two\"\n",
6823 "a: 'one\n two'\n",
6824 "a:\n b: \"one\n two\"\n",
6825 "- a: \"one\n two\"\n",
6826 "? k\n: \"one\n two\"\n",
6827 ] {
6828 let mut scanner = Scanner::new(StrInput::new(input));
6829 loop {
6830 match scanner.next_token() {
6831 Ok(Some(_)) => {}
6832 Ok(None) => break,
6833 Err(error) => panic!("{input:?}: {error}"),
6834 }
6835 }
6836 }
6837 }
6838
6839 #[test]
6840 fn quoted_scalar_trailing_content_error_names_quote_style() {
6841 assert_eq!(
6842 first_scanner_error_kind("'foo' trailing\n"),
6843 ErrorKind::InvalidTrailingSingleQuotedScalar
6844 );
6845 assert_eq!(
6846 first_scanner_error_kind("\"foo\" trailing\n"),
6847 ErrorKind::InvalidTrailingDoubleQuotedScalar
6848 );
6849 }
6850
6851 #[test]
6852 fn quoted_scalar_escape_errors_cover_hex_and_surrogate_edges() {
6853 assert_eq!(
6854 first_scanner_error_kind("\"\\xG0\"\n"),
6855 ErrorKind::InvalidQuotedScalarHexEscape
6856 );
6857 assert_eq!(
6858 first_scanner_error_kind("\"\\uD800\\uGGGG\"\n"),
6859 ErrorKind::InvalidLowSurrogateHexEscape
6860 );
6861 assert_eq!(
6862 first_scanner_error_kind("\"\\uD800\\u0041\"\n"),
6863 ErrorKind::InvalidLowSurrogate
6864 );
6865 assert_eq!(
6866 first_scanner_error_kind("\"\\U00110000\"\n"),
6867 ErrorKind::InvalidUnicodeEscape
6868 );
6869 }
6870
6871 #[test]
6872 fn under_indented_flow_scalar_is_accepted() {
6873 let tokens: Vec<_> = Scanner::new(StrInput::new("a:\n [\nfoo]\n"))
6874 .map(|result| result.expect("under-indented flow entry should scan").1)
6875 .collect();
6876 assert_eq!(
6877 tokens,
6878 [
6879 TokenType::StreamStart,
6880 TokenType::BlockMappingStart,
6881 TokenType::Key,
6882 TokenType::Scalar {
6883 style: ScalarStyle::plain(),
6884 value: "a".into()
6885 },
6886 TokenType::Value,
6887 TokenType::FlowSequenceStart,
6888 TokenType::Scalar {
6889 style: ScalarStyle::plain(),
6890 value: "foo".into()
6891 },
6892 TokenType::FlowSequenceEnd,
6893 TokenType::BlockEnd,
6894 TokenType::StreamEnd,
6895 ]
6896 );
6897 }
6898
6899 #[test]
6900 fn required_simple_key_requires_value_at_stream_end() {
6901 let error = first_scanner_error("a:\n&b\n- c\n");
6902
6903 assert_eq!(error.kind(), &ErrorKind::SimpleKeyExpected);
6904 assert_eq!(error.marker().index(), 3);
6905 assert_eq!(error.marker().line(), 2);
6906 assert_eq!(error.marker().col(), 0);
6907 }
6908
6909 #[test]
6910 fn first_simple_key_tracks_ordered_possible_candidates() {
6911 let deep = alloc::format!(
6912 "{}{}{{[é, z]: v}}{}\n",
6913 "[".repeat(240),
6914 "a, ".repeat(400),
6915 "]".repeat(240)
6916 );
6917 for source in [
6918 "",
6919 "a: b\nmissing",
6920 "a: b\nmissing\n# after\nnext: value\n",
6921 "{[a, {b: c}]: [d, e], []: f}\n",
6922 "[&a !tag [x, y], *a, {z: []}]\n",
6923 "key: {\n&anchor\nname: value}\n",
6924 "---\n{[a, b]: c} # end\n...\n# next\n---\nx: y\n",
6925 "a: b\n[unterminated",
6926 &deep,
6927 ] {
6928 for limit in [0, 4, 1024, usize::MAX] {
6929 #[cfg(feature = "comments")]
6930 let emission_modes = [false, true].as_slice();
6931 #[cfg(not(feature = "comments"))]
6932 let emission_modes = [false].as_slice();
6933 for &emit_comments in emission_modes {
6934 let options = crate::options! { simple_key_max_lookahead: limit };
6935 #[cfg(feature = "comments")]
6936 let options = {
6937 let mut options = options;
6938 options.emit_comments = emit_comments;
6939 options
6940 };
6941 let mut scanner = Scanner::with_options(StrInput::new(source), options);
6942 loop {
6943 let result = scanner.next();
6944 assert_eq!(
6945 scanner.first_simple_key,
6946 scanner.simple_keys.iter().position(|key| key.possible),
6947 "source: {source:?}, limit: {limit}, comments: {emit_comments}"
6948 );
6949 let mut previous = None;
6950 for key in scanner.simple_keys.iter().filter(|key| key.possible) {
6951 assert!(key.token_number >= scanner.tokens_parsed);
6952 if let Some((index, token_number)) = previous {
6953 assert!(key.mark.index() >= index);
6954 assert!(key.token_number >= token_number);
6955 }
6956 previous = Some((key.mark.index(), key.token_number));
6957 }
6958 if result.is_none() {
6959 break;
6960 }
6961 }
6962 }
6963 }
6964 }
6965 }
6966
6967 #[test]
6968 fn plain_scalar_rejects_dash_before_flow_indicator() {
6969 assert_eq!(
6970 first_scanner_error_kind("[-]\n"),
6971 ErrorKind::PlainScalarStartsWithDashFlowIndicator
6972 );
6973 }
6974
6975 #[test]
6976 fn explicit_key_rejects_tab_used_as_indentation() {
6977 assert_eq!(
6978 first_scanner_error_kind("?\n\tfoo\n"),
6979 ErrorKind::TabNotAllowed
6980 );
6981 }
6982
6983 #[test]
6984 fn flow_mapping_rejects_adjacent_collection_value_after_plain_key() {
6985 assert_eq!(
6986 first_scanner_error_kind("[a:[]]\n"),
6987 ErrorKind::FlowMappingValueAdjacentCollection
6988 );
6989 }
6990
6991 #[test]
6992 fn implicit_flow_mapping_colon_cannot_move_to_next_line() {
6993 assert_eq!(
6994 first_scanner_error_kind("[foo\n: bar]\n"),
6995 ErrorKind::InvalidColonPlacement
6996 );
6997 }
6998
6999 #[test]
7000 fn invalid_simple_key_token_positions_are_scan_errors() {
7001 for (tokens_parsed, token_number) in [(1, 0), (0, 1)] {
7002 let mut scanner = Scanner::new(StrInput::new(": value\n"));
7003 scanner.fetch_stream_start();
7004 scanner.tokens.clear();
7005 scanner.tokens_parsed = tokens_parsed;
7006
7007 let simple_key = scanner
7008 .simple_keys
7009 .last_mut()
7010 .expect("stream start should create a simple key slot");
7011 simple_key.possible = true;
7012 simple_key.token_number = token_number;
7013
7014 let error = scanner
7015 .fetch_value()
7016 .expect_err("invalid simple key position should be reported as a scan error");
7017 assert_eq!(error.kind(), &ErrorKind::InvalidSimpleKey);
7018 assert_eq!(error.marker(), &Marker::new(0, 1, 0));
7019 }
7020 }
7021
7022 #[test]
7023 fn issue14_alias_scanner_consumes_colon_as_name_character() {
7024 let mut scanner = Scanner::new(StrInput::new("*foo: bar\n"));
7025
7026 assert!(matches!(
7027 scanner.next_token().unwrap().unwrap().1,
7028 TokenType::StreamStart
7029 ));
7030
7031 let token = scanner.next_token().unwrap().unwrap();
7032
7033 assert!(
7034 matches!(token.1, TokenType::Alias { ref name } if name.as_ref() == "foo:"),
7035 "expected `*foo: bar` to start with Alias(\"foo:\"), got {token:?}"
7036 );
7037 }
7038
7039 #[test]
7040 fn issue14_anchor_scanner_consumes_colon_as_name_character() {
7041 let mut scanner = Scanner::new(StrInput::new("&foo: bar\n"));
7042
7043 assert!(matches!(
7044 scanner.next_token().unwrap().unwrap().1,
7045 TokenType::StreamStart
7046 ));
7047
7048 let token = scanner.next_token().unwrap().unwrap();
7049
7050 assert!(
7051 matches!(token.1, TokenType::Anchor { ref name } if name.as_ref() == "foo:"),
7052 "expected `&foo: bar` to start with Anchor(\"foo:\"), got {token:?}"
7053 );
7054 }
7055}