blob: 6b36315698b9be1067a536f056d36d3b133021c5 [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"`)
David Tolnay4a658402016-10-24 00:21:41 -07009 ByteStr(Vec<u8>, StrStyle),
David Tolnayf4bbbd92016-09-23 14:41:55 -070010 /// 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
David Tolnaydaaf7742016-10-03 11:11:43 -070029 Raw(usize),
David Tolnayf4bbbd92016-09-23 14:41:55 -070030}
31
Pascal Hertleif36342c52016-10-19 10:31:42 +020032impl From<String> for Lit {
33 fn from(input: String) -> Lit {
34 Lit::Str(input, StrStyle::Cooked)
35 }
36}
37
38impl<'a> From<&'a str> for Lit {
39 fn from(input: &str) -> Lit {
40 Lit::Str(input.into(), StrStyle::Cooked)
41 }
42}
43
44impl From<Vec<u8>> for Lit {
45 fn from(input: Vec<u8>) -> Lit {
David Tolnay4a658402016-10-24 00:21:41 -070046 Lit::ByteStr(input, StrStyle::Cooked)
Pascal Hertleif36342c52016-10-19 10:31:42 +020047 }
48}
49
50impl<'a> From<&'a [u8]> for Lit {
51 fn from(input: &[u8]) -> Lit {
David Tolnay4a658402016-10-24 00:21:41 -070052 Lit::ByteStr(input.into(), StrStyle::Cooked)
Pascal Hertleif36342c52016-10-19 10:31:42 +020053 }
54}
55
56impl From<char> for Lit {
57 fn from(input: char) -> Lit {
58 Lit::Char(input)
59 }
60}
61
62impl From<bool> for Lit {
63 fn from(input: bool) -> Lit {
64 Lit::Bool(input)
65 }
66}
67
David Tolnayf4bbbd92016-09-23 14:41:55 -070068#[derive(Debug, Copy, Clone, Eq, PartialEq)]
69pub enum IntTy {
70 Isize,
71 I8,
72 I16,
73 I32,
74 I64,
75 Usize,
76 U8,
77 U16,
78 U32,
79 U64,
David Tolnaydaaf7742016-10-03 11:11:43 -070080 Unsuffixed,
David Tolnayf4bbbd92016-09-23 14:41:55 -070081}
82
83#[derive(Debug, Copy, Clone, Eq, PartialEq)]
84pub enum FloatTy {
85 F32,
86 F64,
87 Unsuffixed,
88}
89
Pascal Hertleif36342c52016-10-19 10:31:42 +020090macro_rules! impl_from_for_lit {
91 (Int, [$($rust_type:ty => $syn_type:expr),+]) => {
92 $(
93 impl From<$rust_type> for Lit {
94 fn from(input: $rust_type) -> Lit {
95 Lit::Int(input as u64, $syn_type)
96 }
97 }
98 )+
99 };
100 (Float, [$($rust_type:ty => $syn_type:expr),+]) => {
101 $(
102 impl From<$rust_type> for Lit {
103 fn from(input: $rust_type) -> Lit {
104 Lit::Float(format!("{}", input), $syn_type)
105 }
106 }
107 )+
108 };
109}
110
111impl_from_for_lit! {Int, [
112 isize => IntTy::Isize,
113 i8 => IntTy::I8,
114 i16 => IntTy::I16,
115 i32 => IntTy::I32,
116 i64 => IntTy::I64,
117 usize => IntTy::Usize,
118 u8 => IntTy::U8,
119 u16 => IntTy::U16,
120 u32 => IntTy::U32,
121 u64 => IntTy::U64
122]}
123
124impl_from_for_lit! {Float, [
125 f32 => FloatTy::F32,
126 f64 => FloatTy::F64
127]}
128
David Tolnayf4bbbd92016-09-23 14:41:55 -0700129#[cfg(feature = "parsing")]
130pub mod parsing {
131 use super::*;
David Tolnay615cf6a2016-10-08 23:07:02 -0700132 use escape::{cooked_char, cooked_string, raw_string};
David Tolnay14cbdeb2016-10-01 12:13:59 -0700133 use space::whitespace;
David Tolnayde206222016-09-30 11:47:01 -0700134 use nom::IResult;
David Tolnayf4bbbd92016-09-23 14:41:55 -0700135
136 named!(pub lit -> Lit, alt!(
David Tolnay210884d2016-10-01 08:18:42 -0700137 string
David Tolnay56d62132016-10-01 16:14:54 -0700138 |
139 byte_string
David Tolnay615cf6a2016-10-08 23:07:02 -0700140 |
141 byte
142 |
143 character
David Tolnayf4bbbd92016-09-23 14:41:55 -0700144 |
145 int => { |(value, ty)| Lit::Int(value, ty) }
David Tolnaydaaf7742016-10-03 11:11:43 -0700146 // TODO: Float
David Tolnay759d2ff2016-10-01 16:18:15 -0700147 |
David Tolnay3ce49d02016-10-23 22:29:19 -0700148 boolean
David Tolnayf4bbbd92016-09-23 14:41:55 -0700149 ));
150
David Tolnay210884d2016-10-01 08:18:42 -0700151 named!(string -> Lit, alt!(
David Tolnay42602292016-10-01 22:25:45 -0700152 quoted_string => { |s| Lit::Str(s, StrStyle::Cooked) }
David Tolnay210884d2016-10-01 08:18:42 -0700153 |
154 preceded!(
155 punct!("r"),
156 raw_string
157 ) => { |(s, n)| Lit::Str(s, StrStyle::Raw(n)) }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700158 ));
159
David Tolnay42602292016-10-01 22:25:45 -0700160 named!(pub quoted_string -> String, delimited!(
161 punct!("\""),
162 cooked_string,
163 tag!("\"")
164 ));
165
David Tolnay56d62132016-10-01 16:14:54 -0700166 named!(byte_string -> Lit, alt!(
167 delimited!(
168 punct!("b\""),
169 cooked_string,
170 tag!("\"")
David Tolnay4a658402016-10-24 00:21:41 -0700171 ) => { |s: String| Lit::ByteStr(s.into_bytes(), StrStyle::Cooked) }
David Tolnay56d62132016-10-01 16:14:54 -0700172 |
173 preceded!(
174 punct!("br"),
175 raw_string
David Tolnay4a658402016-10-24 00:21:41 -0700176 ) => { |(s, n): (String, _)| Lit::ByteStr(s.into_bytes(), StrStyle::Raw(n)) }
David Tolnay56d62132016-10-01 16:14:54 -0700177 ));
178
David Tolnay615cf6a2016-10-08 23:07:02 -0700179 named!(byte -> Lit, do_parse!(
180 punct!("b") >>
181 tag!("'") >>
182 ch: cooked_char >>
183 tag!("'") >>
184 (Lit::Byte(ch as u8))
185 ));
186
187 named!(character -> Lit, do_parse!(
188 punct!("'") >>
189 ch: cooked_char >>
190 tag!("'") >>
191 (Lit::Char(ch))
192 ));
193
David Tolnayde206222016-09-30 11:47:01 -0700194 named!(pub int -> (u64, IntTy), tuple!(
David Tolnay14cbdeb2016-10-01 12:13:59 -0700195 preceded!(
196 option!(whitespace),
197 digits
198 ),
David Tolnayde206222016-09-30 11:47:01 -0700199 alt!(
200 tag!("isize") => { |_| IntTy::Isize }
201 |
202 tag!("i8") => { |_| IntTy::I8 }
203 |
204 tag!("i16") => { |_| IntTy::I16 }
205 |
206 tag!("i32") => { |_| IntTy::I32 }
207 |
208 tag!("i64") => { |_| IntTy::I64 }
209 |
210 tag!("usize") => { |_| IntTy::Usize }
211 |
212 tag!("u8") => { |_| IntTy::U8 }
213 |
214 tag!("u16") => { |_| IntTy::U16 }
215 |
216 tag!("u32") => { |_| IntTy::U32 }
217 |
218 tag!("u64") => { |_| IntTy::U64 }
219 |
220 epsilon!() => { |_| IntTy::Unsuffixed }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700221 )
222 ));
223
David Tolnay3ce49d02016-10-23 22:29:19 -0700224 named!(boolean -> Lit, alt!(
225 keyword!("true") => { |_| Lit::Bool(true) }
226 |
227 keyword!("false") => { |_| Lit::Bool(false) }
228 ));
229
David Tolnayde206222016-09-30 11:47:01 -0700230 pub fn digits(input: &str) -> IResult<&str, u64> {
David Tolnayf4bbbd92016-09-23 14:41:55 -0700231 let mut value = 0u64;
232 let mut len = 0;
233 let mut bytes = input.bytes().peekable();
234 while let Some(&b) = bytes.peek() {
235 match b {
David Tolnaydaaf7742016-10-03 11:11:43 -0700236 b'0'...b'9' => {
David Tolnayf4bbbd92016-09-23 14:41:55 -0700237 value = match value.checked_mul(10) {
238 Some(value) => value,
239 None => return IResult::Error,
240 };
241 value = match value.checked_add((b - b'0') as u64) {
242 Some(value) => value,
243 None => return IResult::Error,
244 };
245 bytes.next();
246 len += 1;
247 }
David Tolnayfa0edf22016-09-23 22:58:24 -0700248 _ => break,
David Tolnayf4bbbd92016-09-23 14:41:55 -0700249 }
250 }
David Tolnayfa0edf22016-09-23 22:58:24 -0700251 if len > 0 {
252 IResult::Done(&input[len..], value)
253 } else {
254 IResult::Error
255 }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700256 }
257}
258
259#[cfg(feature = "printing")]
260mod printing {
261 use super::*;
262 use quote::{Tokens, ToTokens};
David Tolnay56d62132016-10-01 16:14:54 -0700263 use std::{ascii, iter};
David Tolnayf4bbbd92016-09-23 14:41:55 -0700264 use std::fmt::{self, Display};
David Tolnay4a658402016-10-24 00:21:41 -0700265 use std::str;
David Tolnayf4bbbd92016-09-23 14:41:55 -0700266
267 impl ToTokens for Lit {
268 fn to_tokens(&self, tokens: &mut Tokens) {
269 match *self {
270 Lit::Str(ref s, StrStyle::Cooked) => s.to_tokens(tokens),
David Tolnay627e3d52016-10-01 08:27:31 -0700271 Lit::Str(ref s, StrStyle::Raw(n)) => {
David Tolnay56d62132016-10-01 16:14:54 -0700272 tokens.append(&format!("r{delim}\"{string}\"{delim}",
273 delim = iter::repeat("#").take(n).collect::<String>(),
274 string = s));
275 }
David Tolnay4a658402016-10-24 00:21:41 -0700276 Lit::ByteStr(ref v, StrStyle::Cooked) => {
David Tolnay56d62132016-10-01 16:14:54 -0700277 let mut escaped = "b\"".to_string();
278 for &ch in v.iter() {
279 escaped.extend(ascii::escape_default(ch).map(|c| c as char));
David Tolnay627e3d52016-10-01 08:27:31 -0700280 }
David Tolnay56d62132016-10-01 16:14:54 -0700281 escaped.push('"');
282 tokens.append(&escaped);
David Tolnay627e3d52016-10-01 08:27:31 -0700283 }
David Tolnay4a658402016-10-24 00:21:41 -0700284 Lit::ByteStr(ref vec, StrStyle::Raw(n)) => {
285 tokens.append(&format!("br{delim}\"{string}\"{delim}",
286 delim = iter::repeat("#").take(n).collect::<String>(),
287 string = str::from_utf8(vec).unwrap()));
288 }
David Tolnay615cf6a2016-10-08 23:07:02 -0700289 Lit::Byte(b) => tokens.append(&format!("b{:?}", b as char)),
David Tolnayf17fd2f2016-10-07 23:38:08 -0700290 Lit::Char(ch) => ch.to_tokens(tokens),
David Tolnayf4bbbd92016-09-23 14:41:55 -0700291 Lit::Int(value, ty) => tokens.append(&format!("{}{}", value, ty)),
David Tolnayf17fd2f2016-10-07 23:38:08 -0700292 Lit::Float(ref value, ty) => tokens.append(&format!("{}{}", value, ty)),
David Tolnay759d2ff2016-10-01 16:18:15 -0700293 Lit::Bool(true) => tokens.append("true"),
294 Lit::Bool(false) => tokens.append("false"),
David Tolnayf4bbbd92016-09-23 14:41:55 -0700295 }
296 }
297 }
298
299 impl Display for IntTy {
300 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
301 match *self {
302 IntTy::Isize => formatter.write_str("isize"),
303 IntTy::I8 => formatter.write_str("i8"),
304 IntTy::I16 => formatter.write_str("i16"),
305 IntTy::I32 => formatter.write_str("i32"),
306 IntTy::I64 => formatter.write_str("i64"),
307 IntTy::Usize => formatter.write_str("usize"),
308 IntTy::U8 => formatter.write_str("u8"),
309 IntTy::U16 => formatter.write_str("u16"),
310 IntTy::U32 => formatter.write_str("u32"),
311 IntTy::U64 => formatter.write_str("u64"),
312 IntTy::Unsuffixed => Ok(()),
313 }
314 }
315 }
David Tolnayf17fd2f2016-10-07 23:38:08 -0700316
317 impl Display for FloatTy {
318 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
319 match *self {
320 FloatTy::F32 => formatter.write_str("f32"),
321 FloatTy::F64 => formatter.write_str("f64"),
322 FloatTy::Unsuffixed => Ok(()),
323 }
324 }
325 }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700326}