2013-07-29 03:12:41 -05:00
|
|
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
|
|
|
|
// file at the top-level directory of this distribution and at
|
|
|
|
// http://rust-lang.org/COPYRIGHT.
|
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
|
|
|
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
|
|
|
// option. This file may not be copied, modified, or distributed
|
|
|
|
// except according to those terms.
|
|
|
|
|
2014-05-06 11:52:53 -05:00
|
|
|
//! Macro support for format strings
|
2013-10-12 21:02:46 -05:00
|
|
|
//!
|
|
|
|
//! These structures are used when parsing format strings for the compiler.
|
2014-03-16 17:59:04 -05:00
|
|
|
//! Parsing does not happen at runtime: structures of `std::fmt::rt` are
|
|
|
|
//! generated instead.
|
2013-10-12 21:02:46 -05:00
|
|
|
|
2014-07-01 09:12:04 -05:00
|
|
|
#![crate_name = "fmt_macros"]
|
2015-08-13 12:21:36 -05:00
|
|
|
#![unstable(feature = "rustc_private", issue = "27812")]
|
2014-05-06 11:52:53 -05:00
|
|
|
#![crate_type = "rlib"]
|
|
|
|
#![crate_type = "dylib"]
|
2015-08-09 16:15:05 -05:00
|
|
|
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
|
2015-05-15 18:04:01 -05:00
|
|
|
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
|
2015-08-09 16:15:05 -05:00
|
|
|
html_root_url = "https://doc.rust-lang.org/nightly/",
|
2015-11-03 09:30:14 -06:00
|
|
|
html_playground_url = "https://play.rust-lang.org/",
|
|
|
|
test(attr(deny(warnings))))]
|
2016-01-21 17:26:19 -06:00
|
|
|
#![cfg_attr(not(stage0), deny(warnings))]
|
2014-11-30 07:19:29 -06:00
|
|
|
|
2015-01-30 14:26:44 -06:00
|
|
|
#![feature(staged_api)]
|
2015-01-22 20:22:03 -06:00
|
|
|
#![feature(unicode)]
|
2014-12-10 21:46:38 -06:00
|
|
|
|
2014-11-06 02:05:53 -06:00
|
|
|
pub use self::Piece::*;
|
|
|
|
pub use self::Position::*;
|
|
|
|
pub use self::Alignment::*;
|
|
|
|
pub use self::Flag::*;
|
|
|
|
pub use self::Count::*;
|
2014-08-12 22:31:30 -05:00
|
|
|
|
2014-05-06 11:52:53 -05:00
|
|
|
use std::str;
|
2014-09-11 00:07:49 -05:00
|
|
|
use std::string;
|
2015-09-10 07:03:22 -05:00
|
|
|
use std::iter;
|
2013-07-29 03:12:41 -05:00
|
|
|
|
2014-03-16 17:59:04 -05:00
|
|
|
/// A piece is a portion of the format string which represents the next part
|
|
|
|
/// to emit. These are emitted as a stream by the `Parser` class.
|
2015-03-30 08:40:52 -05:00
|
|
|
#[derive(Copy, Clone, PartialEq)]
|
2013-12-10 01:16:18 -06:00
|
|
|
pub enum Piece<'a> {
|
2013-07-29 03:12:41 -05:00
|
|
|
/// A literal string which should directly be emitted
|
2013-12-10 01:16:18 -06:00
|
|
|
String(&'a str),
|
2013-07-29 03:12:41 -05:00
|
|
|
/// This describes that formatting should process the next argument (as
|
|
|
|
/// specified inside) for emission.
|
2014-09-11 00:07:49 -05:00
|
|
|
NextArgument(Argument<'a>),
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Representation of an argument specification.
|
2015-03-30 08:40:52 -05:00
|
|
|
#[derive(Copy, Clone, PartialEq)]
|
2013-12-10 01:16:18 -06:00
|
|
|
pub struct Argument<'a> {
|
2013-07-29 03:12:41 -05:00
|
|
|
/// Where to find this argument
|
2014-03-27 17:09:47 -05:00
|
|
|
pub position: Position<'a>,
|
2013-07-29 03:12:41 -05:00
|
|
|
/// How to format the argument
|
2014-03-27 17:09:47 -05:00
|
|
|
pub format: FormatSpec<'a>,
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Specification for the formatting of an argument in the format string.
|
2015-03-30 08:40:52 -05:00
|
|
|
#[derive(Copy, Clone, PartialEq)]
|
2013-12-10 01:16:18 -06:00
|
|
|
pub struct FormatSpec<'a> {
|
2013-10-12 22:00:58 -05:00
|
|
|
/// Optionally specified character to fill alignment with
|
2014-03-27 17:09:47 -05:00
|
|
|
pub fill: Option<char>,
|
2013-10-12 22:00:58 -05:00
|
|
|
/// Optionally specified alignment
|
2014-03-27 17:09:47 -05:00
|
|
|
pub align: Alignment,
|
2013-10-12 22:00:58 -05:00
|
|
|
/// Packed version of various flags provided
|
2015-02-22 21:07:38 -06:00
|
|
|
pub flags: u32,
|
2013-10-12 22:00:58 -05:00
|
|
|
/// The integer precision to use
|
2014-03-27 17:09:47 -05:00
|
|
|
pub precision: Count<'a>,
|
2013-10-12 22:00:58 -05:00
|
|
|
/// The string width requested for the resulting format
|
2014-03-27 17:09:47 -05:00
|
|
|
pub width: Count<'a>,
|
2013-10-12 22:00:58 -05:00
|
|
|
/// The descriptor string representing the name of the format desired for
|
|
|
|
/// this argument, this can be empty or any number of characters, although
|
|
|
|
/// it is required to be one word.
|
2015-10-13 09:10:51 -05:00
|
|
|
pub ty: &'a str,
|
2013-10-12 22:00:58 -05:00
|
|
|
}
|
|
|
|
|
2013-07-29 03:12:41 -05:00
|
|
|
/// Enum describing where an argument for a format can be located.
|
2015-03-30 08:40:52 -05:00
|
|
|
#[derive(Copy, Clone, PartialEq)]
|
2013-12-10 01:16:18 -06:00
|
|
|
pub enum Position<'a> {
|
2014-03-16 17:59:04 -05:00
|
|
|
/// The argument will be in the next position. This is the default.
|
|
|
|
ArgumentNext,
|
|
|
|
/// The argument is located at a specific index.
|
2015-02-22 21:07:38 -06:00
|
|
|
ArgumentIs(usize),
|
2014-03-16 17:59:04 -05:00
|
|
|
/// The argument has a name.
|
|
|
|
ArgumentNamed(&'a str),
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
|
2013-08-16 00:41:28 -05:00
|
|
|
/// Enum of alignments which are supported.
|
2015-03-30 08:40:52 -05:00
|
|
|
#[derive(Copy, Clone, PartialEq)]
|
2014-03-16 17:59:04 -05:00
|
|
|
pub enum Alignment {
|
|
|
|
/// The value will be aligned to the left.
|
|
|
|
AlignLeft,
|
|
|
|
/// The value will be aligned to the right.
|
|
|
|
AlignRight,
|
2014-08-30 13:27:02 -05:00
|
|
|
/// The value will be aligned in the center.
|
|
|
|
AlignCenter,
|
2014-03-16 17:59:04 -05:00
|
|
|
/// The value will take on a default alignment.
|
|
|
|
AlignUnknown,
|
|
|
|
}
|
2013-07-29 03:12:41 -05:00
|
|
|
|
2014-03-16 17:59:04 -05:00
|
|
|
/// Various flags which can be applied to format strings. The meaning of these
|
2013-07-29 03:12:41 -05:00
|
|
|
/// flags is defined by the formatters themselves.
|
2015-03-30 08:40:52 -05:00
|
|
|
#[derive(Copy, Clone, PartialEq)]
|
2013-07-29 03:12:41 -05:00
|
|
|
pub enum Flag {
|
2014-03-16 17:59:04 -05:00
|
|
|
/// A `+` will be used to denote positive numbers.
|
2013-07-29 03:12:41 -05:00
|
|
|
FlagSignPlus,
|
2014-03-16 17:59:04 -05:00
|
|
|
/// A `-` will be used to denote negative numbers. This is the default.
|
2013-07-29 03:12:41 -05:00
|
|
|
FlagSignMinus,
|
2014-03-16 17:59:04 -05:00
|
|
|
/// An alternate form will be used for the value. In the case of numbers,
|
|
|
|
/// this means that the number will be prefixed with the supplied string.
|
2013-07-29 03:12:41 -05:00
|
|
|
FlagAlternate,
|
2014-03-16 17:59:04 -05:00
|
|
|
/// For numbers, this means that the number will be padded with zeroes,
|
|
|
|
/// and the sign (`+` or `-`) will precede them.
|
2013-08-10 18:50:42 -05:00
|
|
|
FlagSignAwareZeroPad,
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// A count is used for the precision and width parameters of an integer, and
|
|
|
|
/// can reference either an argument or a literal integer.
|
2015-03-30 08:40:52 -05:00
|
|
|
#[derive(Copy, Clone, PartialEq)]
|
2013-12-10 01:16:18 -06:00
|
|
|
pub enum Count<'a> {
|
2014-03-16 17:59:04 -05:00
|
|
|
/// The count is specified explicitly.
|
2015-02-22 21:07:38 -06:00
|
|
|
CountIs(usize),
|
2014-03-16 17:59:04 -05:00
|
|
|
/// The count is specified by the argument with the given name.
|
2013-12-10 01:16:18 -06:00
|
|
|
CountIsName(&'a str),
|
2014-03-16 17:59:04 -05:00
|
|
|
/// The count is specified by the argument at the given index.
|
2015-02-22 21:07:38 -06:00
|
|
|
CountIsParam(usize),
|
2014-03-16 17:59:04 -05:00
|
|
|
/// The count is specified by the next parameter.
|
2013-07-29 03:12:41 -05:00
|
|
|
CountIsNextParam,
|
2014-03-16 17:59:04 -05:00
|
|
|
/// The count is implied and cannot be explicitly specified.
|
2013-07-29 03:12:41 -05:00
|
|
|
CountImplied,
|
|
|
|
}
|
|
|
|
|
|
|
|
/// The parser structure for interpreting the input format string. This is
|
2015-10-13 08:44:11 -05:00
|
|
|
/// modeled as an iterator over `Piece` structures to form a stream of tokens
|
2013-07-29 03:12:41 -05:00
|
|
|
/// being output.
|
|
|
|
///
|
|
|
|
/// This is a recursive-descent parser for the sake of simplicity, and if
|
|
|
|
/// necessary there's probably lots of room for improvement performance-wise.
|
2013-12-10 01:16:18 -06:00
|
|
|
pub struct Parser<'a> {
|
2014-03-27 17:09:47 -05:00
|
|
|
input: &'a str,
|
2015-09-10 07:03:22 -05:00
|
|
|
cur: iter::Peekable<str::CharIndices<'a>>,
|
Remove std::condition
This has been a long time coming. Conditions in rust were initially envisioned
as being a good alternative to error code return pattern. The idea is that all
errors are fatal-by-default, and you can opt-in to handling the error by
registering an error handler.
While sounding nice, conditions ended up having some unforseen shortcomings:
* Actually handling an error has some very awkward syntax:
let mut result = None;
let mut answer = None;
io::io_error::cond.trap(|e| { result = Some(e) }).inside(|| {
answer = Some(some_io_operation());
});
match result {
Some(err) => { /* hit an I/O error */ }
None => {
let answer = answer.unwrap();
/* deal with the result of I/O */
}
}
This pattern can certainly use functions like io::result, but at its core
actually handling conditions is fairly difficult
* The "zero value" of a function is often confusing. One of the main ideas
behind using conditions was to change the signature of I/O functions. Instead
of read_be_u32() returning a result, it returned a u32. Errors were notified
via a condition, and if you caught the condition you understood that the "zero
value" returned is actually a garbage value. These zero values are often
difficult to understand, however.
One case of this is the read_bytes() function. The function takes an integer
length of the amount of bytes to read, and returns an array of that size. The
array may actually be shorter, however, if an error occurred.
Another case is fs::stat(). The theoretical "zero value" is a blank stat
struct, but it's a little awkward to create and return a zero'd out stat
struct on a call to stat().
In general, the return value of functions that can raise error are much more
natural when using a Result as opposed to an always-usable zero-value.
* Conditions impose a necessary runtime requirement on *all* I/O. In theory I/O
is as simple as calling read() and write(), but using conditions imposed the
restriction that a rust local task was required if you wanted to catch errors
with I/O. While certainly an surmountable difficulty, this was always a bit of
a thorn in the side of conditions.
* Functions raising conditions are not always clear that they are raising
conditions. This suffers a similar problem to exceptions where you don't
actually know whether a function raises a condition or not. The documentation
likely explains, but if someone retroactively adds a condition to a function
there's nothing forcing upstream users to acknowledge a new point of task
failure.
* Libaries using I/O are not guaranteed to correctly raise on conditions when an
error occurs. In developing various I/O libraries, it's much easier to just
return `None` from a read rather than raising an error. The silent contract of
"don't raise on EOF" was a little difficult to understand and threw a wrench
into the answer of the question "when do I raise a condition?"
Many of these difficulties can be overcome through documentation, examples, and
general practice. In the end, all of these difficulties added together ended up
being too overwhelming and improving various aspects didn't end up helping that
much.
A result-based I/O error handling strategy also has shortcomings, but the
cognitive burden is much smaller. The tooling necessary to make this strategy as
usable as conditions were is much smaller than the tooling necessary for
conditions.
Perhaps conditions may manifest themselves as a future entity, but for now
we're going to remove them from the standard library.
Closes #9795
Closes #8968
2014-02-04 21:02:10 -06:00
|
|
|
/// Error messages accumulated during parsing
|
2014-09-11 00:07:49 -05:00
|
|
|
pub errors: Vec<string::String>,
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
|
2015-01-01 21:36:34 -06:00
|
|
|
impl<'a> Iterator for Parser<'a> {
|
|
|
|
type Item = Piece<'a>;
|
|
|
|
|
2013-12-10 01:16:18 -06:00
|
|
|
fn next(&mut self) -> Option<Piece<'a>> {
|
2015-09-10 08:48:11 -05:00
|
|
|
if let Some(&(pos, c)) = self.cur.peek() {
|
|
|
|
match c {
|
|
|
|
'{' => {
|
|
|
|
self.cur.next();
|
|
|
|
if self.consume('{') {
|
|
|
|
Some(String(self.string(pos + 1)))
|
|
|
|
} else {
|
|
|
|
let ret = Some(NextArgument(self.argument()));
|
|
|
|
self.must_consume('}');
|
|
|
|
ret
|
|
|
|
}
|
2014-05-28 11:24:28 -05:00
|
|
|
}
|
2015-09-10 08:48:11 -05:00
|
|
|
'}' => {
|
|
|
|
self.cur.next();
|
|
|
|
if self.consume('}') {
|
|
|
|
Some(String(self.string(pos + 1)))
|
|
|
|
} else {
|
|
|
|
self.err("unmatched `}` found");
|
|
|
|
None
|
|
|
|
}
|
2014-05-28 11:24:28 -05:00
|
|
|
}
|
2015-09-10 08:48:11 -05:00
|
|
|
_ => Some(String(self.string(pos))),
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
2015-09-10 08:48:11 -05:00
|
|
|
} else {
|
|
|
|
None
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-12-10 01:16:18 -06:00
|
|
|
impl<'a> Parser<'a> {
|
2013-07-29 03:12:41 -05:00
|
|
|
/// Creates a new parser for the given format string
|
2014-12-12 10:09:32 -06:00
|
|
|
pub fn new(s: &'a str) -> Parser<'a> {
|
2013-07-29 03:12:41 -05:00
|
|
|
Parser {
|
|
|
|
input: s,
|
2015-09-10 07:03:22 -05:00
|
|
|
cur: s.char_indices().peekable(),
|
2015-11-23 17:11:20 -06:00
|
|
|
errors: vec![],
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Notifies of an error. The message doesn't actually need to be of type
|
2014-05-22 18:57:53 -05:00
|
|
|
/// String, but I think it does when this eventually uses conditions so it
|
2013-07-29 03:12:41 -05:00
|
|
|
/// might as well start using it now.
|
Remove std::condition
This has been a long time coming. Conditions in rust were initially envisioned
as being a good alternative to error code return pattern. The idea is that all
errors are fatal-by-default, and you can opt-in to handling the error by
registering an error handler.
While sounding nice, conditions ended up having some unforseen shortcomings:
* Actually handling an error has some very awkward syntax:
let mut result = None;
let mut answer = None;
io::io_error::cond.trap(|e| { result = Some(e) }).inside(|| {
answer = Some(some_io_operation());
});
match result {
Some(err) => { /* hit an I/O error */ }
None => {
let answer = answer.unwrap();
/* deal with the result of I/O */
}
}
This pattern can certainly use functions like io::result, but at its core
actually handling conditions is fairly difficult
* The "zero value" of a function is often confusing. One of the main ideas
behind using conditions was to change the signature of I/O functions. Instead
of read_be_u32() returning a result, it returned a u32. Errors were notified
via a condition, and if you caught the condition you understood that the "zero
value" returned is actually a garbage value. These zero values are often
difficult to understand, however.
One case of this is the read_bytes() function. The function takes an integer
length of the amount of bytes to read, and returns an array of that size. The
array may actually be shorter, however, if an error occurred.
Another case is fs::stat(). The theoretical "zero value" is a blank stat
struct, but it's a little awkward to create and return a zero'd out stat
struct on a call to stat().
In general, the return value of functions that can raise error are much more
natural when using a Result as opposed to an always-usable zero-value.
* Conditions impose a necessary runtime requirement on *all* I/O. In theory I/O
is as simple as calling read() and write(), but using conditions imposed the
restriction that a rust local task was required if you wanted to catch errors
with I/O. While certainly an surmountable difficulty, this was always a bit of
a thorn in the side of conditions.
* Functions raising conditions are not always clear that they are raising
conditions. This suffers a similar problem to exceptions where you don't
actually know whether a function raises a condition or not. The documentation
likely explains, but if someone retroactively adds a condition to a function
there's nothing forcing upstream users to acknowledge a new point of task
failure.
* Libaries using I/O are not guaranteed to correctly raise on conditions when an
error occurs. In developing various I/O libraries, it's much easier to just
return `None` from a read rather than raising an error. The silent contract of
"don't raise on EOF" was a little difficult to understand and threw a wrench
into the answer of the question "when do I raise a condition?"
Many of these difficulties can be overcome through documentation, examples, and
general practice. In the end, all of these difficulties added together ended up
being too overwhelming and improving various aspects didn't end up helping that
much.
A result-based I/O error handling strategy also has shortcomings, but the
cognitive burden is much smaller. The tooling necessary to make this strategy as
usable as conditions were is much smaller than the tooling necessary for
conditions.
Perhaps conditions may manifest themselves as a future entity, but for now
we're going to remove them from the standard library.
Closes #9795
Closes #8968
2014-02-04 21:02:10 -06:00
|
|
|
fn err(&mut self, msg: &str) {
|
2015-09-02 05:13:10 -05:00
|
|
|
self.errors.push(msg.to_owned());
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Optionally consumes the specified character. If the character is not at
|
|
|
|
/// the current position, then the current iterator isn't moved and false is
|
|
|
|
/// returned, otherwise the character is consumed and true is returned.
|
|
|
|
fn consume(&mut self, c: char) -> bool {
|
2015-09-10 08:48:11 -05:00
|
|
|
if let Some(&(_, maybe)) = self.cur.peek() {
|
2015-10-13 09:10:51 -05:00
|
|
|
if c == maybe {
|
|
|
|
self.cur.next();
|
|
|
|
true
|
|
|
|
} else {
|
|
|
|
false
|
|
|
|
}
|
2015-09-10 08:48:11 -05:00
|
|
|
} else {
|
|
|
|
false
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-10-18 12:30:40 -05:00
|
|
|
/// Forces consumption of the specified character. If the character is not
|
|
|
|
/// found, an error is emitted.
|
|
|
|
fn must_consume(&mut self, c: char) {
|
|
|
|
self.ws();
|
2015-09-10 08:48:11 -05:00
|
|
|
if let Some(&(_, maybe)) = self.cur.peek() {
|
|
|
|
if c == maybe {
|
2013-10-18 12:30:40 -05:00
|
|
|
self.cur.next();
|
2015-09-10 08:48:11 -05:00
|
|
|
} else {
|
|
|
|
self.err(&format!("expected `{:?}`, found `{:?}`", c, maybe));
|
2013-10-18 12:30:40 -05:00
|
|
|
}
|
2015-09-10 08:48:11 -05:00
|
|
|
} else {
|
|
|
|
self.err(&format!("expected `{:?}` but string was terminated", c));
|
2013-10-18 12:30:40 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-07-29 03:12:41 -05:00
|
|
|
/// Consumes all whitespace characters until the first non-whitespace
|
|
|
|
/// character
|
|
|
|
fn ws(&mut self) {
|
2015-09-10 08:48:11 -05:00
|
|
|
while let Some(&(_, c)) = self.cur.peek() {
|
2015-10-13 09:10:51 -05:00
|
|
|
if c.is_whitespace() {
|
|
|
|
self.cur.next();
|
|
|
|
} else {
|
2015-11-23 17:11:20 -06:00
|
|
|
break;
|
2015-10-13 09:10:51 -05:00
|
|
|
}
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Parses all of a string which is to be considered a "raw literal" in a
|
|
|
|
/// format string. This is everything outside of the braces.
|
2015-02-22 21:07:38 -06:00
|
|
|
fn string(&mut self, start: usize) -> &'a str {
|
2015-09-10 08:48:11 -05:00
|
|
|
// we may not consume the character, peek the iterator
|
|
|
|
while let Some(&(pos, c)) = self.cur.peek() {
|
|
|
|
match c {
|
2015-10-13 09:10:51 -05:00
|
|
|
'{' | '}' => {
|
|
|
|
return &self.input[start..pos];
|
|
|
|
}
|
|
|
|
_ => {
|
|
|
|
self.cur.next();
|
|
|
|
}
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
}
|
2015-09-10 08:48:11 -05:00
|
|
|
&self.input[start..self.input.len()]
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Parses an Argument structure, or what's contained within braces inside
|
|
|
|
/// the format string
|
2013-12-10 01:16:18 -06:00
|
|
|
fn argument(&mut self) -> Argument<'a> {
|
2013-07-29 03:12:41 -05:00
|
|
|
Argument {
|
|
|
|
position: self.position(),
|
|
|
|
format: self.format(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Parses a positional argument for a format. This could either be an
|
|
|
|
/// integer index of an argument, a named argument, or a blank string.
|
2013-12-10 01:16:18 -06:00
|
|
|
fn position(&mut self) -> Position<'a> {
|
2015-09-10 08:48:11 -05:00
|
|
|
if let Some(i) = self.integer() {
|
|
|
|
ArgumentIs(i)
|
|
|
|
} else {
|
|
|
|
match self.cur.peek() {
|
2015-11-23 17:11:20 -06:00
|
|
|
Some(&(_, c)) if c.is_alphabetic() => ArgumentNamed(self.word()),
|
2015-10-13 09:10:51 -05:00
|
|
|
_ => ArgumentNext,
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Parses a format specifier at the current position, returning all of the
|
|
|
|
/// relevant information in the FormatSpec struct.
|
2013-12-10 01:16:18 -06:00
|
|
|
fn format(&mut self) -> FormatSpec<'a> {
|
2013-07-29 03:12:41 -05:00
|
|
|
let mut spec = FormatSpec {
|
|
|
|
fill: None,
|
2013-08-10 18:50:42 -05:00
|
|
|
align: AlignUnknown,
|
2013-07-29 03:12:41 -05:00
|
|
|
flags: 0,
|
|
|
|
precision: CountImplied,
|
|
|
|
width: CountImplied,
|
2015-01-12 15:59:18 -06:00
|
|
|
ty: &self.input[..0],
|
2013-07-29 03:12:41 -05:00
|
|
|
};
|
2015-10-13 09:10:51 -05:00
|
|
|
if !self.consume(':') {
|
2015-11-23 17:11:20 -06:00
|
|
|
return spec;
|
2015-10-13 09:10:51 -05:00
|
|
|
}
|
2013-07-29 03:12:41 -05:00
|
|
|
|
|
|
|
// fill character
|
2015-09-10 08:48:11 -05:00
|
|
|
if let Some(&(_, c)) = self.cur.peek() {
|
|
|
|
match self.cur.clone().skip(1).next() {
|
|
|
|
Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => {
|
|
|
|
spec.fill = Some(c);
|
|
|
|
self.cur.next();
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
2015-09-10 08:48:11 -05:00
|
|
|
_ => {}
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
// Alignment
|
|
|
|
if self.consume('<') {
|
2013-08-10 18:50:42 -05:00
|
|
|
spec.align = AlignLeft;
|
2013-07-29 03:12:41 -05:00
|
|
|
} else if self.consume('>') {
|
2013-08-10 18:50:42 -05:00
|
|
|
spec.align = AlignRight;
|
2014-08-30 13:27:02 -05:00
|
|
|
} else if self.consume('^') {
|
|
|
|
spec.align = AlignCenter;
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
// Sign flags
|
|
|
|
if self.consume('+') {
|
2015-02-22 21:07:38 -06:00
|
|
|
spec.flags |= 1 << (FlagSignPlus as u32);
|
2013-07-29 03:12:41 -05:00
|
|
|
} else if self.consume('-') {
|
2015-02-22 21:07:38 -06:00
|
|
|
spec.flags |= 1 << (FlagSignMinus as u32);
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
// Alternate marker
|
|
|
|
if self.consume('#') {
|
2015-02-22 21:07:38 -06:00
|
|
|
spec.flags |= 1 << (FlagAlternate as u32);
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
// Width and precision
|
2013-10-12 22:00:58 -05:00
|
|
|
let mut havewidth = false;
|
2013-08-10 18:50:42 -05:00
|
|
|
if self.consume('0') {
|
2013-10-12 22:00:58 -05:00
|
|
|
// small ambiguity with '0$' as a format string. In theory this is a
|
|
|
|
// '0' flag and then an ill-formatted format string with just a '$'
|
|
|
|
// and no count, but this is better if we instead interpret this as
|
|
|
|
// no '0' flag and '0$' as the width instead.
|
|
|
|
if self.consume('$') {
|
|
|
|
spec.width = CountIsParam(0);
|
|
|
|
havewidth = true;
|
|
|
|
} else {
|
2015-02-22 21:07:38 -06:00
|
|
|
spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
|
2013-10-12 22:00:58 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
if !havewidth {
|
|
|
|
spec.width = self.count();
|
2013-08-10 18:50:42 -05:00
|
|
|
}
|
2013-07-29 03:12:41 -05:00
|
|
|
if self.consume('.') {
|
|
|
|
if self.consume('*') {
|
|
|
|
spec.precision = CountIsNextParam;
|
|
|
|
} else {
|
|
|
|
spec.precision = self.count();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// Finally the actual format specifier
|
2013-08-14 22:40:15 -05:00
|
|
|
if self.consume('?') {
|
|
|
|
spec.ty = "?";
|
|
|
|
} else {
|
|
|
|
spec.ty = self.word();
|
|
|
|
}
|
2015-09-02 05:13:10 -05:00
|
|
|
spec
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Parses a Count parameter at the current position. This does not check
|
|
|
|
/// for 'CountIsNextParam' because that is only used in precision, not
|
|
|
|
/// width.
|
2013-12-10 01:16:18 -06:00
|
|
|
fn count(&mut self) -> Count<'a> {
|
2015-09-10 08:48:11 -05:00
|
|
|
if let Some(i) = self.integer() {
|
2015-10-13 09:10:51 -05:00
|
|
|
if self.consume('$') {
|
|
|
|
CountIsParam(i)
|
|
|
|
} else {
|
|
|
|
CountIs(i)
|
|
|
|
}
|
2015-09-10 08:48:11 -05:00
|
|
|
} else {
|
|
|
|
let tmp = self.cur.clone();
|
|
|
|
let word = self.word();
|
|
|
|
if word.is_empty() {
|
|
|
|
self.cur = tmp;
|
|
|
|
CountImplied
|
|
|
|
} else {
|
2013-10-12 22:00:58 -05:00
|
|
|
if self.consume('$') {
|
2015-09-10 08:48:11 -05:00
|
|
|
CountIsName(word)
|
2013-10-12 22:00:58 -05:00
|
|
|
} else {
|
2015-09-10 08:48:11 -05:00
|
|
|
self.cur = tmp;
|
|
|
|
CountImplied
|
2013-10-12 22:00:58 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2013-07-29 03:12:41 -05:00
|
|
|
|
|
|
|
/// Parses a word starting at the current position. A word is considered to
|
|
|
|
/// be an alphabetic character followed by any number of alphanumeric
|
|
|
|
/// characters.
|
2013-12-10 01:16:18 -06:00
|
|
|
fn word(&mut self) -> &'a str {
|
2015-09-10 07:03:22 -05:00
|
|
|
let start = match self.cur.peek() {
|
2015-10-13 09:10:51 -05:00
|
|
|
Some(&(pos, c)) if c.is_xid_start() => {
|
|
|
|
self.cur.next();
|
|
|
|
pos
|
|
|
|
}
|
|
|
|
_ => {
|
|
|
|
return &self.input[..0];
|
|
|
|
}
|
2013-07-29 03:12:41 -05:00
|
|
|
};
|
2015-09-10 08:48:11 -05:00
|
|
|
while let Some(&(pos, c)) = self.cur.peek() {
|
|
|
|
if c.is_xid_continue() {
|
|
|
|
self.cur.next();
|
|
|
|
} else {
|
|
|
|
return &self.input[start..pos];
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
}
|
2015-09-10 08:48:11 -05:00
|
|
|
&self.input[start..self.input.len()]
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Optionally parses an integer at the current position. This doesn't deal
|
|
|
|
/// with overflow at all, it's just accumulating digits.
|
2015-02-22 21:07:38 -06:00
|
|
|
fn integer(&mut self) -> Option<usize> {
|
2013-07-29 03:12:41 -05:00
|
|
|
let mut cur = 0;
|
|
|
|
let mut found = false;
|
2015-09-10 07:03:22 -05:00
|
|
|
while let Some(&(_, c)) = self.cur.peek() {
|
2015-09-02 05:13:10 -05:00
|
|
|
if let Some(i) = c.to_digit(10) {
|
|
|
|
cur = cur * 10 + i as usize;
|
|
|
|
found = true;
|
|
|
|
self.cur.next();
|
|
|
|
} else {
|
2015-11-23 17:11:20 -06:00
|
|
|
break;
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
}
|
2015-10-13 17:21:05 -05:00
|
|
|
if found {
|
|
|
|
Some(cur)
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
|
2014-04-08 20:46:49 -05:00
|
|
|
fn same(fmt: &'static str, p: &[Piece<'static>]) {
|
2015-01-26 21:56:50 -06:00
|
|
|
let parser = Parser::new(fmt);
|
2015-03-10 19:59:23 -05:00
|
|
|
assert!(parser.collect::<Vec<Piece<'static>>>() == p);
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
fn fmtdflt() -> FormatSpec<'static> {
|
|
|
|
return FormatSpec {
|
|
|
|
fill: None,
|
2013-08-10 18:50:42 -05:00
|
|
|
align: AlignUnknown,
|
2013-07-29 03:12:41 -05:00
|
|
|
flags: 0,
|
|
|
|
precision: CountImplied,
|
|
|
|
width: CountImplied,
|
|
|
|
ty: "",
|
2015-11-23 17:11:20 -06:00
|
|
|
};
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
fn musterr(s: &str) {
|
Remove std::condition
This has been a long time coming. Conditions in rust were initially envisioned
as being a good alternative to error code return pattern. The idea is that all
errors are fatal-by-default, and you can opt-in to handling the error by
registering an error handler.
While sounding nice, conditions ended up having some unforseen shortcomings:
* Actually handling an error has some very awkward syntax:
let mut result = None;
let mut answer = None;
io::io_error::cond.trap(|e| { result = Some(e) }).inside(|| {
answer = Some(some_io_operation());
});
match result {
Some(err) => { /* hit an I/O error */ }
None => {
let answer = answer.unwrap();
/* deal with the result of I/O */
}
}
This pattern can certainly use functions like io::result, but at its core
actually handling conditions is fairly difficult
* The "zero value" of a function is often confusing. One of the main ideas
behind using conditions was to change the signature of I/O functions. Instead
of read_be_u32() returning a result, it returned a u32. Errors were notified
via a condition, and if you caught the condition you understood that the "zero
value" returned is actually a garbage value. These zero values are often
difficult to understand, however.
One case of this is the read_bytes() function. The function takes an integer
length of the amount of bytes to read, and returns an array of that size. The
array may actually be shorter, however, if an error occurred.
Another case is fs::stat(). The theoretical "zero value" is a blank stat
struct, but it's a little awkward to create and return a zero'd out stat
struct on a call to stat().
In general, the return value of functions that can raise error are much more
natural when using a Result as opposed to an always-usable zero-value.
* Conditions impose a necessary runtime requirement on *all* I/O. In theory I/O
is as simple as calling read() and write(), but using conditions imposed the
restriction that a rust local task was required if you wanted to catch errors
with I/O. While certainly an surmountable difficulty, this was always a bit of
a thorn in the side of conditions.
* Functions raising conditions are not always clear that they are raising
conditions. This suffers a similar problem to exceptions where you don't
actually know whether a function raises a condition or not. The documentation
likely explains, but if someone retroactively adds a condition to a function
there's nothing forcing upstream users to acknowledge a new point of task
failure.
* Libaries using I/O are not guaranteed to correctly raise on conditions when an
error occurs. In developing various I/O libraries, it's much easier to just
return `None` from a read rather than raising an error. The silent contract of
"don't raise on EOF" was a little difficult to understand and threw a wrench
into the answer of the question "when do I raise a condition?"
Many of these difficulties can be overcome through documentation, examples, and
general practice. In the end, all of these difficulties added together ended up
being too overwhelming and improving various aspects didn't end up helping that
much.
A result-based I/O error handling strategy also has shortcomings, but the
cognitive burden is much smaller. The tooling necessary to make this strategy as
usable as conditions were is much smaller than the tooling necessary for
conditions.
Perhaps conditions may manifest themselves as a future entity, but for now
we're going to remove them from the standard library.
Closes #9795
Closes #8968
2014-02-04 21:02:10 -06:00
|
|
|
let mut p = Parser::new(s);
|
|
|
|
p.next();
|
2015-03-24 18:54:09 -05:00
|
|
|
assert!(!p.errors.is_empty());
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn simple() {
|
2014-11-17 02:39:01 -06:00
|
|
|
same("asdf", &[String("asdf")]);
|
|
|
|
same("a{{b", &[String("a"), String("{b")]);
|
|
|
|
same("a}}b", &[String("a"), String("}b")]);
|
|
|
|
same("a}}", &[String("a"), String("}")]);
|
|
|
|
same("}}", &[String("}")]);
|
|
|
|
same("\\}}", &[String("\\"), String("}")]);
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
|
2015-10-13 09:10:51 -05:00
|
|
|
#[test]
|
|
|
|
fn invalid01() {
|
|
|
|
musterr("{")
|
|
|
|
}
|
|
|
|
#[test]
|
|
|
|
fn invalid02() {
|
|
|
|
musterr("}")
|
|
|
|
}
|
|
|
|
#[test]
|
|
|
|
fn invalid04() {
|
|
|
|
musterr("{3a}")
|
|
|
|
}
|
|
|
|
#[test]
|
|
|
|
fn invalid05() {
|
|
|
|
musterr("{:|}")
|
|
|
|
}
|
|
|
|
#[test]
|
|
|
|
fn invalid06() {
|
|
|
|
musterr("{:>>>}")
|
|
|
|
}
|
2013-07-29 03:12:41 -05:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn format_nothing() {
|
2015-10-13 09:10:51 -05:00
|
|
|
same("{}",
|
|
|
|
&[NextArgument(Argument {
|
|
|
|
position: ArgumentNext,
|
|
|
|
format: fmtdflt(),
|
|
|
|
})]);
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
#[test]
|
|
|
|
fn format_position() {
|
2015-10-13 09:10:51 -05:00
|
|
|
same("{3}",
|
|
|
|
&[NextArgument(Argument {
|
|
|
|
position: ArgumentIs(3),
|
|
|
|
format: fmtdflt(),
|
|
|
|
})]);
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
#[test]
|
|
|
|
fn format_position_nothing_else() {
|
2015-10-13 09:10:51 -05:00
|
|
|
same("{3:}",
|
|
|
|
&[NextArgument(Argument {
|
|
|
|
position: ArgumentIs(3),
|
|
|
|
format: fmtdflt(),
|
|
|
|
})]);
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
#[test]
|
|
|
|
fn format_type() {
|
2015-10-13 09:10:51 -05:00
|
|
|
same("{3:a}",
|
|
|
|
&[NextArgument(Argument {
|
|
|
|
position: ArgumentIs(3),
|
|
|
|
format: FormatSpec {
|
|
|
|
fill: None,
|
|
|
|
align: AlignUnknown,
|
|
|
|
flags: 0,
|
|
|
|
precision: CountImplied,
|
|
|
|
width: CountImplied,
|
|
|
|
ty: "a",
|
|
|
|
},
|
|
|
|
})]);
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
#[test]
|
|
|
|
fn format_align_fill() {
|
2015-10-13 09:10:51 -05:00
|
|
|
same("{3:>}",
|
|
|
|
&[NextArgument(Argument {
|
|
|
|
position: ArgumentIs(3),
|
|
|
|
format: FormatSpec {
|
|
|
|
fill: None,
|
|
|
|
align: AlignRight,
|
|
|
|
flags: 0,
|
|
|
|
precision: CountImplied,
|
|
|
|
width: CountImplied,
|
|
|
|
ty: "",
|
|
|
|
},
|
|
|
|
})]);
|
|
|
|
same("{3:0<}",
|
|
|
|
&[NextArgument(Argument {
|
|
|
|
position: ArgumentIs(3),
|
|
|
|
format: FormatSpec {
|
|
|
|
fill: Some('0'),
|
|
|
|
align: AlignLeft,
|
|
|
|
flags: 0,
|
|
|
|
precision: CountImplied,
|
|
|
|
width: CountImplied,
|
|
|
|
ty: "",
|
|
|
|
},
|
|
|
|
})]);
|
|
|
|
same("{3:*<abcd}",
|
|
|
|
&[NextArgument(Argument {
|
|
|
|
position: ArgumentIs(3),
|
|
|
|
format: FormatSpec {
|
|
|
|
fill: Some('*'),
|
|
|
|
align: AlignLeft,
|
|
|
|
flags: 0,
|
|
|
|
precision: CountImplied,
|
|
|
|
width: CountImplied,
|
|
|
|
ty: "abcd",
|
|
|
|
},
|
|
|
|
})]);
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
#[test]
|
|
|
|
fn format_counts() {
|
2015-10-13 09:10:51 -05:00
|
|
|
same("{:10s}",
|
|
|
|
&[NextArgument(Argument {
|
|
|
|
position: ArgumentNext,
|
|
|
|
format: FormatSpec {
|
|
|
|
fill: None,
|
|
|
|
align: AlignUnknown,
|
|
|
|
flags: 0,
|
|
|
|
precision: CountImplied,
|
|
|
|
width: CountIs(10),
|
|
|
|
ty: "s",
|
|
|
|
},
|
|
|
|
})]);
|
|
|
|
same("{:10$.10s}",
|
|
|
|
&[NextArgument(Argument {
|
|
|
|
position: ArgumentNext,
|
|
|
|
format: FormatSpec {
|
|
|
|
fill: None,
|
|
|
|
align: AlignUnknown,
|
|
|
|
flags: 0,
|
|
|
|
precision: CountIs(10),
|
|
|
|
width: CountIsParam(10),
|
|
|
|
ty: "s",
|
|
|
|
},
|
|
|
|
})]);
|
|
|
|
same("{:.*s}",
|
|
|
|
&[NextArgument(Argument {
|
|
|
|
position: ArgumentNext,
|
|
|
|
format: FormatSpec {
|
|
|
|
fill: None,
|
|
|
|
align: AlignUnknown,
|
|
|
|
flags: 0,
|
|
|
|
precision: CountIsNextParam,
|
|
|
|
width: CountImplied,
|
|
|
|
ty: "s",
|
|
|
|
},
|
|
|
|
})]);
|
|
|
|
same("{:.10$s}",
|
|
|
|
&[NextArgument(Argument {
|
|
|
|
position: ArgumentNext,
|
|
|
|
format: FormatSpec {
|
|
|
|
fill: None,
|
|
|
|
align: AlignUnknown,
|
|
|
|
flags: 0,
|
|
|
|
precision: CountIsParam(10),
|
|
|
|
width: CountImplied,
|
|
|
|
ty: "s",
|
|
|
|
},
|
|
|
|
})]);
|
|
|
|
same("{:a$.b$s}",
|
|
|
|
&[NextArgument(Argument {
|
|
|
|
position: ArgumentNext,
|
|
|
|
format: FormatSpec {
|
|
|
|
fill: None,
|
|
|
|
align: AlignUnknown,
|
|
|
|
flags: 0,
|
|
|
|
precision: CountIsName("b"),
|
|
|
|
width: CountIsName("a"),
|
|
|
|
ty: "s",
|
|
|
|
},
|
|
|
|
})]);
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
#[test]
|
|
|
|
fn format_flags() {
|
2015-10-13 09:10:51 -05:00
|
|
|
same("{:-}",
|
|
|
|
&[NextArgument(Argument {
|
|
|
|
position: ArgumentNext,
|
|
|
|
format: FormatSpec {
|
|
|
|
fill: None,
|
|
|
|
align: AlignUnknown,
|
|
|
|
flags: (1 << FlagSignMinus as u32),
|
|
|
|
precision: CountImplied,
|
|
|
|
width: CountImplied,
|
|
|
|
ty: "",
|
|
|
|
},
|
|
|
|
})]);
|
|
|
|
same("{:+#}",
|
|
|
|
&[NextArgument(Argument {
|
|
|
|
position: ArgumentNext,
|
|
|
|
format: FormatSpec {
|
|
|
|
fill: None,
|
|
|
|
align: AlignUnknown,
|
|
|
|
flags: (1 << FlagSignPlus as u32) | (1 << FlagAlternate as u32),
|
|
|
|
precision: CountImplied,
|
|
|
|
width: CountImplied,
|
|
|
|
ty: "",
|
|
|
|
},
|
|
|
|
})]);
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
#[test]
|
|
|
|
fn format_mixture() {
|
2015-10-13 09:10:51 -05:00
|
|
|
same("abcd {3:a} efg",
|
|
|
|
&[String("abcd "),
|
|
|
|
NextArgument(Argument {
|
|
|
|
position: ArgumentIs(3),
|
|
|
|
format: FormatSpec {
|
|
|
|
fill: None,
|
|
|
|
align: AlignUnknown,
|
|
|
|
flags: 0,
|
|
|
|
precision: CountImplied,
|
|
|
|
width: CountImplied,
|
|
|
|
ty: "a",
|
|
|
|
},
|
|
|
|
}),
|
|
|
|
String(" efg")]);
|
2013-07-29 03:12:41 -05:00
|
|
|
}
|
|
|
|
}
|