#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/",
html_playground_url = "http://play.rust-lang.org/")]
extern crate unicode_xid;
pub use self::Piece::*;
pub use self::Position::*;
pub use self::Alignment::*;
pub use self::Flag::*;
pub use self::Count::*;
use std::str;
use std::string;
use unicode_xid::UnicodeXID;
#[derive(Copy, Clone, PartialEq)]
pub enum Piece<'a> {
String(&'a str),
NextArgument(Argument<'a>),
}
#[derive(Copy, Clone, PartialEq)]
pub struct Argument<'a> {
pub position: Position<'a>,
pub format: FormatSpec<'a>,
}
#[derive(Copy, Clone, PartialEq)]
pub struct FormatSpec<'a> {
pub fill: Option<char>,
pub align: Alignment,
pub flags: u32,
pub precision: Count<'a>,
pub width: Count<'a>,
pub ty: &'a str
}
#[derive(Copy, Clone, PartialEq)]
pub enum Position<'a> {
ArgumentNext,
ArgumentIs(usize),
ArgumentNamed(&'a str),
}
#[derive(Copy, Clone, PartialEq)]
pub enum Alignment {
AlignLeft,
AlignRight,
AlignCenter,
AlignUnknown,
}
#[derive(Copy, Clone, PartialEq)]
pub enum Flag {
FlagSignPlus,
FlagSignMinus,
FlagAlternate,
FlagSignAwareZeroPad,
}
#[derive(Copy, Clone, PartialEq)]
pub enum Count<'a> {
CountIs(usize),
CountIsName(&'a str),
CountIsParam(usize),
CountIsNextParam,
CountImplied,
}
pub struct Parser<'a> {
input: &'a str,
cur: str::CharIndices<'a>,
pub errors: Vec<string::String>,
}
impl<'a> Iterator for Parser<'a> {
type Item = Piece<'a>;
fn next(&mut self) -> Option<Piece<'a>> {
match self.cur.clone().next() {
Some((pos, '{')) => {
self.cur.next();
if self.consume('{') {
Some(String(self.string(pos + 1)))
} else {
let ret = Some(NextArgument(self.argument()));
self.must_consume('}');
ret
}
}
Some((pos, '}')) => {
self.cur.next();
if self.consume('}') {
Some(String(self.string(pos + 1)))
} else {
self.err("unmatched `}` found");
None
}
}
Some((pos, _)) => { Some(String(self.string(pos))) }
None => None
}
}
}
impl<'a> Parser<'a> {
pub fn new(s: &'a str) -> Parser<'a> {
Parser {
input: s,
cur: s.char_indices(),
errors: vec!(),
}
}
fn err(&mut self, msg: &str) {
self.errors.push(msg.to_string());
}
fn consume(&mut self, c: char) -> bool {
match self.cur.clone().next() {
Some((_, maybe)) if c == maybe => {
self.cur.next();
true
}
Some(..) | None => false,
}
}
fn must_consume(&mut self, c: char) {
self.ws();
match self.cur.clone().next() {
Some((_, maybe)) if c == maybe => {
self.cur.next();
}
Some((_, other)) => {
self.err(&format!("expected `{:?}`, found `{:?}`", c,
other));
}
None => {
self.err(&format!("expected `{:?}` but string was terminated",
c));
}
}
}
fn ws(&mut self) {
loop {
match self.cur.clone().next() {
Some((_, c)) if c.is_whitespace() => { self.cur.next(); }
Some(..) | None => { return }
}
}
}
fn string(&mut self, start: usize) -> &'a str {
loop {
match self.cur.clone().next() {
Some((pos, '}')) | Some((pos, '{')) => {
return &self.input[start..pos];
}
Some(..) => { self.cur.next(); }
None => {
self.cur.next();
return &self.input[start..self.input.len()];
}
}
}
}
fn argument(&mut self) -> Argument<'a> {
Argument {
position: self.position(),
format: self.format(),
}
}
fn position(&mut self) -> Position<'a> {
match self.integer() {
Some(i) => { ArgumentIs(i) }
None => {
match self.cur.clone().next() {
Some((_, c)) if c.is_alphabetic() => {
ArgumentNamed(self.word())
}
_ => ArgumentNext
}
}
}
}
fn format(&mut self) -> FormatSpec<'a> {
let mut spec = FormatSpec {
fill: None,
align: AlignUnknown,
flags: 0,
precision: CountImplied,
width: CountImplied,
ty: &self.input[..0],
};
if !self.consume(':') { return spec }
match self.cur.clone().next() {
Some((_, c)) => {
match self.cur.clone().skip(1).next() {
Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => {
spec.fill = Some(c);
self.cur.next();
}
Some(..) | None => {}
}
}
None => {}
}
if self.consume('<') {
spec.align = AlignLeft;
} else if self.consume('>') {
spec.align = AlignRight;
} else if self.consume('^') {
spec.align = AlignCenter;
}
if self.consume('+') {
spec.flags |= 1 << (FlagSignPlus as u32);
} else if self.consume('-') {
spec.flags |= 1 << (FlagSignMinus as u32);
}
if self.consume('#') {
spec.flags |= 1 << (FlagAlternate as u32);
}
let mut havewidth = false;
if self.consume('0') {
if self.consume('$') {
spec.width = CountIsParam(0);
havewidth = true;
} else {
spec.flags |= 1 << (FlagSignAwareZeroPad as u32);
}
}
if !havewidth {
spec.width = self.count();
}
if self.consume('.') {
if self.consume('*') {
spec.precision = CountIsNextParam;
} else {
spec.precision = self.count();
}
}
if self.consume('?') {
spec.ty = "?";
} else {
spec.ty = self.word();
}
return spec;
}
fn count(&mut self) -> Count<'a> {
match self.integer() {
Some(i) => {
if self.consume('$') {
CountIsParam(i)
} else {
CountIs(i)
}
}
None => {
let tmp = self.cur.clone();
match self.word() {
word if !word.is_empty() => {
if self.consume('$') {
CountIsName(word)
} else {
self.cur = tmp;
CountImplied
}
}
_ => {
self.cur = tmp;
CountImplied
}
}
}
}
}
fn word(&mut self) -> &'a str {
let start = match self.cur.clone().next() {
Some((pos, c)) if UnicodeXID::is_xid_start(c) => {
self.cur.next();
pos
}
Some(..) | None => { return &self.input[..0]; }
};
let mut end;
loop {
match self.cur.clone().next() {
Some((_, c)) if UnicodeXID::is_xid_continue(c) => {
self.cur.next();
}
Some((pos, _)) => { end = pos; break }
None => { end = self.input.len(); break }
}
}
&self.input[start..end]
}
fn integer(&mut self) -> Option<usize> {
let mut cur = 0;
let mut found = false;
loop {
match self.cur.clone().next() {
Some((_, c)) => {
match c.to_digit(10) {
Some(i) => {
cur = cur * 10 + i as usize;
found = true;
self.cur.next();
}
None => { break }
}
}
None => { break }
}
}
if found {
return Some(cur);
} else {
return None;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn same(fmt: &'static str, p: &[Piece<'static>]) {
let parser = Parser::new(fmt);
assert!(parser.collect::<Vec<Piece<'static>>>() == p);
}
fn fmtdflt() -> FormatSpec<'static> {
return FormatSpec {
fill: None,
align: AlignUnknown,
flags: 0,
precision: CountImplied,
width: CountImplied,
ty: "",
}
}
fn musterr(s: &str) {
let mut p = Parser::new(s);
p.next();
assert!(!p.errors.is_empty());
}
#[test]
fn simple() {
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("}")]);
}
#[test] fn invalid01() { musterr("{") }
#[test] fn invalid02() { musterr("}") }
#[test] fn invalid04() { musterr("{3a}") }
#[test] fn invalid05() { musterr("{:|}") }
#[test] fn invalid06() { musterr("{:>>>}") }
#[test]
fn format_nothing() {
same("{}", &[NextArgument(Argument {
position: ArgumentNext,
format: fmtdflt(),
})]);
}
#[test]
fn format_position() {
same("{3}", &[NextArgument(Argument {
position: ArgumentIs(3),
format: fmtdflt(),
})]);
}
#[test]
fn format_position_nothing_else() {
same("{3:}", &[NextArgument(Argument {
position: ArgumentIs(3),
format: fmtdflt(),
})]);
}
#[test]
fn format_type() {
same("{3:a}", &[NextArgument(Argument {
position: ArgumentIs(3),
format: FormatSpec {
fill: None,
align: AlignUnknown,
flags: 0,
precision: CountImplied,
width: CountImplied,
ty: "a",
},
})]);
}
#[test]
fn format_align_fill() {
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",
},
})]);
}
#[test]
fn format_counts() {
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",
},
})]);
}
#[test]
fn format_flags() {
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: "",
},
})]);
}
#[test]
fn format_mixture() {
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")]);
}
}