blob: 51ade4b9e4a7380e3f6369ef2d6d5a01b262908f [file] [log] [blame]
David Tolnay55535012018-01-05 16:39:23 -08001// Copyright 2018 Syn Developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
Alex Crichton9a4dca22018-03-28 06:32:19 -07009use proc_macro2::{Literal, Span};
David Tolnay360efd22018-01-04 23:35:26 -080010use std::str;
11
David Tolnay7d1d1282018-01-06 16:10:51 -080012#[cfg(feature = "printing")]
Alex Crichtona74a1c82018-05-16 10:20:44 -070013use proc_macro2::Ident;
David Tolnay7d1d1282018-01-06 16:10:51 -080014
David Tolnayd53ac2b2018-01-27 19:00:06 -080015#[cfg(feature = "parsing")]
16use proc_macro2::TokenStream;
17#[cfg(feature = "parsing")]
David Tolnaye82a2b12018-08-30 16:31:10 -070018use Error;
David Tolnayd53ac2b2018-01-27 19:00:06 -080019
David Tolnay60fafad2018-02-03 09:18:03 -080020use proc_macro2::TokenTree;
21
David Tolnay360efd22018-01-04 23:35:26 -080022#[cfg(feature = "extra-traits")]
Alex Crichtonccbb45d2017-05-23 10:58:24 -070023use std::hash::{Hash, Hasher};
24
David Tolnay4fb71232018-08-25 23:14:50 -040025#[cfg(feature = "parsing")]
26use lookahead;
David Tolnaye82a2b12018-08-30 16:31:10 -070027#[cfg(feature = "parsing")]
28use parse::Parse;
David Tolnay4fb71232018-08-25 23:14:50 -040029
David Tolnay360efd22018-01-04 23:35:26 -080030ast_enum_of_structs! {
David Tolnayabf5c2e2018-01-06 23:30:04 -080031 /// A Rust literal such as a string or integer or boolean.
David Tolnay614a0142018-01-07 10:25:43 -080032 ///
David Tolnay461d98e2018-01-07 11:07:19 -080033 /// *This type is available if Syn is built with the `"derive"` or `"full"`
34 /// feature.*
35 ///
David Tolnay614a0142018-01-07 10:25:43 -080036 /// # Syntax tree enum
37 ///
38 /// This type is a [syntax tree enum].
39 ///
40 /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums
David Tolnay360efd22018-01-04 23:35:26 -080041 pub enum Lit {
David Tolnayabf5c2e2018-01-06 23:30:04 -080042 /// A UTF-8 string literal: `"foo"`.
David Tolnay461d98e2018-01-07 11:07:19 -080043 ///
44 /// *This type is available if Syn is built with the `"derive"` or
45 /// `"full"` feature.*
David Tolnay360efd22018-01-04 23:35:26 -080046 pub Str(LitStr #manual_extra_traits {
47 token: Literal,
David Tolnay360efd22018-01-04 23:35:26 -080048 }),
Alex Crichtonccbb45d2017-05-23 10:58:24 -070049
David Tolnayabf5c2e2018-01-06 23:30:04 -080050 /// A byte string literal: `b"foo"`.
David Tolnay461d98e2018-01-07 11:07:19 -080051 ///
52 /// *This type is available if Syn is built with the `"derive"` or
53 /// `"full"` feature.*
David Tolnay360efd22018-01-04 23:35:26 -080054 pub ByteStr(LitByteStr #manual_extra_traits {
55 token: Literal,
David Tolnay360efd22018-01-04 23:35:26 -080056 }),
57
David Tolnayabf5c2e2018-01-06 23:30:04 -080058 /// A byte literal: `b'f'`.
David Tolnay461d98e2018-01-07 11:07:19 -080059 ///
60 /// *This type is available if Syn is built with the `"derive"` or
61 /// `"full"` feature.*
David Tolnay360efd22018-01-04 23:35:26 -080062 pub Byte(LitByte #manual_extra_traits {
63 token: Literal,
David Tolnay360efd22018-01-04 23:35:26 -080064 }),
65
David Tolnayabf5c2e2018-01-06 23:30:04 -080066 /// A character literal: `'a'`.
David Tolnay461d98e2018-01-07 11:07:19 -080067 ///
68 /// *This type is available if Syn is built with the `"derive"` or
69 /// `"full"` feature.*
David Tolnay360efd22018-01-04 23:35:26 -080070 pub Char(LitChar #manual_extra_traits {
71 token: Literal,
David Tolnay360efd22018-01-04 23:35:26 -080072 }),
73
David Tolnayabf5c2e2018-01-06 23:30:04 -080074 /// An integer literal: `1` or `1u16`.
David Tolnay360efd22018-01-04 23:35:26 -080075 ///
76 /// Holds up to 64 bits of data. Use `LitVerbatim` for any larger
77 /// integer literal.
David Tolnay461d98e2018-01-07 11:07:19 -080078 ///
79 /// *This type is available if Syn is built with the `"derive"` or
80 /// `"full"` feature.*
David Tolnay360efd22018-01-04 23:35:26 -080081 pub Int(LitInt #manual_extra_traits {
82 token: Literal,
David Tolnay360efd22018-01-04 23:35:26 -080083 }),
84
David Tolnayabf5c2e2018-01-06 23:30:04 -080085 /// A floating point literal: `1f64` or `1.0e10f64`.
David Tolnay360efd22018-01-04 23:35:26 -080086 ///
87 /// Must be finite. May not be infinte or NaN.
David Tolnay461d98e2018-01-07 11:07:19 -080088 ///
89 /// *This type is available if Syn is built with the `"derive"` or
90 /// `"full"` feature.*
David Tolnay360efd22018-01-04 23:35:26 -080091 pub Float(LitFloat #manual_extra_traits {
92 token: Literal,
David Tolnay360efd22018-01-04 23:35:26 -080093 }),
94
David Tolnayabf5c2e2018-01-06 23:30:04 -080095 /// A boolean literal: `true` or `false`.
David Tolnay461d98e2018-01-07 11:07:19 -080096 ///
97 /// *This type is available if Syn is built with the `"derive"` or
98 /// `"full"` feature.*
David Tolnay360efd22018-01-04 23:35:26 -080099 pub Bool(LitBool #manual_extra_traits {
100 pub value: bool,
101 pub span: Span,
102 }),
103
David Tolnayabf5c2e2018-01-06 23:30:04 -0800104 /// A raw token literal not interpreted by Syn, possibly because it
105 /// represents an integer larger than 64 bits.
David Tolnay461d98e2018-01-07 11:07:19 -0800106 ///
107 /// *This type is available if Syn is built with the `"derive"` or
108 /// `"full"` feature.*
David Tolnay360efd22018-01-04 23:35:26 -0800109 pub Verbatim(LitVerbatim #manual_extra_traits {
110 pub token: Literal,
David Tolnay360efd22018-01-04 23:35:26 -0800111 }),
112 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700113}
114
David Tolnay360efd22018-01-04 23:35:26 -0800115impl LitStr {
116 pub fn new(value: &str, span: Span) -> Self {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700117 let mut lit = Literal::string(value);
118 lit.set_span(span);
David Tolnay94d2b792018-04-29 12:26:10 -0700119 LitStr { token: lit }
David Tolnay360efd22018-01-04 23:35:26 -0800120 }
121
122 pub fn value(&self) -> String {
123 value::parse_lit_str(&self.token.to_string())
124 }
David Tolnayd53ac2b2018-01-27 19:00:06 -0800125
126 /// Parse a syntax tree node from the content of this string literal.
127 ///
128 /// All spans in the syntax tree will point to the span of this `LitStr`.
129 #[cfg(feature = "parsing")]
David Tolnaye82a2b12018-08-30 16:31:10 -0700130 pub fn parse<T: Parse>(&self) -> Result<T, Error> {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700131 use proc_macro2::Group;
132
David Tolnayd53ac2b2018-01-27 19:00:06 -0800133 // Parse string literal into a token stream with every span equal to the
134 // original literal's span.
David Tolnayad4b2472018-08-25 08:25:24 -0400135 fn spanned_tokens(s: &LitStr) -> Result<TokenStream, Error> {
David Tolnayd53ac2b2018-01-27 19:00:06 -0800136 let stream = ::parse_str(&s.value())?;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700137 Ok(respan_token_stream(stream, s.span()))
David Tolnayd53ac2b2018-01-27 19:00:06 -0800138 }
139
140 // Token stream with every span replaced by the given one.
141 fn respan_token_stream(stream: TokenStream, span: Span) -> TokenStream {
David Tolnay94d2b792018-04-29 12:26:10 -0700142 stream
143 .into_iter()
144 .map(|token| respan_token_tree(token, span))
145 .collect()
David Tolnayd53ac2b2018-01-27 19:00:06 -0800146 }
147
148 // Token tree with every span replaced by the given one.
Alex Crichton9a4dca22018-03-28 06:32:19 -0700149 fn respan_token_tree(mut token: TokenTree, span: Span) -> TokenTree {
150 match token {
151 TokenTree::Group(ref mut g) => {
152 let stream = respan_token_stream(g.stream().clone(), span);
153 *g = Group::new(g.delimiter(), stream);
154 g.set_span(span);
155 }
156 ref mut other => other.set_span(span),
David Tolnayd53ac2b2018-01-27 19:00:06 -0800157 }
Alex Crichton9a4dca22018-03-28 06:32:19 -0700158 token
David Tolnayd53ac2b2018-01-27 19:00:06 -0800159 }
160
161 spanned_tokens(self).and_then(::parse2)
162 }
Alex Crichton9a4dca22018-03-28 06:32:19 -0700163
164 pub fn span(&self) -> Span {
165 self.token.span()
166 }
167
168 pub fn set_span(&mut self, span: Span) {
169 self.token.set_span(span)
170 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700171}
172
David Tolnay360efd22018-01-04 23:35:26 -0800173impl LitByteStr {
174 pub fn new(value: &[u8], span: Span) -> Self {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700175 let mut token = Literal::byte_string(value);
176 token.set_span(span);
177 LitByteStr { token: token }
David Tolnay360efd22018-01-04 23:35:26 -0800178 }
179
180 pub fn value(&self) -> Vec<u8> {
181 value::parse_lit_byte_str(&self.token.to_string())
182 }
Alex Crichton9a4dca22018-03-28 06:32:19 -0700183
184 pub fn span(&self) -> Span {
185 self.token.span()
186 }
187
188 pub fn set_span(&mut self, span: Span) {
189 self.token.set_span(span)
190 }
David Tolnay360efd22018-01-04 23:35:26 -0800191}
192
193impl LitByte {
194 pub fn new(value: u8, span: Span) -> Self {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700195 let mut token = Literal::u8_suffixed(value);
196 token.set_span(span);
197 LitByte { token: token }
David Tolnay360efd22018-01-04 23:35:26 -0800198 }
199
200 pub fn value(&self) -> u8 {
201 value::parse_lit_byte(&self.token.to_string())
202 }
Alex Crichton9a4dca22018-03-28 06:32:19 -0700203
204 pub fn span(&self) -> Span {
205 self.token.span()
206 }
207
208 pub fn set_span(&mut self, span: Span) {
209 self.token.set_span(span)
210 }
David Tolnay360efd22018-01-04 23:35:26 -0800211}
212
213impl LitChar {
214 pub fn new(value: char, span: Span) -> Self {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700215 let mut token = Literal::character(value);
216 token.set_span(span);
217 LitChar { token: token }
David Tolnay360efd22018-01-04 23:35:26 -0800218 }
219
220 pub fn value(&self) -> char {
221 value::parse_lit_char(&self.token.to_string())
222 }
Alex Crichton9a4dca22018-03-28 06:32:19 -0700223
224 pub fn span(&self) -> Span {
225 self.token.span()
226 }
227
228 pub fn set_span(&mut self, span: Span) {
229 self.token.set_span(span)
230 }
David Tolnay360efd22018-01-04 23:35:26 -0800231}
232
233impl LitInt {
234 pub fn new(value: u64, suffix: IntSuffix, span: Span) -> Self {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700235 let mut token = match suffix {
236 IntSuffix::Isize => Literal::isize_suffixed(value as isize),
237 IntSuffix::I8 => Literal::i8_suffixed(value as i8),
238 IntSuffix::I16 => Literal::i16_suffixed(value as i16),
239 IntSuffix::I32 => Literal::i32_suffixed(value as i32),
240 IntSuffix::I64 => Literal::i64_suffixed(value as i64),
241 IntSuffix::I128 => value::to_literal(&format!("{}i128", value)),
242 IntSuffix::Usize => Literal::usize_suffixed(value as usize),
243 IntSuffix::U8 => Literal::u8_suffixed(value as u8),
244 IntSuffix::U16 => Literal::u16_suffixed(value as u16),
245 IntSuffix::U32 => Literal::u32_suffixed(value as u32),
246 IntSuffix::U64 => Literal::u64_suffixed(value),
247 IntSuffix::U128 => value::to_literal(&format!("{}u128", value)),
248 IntSuffix::None => Literal::u64_unsuffixed(value),
249 };
250 token.set_span(span);
251 LitInt { token: token }
David Tolnay360efd22018-01-04 23:35:26 -0800252 }
253
254 pub fn value(&self) -> u64 {
255 value::parse_lit_int(&self.token.to_string()).unwrap()
256 }
257
258 pub fn suffix(&self) -> IntSuffix {
259 let value = self.token.to_string();
260 for (s, suffix) in vec![
261 ("i8", IntSuffix::I8),
262 ("i16", IntSuffix::I16),
263 ("i32", IntSuffix::I32),
264 ("i64", IntSuffix::I64),
265 ("i128", IntSuffix::I128),
266 ("isize", IntSuffix::Isize),
267 ("u8", IntSuffix::U8),
268 ("u16", IntSuffix::U16),
269 ("u32", IntSuffix::U32),
270 ("u64", IntSuffix::U64),
271 ("u128", IntSuffix::U128),
272 ("usize", IntSuffix::Usize),
273 ] {
274 if value.ends_with(s) {
275 return suffix;
276 }
277 }
278 IntSuffix::None
279 }
Alex Crichton9a4dca22018-03-28 06:32:19 -0700280
281 pub fn span(&self) -> Span {
282 self.token.span()
283 }
284
285 pub fn set_span(&mut self, span: Span) {
286 self.token.set_span(span)
287 }
David Tolnay360efd22018-01-04 23:35:26 -0800288}
289
290impl LitFloat {
291 pub fn new(value: f64, suffix: FloatSuffix, span: Span) -> Self {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700292 let mut token = match suffix {
293 FloatSuffix::F32 => Literal::f32_suffixed(value as f32),
294 FloatSuffix::F64 => Literal::f64_suffixed(value),
295 FloatSuffix::None => Literal::f64_unsuffixed(value),
296 };
297 token.set_span(span);
298 LitFloat { token: token }
David Tolnay360efd22018-01-04 23:35:26 -0800299 }
300
301 pub fn value(&self) -> f64 {
302 value::parse_lit_float(&self.token.to_string())
303 }
304
305 pub fn suffix(&self) -> FloatSuffix {
306 let value = self.token.to_string();
David Tolnay61037c62018-01-05 16:21:03 -0800307 for (s, suffix) in vec![("f32", FloatSuffix::F32), ("f64", FloatSuffix::F64)] {
David Tolnay360efd22018-01-04 23:35:26 -0800308 if value.ends_with(s) {
309 return suffix;
310 }
311 }
312 FloatSuffix::None
313 }
Alex Crichton9a4dca22018-03-28 06:32:19 -0700314
315 pub fn span(&self) -> Span {
316 self.token.span()
317 }
318
319 pub fn set_span(&mut self, span: Span) {
320 self.token.set_span(span)
321 }
David Tolnay360efd22018-01-04 23:35:26 -0800322}
323
324macro_rules! lit_extra_traits {
325 ($ty:ident, $field:ident) => {
326 #[cfg(feature = "extra-traits")]
327 impl Eq for $ty {}
328
329 #[cfg(feature = "extra-traits")]
330 impl PartialEq for $ty {
331 fn eq(&self, other: &Self) -> bool {
332 self.$field.to_string() == other.$field.to_string()
333 }
334 }
335
336 #[cfg(feature = "extra-traits")]
337 impl Hash for $ty {
338 fn hash<H>(&self, state: &mut H)
339 where
340 H: Hasher,
341 {
342 self.$field.to_string().hash(state);
343 }
David Tolnay9c76bcb2017-12-26 23:14:59 -0500344 }
David Tolnay6a170ce2018-08-26 22:29:24 -0700345
346 #[cfg(feature = "parsing")]
347 #[doc(hidden)]
348 #[allow(non_snake_case)]
349 pub fn $ty(marker: lookahead::TokenMarker) -> $ty {
350 match marker {}
351 }
David Tolnay94d2b792018-04-29 12:26:10 -0700352 };
David Tolnayf4bbbd92016-09-23 14:41:55 -0700353}
354
Alex Crichton9a4dca22018-03-28 06:32:19 -0700355impl LitVerbatim {
356 pub fn span(&self) -> Span {
357 self.token.span()
358 }
359
360 pub fn set_span(&mut self, span: Span) {
361 self.token.set_span(span)
362 }
363}
364
David Tolnay360efd22018-01-04 23:35:26 -0800365lit_extra_traits!(LitStr, token);
366lit_extra_traits!(LitByteStr, token);
367lit_extra_traits!(LitByte, token);
368lit_extra_traits!(LitChar, token);
369lit_extra_traits!(LitInt, token);
370lit_extra_traits!(LitFloat, token);
371lit_extra_traits!(LitBool, value);
372lit_extra_traits!(LitVerbatim, token);
373
374ast_enum! {
David Tolnay05658502018-01-07 09:56:37 -0800375 /// The style of a string literal, either plain quoted or a raw string like
David Tolnayabf5c2e2018-01-06 23:30:04 -0800376 /// `r##"data"##`.
David Tolnay461d98e2018-01-07 11:07:19 -0800377 ///
378 /// *This type is available if Syn is built with the `"derive"` or `"full"`
379 /// feature.*
David Tolnay360efd22018-01-04 23:35:26 -0800380 pub enum StrStyle #no_visit {
David Tolnayabf5c2e2018-01-06 23:30:04 -0800381 /// An ordinary string like `"data"`.
David Tolnay360efd22018-01-04 23:35:26 -0800382 Cooked,
David Tolnayabf5c2e2018-01-06 23:30:04 -0800383 /// A raw string like `r##"data"##`.
David Tolnay360efd22018-01-04 23:35:26 -0800384 ///
385 /// The unsigned integer is the number of `#` symbols used.
386 Raw(usize),
Alex Crichton62a0a592017-05-22 13:58:53 -0700387 }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700388}
389
David Tolnay360efd22018-01-04 23:35:26 -0800390ast_enum! {
David Tolnayabf5c2e2018-01-06 23:30:04 -0800391 /// The suffix on an integer literal if any, like the `u8` in `127u8`.
David Tolnay461d98e2018-01-07 11:07:19 -0800392 ///
393 /// *This type is available if Syn is built with the `"derive"` or `"full"`
394 /// feature.*
David Tolnay360efd22018-01-04 23:35:26 -0800395 pub enum IntSuffix #no_visit {
396 I8,
397 I16,
398 I32,
399 I64,
400 I128,
401 Isize,
402 U8,
403 U16,
404 U32,
405 U64,
406 U128,
407 Usize,
408 None,
Pascal Hertleif36342c52016-10-19 10:31:42 +0200409 }
410}
411
David Tolnay360efd22018-01-04 23:35:26 -0800412ast_enum! {
David Tolnayabf5c2e2018-01-06 23:30:04 -0800413 /// The suffix on a floating point literal if any, like the `f32` in
414 /// `1.0f32`.
David Tolnay461d98e2018-01-07 11:07:19 -0800415 ///
416 /// *This type is available if Syn is built with the `"derive"` or `"full"`
417 /// feature.*
David Tolnay360efd22018-01-04 23:35:26 -0800418 pub enum FloatSuffix #no_visit {
419 F32,
420 F64,
421 None,
Alex Crichton2e0229c2017-05-23 09:34:50 -0700422 }
David Tolnay5fe14fc2017-01-27 16:22:08 -0800423}
424
425#[cfg(feature = "parsing")]
David Tolnay4fb71232018-08-25 23:14:50 -0400426#[doc(hidden)]
427#[allow(non_snake_case)]
428pub fn Lit(marker: lookahead::TokenMarker) -> Lit {
429 match marker {}
430}
431
432#[cfg(feature = "parsing")]
David Tolnayf4bbbd92016-09-23 14:41:55 -0700433pub mod parsing {
434 use super::*;
David Tolnay4fb71232018-08-25 23:14:50 -0400435 use parse::{Parse, ParseStream, Result};
David Tolnayf4bbbd92016-09-23 14:41:55 -0700436
David Tolnay4fb71232018-08-25 23:14:50 -0400437 impl Parse for Lit {
438 fn parse(input: ParseStream) -> Result<Self> {
David Tolnay73b7ca12018-08-30 21:05:13 -0700439 input.step_cursor(|cursor| match cursor.literal() {
440 Some((lit, rest)) => Ok((Lit::new(lit), rest)),
441 _ => match cursor.ident() {
442 Some((ident, rest)) => Ok((
443 Lit::Bool(LitBool {
444 value: if ident == "true" {
445 true
446 } else if ident == "false" {
447 false
448 } else {
449 return Err(cursor.error("expected literal"));
450 },
451 span: ident.span(),
452 }),
453 rest,
454 )),
455 _ => Err(cursor.error("expected literal")),
456 },
David Tolnay4fb71232018-08-25 23:14:50 -0400457 })
Sergio Benitez5680d6a2017-12-29 11:20:29 -0800458 }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700459 }
David Tolnay360efd22018-01-04 23:35:26 -0800460
David Tolnaya7d69fc2018-08-26 13:30:24 -0400461 impl Parse for LitStr {
462 fn parse(input: ParseStream) -> Result<Self> {
463 let head = input.fork();
464 match input.parse()? {
465 Lit::Str(lit) => Ok(lit),
466 _ => Err(head.error("expected string literal")),
467 }
468 }
469 }
David Tolnay360efd22018-01-04 23:35:26 -0800470
David Tolnaya7d69fc2018-08-26 13:30:24 -0400471 impl Parse for LitByteStr {
472 fn parse(input: ParseStream) -> Result<Self> {
473 let head = input.fork();
474 match input.parse()? {
475 Lit::ByteStr(lit) => Ok(lit),
476 _ => Err(head.error("expected byte string literal")),
477 }
478 }
479 }
David Tolnay360efd22018-01-04 23:35:26 -0800480
David Tolnaya7d69fc2018-08-26 13:30:24 -0400481 impl Parse for LitByte {
482 fn parse(input: ParseStream) -> Result<Self> {
483 let head = input.fork();
484 match input.parse()? {
485 Lit::Byte(lit) => Ok(lit),
486 _ => Err(head.error("expected byte literal")),
487 }
488 }
489 }
David Tolnay360efd22018-01-04 23:35:26 -0800490
David Tolnaya7d69fc2018-08-26 13:30:24 -0400491 impl Parse for LitChar {
492 fn parse(input: ParseStream) -> Result<Self> {
493 let head = input.fork();
494 match input.parse()? {
495 Lit::Char(lit) => Ok(lit),
496 _ => Err(head.error("expected character literal")),
497 }
498 }
499 }
David Tolnay360efd22018-01-04 23:35:26 -0800500
David Tolnaya7d69fc2018-08-26 13:30:24 -0400501 impl Parse for LitInt {
502 fn parse(input: ParseStream) -> Result<Self> {
503 let head = input.fork();
504 match input.parse()? {
505 Lit::Int(lit) => Ok(lit),
506 _ => Err(head.error("expected integer literal")),
507 }
508 }
509 }
David Tolnay360efd22018-01-04 23:35:26 -0800510
David Tolnaya7d69fc2018-08-26 13:30:24 -0400511 impl Parse for LitFloat {
512 fn parse(input: ParseStream) -> Result<Self> {
513 let head = input.fork();
514 match input.parse()? {
515 Lit::Float(lit) => Ok(lit),
516 _ => Err(head.error("expected floating point literal")),
517 }
518 }
519 }
David Tolnay360efd22018-01-04 23:35:26 -0800520
David Tolnaya7d69fc2018-08-26 13:30:24 -0400521 impl Parse for LitBool {
522 fn parse(input: ParseStream) -> Result<Self> {
523 let head = input.fork();
524 match input.parse()? {
525 Lit::Bool(lit) => Ok(lit),
526 _ => Err(head.error("expected boolean literal")),
527 }
528 }
529 }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700530}
531
532#[cfg(feature = "printing")]
533mod printing {
534 use super::*;
Alex Crichtona74a1c82018-05-16 10:20:44 -0700535 use proc_macro2::TokenStream;
David Tolnay65fb5662018-05-20 20:02:28 -0700536 use quote::{ToTokens, TokenStreamExt};
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700537
David Tolnay360efd22018-01-04 23:35:26 -0800538 impl ToTokens for LitStr {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700539 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700540 self.token.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800541 }
542 }
543
544 impl ToTokens for LitByteStr {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700545 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700546 self.token.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800547 }
548 }
549
550 impl ToTokens for LitByte {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700551 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700552 self.token.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800553 }
554 }
555
556 impl ToTokens for LitChar {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700557 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700558 self.token.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800559 }
560 }
561
562 impl ToTokens for LitInt {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700563 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700564 self.token.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800565 }
566 }
567
568 impl ToTokens for LitFloat {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700569 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700570 self.token.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800571 }
572 }
573
574 impl ToTokens for LitBool {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700575 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700576 let s = if self.value { "true" } else { "false" };
Alex Crichtona74a1c82018-05-16 10:20:44 -0700577 tokens.append(Ident::new(s, self.span));
David Tolnay360efd22018-01-04 23:35:26 -0800578 }
579 }
580
581 impl ToTokens for LitVerbatim {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700582 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700583 self.token.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800584 }
585 }
586}
587
588mod value {
589 use super::*;
David Tolnay94d2b792018-04-29 12:26:10 -0700590 use proc_macro2::TokenStream;
David Tolnay360efd22018-01-04 23:35:26 -0800591 use std::char;
592 use std::ops::{Index, RangeFrom};
David Tolnay360efd22018-01-04 23:35:26 -0800593
David Tolnay7d1d1282018-01-06 16:10:51 -0800594 impl Lit {
David Tolnay780292d2018-01-22 23:26:44 -0800595 /// Interpret a Syn literal from a proc-macro2 literal.
596 ///
597 /// Not all proc-macro2 literals are valid Syn literals. In particular,
598 /// doc comments are considered by proc-macro2 to be literals but in Syn
599 /// they are [`Attribute`].
600 ///
601 /// [`Attribute`]: struct.Attribute.html
602 ///
603 /// # Panics
604 ///
605 /// Panics if the input is a doc comment literal.
Alex Crichton9a4dca22018-03-28 06:32:19 -0700606 pub fn new(token: Literal) -> Self {
David Tolnay7d1d1282018-01-06 16:10:51 -0800607 let value = token.to_string();
608
609 match value::byte(&value, 0) {
David Tolnay94d2b792018-04-29 12:26:10 -0700610 b'"' | b'r' => return Lit::Str(LitStr { token: token }),
David Tolnay7d1d1282018-01-06 16:10:51 -0800611 b'b' => match value::byte(&value, 1) {
David Tolnay94d2b792018-04-29 12:26:10 -0700612 b'"' | b'r' => return Lit::ByteStr(LitByteStr { token: token }),
613 b'\'' => return Lit::Byte(LitByte { token: token }),
David Tolnay7d1d1282018-01-06 16:10:51 -0800614 _ => {}
615 },
David Tolnay94d2b792018-04-29 12:26:10 -0700616 b'\'' => return Lit::Char(LitChar { token: token }),
David Tolnay7d1d1282018-01-06 16:10:51 -0800617 b'0'...b'9' => if number_is_int(&value) {
David Tolnay94d2b792018-04-29 12:26:10 -0700618 return Lit::Int(LitInt { token: token });
David Tolnay7d1d1282018-01-06 16:10:51 -0800619 } else if number_is_float(&value) {
David Tolnay94d2b792018-04-29 12:26:10 -0700620 return Lit::Float(LitFloat { token: token });
David Tolnay7d1d1282018-01-06 16:10:51 -0800621 } else {
622 // number overflow
David Tolnay94d2b792018-04-29 12:26:10 -0700623 return Lit::Verbatim(LitVerbatim { token: token });
David Tolnay7d1d1282018-01-06 16:10:51 -0800624 },
625 _ => if value == "true" || value == "false" {
626 return Lit::Bool(LitBool {
627 value: value == "true",
Alex Crichton9a4dca22018-03-28 06:32:19 -0700628 span: token.span(),
David Tolnay7d1d1282018-01-06 16:10:51 -0800629 });
630 },
631 }
632
633 panic!("Unrecognized literal: {}", value);
634 }
635 }
636
637 fn number_is_int(value: &str) -> bool {
638 if number_is_float(value) {
639 false
640 } else {
641 value::parse_lit_int(value).is_some()
642 }
643 }
644
645 fn number_is_float(value: &str) -> bool {
646 if value.contains('.') {
647 true
648 } else if value.starts_with("0x") || value.ends_with("size") {
649 false
650 } else {
651 value.contains('e') || value.contains('E')
652 }
653 }
654
David Tolnay360efd22018-01-04 23:35:26 -0800655 /// Get the byte at offset idx, or a default of `b'\0'` if we're looking
656 /// past the end of the input buffer.
657 pub fn byte<S: AsRef<[u8]> + ?Sized>(s: &S, idx: usize) -> u8 {
658 let s = s.as_ref();
659 if idx < s.len() {
660 s[idx]
661 } else {
662 0
663 }
664 }
665
666 fn next_chr(s: &str) -> char {
667 s.chars().next().unwrap_or('\0')
668 }
669
670 pub fn parse_lit_str(s: &str) -> String {
671 match byte(s, 0) {
672 b'"' => parse_lit_str_cooked(s),
673 b'r' => parse_lit_str_raw(s),
674 _ => unreachable!(),
675 }
676 }
677
David Tolnay76ebcdd2018-01-05 17:07:26 -0800678 // Clippy false positive
679 // https://github.com/rust-lang-nursery/rust-clippy/issues/2329
680 #[cfg_attr(feature = "cargo-clippy", allow(needless_continue))]
David Tolnay360efd22018-01-04 23:35:26 -0800681 fn parse_lit_str_cooked(mut s: &str) -> String {
682 assert_eq!(byte(s, 0), b'"');
683 s = &s[1..];
684
685 let mut out = String::new();
686 'outer: loop {
687 let ch = match byte(s, 0) {
688 b'"' => break,
689 b'\\' => {
690 let b = byte(s, 1);
691 s = &s[2..];
692 match b {
693 b'x' => {
694 let (byte, rest) = backslash_x(s);
695 s = rest;
696 assert!(byte <= 0x80, "Invalid \\x byte in string literal");
David Tolnay76ebcdd2018-01-05 17:07:26 -0800697 char::from_u32(u32::from(byte)).unwrap()
David Tolnay360efd22018-01-04 23:35:26 -0800698 }
699 b'u' => {
David Tolnay76ebcdd2018-01-05 17:07:26 -0800700 let (chr, rest) = backslash_u(s);
David Tolnay360efd22018-01-04 23:35:26 -0800701 s = rest;
702 chr
703 }
704 b'n' => '\n',
705 b'r' => '\r',
706 b't' => '\t',
707 b'\\' => '\\',
708 b'0' => '\0',
709 b'\'' => '\'',
710 b'"' => '"',
David Tolnay61037c62018-01-05 16:21:03 -0800711 b'\r' | b'\n' => loop {
712 let ch = next_chr(s);
713 if ch.is_whitespace() {
714 s = &s[ch.len_utf8()..];
715 } else {
716 continue 'outer;
David Tolnay360efd22018-01-04 23:35:26 -0800717 }
David Tolnay61037c62018-01-05 16:21:03 -0800718 },
719 b => panic!("unexpected byte {:?} after \\ character in byte literal", b),
David Tolnay360efd22018-01-04 23:35:26 -0800720 }
721 }
722 b'\r' => {
723 assert_eq!(byte(s, 1), b'\n', "Bare CR not allowed in string");
724 s = &s[2..];
725 '\n'
726 }
727 _ => {
728 let ch = next_chr(s);
729 s = &s[ch.len_utf8()..];
730 ch
731 }
732 };
733 out.push(ch);
734 }
735
736 assert_eq!(s, "\"");
737 out
738 }
739
740 fn parse_lit_str_raw(mut s: &str) -> String {
741 assert_eq!(byte(s, 0), b'r');
742 s = &s[1..];
743
744 let mut pounds = 0;
745 while byte(s, pounds) == b'#' {
746 pounds += 1;
747 }
748 assert_eq!(byte(s, pounds), b'"');
749 assert_eq!(byte(s, s.len() - pounds - 1), b'"');
750 for end in s[s.len() - pounds..].bytes() {
751 assert_eq!(end, b'#');
752 }
753
754 s[pounds + 1..s.len() - pounds - 1].to_owned()
755 }
756
757 pub fn parse_lit_byte_str(s: &str) -> Vec<u8> {
758 assert_eq!(byte(s, 0), b'b');
759 match byte(s, 1) {
760 b'"' => parse_lit_byte_str_cooked(s),
761 b'r' => parse_lit_byte_str_raw(s),
762 _ => unreachable!(),
763 }
764 }
765
David Tolnay76ebcdd2018-01-05 17:07:26 -0800766 // Clippy false positive
767 // https://github.com/rust-lang-nursery/rust-clippy/issues/2329
768 #[cfg_attr(feature = "cargo-clippy", allow(needless_continue))]
David Tolnay360efd22018-01-04 23:35:26 -0800769 fn parse_lit_byte_str_cooked(mut s: &str) -> Vec<u8> {
770 assert_eq!(byte(s, 0), b'b');
771 assert_eq!(byte(s, 1), b'"');
772 s = &s[2..];
773
774 // We're going to want to have slices which don't respect codepoint boundaries.
775 let mut s = s.as_bytes();
776
777 let mut out = Vec::new();
778 'outer: loop {
779 let byte = match byte(s, 0) {
780 b'"' => break,
781 b'\\' => {
782 let b = byte(s, 1);
783 s = &s[2..];
784 match b {
785 b'x' => {
786 let (b, rest) = backslash_x(s);
787 s = rest;
788 b
789 }
790 b'n' => b'\n',
791 b'r' => b'\r',
792 b't' => b'\t',
793 b'\\' => b'\\',
794 b'0' => b'\0',
795 b'\'' => b'\'',
796 b'"' => b'"',
David Tolnay61037c62018-01-05 16:21:03 -0800797 b'\r' | b'\n' => loop {
798 let byte = byte(s, 0);
David Tolnay76ebcdd2018-01-05 17:07:26 -0800799 let ch = char::from_u32(u32::from(byte)).unwrap();
David Tolnay61037c62018-01-05 16:21:03 -0800800 if ch.is_whitespace() {
801 s = &s[1..];
802 } else {
803 continue 'outer;
David Tolnay360efd22018-01-04 23:35:26 -0800804 }
David Tolnay61037c62018-01-05 16:21:03 -0800805 },
806 b => panic!("unexpected byte {:?} after \\ character in byte literal", b),
David Tolnay360efd22018-01-04 23:35:26 -0800807 }
808 }
809 b'\r' => {
810 assert_eq!(byte(s, 1), b'\n', "Bare CR not allowed in string");
811 s = &s[2..];
812 b'\n'
813 }
814 b => {
815 s = &s[1..];
816 b
817 }
818 };
819 out.push(byte);
820 }
821
822 assert_eq!(s, b"\"");
823 out
824 }
825
826 fn parse_lit_byte_str_raw(s: &str) -> Vec<u8> {
827 assert_eq!(byte(s, 0), b'b');
828 parse_lit_str_raw(&s[1..]).into_bytes()
829 }
830
831 pub fn parse_lit_byte(s: &str) -> u8 {
832 assert_eq!(byte(s, 0), b'b');
833 assert_eq!(byte(s, 1), b'\'');
834
835 // We're going to want to have slices which don't respect codepoint boundaries.
836 let mut s = s[2..].as_bytes();
837
838 let b = match byte(s, 0) {
839 b'\\' => {
840 let b = byte(s, 1);
841 s = &s[2..];
842 match b {
843 b'x' => {
844 let (b, rest) = backslash_x(s);
845 s = rest;
846 b
847 }
848 b'n' => b'\n',
849 b'r' => b'\r',
850 b't' => b'\t',
851 b'\\' => b'\\',
852 b'0' => b'\0',
853 b'\'' => b'\'',
854 b'"' => b'"',
David Tolnay61037c62018-01-05 16:21:03 -0800855 b => panic!("unexpected byte {:?} after \\ character in byte literal", b),
David Tolnay360efd22018-01-04 23:35:26 -0800856 }
857 }
858 b => {
859 s = &s[1..];
860 b
861 }
862 };
863
864 assert_eq!(byte(s, 0), b'\'');
865 b
866 }
867
868 pub fn parse_lit_char(mut s: &str) -> char {
869 assert_eq!(byte(s, 0), b'\'');
870 s = &s[1..];
871
872 let ch = match byte(s, 0) {
873 b'\\' => {
874 let b = byte(s, 1);
875 s = &s[2..];
876 match b {
877 b'x' => {
878 let (byte, rest) = backslash_x(s);
879 s = rest;
880 assert!(byte <= 0x80, "Invalid \\x byte in string literal");
David Tolnay76ebcdd2018-01-05 17:07:26 -0800881 char::from_u32(u32::from(byte)).unwrap()
David Tolnay360efd22018-01-04 23:35:26 -0800882 }
883 b'u' => {
884 let (chr, rest) = backslash_u(s);
885 s = rest;
886 chr
887 }
888 b'n' => '\n',
889 b'r' => '\r',
890 b't' => '\t',
891 b'\\' => '\\',
892 b'0' => '\0',
893 b'\'' => '\'',
894 b'"' => '"',
David Tolnay61037c62018-01-05 16:21:03 -0800895 b => panic!("unexpected byte {:?} after \\ character in byte literal", b),
David Tolnay360efd22018-01-04 23:35:26 -0800896 }
897 }
898 _ => {
899 let ch = next_chr(s);
900 s = &s[ch.len_utf8()..];
901 ch
902 }
903 };
904 assert_eq!(s, "\'", "Expected end of char literal");
905 ch
906 }
907
908 fn backslash_x<S>(s: &S) -> (u8, &S)
David Tolnay61037c62018-01-05 16:21:03 -0800909 where
910 S: Index<RangeFrom<usize>, Output = S> + AsRef<[u8]> + ?Sized,
David Tolnay360efd22018-01-04 23:35:26 -0800911 {
912 let mut ch = 0;
913 let b0 = byte(s, 0);
914 let b1 = byte(s, 1);
915 ch += 0x10 * match b0 {
916 b'0'...b'9' => b0 - b'0',
917 b'a'...b'f' => 10 + (b0 - b'a'),
918 b'A'...b'F' => 10 + (b0 - b'A'),
919 _ => panic!("unexpected non-hex character after \\x"),
920 };
David Tolnay76ebcdd2018-01-05 17:07:26 -0800921 ch += match b1 {
David Tolnay360efd22018-01-04 23:35:26 -0800922 b'0'...b'9' => b1 - b'0',
923 b'a'...b'f' => 10 + (b1 - b'a'),
924 b'A'...b'F' => 10 + (b1 - b'A'),
925 _ => panic!("unexpected non-hex character after \\x"),
926 };
927 (ch, &s[2..])
928 }
929
930 fn backslash_u(mut s: &str) -> (char, &str) {
931 if byte(s, 0) != b'{' {
932 panic!("expected {{ after \\u");
933 }
934 s = &s[1..];
935
936 let mut ch = 0;
937 for _ in 0..6 {
938 let b = byte(s, 0);
939 match b {
940 b'0'...b'9' => {
941 ch *= 0x10;
David Tolnay76ebcdd2018-01-05 17:07:26 -0800942 ch += u32::from(b - b'0');
David Tolnay360efd22018-01-04 23:35:26 -0800943 s = &s[1..];
944 }
945 b'a'...b'f' => {
946 ch *= 0x10;
David Tolnay76ebcdd2018-01-05 17:07:26 -0800947 ch += u32::from(10 + b - b'a');
David Tolnay360efd22018-01-04 23:35:26 -0800948 s = &s[1..];
949 }
950 b'A'...b'F' => {
951 ch *= 0x10;
David Tolnay76ebcdd2018-01-05 17:07:26 -0800952 ch += u32::from(10 + b - b'A');
David Tolnay360efd22018-01-04 23:35:26 -0800953 s = &s[1..];
954 }
955 b'}' => break,
956 _ => panic!("unexpected non-hex character after \\u"),
957 }
958 }
959 assert!(byte(s, 0) == b'}');
960 s = &s[1..];
961
962 if let Some(ch) = char::from_u32(ch) {
963 (ch, s)
964 } else {
965 panic!("character code {:x} is not a valid unicode character", ch);
966 }
967 }
968
969 pub fn parse_lit_int(mut s: &str) -> Option<u64> {
970 let base = match (byte(s, 0), byte(s, 1)) {
971 (b'0', b'x') => {
972 s = &s[2..];
973 16
974 }
975 (b'0', b'o') => {
976 s = &s[2..];
977 8
978 }
979 (b'0', b'b') => {
980 s = &s[2..];
981 2
982 }
983 (b'0'...b'9', _) => 10,
984 _ => unreachable!(),
985 };
986
987 let mut value = 0u64;
988 loop {
989 let b = byte(s, 0);
990 let digit = match b {
David Tolnay76ebcdd2018-01-05 17:07:26 -0800991 b'0'...b'9' => u64::from(b - b'0'),
992 b'a'...b'f' if base > 10 => 10 + u64::from(b - b'a'),
993 b'A'...b'F' if base > 10 => 10 + u64::from(b - b'A'),
David Tolnay360efd22018-01-04 23:35:26 -0800994 b'_' => {
995 s = &s[1..];
996 continue;
997 }
998 // NOTE: Looking at a floating point literal, we don't want to
999 // consider these integers.
1000 b'.' if base == 10 => return None,
1001 b'e' | b'E' if base == 10 => return None,
1002 _ => break,
1003 };
1004
1005 if digit >= base {
1006 panic!("Unexpected digit {:x} out of base range", digit);
1007 }
1008
1009 value = match value.checked_mul(base) {
1010 Some(value) => value,
1011 None => return None,
1012 };
1013 value = match value.checked_add(digit) {
1014 Some(value) => value,
1015 None => return None,
1016 };
1017 s = &s[1..];
1018 }
1019
1020 Some(value)
1021 }
1022
1023 pub fn parse_lit_float(input: &str) -> f64 {
1024 // Rust's floating point literals are very similar to the ones parsed by
1025 // the standard library, except that rust's literals can contain
1026 // ignorable underscores. Let's remove those underscores.
1027 let mut bytes = input.to_owned().into_bytes();
1028 let mut write = 0;
1029 for read in 0..bytes.len() {
1030 if bytes[read] == b'_' {
1031 continue; // Don't increase write
David Tolnay76ebcdd2018-01-05 17:07:26 -08001032 }
1033 if write != read {
David Tolnay360efd22018-01-04 23:35:26 -08001034 let x = bytes[read];
1035 bytes[write] = x;
1036 }
1037 write += 1;
1038 }
1039 bytes.truncate(write);
1040 let input = String::from_utf8(bytes).unwrap();
David Tolnay76ebcdd2018-01-05 17:07:26 -08001041 let end = input.find('f').unwrap_or_else(|| input.len());
David Tolnay360efd22018-01-04 23:35:26 -08001042 input[..end].parse().unwrap()
1043 }
1044
1045 pub fn to_literal(s: &str) -> Literal {
1046 let stream = s.parse::<TokenStream>().unwrap();
Alex Crichton9a4dca22018-03-28 06:32:19 -07001047 match stream.into_iter().next().unwrap() {
1048 TokenTree::Literal(l) => l,
David Tolnay360efd22018-01-04 23:35:26 -08001049 _ => unreachable!(),
David Tolnayf17fd2f2016-10-07 23:38:08 -07001050 }
1051 }
David Tolnayf4bbbd92016-09-23 14:41:55 -07001052}