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