blob: b3d29540c17f3cb6a6a260c84d72ad4a44783107 [file] [log] [blame]
David Tolnayf4bbbd92016-09-23 14:41:55 -07001/// Literal kind.
2///
3/// E.g. `"foo"`, `42`, `12.34` or `bool`
4#[derive(Debug, Clone, Eq, PartialEq)]
5pub enum Lit {
6 /// A string literal (`"foo"`)
7 Str(String, StrStyle),
8 /// A byte string (`b"foo"`)
9 ByteStr(Vec<u8>),
10 /// A byte char (`b'f'`)
11 Byte(u8),
12 /// A character literal (`'a'`)
13 Char(char),
14 /// An integer literal (`1`)
15 Int(u64, IntTy),
16 /// A float literal (`1f64` or `1E10f64` or `1.0E10`)
17 Float(String, FloatTy),
18 /// A boolean literal
19 Bool(bool),
20}
21
22#[derive(Debug, Copy, Clone, Eq, PartialEq)]
23pub enum StrStyle {
24 /// A regular string, like `"foo"`
25 Cooked,
26 /// A raw string, like `r##"foo"##`
27 ///
28 /// The uint is the number of `#` symbols used
29 Raw(usize)
30}
31
32#[derive(Debug, Copy, Clone, Eq, PartialEq)]
33pub enum IntTy {
34 Isize,
35 I8,
36 I16,
37 I32,
38 I64,
39 Usize,
40 U8,
41 U16,
42 U32,
43 U64,
44 Unsuffixed
45}
46
47#[derive(Debug, Copy, Clone, Eq, PartialEq)]
48pub enum FloatTy {
49 F32,
50 F64,
51 Unsuffixed,
52}
53
54#[cfg(feature = "parsing")]
55pub mod parsing {
56 use super::*;
David Tolnay210884d2016-10-01 08:18:42 -070057 use escape::{cooked_string, raw_string};
David Tolnay14cbdeb2016-10-01 12:13:59 -070058 use space::whitespace;
David Tolnayde206222016-09-30 11:47:01 -070059 use nom::IResult;
David Tolnayf4bbbd92016-09-23 14:41:55 -070060
61 named!(pub lit -> Lit, alt!(
David Tolnay210884d2016-10-01 08:18:42 -070062 string
David Tolnay56d62132016-10-01 16:14:54 -070063 |
64 byte_string
David Tolnay7de67d22016-09-24 07:23:32 -070065 // TODO: Byte
66 // TODO: Char
David Tolnayf4bbbd92016-09-23 14:41:55 -070067 |
68 int => { |(value, ty)| Lit::Int(value, ty) }
David Tolnay7de67d22016-09-24 07:23:32 -070069 // TODO: Float
David Tolnay759d2ff2016-10-01 16:18:15 -070070 |
71 keyword!("true") => { |_| Lit::Bool(true) }
72 |
73 keyword!("false") => { |_| Lit::Bool(false) }
David Tolnayf4bbbd92016-09-23 14:41:55 -070074 ));
75
David Tolnay210884d2016-10-01 08:18:42 -070076 named!(string -> Lit, alt!(
77 delimited!(
78 punct!("\""),
79 cooked_string,
80 tag!("\"")
81 ) => { |s| Lit::Str(s, StrStyle::Cooked) }
82 |
83 preceded!(
84 punct!("r"),
85 raw_string
86 ) => { |(s, n)| Lit::Str(s, StrStyle::Raw(n)) }
David Tolnayf4bbbd92016-09-23 14:41:55 -070087 ));
88
David Tolnay56d62132016-10-01 16:14:54 -070089 named!(byte_string -> Lit, alt!(
90 delimited!(
91 punct!("b\""),
92 cooked_string,
93 tag!("\"")
94 ) => { |s: String| Lit::ByteStr(s.into_bytes()) }
95 |
96 preceded!(
97 punct!("br"),
98 raw_string
99 ) => { |(s, _): (String, _)| Lit::ByteStr(s.into_bytes()) }
100 ));
101
David Tolnayde206222016-09-30 11:47:01 -0700102 named!(pub int -> (u64, IntTy), tuple!(
David Tolnay14cbdeb2016-10-01 12:13:59 -0700103 preceded!(
104 option!(whitespace),
105 digits
106 ),
David Tolnayde206222016-09-30 11:47:01 -0700107 alt!(
108 tag!("isize") => { |_| IntTy::Isize }
109 |
110 tag!("i8") => { |_| IntTy::I8 }
111 |
112 tag!("i16") => { |_| IntTy::I16 }
113 |
114 tag!("i32") => { |_| IntTy::I32 }
115 |
116 tag!("i64") => { |_| IntTy::I64 }
117 |
118 tag!("usize") => { |_| IntTy::Usize }
119 |
120 tag!("u8") => { |_| IntTy::U8 }
121 |
122 tag!("u16") => { |_| IntTy::U16 }
123 |
124 tag!("u32") => { |_| IntTy::U32 }
125 |
126 tag!("u64") => { |_| IntTy::U64 }
127 |
128 epsilon!() => { |_| IntTy::Unsuffixed }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700129 )
130 ));
131
David Tolnayde206222016-09-30 11:47:01 -0700132 pub fn digits(input: &str) -> IResult<&str, u64> {
David Tolnayf4bbbd92016-09-23 14:41:55 -0700133 let mut value = 0u64;
134 let mut len = 0;
135 let mut bytes = input.bytes().peekable();
136 while let Some(&b) = bytes.peek() {
137 match b {
138 b'0' ... b'9' => {
139 value = match value.checked_mul(10) {
140 Some(value) => value,
141 None => return IResult::Error,
142 };
143 value = match value.checked_add((b - b'0') as u64) {
144 Some(value) => value,
145 None => return IResult::Error,
146 };
147 bytes.next();
148 len += 1;
149 }
David Tolnayfa0edf22016-09-23 22:58:24 -0700150 _ => break,
David Tolnayf4bbbd92016-09-23 14:41:55 -0700151 }
152 }
David Tolnayfa0edf22016-09-23 22:58:24 -0700153 if len > 0 {
154 IResult::Done(&input[len..], value)
155 } else {
156 IResult::Error
157 }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700158 }
159}
160
161#[cfg(feature = "printing")]
162mod printing {
163 use super::*;
164 use quote::{Tokens, ToTokens};
David Tolnay56d62132016-10-01 16:14:54 -0700165 use std::{ascii, iter};
David Tolnayf4bbbd92016-09-23 14:41:55 -0700166 use std::fmt::{self, Display};
167
168 impl ToTokens for Lit {
169 fn to_tokens(&self, tokens: &mut Tokens) {
170 match *self {
171 Lit::Str(ref s, StrStyle::Cooked) => s.to_tokens(tokens),
David Tolnay627e3d52016-10-01 08:27:31 -0700172 Lit::Str(ref s, StrStyle::Raw(n)) => {
David Tolnay56d62132016-10-01 16:14:54 -0700173 tokens.append(&format!("r{delim}\"{string}\"{delim}",
174 delim = iter::repeat("#").take(n).collect::<String>(),
175 string = s));
176 }
177 Lit::ByteStr(ref v) => {
178 let mut escaped = "b\"".to_string();
179 for &ch in v.iter() {
180 escaped.extend(ascii::escape_default(ch).map(|c| c as char));
David Tolnay627e3d52016-10-01 08:27:31 -0700181 }
David Tolnay56d62132016-10-01 16:14:54 -0700182 escaped.push('"');
183 tokens.append(&escaped);
David Tolnay627e3d52016-10-01 08:27:31 -0700184 }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700185 Lit::Int(value, ty) => tokens.append(&format!("{}{}", value, ty)),
David Tolnay759d2ff2016-10-01 16:18:15 -0700186 Lit::Bool(true) => tokens.append("true"),
187 Lit::Bool(false) => tokens.append("false"),
David Tolnayf4bbbd92016-09-23 14:41:55 -0700188 _ => unimplemented!(),
189 }
190 }
191 }
192
193 impl Display for IntTy {
194 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
195 match *self {
196 IntTy::Isize => formatter.write_str("isize"),
197 IntTy::I8 => formatter.write_str("i8"),
198 IntTy::I16 => formatter.write_str("i16"),
199 IntTy::I32 => formatter.write_str("i32"),
200 IntTy::I64 => formatter.write_str("i64"),
201 IntTy::Usize => formatter.write_str("usize"),
202 IntTy::U8 => formatter.write_str("u8"),
203 IntTy::U16 => formatter.write_str("u16"),
204 IntTy::U32 => formatter.write_str("u32"),
205 IntTy::U64 => formatter.write_str("u64"),
206 IntTy::Unsuffixed => Ok(()),
207 }
208 }
209 }
210}