blob: aba020a32a0ef4e4361e732e0488221214d98c81 [file] [log] [blame]
David Tolnayf4bbbd92016-09-23 14:41:55 -07001/// Literal kind.
2///
3/// E.g. `"foo"`, `42`, `12.34` or `bool`
David Tolnay9bf4af82017-01-07 11:17:46 -08004#[derive(Debug, Clone, Eq, PartialEq, Hash)]
David Tolnayf4bbbd92016-09-23 14:41:55 -07005pub 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
David Tolnay9bf4af82017-01-07 11:17:46 -080022#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
David Tolnayf4bbbd92016-09-23 14:41:55 -070023pub 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 Tolnay9bf4af82017-01-07 11:17:46 -080068#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
David Tolnayf4bbbd92016-09-23 14:41:55 -070069pub 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
David Tolnay9bf4af82017-01-07 11:17:46 -080083#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
David Tolnayf4bbbd92016-09-23 14:41:55 -070084pub 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 Tolnayfe373a32016-10-26 23:51:19 -0700132 use escape::{cooked_byte, cooked_byte_string, cooked_char, cooked_string, raw_string};
Michael Layzell5bde96f2017-01-24 17:59:21 -0500133 use nom::space::skip_whitespace;
Michael Layzell5e107ff2017-01-24 19:58:39 -0500134 use nom::IResult;
David Tolnay4f5f60f2016-10-24 00:52:58 -0700135 use unicode_xid::UnicodeXID;
David Tolnayf4bbbd92016-09-23 14:41:55 -0700136
137 named!(pub lit -> Lit, alt!(
Michael Layzell5e107ff2017-01-24 19:58:39 -0500138 string => { |(value, style)| Lit::Str(value, style) }
David Tolnay56d62132016-10-01 16:14:54 -0700139 |
Michael Layzell5e107ff2017-01-24 19:58:39 -0500140 byte_string => { |(value, style)| Lit::ByteStr(value, style) }
David Tolnay615cf6a2016-10-08 23:07:02 -0700141 |
Michael Layzell5e107ff2017-01-24 19:58:39 -0500142 byte => { |b| Lit::Byte(b) }
David Tolnay615cf6a2016-10-08 23:07:02 -0700143 |
Michael Layzell5e107ff2017-01-24 19:58:39 -0500144 character => { |ch| Lit::Char(ch) }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700145 |
Michael Layzell5e107ff2017-01-24 19:58:39 -0500146 float => { |(value, suffix)| Lit::Float(value, suffix) } // must be before int
David Tolnay4f5f60f2016-10-24 00:52:58 -0700147 |
David Tolnayf4bbbd92016-09-23 14:41:55 -0700148 int => { |(value, ty)| Lit::Int(value, ty) }
David Tolnay759d2ff2016-10-01 16:18:15 -0700149 |
Michael Layzell5e107ff2017-01-24 19:58:39 -0500150 boolean => { |value| Lit::Bool(value) }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700151 ));
152
Michael Layzell5e107ff2017-01-24 19:58:39 -0500153 named!(pub string -> (String, StrStyle), alt!(
154 quoted_string => { |s| (s, StrStyle::Cooked) }
David Tolnay210884d2016-10-01 08:18:42 -0700155 |
156 preceded!(
157 punct!("r"),
158 raw_string
Michael Layzell5e107ff2017-01-24 19:58:39 -0500159 ) => { |(s, n)| (s, StrStyle::Raw(n)) }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700160 ));
161
David Tolnay42602292016-10-01 22:25:45 -0700162 named!(pub quoted_string -> String, delimited!(
163 punct!("\""),
164 cooked_string,
165 tag!("\"")
166 ));
167
Michael Layzell5e107ff2017-01-24 19:58:39 -0500168 named!(pub byte_string -> (Vec<u8>, StrStyle), alt!(
David Tolnay56d62132016-10-01 16:14:54 -0700169 delimited!(
170 punct!("b\""),
David Tolnaya73e0f02016-10-26 23:25:49 -0700171 cooked_byte_string,
David Tolnay56d62132016-10-01 16:14:54 -0700172 tag!("\"")
Michael Layzell5e107ff2017-01-24 19:58:39 -0500173 ) => { |vec| (vec, StrStyle::Cooked) }
David Tolnay56d62132016-10-01 16:14:54 -0700174 |
175 preceded!(
176 punct!("br"),
177 raw_string
Michael Layzell5e107ff2017-01-24 19:58:39 -0500178 ) => { |(s, n): (String, _)| (s.into_bytes(), StrStyle::Raw(n)) }
David Tolnay56d62132016-10-01 16:14:54 -0700179 ));
180
Michael Layzell5e107ff2017-01-24 19:58:39 -0500181 named!(pub byte -> u8, do_parse!(
David Tolnay615cf6a2016-10-08 23:07:02 -0700182 punct!("b") >>
183 tag!("'") >>
David Tolnayfe373a32016-10-26 23:51:19 -0700184 b: cooked_byte >>
David Tolnay615cf6a2016-10-08 23:07:02 -0700185 tag!("'") >>
Michael Layzell5e107ff2017-01-24 19:58:39 -0500186 (b)
David Tolnay615cf6a2016-10-08 23:07:02 -0700187 ));
188
Michael Layzell5e107ff2017-01-24 19:58:39 -0500189 named!(pub character -> char, do_parse!(
David Tolnay615cf6a2016-10-08 23:07:02 -0700190 punct!("'") >>
191 ch: cooked_char >>
192 tag!("'") >>
Michael Layzell5e107ff2017-01-24 19:58:39 -0500193 (ch)
David Tolnay615cf6a2016-10-08 23:07:02 -0700194 ));
195
Michael Layzell5e107ff2017-01-24 19:58:39 -0500196 named!(pub float -> (String, FloatTy), tuple!(
197 float_string,
198 alt!(
David Tolnay4f5f60f2016-10-24 00:52:58 -0700199 tag!("f32") => { |_| FloatTy::F32 }
200 |
201 tag!("f64") => { |_| FloatTy::F64 }
202 |
203 epsilon!() => { |_| FloatTy::Unsuffixed }
Michael Layzell5e107ff2017-01-24 19:58:39 -0500204 )
David Tolnay4f5f60f2016-10-24 00:52:58 -0700205 ));
206
David Tolnayde206222016-09-30 11:47:01 -0700207 named!(pub int -> (u64, IntTy), tuple!(
David Tolnaydef66372016-10-24 21:51:32 -0700208 digits,
David Tolnayde206222016-09-30 11:47:01 -0700209 alt!(
210 tag!("isize") => { |_| IntTy::Isize }
211 |
212 tag!("i8") => { |_| IntTy::I8 }
213 |
214 tag!("i16") => { |_| IntTy::I16 }
215 |
216 tag!("i32") => { |_| IntTy::I32 }
217 |
218 tag!("i64") => { |_| IntTy::I64 }
219 |
220 tag!("usize") => { |_| IntTy::Usize }
221 |
222 tag!("u8") => { |_| IntTy::U8 }
223 |
224 tag!("u16") => { |_| IntTy::U16 }
225 |
226 tag!("u32") => { |_| IntTy::U32 }
227 |
228 tag!("u64") => { |_| IntTy::U64 }
229 |
230 epsilon!() => { |_| IntTy::Unsuffixed }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700231 )
232 ));
233
Michael Layzell5e107ff2017-01-24 19:58:39 -0500234 named!(pub boolean -> bool, alt!(
235 keyword!("true") => { |_| true }
David Tolnay3ce49d02016-10-23 22:29:19 -0700236 |
Michael Layzell5e107ff2017-01-24 19:58:39 -0500237 keyword!("false") => { |_| false }
David Tolnay3ce49d02016-10-23 22:29:19 -0700238 ));
239
David Tolnaydef66372016-10-24 21:51:32 -0700240 fn float_string(mut input: &str) -> IResult<&str, String> {
241 input = skip_whitespace(input);
242
David Tolnay4f5f60f2016-10-24 00:52:58 -0700243 let mut chars = input.chars().peekable();
244 match chars.next() {
245 Some(ch) if ch >= '0' && ch <= '9' => {}
246 _ => return IResult::Error,
247 }
248
249 let mut len = 1;
250 let mut has_dot = false;
251 let mut has_exp = false;
252 while let Some(&ch) = chars.peek() {
253 match ch {
254 '0'...'9' | '_' => {
255 chars.next();
256 len += 1;
257 }
258 '.' => {
259 if has_dot {
260 break;
261 }
262 chars.next();
263 if chars.peek()
264 .map(|&ch| ch == '.' || UnicodeXID::is_xid_start(ch))
265 .unwrap_or(false) {
266 return IResult::Error;
267 }
268 len += 1;
269 has_dot = true;
270 }
271 'e' | 'E' => {
272 chars.next();
273 len += 1;
274 has_exp = true;
275 break;
276 }
277 _ => break,
278 }
279 }
280
281 let rest = &input[len..];
282 if !(has_dot || has_exp || rest.starts_with("f32") || rest.starts_with("f64")) {
283 return IResult::Error;
284 }
285
286 if has_exp {
287 let mut has_exp_value = false;
288 while let Some(&ch) = chars.peek() {
289 match ch {
290 '+' | '-' => {
291 if has_exp_value {
292 break;
293 }
294 chars.next();
295 len += 1;
296 }
297 '0'...'9' => {
298 chars.next();
299 len += 1;
300 has_exp_value = true;
301 }
302 '_' => {
303 chars.next();
304 len += 1;
305 }
306 _ => break,
307 }
308 }
309 if !has_exp_value {
310 return IResult::Error;
311 }
312 }
313
David Tolnayc7b636a2016-10-24 13:01:08 -0700314 IResult::Done(&input[len..], input[..len].replace("_", ""))
David Tolnay4f5f60f2016-10-24 00:52:58 -0700315 }
316
David Tolnay8a19e6d2016-10-24 01:23:40 -0700317 pub fn digits(mut input: &str) -> IResult<&str, u64> {
David Tolnaydef66372016-10-24 21:51:32 -0700318 input = skip_whitespace(input);
319
David Tolnay8a19e6d2016-10-24 01:23:40 -0700320 let base = if input.starts_with("0x") {
321 input = &input[2..];
322 16
323 } else if input.starts_with("0o") {
324 input = &input[2..];
325 8
326 } else if input.starts_with("0b") {
327 input = &input[2..];
328 2
329 } else {
330 10
331 };
332
David Tolnayf4bbbd92016-09-23 14:41:55 -0700333 let mut value = 0u64;
334 let mut len = 0;
David Tolnay24b5ff72016-10-24 01:05:05 -0700335 let mut empty = true;
336 for b in input.bytes() {
David Tolnay8a19e6d2016-10-24 01:23:40 -0700337 let digit = match b {
338 b'0'...b'9' => (b - b'0') as u64,
339 b'a'...b'f' => 10 + (b - b'a') as u64,
340 b'A'...b'F' => 10 + (b - b'A') as u64,
David Tolnay24b5ff72016-10-24 01:05:05 -0700341 b'_' => {
David Tolnayc814a762016-10-27 23:11:28 -0700342 if empty && base == 10 {
David Tolnay24b5ff72016-10-24 01:05:05 -0700343 return IResult::Error;
344 }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700345 len += 1;
David Tolnay8a19e6d2016-10-24 01:23:40 -0700346 continue;
David Tolnayf4bbbd92016-09-23 14:41:55 -0700347 }
David Tolnayfa0edf22016-09-23 22:58:24 -0700348 _ => break,
David Tolnay8a19e6d2016-10-24 01:23:40 -0700349 };
350 if digit >= base {
351 return IResult::Error;
David Tolnayf4bbbd92016-09-23 14:41:55 -0700352 }
David Tolnay8a19e6d2016-10-24 01:23:40 -0700353 value = match value.checked_mul(base) {
354 Some(value) => value,
355 None => return IResult::Error,
356 };
357 value = match value.checked_add(digit) {
358 Some(value) => value,
359 None => return IResult::Error,
360 };
361 len += 1;
362 empty = false;
David Tolnayf4bbbd92016-09-23 14:41:55 -0700363 }
David Tolnay24b5ff72016-10-24 01:05:05 -0700364 if empty {
David Tolnayfa0edf22016-09-23 22:58:24 -0700365 IResult::Error
David Tolnay24b5ff72016-10-24 01:05:05 -0700366 } else {
367 IResult::Done(&input[len..], value)
David Tolnayfa0edf22016-09-23 22:58:24 -0700368 }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700369 }
370}
371
372#[cfg(feature = "printing")]
373mod printing {
374 use super::*;
375 use quote::{Tokens, ToTokens};
David Tolnay56d62132016-10-01 16:14:54 -0700376 use std::{ascii, iter};
David Tolnayf4bbbd92016-09-23 14:41:55 -0700377 use std::fmt::{self, Display};
David Tolnay4a658402016-10-24 00:21:41 -0700378 use std::str;
David Tolnayf4bbbd92016-09-23 14:41:55 -0700379
380 impl ToTokens for Lit {
381 fn to_tokens(&self, tokens: &mut Tokens) {
382 match *self {
383 Lit::Str(ref s, StrStyle::Cooked) => s.to_tokens(tokens),
David Tolnay627e3d52016-10-01 08:27:31 -0700384 Lit::Str(ref s, StrStyle::Raw(n)) => {
David Tolnay56d62132016-10-01 16:14:54 -0700385 tokens.append(&format!("r{delim}\"{string}\"{delim}",
386 delim = iter::repeat("#").take(n).collect::<String>(),
387 string = s));
388 }
David Tolnay4a658402016-10-24 00:21:41 -0700389 Lit::ByteStr(ref v, StrStyle::Cooked) => {
David Tolnay56d62132016-10-01 16:14:54 -0700390 let mut escaped = "b\"".to_string();
391 for &ch in v.iter() {
David Tolnay289f4c72016-10-25 00:00:09 -0700392 match ch {
393 0 => escaped.push_str(r"\0"),
394 b'\'' => escaped.push('\''),
395 _ => escaped.extend(ascii::escape_default(ch).map(|c| c as char)),
396 }
David Tolnay627e3d52016-10-01 08:27:31 -0700397 }
David Tolnay56d62132016-10-01 16:14:54 -0700398 escaped.push('"');
399 tokens.append(&escaped);
David Tolnay627e3d52016-10-01 08:27:31 -0700400 }
David Tolnay4a658402016-10-24 00:21:41 -0700401 Lit::ByteStr(ref vec, StrStyle::Raw(n)) => {
402 tokens.append(&format!("br{delim}\"{string}\"{delim}",
403 delim = iter::repeat("#").take(n).collect::<String>(),
404 string = str::from_utf8(vec).unwrap()));
405 }
David Tolnay289f4c72016-10-25 00:00:09 -0700406 Lit::Byte(b) => {
407 match b {
408 0 => tokens.append(r"b'\0'"),
409 b'\"' => tokens.append("b'\"'"),
410 _ => {
411 let mut escaped = "b'".to_string();
412 escaped.extend(ascii::escape_default(b).map(|c| c as char));
413 escaped.push('\'');
414 tokens.append(&escaped);
415 }
416 }
417 }
David Tolnayf17fd2f2016-10-07 23:38:08 -0700418 Lit::Char(ch) => ch.to_tokens(tokens),
David Tolnayf4bbbd92016-09-23 14:41:55 -0700419 Lit::Int(value, ty) => tokens.append(&format!("{}{}", value, ty)),
David Tolnayf17fd2f2016-10-07 23:38:08 -0700420 Lit::Float(ref value, ty) => tokens.append(&format!("{}{}", value, ty)),
David Tolnay759d2ff2016-10-01 16:18:15 -0700421 Lit::Bool(true) => tokens.append("true"),
422 Lit::Bool(false) => tokens.append("false"),
David Tolnayf4bbbd92016-09-23 14:41:55 -0700423 }
424 }
425 }
426
427 impl Display for IntTy {
428 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
429 match *self {
430 IntTy::Isize => formatter.write_str("isize"),
431 IntTy::I8 => formatter.write_str("i8"),
432 IntTy::I16 => formatter.write_str("i16"),
433 IntTy::I32 => formatter.write_str("i32"),
434 IntTy::I64 => formatter.write_str("i64"),
435 IntTy::Usize => formatter.write_str("usize"),
436 IntTy::U8 => formatter.write_str("u8"),
437 IntTy::U16 => formatter.write_str("u16"),
438 IntTy::U32 => formatter.write_str("u32"),
439 IntTy::U64 => formatter.write_str("u64"),
440 IntTy::Unsuffixed => Ok(()),
441 }
442 }
443 }
David Tolnayf17fd2f2016-10-07 23:38:08 -0700444
445 impl Display for FloatTy {
446 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
447 match *self {
448 FloatTy::F32 => formatter.write_str("f32"),
449 FloatTy::F64 => formatter.write_str("f64"),
450 FloatTy::Unsuffixed => Ok(()),
451 }
452 }
453 }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700454}