Skip to content

Commit

Permalink
Byte ahd char literals
Browse files Browse the repository at this point in the history
  • Loading branch information
dtolnay committed Oct 9, 2016
1 parent 1a8b352 commit 615cf6a
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 4 deletions.
25 changes: 25 additions & 0 deletions src/escape.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,31 @@ pub fn cooked_string(input: &str) -> IResult<&str, String> {
IResult::Error
}

pub fn cooked_char(input: &str) -> IResult<&str, char> {
let mut chars = input.char_indices();
let ch = match chars.next().map(|(_, ch)| ch) {
Some('\\') => {
match chars.next().map(|(_, ch)| ch) {
Some('x') => backslash_x(&mut chars),
Some('n') => Some('\n'),
Some('r') => Some('\r'),
Some('t') => Some('\t'),
Some('\\') => Some('\\'),
Some('0') => Some('\0'),
Some('u') => backslash_u(&mut chars),
Some('\'') => Some('\''),
Some('"') => Some('"'),
_ => None,
}
}
ch => ch,
};
match ch {
Some(ch) => IResult::Done(chars.as_str(), ch),
None => IResult::Error,
}
}

pub fn raw_string(input: &str) -> IResult<&str, (String, usize)> {
let mut chars = input.char_indices();
let mut n = 0;
Expand Down
25 changes: 21 additions & 4 deletions src/lit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,16 +54,18 @@ pub enum FloatTy {
#[cfg(feature = "parsing")]
pub mod parsing {
use super::*;
use escape::{cooked_string, raw_string};
use escape::{cooked_char, cooked_string, raw_string};
use space::whitespace;
use nom::IResult;

named!(pub lit -> Lit, alt!(
string
|
byte_string
// TODO: Byte
// TODO: Char
|
byte
|
character
|
int => { |(value, ty)| Lit::Int(value, ty) }
// TODO: Float
Expand Down Expand Up @@ -101,6 +103,21 @@ pub mod parsing {
) => { |(s, _): (String, _)| Lit::ByteStr(s.into_bytes()) }
));

named!(byte -> Lit, do_parse!(
punct!("b") >>
tag!("'") >>
ch: cooked_char >>
tag!("'") >>
(Lit::Byte(ch as u8))
));

named!(character -> Lit, do_parse!(
punct!("'") >>
ch: cooked_char >>
tag!("'") >>
(Lit::Char(ch))
));

named!(pub int -> (u64, IntTy), tuple!(
preceded!(
option!(whitespace),
Expand Down Expand Up @@ -184,7 +201,7 @@ mod printing {
escaped.push('"');
tokens.append(&escaped);
}
Lit::Byte(b) => tokens.append(&format!("b{:?}", b)),
Lit::Byte(b) => tokens.append(&format!("b{:?}", b as char)),
Lit::Char(ch) => ch.to_tokens(tokens),
Lit::Int(value, ty) => tokens.append(&format!("{}{}", value, ty)),
Lit::Float(ref value, ty) => tokens.append(&format!("{}{}", value, ty)),
Expand Down

0 comments on commit 615cf6a

Please sign in to comment.