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