]> git.proxmox.com Git - rustc.git/blob - src/libfmt_macros/lib.rs
New upstream version 1.30.0~beta.7+dfsg1
[rustc.git] / src / libfmt_macros / lib.rs
1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Macro support for format strings
12 //!
13 //! These structures are used when parsing format strings for the compiler.
14 //! Parsing does not happen at runtime: structures of `std::fmt::rt` are
15 //! generated instead.
16
17 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
18 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
19 html_root_url = "https://doc.rust-lang.org/nightly/",
20 html_playground_url = "https://play.rust-lang.org/",
21 test(attr(deny(warnings))))]
22
23 #![cfg_attr(not(stage0), feature(nll))]
24
25 pub use self::Piece::*;
26 pub use self::Position::*;
27 pub use self::Alignment::*;
28 pub use self::Flag::*;
29 pub use self::Count::*;
30
31 use std::str;
32 use std::string;
33 use std::iter;
34
35 /// A piece is a portion of the format string which represents the next part
36 /// to emit. These are emitted as a stream by the `Parser` class.
37 #[derive(Copy, Clone, PartialEq)]
38 pub enum Piece<'a> {
39 /// A literal string which should directly be emitted
40 String(&'a str),
41 /// This describes that formatting should process the next argument (as
42 /// specified inside) for emission.
43 NextArgument(Argument<'a>),
44 }
45
46 /// Representation of an argument specification.
47 #[derive(Copy, Clone, PartialEq)]
48 pub struct Argument<'a> {
49 /// Where to find this argument
50 pub position: Position<'a>,
51 /// How to format the argument
52 pub format: FormatSpec<'a>,
53 }
54
55 /// Specification for the formatting of an argument in the format string.
56 #[derive(Copy, Clone, PartialEq)]
57 pub struct FormatSpec<'a> {
58 /// Optionally specified character to fill alignment with
59 pub fill: Option<char>,
60 /// Optionally specified alignment
61 pub align: Alignment,
62 /// Packed version of various flags provided
63 pub flags: u32,
64 /// The integer precision to use
65 pub precision: Count<'a>,
66 /// The string width requested for the resulting format
67 pub width: Count<'a>,
68 /// The descriptor string representing the name of the format desired for
69 /// this argument, this can be empty or any number of characters, although
70 /// it is required to be one word.
71 pub ty: &'a str,
72 }
73
74 /// Enum describing where an argument for a format can be located.
75 #[derive(Copy, Clone, PartialEq)]
76 pub enum Position<'a> {
77 /// The argument is implied to be located at an index
78 ArgumentImplicitlyIs(usize),
79 /// The argument is located at a specific index given in the format
80 ArgumentIs(usize),
81 /// The argument has a name.
82 ArgumentNamed(&'a str),
83 }
84
85 /// Enum of alignments which are supported.
86 #[derive(Copy, Clone, PartialEq)]
87 pub enum Alignment {
88 /// The value will be aligned to the left.
89 AlignLeft,
90 /// The value will be aligned to the right.
91 AlignRight,
92 /// The value will be aligned in the center.
93 AlignCenter,
94 /// The value will take on a default alignment.
95 AlignUnknown,
96 }
97
98 /// Various flags which can be applied to format strings. The meaning of these
99 /// flags is defined by the formatters themselves.
100 #[derive(Copy, Clone, PartialEq)]
101 pub enum Flag {
102 /// A `+` will be used to denote positive numbers.
103 FlagSignPlus,
104 /// A `-` will be used to denote negative numbers. This is the default.
105 FlagSignMinus,
106 /// An alternate form will be used for the value. In the case of numbers,
107 /// this means that the number will be prefixed with the supplied string.
108 FlagAlternate,
109 /// For numbers, this means that the number will be padded with zeroes,
110 /// and the sign (`+` or `-`) will precede them.
111 FlagSignAwareZeroPad,
112 /// For Debug / `?`, format integers in lower-case hexadecimal.
113 FlagDebugLowerHex,
114 /// For Debug / `?`, format integers in upper-case hexadecimal.
115 FlagDebugUpperHex,
116 }
117
118 /// A count is used for the precision and width parameters of an integer, and
119 /// can reference either an argument or a literal integer.
120 #[derive(Copy, Clone, PartialEq)]
121 pub enum Count<'a> {
122 /// The count is specified explicitly.
123 CountIs(usize),
124 /// The count is specified by the argument with the given name.
125 CountIsName(&'a str),
126 /// The count is specified by the argument at the given index.
127 CountIsParam(usize),
128 /// The count is implied and cannot be explicitly specified.
129 CountImplied,
130 }
131
132 pub struct ParseError {
133 pub description: string::String,
134 pub note: Option<string::String>,
135 pub label: string::String,
136 pub start: usize,
137 pub end: usize,
138 }
139
140 /// The parser structure for interpreting the input format string. This is
141 /// modeled as an iterator over `Piece` structures to form a stream of tokens
142 /// being output.
143 ///
144 /// This is a recursive-descent parser for the sake of simplicity, and if
145 /// necessary there's probably lots of room for improvement performance-wise.
146 pub struct Parser<'a> {
147 input: &'a str,
148 cur: iter::Peekable<str::CharIndices<'a>>,
149 /// Error messages accumulated during parsing
150 pub errors: Vec<ParseError>,
151 /// Current position of implicit positional argument pointer
152 curarg: usize,
153 /// `Some(raw count)` when the string is "raw", used to position spans correctly
154 style: Option<usize>,
155 /// How many newlines have been seen in the string so far, to adjust the error spans
156 seen_newlines: usize,
157 /// Start and end byte offset of every successfully parsed argument
158 pub arg_places: Vec<(usize, usize)>,
159 }
160
161 impl<'a> Iterator for Parser<'a> {
162 type Item = Piece<'a>;
163
164 fn next(&mut self) -> Option<Piece<'a>> {
165 let raw = self.style.map(|raw| raw + self.seen_newlines).unwrap_or(0);
166 if let Some(&(pos, c)) = self.cur.peek() {
167 match c {
168 '{' => {
169 self.cur.next();
170 if self.consume('{') {
171 Some(String(self.string(pos + 1)))
172 } else {
173 let arg = self.argument();
174 if let Some(arg_pos) = self.must_consume('}').map(|end| {
175 (pos + raw + 1, end + raw + 2)
176 }) {
177 self.arg_places.push(arg_pos);
178 }
179 Some(NextArgument(arg))
180 }
181 }
182 '}' => {
183 self.cur.next();
184 if self.consume('}') {
185 Some(String(self.string(pos + 1)))
186 } else {
187 let err_pos = pos + raw + 1;
188 self.err_with_note(
189 "unmatched `}` found",
190 "unmatched `}`",
191 "if you intended to print `}`, you can escape it using `}}`",
192 err_pos,
193 err_pos,
194 );
195 None
196 }
197 }
198 '\n' => {
199 self.seen_newlines += 1;
200 Some(String(self.string(pos)))
201 }
202 _ => Some(String(self.string(pos))),
203 }
204 } else {
205 None
206 }
207 }
208 }
209
210 impl<'a> Parser<'a> {
211 /// Creates a new parser for the given format string
212 pub fn new(s: &'a str, style: Option<usize>) -> Parser<'a> {
213 Parser {
214 input: s,
215 cur: s.char_indices().peekable(),
216 errors: vec![],
217 curarg: 0,
218 style,
219 seen_newlines: 0,
220 arg_places: vec![],
221 }
222 }
223
224 /// Notifies of an error. The message doesn't actually need to be of type
225 /// String, but I think it does when this eventually uses conditions so it
226 /// might as well start using it now.
227 fn err<S1: Into<string::String>, S2: Into<string::String>>(
228 &mut self,
229 description: S1,
230 label: S2,
231 start: usize,
232 end: usize,
233 ) {
234 self.errors.push(ParseError {
235 description: description.into(),
236 note: None,
237 label: label.into(),
238 start,
239 end,
240 });
241 }
242
243 /// Notifies of an error. The message doesn't actually need to be of type
244 /// String, but I think it does when this eventually uses conditions so it
245 /// might as well start using it now.
246 fn err_with_note<S1: Into<string::String>, S2: Into<string::String>, S3: Into<string::String>>(
247 &mut self,
248 description: S1,
249 label: S2,
250 note: S3,
251 start: usize,
252 end: usize,
253 ) {
254 self.errors.push(ParseError {
255 description: description.into(),
256 note: Some(note.into()),
257 label: label.into(),
258 start,
259 end,
260 });
261 }
262
263 /// Optionally consumes the specified character. If the character is not at
264 /// the current position, then the current iterator isn't moved and false is
265 /// returned, otherwise the character is consumed and true is returned.
266 fn consume(&mut self, c: char) -> bool {
267 if let Some(&(_, maybe)) = self.cur.peek() {
268 if c == maybe {
269 self.cur.next();
270 true
271 } else {
272 false
273 }
274 } else {
275 false
276 }
277 }
278
279 /// Forces consumption of the specified character. If the character is not
280 /// found, an error is emitted.
281 fn must_consume(&mut self, c: char) -> Option<usize> {
282 self.ws();
283 let raw = self.style.unwrap_or(0);
284
285 let padding = raw + self.seen_newlines;
286 if let Some(&(pos, maybe)) = self.cur.peek() {
287 if c == maybe {
288 self.cur.next();
289 Some(pos)
290 } else {
291 let pos = pos + padding + 1;
292 self.err(format!("expected `{:?}`, found `{:?}`", c, maybe),
293 format!("expected `{}`", c),
294 pos,
295 pos);
296 None
297 }
298 } else {
299 let msg = format!("expected `{:?}` but string was terminated", c);
300 // point at closing `"`, unless the last char is `\n` to account for `println`
301 let pos = match self.input.chars().last() {
302 Some('\n') => self.input.len(),
303 _ => self.input.len() + 1,
304 };
305 if c == '}' {
306 self.err_with_note(msg,
307 format!("expected `{:?}`", c),
308 "if you intended to print `{`, you can escape it using `{{`",
309 pos + padding,
310 pos + padding);
311 } else {
312 self.err(msg, format!("expected `{:?}`", c), pos, pos);
313 }
314 None
315 }
316 }
317
318 /// Consumes all whitespace characters until the first non-whitespace
319 /// character
320 fn ws(&mut self) {
321 while let Some(&(_, c)) = self.cur.peek() {
322 if c.is_whitespace() {
323 self.cur.next();
324 } else {
325 break;
326 }
327 }
328 }
329
330 /// Parses all of a string which is to be considered a "raw literal" in a
331 /// format string. This is everything outside of the braces.
332 fn string(&mut self, start: usize) -> &'a str {
333 // we may not consume the character, peek the iterator
334 while let Some(&(pos, c)) = self.cur.peek() {
335 match c {
336 '{' | '}' => {
337 return &self.input[start..pos];
338 }
339 _ => {
340 self.cur.next();
341 }
342 }
343 }
344 &self.input[start..self.input.len()]
345 }
346
347 /// Parses an Argument structure, or what's contained within braces inside
348 /// the format string
349 fn argument(&mut self) -> Argument<'a> {
350 let pos = self.position();
351 let format = self.format();
352
353 // Resolve position after parsing format spec.
354 let pos = match pos {
355 Some(position) => position,
356 None => {
357 let i = self.curarg;
358 self.curarg += 1;
359 ArgumentImplicitlyIs(i)
360 }
361 };
362
363 Argument {
364 position: pos,
365 format,
366 }
367 }
368
369 /// Parses a positional argument for a format. This could either be an
370 /// integer index of an argument, a named argument, or a blank string.
371 /// Returns `Some(parsed_position)` if the position is not implicitly
372 /// consuming a macro argument, `None` if it's the case.
373 fn position(&mut self) -> Option<Position<'a>> {
374 if let Some(i) = self.integer() {
375 Some(ArgumentIs(i))
376 } else {
377 match self.cur.peek() {
378 Some(&(_, c)) if c.is_alphabetic() => Some(ArgumentNamed(self.word())),
379 Some(&(pos, c)) if c == '_' => {
380 let invalid_name = self.string(pos);
381 self.err_with_note(format!("invalid argument name `{}`", invalid_name),
382 "invalid argument name",
383 "argument names cannot start with an underscore",
384 pos + 1, // add 1 to account for leading `{`
385 pos + 1 + invalid_name.len());
386 Some(ArgumentNamed(invalid_name))
387 },
388
389 // This is an `ArgumentNext`.
390 // Record the fact and do the resolution after parsing the
391 // format spec, to make things like `{:.*}` work.
392 _ => None,
393 }
394 }
395 }
396
397 /// Parses a format specifier at the current position, returning all of the
398 /// relevant information in the FormatSpec struct.
399 fn format(&mut self) -> FormatSpec<'a> {
400 let mut spec = FormatSpec {
401 fill: None,
402 align: AlignUnknown,
403 flags: 0,
404 precision: CountImplied,
405 width: CountImplied,
406 ty: &self.input[..0],
407 };
408 if !self.consume(':') {
409 return spec;
410 }
411
412 // fill character
413 if let Some(&(_, c)) = self.cur.peek() {
414 match self.cur.clone().nth(1) {
415 Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => {
416 spec.fill = Some(c);
417 self.cur.next();
418 }
419 _ => {}
420 }
421 }
422 // Alignment
423 if self.consume('<') {
424 spec.align = AlignLeft;
425 } else if self.consume('>') {
426 spec.align = AlignRight;
427 } else if self.consume('^') {
428 spec.align = AlignCenter;
429 }
430 // Sign flags
431 if self.consume('+') {
432 spec.flags |= 1 << (FlagSignPlus as u32);
433 } else if self.consume('-') {
434 spec.flags |= 1 << (FlagSignMinus as u32);
435 }
436 // Alternate marker
437 if self.consume('#') {
438 spec.flags |= 1 << (FlagAlternate as u32);
439 }
440 // Width and precision
441 let mut havewidth = false;
442 if self.consume('0') {
443 // small ambiguity with '0$' as a format string. In theory this is a
444 // '0' flag and then an ill-formatted format string with just a '$'
445 // and no count, but this is better if we instead interpret this as
446 // no '0' flag and '0$' as the width instead.
447 if self.consume('$') {
448 spec.width = CountIsParam(0);
449 havewidth = true;
450 } else {
451 spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
452 }
453 }
454 if !havewidth {
455 spec.width = self.count();
456 }
457 if self.consume('.') {
458 if self.consume('*') {
459 // Resolve `CountIsNextParam`.
460 // We can do this immediately as `position` is resolved later.
461 let i = self.curarg;
462 self.curarg += 1;
463 spec.precision = CountIsParam(i);
464 } else {
465 spec.precision = self.count();
466 }
467 }
468 // Optional radix followed by the actual format specifier
469 if self.consume('x') {
470 if self.consume('?') {
471 spec.flags |= 1 << (FlagDebugLowerHex as u32);
472 spec.ty = "?";
473 } else {
474 spec.ty = "x";
475 }
476 } else if self.consume('X') {
477 if self.consume('?') {
478 spec.flags |= 1 << (FlagDebugUpperHex as u32);
479 spec.ty = "?";
480 } else {
481 spec.ty = "X";
482 }
483 } else if self.consume('?') {
484 spec.ty = "?";
485 } else {
486 spec.ty = self.word();
487 }
488 spec
489 }
490
491 /// Parses a Count parameter at the current position. This does not check
492 /// for 'CountIsNextParam' because that is only used in precision, not
493 /// width.
494 fn count(&mut self) -> Count<'a> {
495 if let Some(i) = self.integer() {
496 if self.consume('$') {
497 CountIsParam(i)
498 } else {
499 CountIs(i)
500 }
501 } else {
502 let tmp = self.cur.clone();
503 let word = self.word();
504 if word.is_empty() {
505 self.cur = tmp;
506 CountImplied
507 } else if self.consume('$') {
508 CountIsName(word)
509 } else {
510 self.cur = tmp;
511 CountImplied
512 }
513 }
514 }
515
516 /// Parses a word starting at the current position. A word is considered to
517 /// be an alphabetic character followed by any number of alphanumeric
518 /// characters.
519 fn word(&mut self) -> &'a str {
520 let start = match self.cur.peek() {
521 Some(&(pos, c)) if c.is_xid_start() => {
522 self.cur.next();
523 pos
524 }
525 _ => {
526 return &self.input[..0];
527 }
528 };
529 while let Some(&(pos, c)) = self.cur.peek() {
530 if c.is_xid_continue() {
531 self.cur.next();
532 } else {
533 return &self.input[start..pos];
534 }
535 }
536 &self.input[start..self.input.len()]
537 }
538
539 /// Optionally parses an integer at the current position. This doesn't deal
540 /// with overflow at all, it's just accumulating digits.
541 fn integer(&mut self) -> Option<usize> {
542 let mut cur = 0;
543 let mut found = false;
544 while let Some(&(_, c)) = self.cur.peek() {
545 if let Some(i) = c.to_digit(10) {
546 cur = cur * 10 + i as usize;
547 found = true;
548 self.cur.next();
549 } else {
550 break;
551 }
552 }
553 if found {
554 Some(cur)
555 } else {
556 None
557 }
558 }
559 }
560
561 #[cfg(test)]
562 mod tests {
563 use super::*;
564
565 fn same(fmt: &'static str, p: &[Piece<'static>]) {
566 let parser = Parser::new(fmt, None);
567 assert!(parser.collect::<Vec<Piece<'static>>>() == p);
568 }
569
570 fn fmtdflt() -> FormatSpec<'static> {
571 return FormatSpec {
572 fill: None,
573 align: AlignUnknown,
574 flags: 0,
575 precision: CountImplied,
576 width: CountImplied,
577 ty: "",
578 };
579 }
580
581 fn musterr(s: &str) {
582 let mut p = Parser::new(s, None);
583 p.next();
584 assert!(!p.errors.is_empty());
585 }
586
587 #[test]
588 fn simple() {
589 same("asdf", &[String("asdf")]);
590 same("a{{b", &[String("a"), String("{b")]);
591 same("a}}b", &[String("a"), String("}b")]);
592 same("a}}", &[String("a"), String("}")]);
593 same("}}", &[String("}")]);
594 same("\\}}", &[String("\\"), String("}")]);
595 }
596
597 #[test]
598 fn invalid01() {
599 musterr("{")
600 }
601 #[test]
602 fn invalid02() {
603 musterr("}")
604 }
605 #[test]
606 fn invalid04() {
607 musterr("{3a}")
608 }
609 #[test]
610 fn invalid05() {
611 musterr("{:|}")
612 }
613 #[test]
614 fn invalid06() {
615 musterr("{:>>>}")
616 }
617
618 #[test]
619 fn format_nothing() {
620 same("{}",
621 &[NextArgument(Argument {
622 position: ArgumentImplicitlyIs(0),
623 format: fmtdflt(),
624 })]);
625 }
626 #[test]
627 fn format_position() {
628 same("{3}",
629 &[NextArgument(Argument {
630 position: ArgumentIs(3),
631 format: fmtdflt(),
632 })]);
633 }
634 #[test]
635 fn format_position_nothing_else() {
636 same("{3:}",
637 &[NextArgument(Argument {
638 position: ArgumentIs(3),
639 format: fmtdflt(),
640 })]);
641 }
642 #[test]
643 fn format_type() {
644 same("{3:a}",
645 &[NextArgument(Argument {
646 position: ArgumentIs(3),
647 format: FormatSpec {
648 fill: None,
649 align: AlignUnknown,
650 flags: 0,
651 precision: CountImplied,
652 width: CountImplied,
653 ty: "a",
654 },
655 })]);
656 }
657 #[test]
658 fn format_align_fill() {
659 same("{3:>}",
660 &[NextArgument(Argument {
661 position: ArgumentIs(3),
662 format: FormatSpec {
663 fill: None,
664 align: AlignRight,
665 flags: 0,
666 precision: CountImplied,
667 width: CountImplied,
668 ty: "",
669 },
670 })]);
671 same("{3:0<}",
672 &[NextArgument(Argument {
673 position: ArgumentIs(3),
674 format: FormatSpec {
675 fill: Some('0'),
676 align: AlignLeft,
677 flags: 0,
678 precision: CountImplied,
679 width: CountImplied,
680 ty: "",
681 },
682 })]);
683 same("{3:*<abcd}",
684 &[NextArgument(Argument {
685 position: ArgumentIs(3),
686 format: FormatSpec {
687 fill: Some('*'),
688 align: AlignLeft,
689 flags: 0,
690 precision: CountImplied,
691 width: CountImplied,
692 ty: "abcd",
693 },
694 })]);
695 }
696 #[test]
697 fn format_counts() {
698 same("{:10s}",
699 &[NextArgument(Argument {
700 position: ArgumentImplicitlyIs(0),
701 format: FormatSpec {
702 fill: None,
703 align: AlignUnknown,
704 flags: 0,
705 precision: CountImplied,
706 width: CountIs(10),
707 ty: "s",
708 },
709 })]);
710 same("{:10$.10s}",
711 &[NextArgument(Argument {
712 position: ArgumentImplicitlyIs(0),
713 format: FormatSpec {
714 fill: None,
715 align: AlignUnknown,
716 flags: 0,
717 precision: CountIs(10),
718 width: CountIsParam(10),
719 ty: "s",
720 },
721 })]);
722 same("{:.*s}",
723 &[NextArgument(Argument {
724 position: ArgumentImplicitlyIs(1),
725 format: FormatSpec {
726 fill: None,
727 align: AlignUnknown,
728 flags: 0,
729 precision: CountIsParam(0),
730 width: CountImplied,
731 ty: "s",
732 },
733 })]);
734 same("{:.10$s}",
735 &[NextArgument(Argument {
736 position: ArgumentImplicitlyIs(0),
737 format: FormatSpec {
738 fill: None,
739 align: AlignUnknown,
740 flags: 0,
741 precision: CountIsParam(10),
742 width: CountImplied,
743 ty: "s",
744 },
745 })]);
746 same("{:a$.b$s}",
747 &[NextArgument(Argument {
748 position: ArgumentImplicitlyIs(0),
749 format: FormatSpec {
750 fill: None,
751 align: AlignUnknown,
752 flags: 0,
753 precision: CountIsName("b"),
754 width: CountIsName("a"),
755 ty: "s",
756 },
757 })]);
758 }
759 #[test]
760 fn format_flags() {
761 same("{:-}",
762 &[NextArgument(Argument {
763 position: ArgumentImplicitlyIs(0),
764 format: FormatSpec {
765 fill: None,
766 align: AlignUnknown,
767 flags: (1 << FlagSignMinus as u32),
768 precision: CountImplied,
769 width: CountImplied,
770 ty: "",
771 },
772 })]);
773 same("{:+#}",
774 &[NextArgument(Argument {
775 position: ArgumentImplicitlyIs(0),
776 format: FormatSpec {
777 fill: None,
778 align: AlignUnknown,
779 flags: (1 << FlagSignPlus as u32) | (1 << FlagAlternate as u32),
780 precision: CountImplied,
781 width: CountImplied,
782 ty: "",
783 },
784 })]);
785 }
786 #[test]
787 fn format_mixture() {
788 same("abcd {3:a} efg",
789 &[String("abcd "),
790 NextArgument(Argument {
791 position: ArgumentIs(3),
792 format: FormatSpec {
793 fill: None,
794 align: AlignUnknown,
795 flags: 0,
796 precision: CountImplied,
797 width: CountImplied,
798 ty: "a",
799 },
800 }),
801 String(" efg")]);
802 }
803 }