1mod display;
8
9pub use Alignment::*;
10pub use Count::*;
11pub use Flag::*;
12pub use Piece::*;
13pub use Position::*;
14
15use std::iter;
16use std::str;
17use std::string;
18
19#[derive(Copy, Clone, PartialEq, Eq, Debug)]
22pub struct InnerSpan {
23 pub start: usize,
24 pub end: usize,
25}
26
27impl InnerSpan {
28 pub fn new(start: usize, end: usize) -> InnerSpan {
29 InnerSpan { start, end }
30 }
31}
32
33#[derive(Copy, Clone, Debug, Eq, PartialEq)]
35pub enum ParseMode {
36 Format,
38 InlineAsm,
40}
41
42#[derive(Copy, Clone, Debug, Eq, PartialEq)]
43struct InnerOffset(pub usize);
44
45impl InnerOffset {
46 fn to(self, end: InnerOffset) -> InnerSpan {
47 InnerSpan::new(self.0, end.0)
48 }
49}
50
51#[derive(Copy, Clone, Debug, Eq, PartialEq)]
54pub enum Piece<'a> {
55 String(&'a str),
57 NextArgument(Argument<'a>),
60}
61
62#[derive(Copy, Clone, Debug, Eq, PartialEq)]
64pub struct Argument<'a> {
65 pub position: Position<'a>,
67 pub position_span: InnerSpan,
70 pub format: FormatSpec<'a>,
72}
73
74#[derive(Copy, Clone, Debug, Eq, PartialEq)]
76pub struct FormatSpec<'a> {
77 pub fill: Option<char>,
79 pub align: Alignment,
81 pub flags: u32,
83 pub precision: Count<'a>,
85 pub precision_span: Option<InnerSpan>,
87 pub width: Count<'a>,
89 pub width_span: Option<InnerSpan>,
91 pub ty: &'a str,
95 pub ty_span: Option<InnerSpan>,
97}
98
99impl<'a> FormatSpec<'a> {
100 pub fn new(ty: &'a str) -> Self {
101 Self {
102 fill: None,
103 align: AlignUnknown,
104 flags: 0,
105 precision: CountImplied,
106 precision_span: None,
107 width: CountImplied,
108 width_span: None,
109 ty,
110 ty_span: None,
111 }
112 }
113 pub fn is_empty(&self) -> bool {
114 self.fill.is_none()
115 && self.align == AlignUnknown
116 && self.flags == 0
117 && self.precision == CountImplied
118 && self.width == CountImplied
119 && self.ty.is_empty()
120 }
121}
122
123impl<'a> Default for FormatSpec<'a> {
124 #[inline]
125 fn default() -> Self {
126 Self::new("")
127 }
128}
129
130#[derive(Copy, Clone, Debug, Eq, PartialEq)]
132pub enum Position<'a> {
133 ArgumentImplicitlyIs(usize),
135 ArgumentIs(usize),
137 ArgumentNamed(&'a str),
139}
140
141impl Position<'_> {
142 pub fn index(&self) -> Option<usize> {
143 match self {
144 ArgumentIs(i, ..) | ArgumentImplicitlyIs(i) => Some(*i),
145 _ => None,
146 }
147 }
148}
149
150#[derive(Copy, Clone, Debug, Eq, PartialEq)]
152pub enum Alignment {
153 AlignLeft,
155 AlignRight,
157 AlignCenter,
159 AlignUnknown,
161}
162
163#[derive(Copy, Clone, Debug, Eq, PartialEq)]
166pub enum Flag {
167 FlagSignPlus,
169 FlagSignMinus,
171 FlagAlternate,
174 FlagSignAwareZeroPad,
177 FlagDebugLowerHex,
179 FlagDebugUpperHex,
181}
182
183#[derive(Copy, Clone, Debug, Eq, PartialEq)]
186pub enum Count<'a> {
187 CountIs(usize),
189 CountIsName(&'a str, InnerSpan),
191 CountIsParam(usize),
193 CountIsStar(usize),
195 CountImplied,
197}
198
199#[derive(Clone, Debug, Eq, PartialEq)]
200pub struct ParseError {
201 pub description: string::String,
202 pub note: Option<string::String>,
203 pub label: string::String,
204 pub span: InnerSpan,
205 pub secondary_label: Option<(string::String, InnerSpan)>,
206 pub should_be_replaced_with_positional_argument: bool,
207}
208
209#[derive(Clone, Debug)]
216pub struct Parser<'a> {
217 mode: ParseMode,
218 input: &'a str,
219 cur: iter::Peekable<str::CharIndices<'a>>,
220 pub errors: Vec<ParseError>,
222 pub curarg: usize,
224 style: Option<usize>,
226 pub arg_places: Vec<InnerSpan>,
228 skips: Vec<usize>,
230 last_opening_brace: Option<InnerSpan>,
232 append_newline: bool,
234 pub is_literal: bool,
236 cur_line_start: usize,
238 pub line_spans: Vec<InnerSpan>,
241}
242
243impl<'a> Iterator for Parser<'a> {
244 type Item = Piece<'a>;
245
246 fn next(&mut self) -> Option<Piece<'a>> {
247 if let Some(&(pos, c)) = self.cur.peek() {
248 match c {
249 '{' => {
250 let curr_last_brace = self.last_opening_brace;
251 let byte_pos = self.to_span_index(pos);
252 let lbrace_end = self.to_span_index(pos + 1);
253 self.last_opening_brace = Some(byte_pos.to(lbrace_end));
254 self.cur.next();
255 if self.consume('{') {
256 self.last_opening_brace = curr_last_brace;
257
258 Some(String(self.string(pos + 1)))
259 } else {
260 let arg = self.argument(lbrace_end);
261 if let Some(rbrace_byte_idx) = self.must_consume('}') {
262 let lbrace_inner_offset = self.to_span_index(pos);
263 let rbrace_inner_offset = self.to_span_index(rbrace_byte_idx);
264 if self.is_literal {
265 self.arg_places.push(
266 lbrace_inner_offset.to(InnerOffset(rbrace_inner_offset.0 + 1)),
267 );
268 }
269 } else {
270 self.suggest_positional_arg_instead_of_captured_arg(arg);
271 }
272 Some(NextArgument(arg))
273 }
274 }
275 '}' => {
276 self.cur.next();
277 if self.consume('}') {
278 Some(String(self.string(pos + 1)))
279 } else {
280 let err_pos = self.to_span_index(pos);
281 self.err_with_note(
282 "unmatched `}` found",
283 "unmatched `}`",
284 "if you intended to print `}`, you can escape it using `}}`",
285 err_pos.to(err_pos),
286 );
287 None
288 }
289 }
290 _ => Some(String(self.string(pos))),
291 }
292 } else {
293 if self.is_literal {
294 let span = self.span(self.cur_line_start, self.input.len());
295 if self.line_spans.last() != Some(&span) {
296 self.line_spans.push(span);
297 }
298 }
299 None
300 }
301 }
302}
303
304impl<'a> Parser<'a> {
305 pub fn new(
307 s: &'a str,
308 style: Option<usize>,
309 snippet: Option<string::String>,
310 append_newline: bool,
311 mode: ParseMode,
312 ) -> Parser<'a> {
313 let (skips, is_literal) = find_skips_from_snippet(snippet, style);
314 Parser {
315 mode,
316 input: s,
317 cur: s.char_indices().peekable(),
318 errors: vec![],
319 curarg: 0,
320 style,
321 arg_places: vec![],
322 skips,
323 last_opening_brace: None,
324 append_newline,
325 is_literal,
326 cur_line_start: 0,
327 line_spans: vec![],
328 }
329 }
330
331 fn err<S1: Into<string::String>, S2: Into<string::String>>(
335 &mut self,
336 description: S1,
337 label: S2,
338 span: InnerSpan,
339 ) {
340 self.errors.push(ParseError {
341 description: description.into(),
342 note: None,
343 label: label.into(),
344 span,
345 secondary_label: None,
346 should_be_replaced_with_positional_argument: false,
347 });
348 }
349
350 fn err_with_note<
354 S1: Into<string::String>,
355 S2: Into<string::String>,
356 S3: Into<string::String>,
357 >(
358 &mut self,
359 description: S1,
360 label: S2,
361 note: S3,
362 span: InnerSpan,
363 ) {
364 self.errors.push(ParseError {
365 description: description.into(),
366 note: Some(note.into()),
367 label: label.into(),
368 span,
369 secondary_label: None,
370 should_be_replaced_with_positional_argument: false,
371 });
372 }
373
374 fn consume(&mut self, c: char) -> bool {
378 self.consume_pos(c).is_some()
379 }
380
381 fn consume_pos(&mut self, c: char) -> Option<usize> {
386 if let Some(&(pos, maybe)) = self.cur.peek() {
387 if c == maybe {
388 self.cur.next();
389 return Some(pos);
390 }
391 }
392 None
393 }
394
395 fn to_span_index(&self, pos: usize) -> InnerOffset {
396 let mut pos = pos;
397 let raw = self.style.map_or(0, |raw| raw + 1);
400 for skip in &self.skips {
401 if pos > *skip {
402 pos += 1;
403 } else if pos == *skip && raw == 0 {
404 pos += 1;
405 } else {
406 break;
407 }
408 }
409 InnerOffset(raw + pos + 1)
410 }
411
412 fn span(&self, start_pos: usize, end_pos: usize) -> InnerSpan {
413 let start = self.to_span_index(start_pos);
414 let end = self.to_span_index(end_pos);
415 start.to(end)
416 }
417
418 fn must_consume(&mut self, c: char) -> Option<usize> {
421 self.ws();
422
423 if let Some(&(pos, maybe)) = self.cur.peek() {
424 if c == maybe {
425 self.cur.next();
426 Some(pos)
427 } else {
428 let pos = self.to_span_index(pos);
429 let description = format!("expected `'}}'`, found `{:?}`", maybe);
430 let label = "expected `}`".to_owned();
431 let (note, secondary_label) = if c == '}' {
432 (
433 Some(
434 "if you intended to print `{`, you can escape it using `{{`".to_owned(),
435 ),
436 self.last_opening_brace
437 .map(|sp| ("because of this opening brace".to_owned(), sp)),
438 )
439 } else {
440 (None, None)
441 };
442 self.errors.push(ParseError {
443 description,
444 note,
445 label,
446 span: pos.to(pos),
447 secondary_label,
448 should_be_replaced_with_positional_argument: false,
449 });
450 None
451 }
452 } else {
453 let description = format!("expected `{:?}` but string was terminated", c);
454 let pos = self.input.len() - if self.append_newline { 1 } else { 0 };
456 let pos = self.to_span_index(pos);
457 if c == '}' {
458 let label = format!("expected `{:?}`", c);
459 let (note, secondary_label) = if c == '}' {
460 (
461 Some(
462 "if you intended to print `{`, you can escape it using `{{`".to_owned(),
463 ),
464 self.last_opening_brace
465 .map(|sp| ("because of this opening brace".to_owned(), sp)),
466 )
467 } else {
468 (None, None)
469 };
470 self.errors.push(ParseError {
471 description,
472 note,
473 label,
474 span: pos.to(pos),
475 secondary_label,
476 should_be_replaced_with_positional_argument: false,
477 });
478 } else {
479 self.err(description, format!("expected `{:?}`", c), pos.to(pos));
480 }
481 None
482 }
483 }
484
485 fn ws(&mut self) {
487 while let Some(&(_, c)) = self.cur.peek() {
488 if c.is_whitespace() {
489 self.cur.next();
490 } else {
491 break;
492 }
493 }
494 }
495
496 fn string(&mut self, start: usize) -> &'a str {
499 while let Some(&(pos, c)) = self.cur.peek() {
501 match c {
502 '{' | '}' => {
503 return &self.input[start..pos];
504 }
505 '\n' if self.is_literal => {
506 self.line_spans.push(self.span(self.cur_line_start, pos));
507 self.cur_line_start = pos + 1;
508 self.cur.next();
509 }
510 _ => {
511 if self.is_literal && pos == self.cur_line_start && c.is_whitespace() {
512 self.cur_line_start = pos + c.len_utf8();
513 }
514 self.cur.next();
515 }
516 }
517 }
518 &self.input[start..self.input.len()]
519 }
520
521 fn argument(&mut self, start: InnerOffset) -> Argument<'a> {
523 let pos = self.position();
524
525 let end = self
526 .cur
527 .clone()
528 .find(|(_, ch)| !ch.is_whitespace())
529 .map_or(start, |(end, _)| self.to_span_index(end));
530 let position_span = start.to(end);
531
532 let format = match self.mode {
533 ParseMode::Format => self.format(),
534 ParseMode::InlineAsm => self.inline_asm(),
535 };
536
537 let pos = match pos {
539 Some(position) => position,
540 None => {
541 let i = self.curarg;
542 self.curarg += 1;
543 ArgumentImplicitlyIs(i)
544 }
545 };
546
547 Argument {
548 position: pos,
549 position_span,
550 format,
551 }
552 }
553
554 fn position(&mut self) -> Option<Position<'a>> {
559 if let Some(i) = self.integer() {
560 Some(ArgumentIs(i))
561 } else {
562 match self.cur.peek() {
563 Some(&(_, c)) if is_id_start(c) => Some(ArgumentNamed(self.word())),
564
565 _ => None,
569 }
570 }
571 }
572
573 fn current_pos(&mut self) -> usize {
574 if let Some(&(pos, _)) = self.cur.peek() {
575 pos
576 } else {
577 self.input.len()
578 }
579 }
580
581 fn format(&mut self) -> FormatSpec<'a> {
584 let mut spec = FormatSpec::new(&self.input[..0]);
585
586 if !self.consume(':') {
587 return spec;
588 }
589
590 if let Some(&(_, c)) = self.cur.peek() {
592 if let Some((_, '>' | '<' | '^')) = self.cur.clone().nth(1) {
593 spec.fill = Some(c);
594 self.cur.next();
595 }
596 }
597 if self.consume('<') {
599 spec.align = AlignLeft;
600 } else if self.consume('>') {
601 spec.align = AlignRight;
602 } else if self.consume('^') {
603 spec.align = AlignCenter;
604 }
605 if self.consume('+') {
607 spec.flags |= 1 << (FlagSignPlus as u32);
608 } else if self.consume('-') {
609 spec.flags |= 1 << (FlagSignMinus as u32);
610 }
611 if self.consume('#') {
613 spec.flags |= 1 << (FlagAlternate as u32);
614 }
615 let mut havewidth = false;
617
618 if self.consume('0') {
619 if let Some(end) = self.consume_pos('$') {
624 spec.width = CountIsParam(0);
625 spec.width_span = Some(self.span(end - 1, end + 1));
626 havewidth = true;
627 } else {
628 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
629 }
630 }
631
632 if !havewidth {
633 let start = self.current_pos();
634 spec.width = self.count(start);
635 if spec.width != CountImplied {
636 let end = self.current_pos();
637 spec.width_span = Some(self.span(start, end));
638 }
639 }
640
641 if let Some(start) = self.consume_pos('.') {
642 if self.consume('*') {
643 let i = self.curarg;
646 self.curarg += 1;
647 spec.precision = CountIsStar(i);
648 } else {
649 spec.precision = self.count(start + 1);
650 }
651 let end = self.current_pos();
652 spec.precision_span = Some(self.span(start, end));
653 }
654
655 let ty_span_start = self.current_pos();
656 if self.consume('x') {
658 if self.consume('?') {
659 spec.flags |= 1 << (FlagDebugLowerHex as u32);
660 spec.ty = "?";
661 } else {
662 spec.ty = "x";
663 }
664 } else if self.consume('X') {
665 if self.consume('?') {
666 spec.flags |= 1 << (FlagDebugUpperHex as u32);
667 spec.ty = "?";
668 } else {
669 spec.ty = "X";
670 }
671 } else if self.consume('?') {
672 spec.ty = "?";
673 } else {
674 spec.ty = self.word();
675 if !spec.ty.is_empty() {
676 let ty_span_end = self.current_pos();
677 spec.ty_span = Some(self.span(ty_span_start, ty_span_end));
678 }
679 }
680 spec
681 }
682
683 fn inline_asm(&mut self) -> FormatSpec<'a> {
686 let mut spec = FormatSpec::new(&self.input[..0]);
687
688 if !self.consume(':') {
689 return spec;
690 }
691
692 let ty_span_start = self.current_pos();
693 spec.ty = self.word();
694 if !spec.ty.is_empty() {
695 let ty_span_end = self.current_pos();
696 spec.ty_span = Some(self.span(ty_span_start, ty_span_end));
697 }
698
699 spec
700 }
701
702 fn count(&mut self, start: usize) -> Count<'a> {
706 if let Some(i) = self.integer() {
707 if self.consume('$') {
708 CountIsParam(i)
709 } else {
710 CountIs(i)
711 }
712 } else {
713 let tmp = self.cur.clone();
714 let word = self.word();
715 if word.is_empty() {
716 self.cur = tmp;
717 CountImplied
718 } else if let Some(end) = self.consume_pos('$') {
719 let name_span = self.span(start, end);
720 CountIsName(word, name_span)
721 } else {
722 self.cur = tmp;
723 CountImplied
724 }
725 }
726 }
727
728 fn word(&mut self) -> &'a str {
731 let start = match self.cur.peek() {
732 Some(&(pos, c)) if is_id_start(c) => {
733 self.cur.next();
734 pos
735 }
736 _ => {
737 return "";
738 }
739 };
740 let mut end = None;
741 while let Some(&(pos, c)) = self.cur.peek() {
742 if is_id_continue(c) {
743 self.cur.next();
744 } else {
745 end = Some(pos);
746 break;
747 }
748 }
749 let end = end.unwrap_or(self.input.len());
750 let word = &self.input[start..end];
751 if word == "_" {
752 self.err_with_note(
753 "invalid argument name `_`",
754 "invalid argument name",
755 "argument name cannot be a single underscore",
756 self.span(start, end),
757 );
758 }
759 word
760 }
761
762 fn integer(&mut self) -> Option<usize> {
763 let mut cur: usize = 0;
764 let mut found = false;
765 let mut overflow = false;
766 let start = self.current_pos();
767 while let Some(&(_, c)) = self.cur.peek() {
768 if let Some(i) = c.to_digit(10) {
769 let (tmp, mul_overflow) = cur.overflowing_mul(10);
770 let (tmp, add_overflow) = tmp.overflowing_add(i as usize);
771 if mul_overflow || add_overflow {
772 overflow = true;
773 }
774 cur = tmp;
775 found = true;
776 self.cur.next();
777 } else {
778 break;
779 }
780 }
781
782 if overflow {
783 let end = self.current_pos();
784 let overflowed_int = &self.input[start..end];
785 self.err(
786 format!(
787 "integer `{}` does not fit into the type `usize` whose range is `0..={}`",
788 overflowed_int,
789 usize::MAX
790 ),
791 "integer out of range for `usize`",
792 self.span(start, end),
793 );
794 }
795
796 if found {
797 Some(cur)
798 } else {
799 None
800 }
801 }
802
803 fn suggest_positional_arg_instead_of_captured_arg(&mut self, arg: Argument<'a>) {
804 if let Some(end) = self.consume_pos('.') {
805 let byte_pos = self.to_span_index(end);
806 let start = InnerOffset(byte_pos.0 + 1);
807 let field = self.argument(start);
808 if !self.consume('}') {
811 return;
812 }
813 if let ArgumentNamed(_) = arg.position {
814 if let ArgumentNamed(_) = field.position {
815 self.errors.insert(
816 0,
817 ParseError {
818 description: "field access isn't supported".to_string(),
819 note: None,
820 label: "not supported".to_string(),
821 span: InnerSpan::new(arg.position_span.start, field.position_span.end),
822 secondary_label: None,
823 should_be_replaced_with_positional_argument: true,
824 },
825 );
826 }
827 }
828 }
829 }
830}
831
832fn find_skips_from_snippet(
836 snippet: Option<string::String>,
837 str_style: Option<usize>,
838) -> (Vec<usize>, bool) {
839 let snippet = match snippet {
840 Some(ref s) if s.starts_with('"') || s.starts_with("r\"") || s.starts_with("r#") => s,
841 _ => return (vec![], false),
842 };
843
844 if str_style.is_some() {
845 return (vec![], true);
846 }
847
848 let snippet = &snippet[1..snippet.len() - 1];
849
850 let mut s = snippet.char_indices();
851 let mut skips = vec![];
852 while let Some((pos, c)) = s.next() {
853 match (c, s.clone().next()) {
854 ('\\', Some((next_pos, '\n'))) => {
856 skips.push(pos);
857 skips.push(next_pos);
858 let _ = s.next();
859
860 while let Some((pos, c)) = s.clone().next() {
861 if matches!(c, ' ' | '\n' | '\t') {
862 skips.push(pos);
863 let _ = s.next();
864 } else {
865 break;
866 }
867 }
868 }
869 ('\\', Some((next_pos, 'n' | 't' | 'r' | '0' | '\\' | '\'' | '\"'))) => {
870 skips.push(next_pos);
871 let _ = s.next();
872 }
873 ('\\', Some((_, 'x'))) => {
874 for _ in 0..3 {
875 if let Some((pos, _)) = s.next() {
877 skips.push(pos);
878 } else {
879 break;
880 }
881 }
882 }
883 ('\\', Some((_, 'u'))) => {
884 if let Some((pos, _)) = s.next() {
885 skips.push(pos);
886 }
887 if let Some((next_pos, next_c)) = s.next() {
888 if next_c == '{' {
889 let digits_len = s
891 .clone()
892 .take(6)
893 .take_while(|(_, c)| c.is_digit(16))
894 .count();
895
896 let len_utf8 = s
897 .as_str()
898 .get(..digits_len)
899 .and_then(|digits| u32::from_str_radix(digits, 16).ok())
900 .and_then(char::from_u32)
901 .map_or(1, char::len_utf8);
902
903 let required_skips = digits_len.saturating_sub(len_utf8.saturating_sub(1));
908
909 for pos in (next_pos..).take(required_skips + 2) {
911 skips.push(pos)
912 }
913
914 s.nth(digits_len);
915 } else if next_c.is_digit(16) {
916 skips.push(next_pos);
917 let mut i = 0; while let (Some((next_pos, c)), _) = (s.next(), i < 6) {
921 if c.is_digit(16) {
922 skips.push(next_pos);
923 } else {
924 break;
925 }
926 i += 1;
927 }
928 }
929 }
930 }
931 _ => {}
932 }
933 }
934 (skips, true)
935}
936
937#[inline]
938fn is_id_start(ch: char) -> bool {
939 ch == '_' || unicode_ident::is_xid_start(ch)
940}
941
942#[inline]
943fn is_id_continue(ch: char) -> bool {
944 unicode_ident::is_xid_start(ch)
945}
946
947#[cfg(test)]
948mod tests;