blob: 1b9efac49291e1348d535717c8609dd71d1c2200 [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 Tolnay203557a2017-12-27 23:59:33 -0500436 use parse_error;
David Tolnayf4bbbd92016-09-23 14:41:55 -0700437
David Tolnay4fb71232018-08-25 23:14:50 -0400438 impl Parse for Lit {
439 fn parse(input: ParseStream) -> Result<Self> {
440 input.step_cursor(|cursor| {
441 match cursor.literal() {
442 Some((lit, rest)) => {
443 if lit.to_string().starts_with('/') {
444 // Doc comment literal which is not a Syn literal
445 parse_error()
446 } else {
447 Ok((Lit::new(lit), rest))
448 }
David Tolnay7037c9b2018-01-23 09:34:09 -0800449 }
David Tolnay4fb71232018-08-25 23:14:50 -0400450 _ => match cursor.ident() {
451 Some((ident, rest)) => Ok((
452 Lit::Bool(LitBool {
453 value: if ident == "true" {
454 true
455 } else if ident == "false" {
456 false
457 } else {
458 return parse_error();
459 },
460 span: ident.span(),
461 }),
462 rest,
463 )),
464 _ => parse_error(),
465 },
David Tolnay7037c9b2018-01-23 09:34:09 -0800466 }
David Tolnay4fb71232018-08-25 23:14:50 -0400467 })
Sergio Benitez5680d6a2017-12-29 11:20:29 -0800468 }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700469 }
David Tolnay360efd22018-01-04 23:35:26 -0800470
David Tolnaya7d69fc2018-08-26 13:30:24 -0400471 impl Parse for LitStr {
472 fn parse(input: ParseStream) -> Result<Self> {
473 let head = input.fork();
474 match input.parse()? {
475 Lit::Str(lit) => Ok(lit),
476 _ => Err(head.error("expected string literal")),
477 }
478 }
479 }
David Tolnay360efd22018-01-04 23:35:26 -0800480
David Tolnaya7d69fc2018-08-26 13:30:24 -0400481 impl Parse for LitByteStr {
482 fn parse(input: ParseStream) -> Result<Self> {
483 let head = input.fork();
484 match input.parse()? {
485 Lit::ByteStr(lit) => Ok(lit),
486 _ => Err(head.error("expected byte string literal")),
487 }
488 }
489 }
David Tolnay360efd22018-01-04 23:35:26 -0800490
David Tolnaya7d69fc2018-08-26 13:30:24 -0400491 impl Parse for LitByte {
492 fn parse(input: ParseStream) -> Result<Self> {
493 let head = input.fork();
494 match input.parse()? {
495 Lit::Byte(lit) => Ok(lit),
496 _ => Err(head.error("expected byte literal")),
497 }
498 }
499 }
David Tolnay360efd22018-01-04 23:35:26 -0800500
David Tolnaya7d69fc2018-08-26 13:30:24 -0400501 impl Parse for LitChar {
502 fn parse(input: ParseStream) -> Result<Self> {
503 let head = input.fork();
504 match input.parse()? {
505 Lit::Char(lit) => Ok(lit),
506 _ => Err(head.error("expected character literal")),
507 }
508 }
509 }
David Tolnay360efd22018-01-04 23:35:26 -0800510
David Tolnaya7d69fc2018-08-26 13:30:24 -0400511 impl Parse for LitInt {
512 fn parse(input: ParseStream) -> Result<Self> {
513 let head = input.fork();
514 match input.parse()? {
515 Lit::Int(lit) => Ok(lit),
516 _ => Err(head.error("expected integer literal")),
517 }
518 }
519 }
David Tolnay360efd22018-01-04 23:35:26 -0800520
David Tolnaya7d69fc2018-08-26 13:30:24 -0400521 impl Parse for LitFloat {
522 fn parse(input: ParseStream) -> Result<Self> {
523 let head = input.fork();
524 match input.parse()? {
525 Lit::Float(lit) => Ok(lit),
526 _ => Err(head.error("expected floating point literal")),
527 }
528 }
529 }
David Tolnay360efd22018-01-04 23:35:26 -0800530
David Tolnaya7d69fc2018-08-26 13:30:24 -0400531 impl Parse for LitBool {
532 fn parse(input: ParseStream) -> Result<Self> {
533 let head = input.fork();
534 match input.parse()? {
535 Lit::Bool(lit) => Ok(lit),
536 _ => Err(head.error("expected boolean literal")),
537 }
538 }
539 }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700540}
541
542#[cfg(feature = "printing")]
543mod printing {
544 use super::*;
Alex Crichtona74a1c82018-05-16 10:20:44 -0700545 use proc_macro2::TokenStream;
David Tolnay65fb5662018-05-20 20:02:28 -0700546 use quote::{ToTokens, TokenStreamExt};
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700547
David Tolnay360efd22018-01-04 23:35:26 -0800548 impl ToTokens for LitStr {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700549 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700550 self.token.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800551 }
552 }
553
554 impl ToTokens for LitByteStr {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700555 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700556 self.token.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800557 }
558 }
559
560 impl ToTokens for LitByte {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700561 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700562 self.token.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800563 }
564 }
565
566 impl ToTokens for LitChar {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700567 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700568 self.token.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800569 }
570 }
571
572 impl ToTokens for LitInt {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700573 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700574 self.token.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800575 }
576 }
577
578 impl ToTokens for LitFloat {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700579 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700580 self.token.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800581 }
582 }
583
584 impl ToTokens for LitBool {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700585 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700586 let s = if self.value { "true" } else { "false" };
Alex Crichtona74a1c82018-05-16 10:20:44 -0700587 tokens.append(Ident::new(s, self.span));
David Tolnay360efd22018-01-04 23:35:26 -0800588 }
589 }
590
591 impl ToTokens for LitVerbatim {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700592 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700593 self.token.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800594 }
595 }
596}
597
598mod value {
599 use super::*;
David Tolnay94d2b792018-04-29 12:26:10 -0700600 use proc_macro2::TokenStream;
David Tolnay360efd22018-01-04 23:35:26 -0800601 use std::char;
602 use std::ops::{Index, RangeFrom};
David Tolnay360efd22018-01-04 23:35:26 -0800603
David Tolnay7d1d1282018-01-06 16:10:51 -0800604 impl Lit {
David Tolnay780292d2018-01-22 23:26:44 -0800605 /// Interpret a Syn literal from a proc-macro2 literal.
606 ///
607 /// Not all proc-macro2 literals are valid Syn literals. In particular,
608 /// doc comments are considered by proc-macro2 to be literals but in Syn
609 /// they are [`Attribute`].
610 ///
611 /// [`Attribute`]: struct.Attribute.html
612 ///
613 /// # Panics
614 ///
615 /// Panics if the input is a doc comment literal.
Alex Crichton9a4dca22018-03-28 06:32:19 -0700616 pub fn new(token: Literal) -> Self {
David Tolnay7d1d1282018-01-06 16:10:51 -0800617 let value = token.to_string();
618
619 match value::byte(&value, 0) {
David Tolnay94d2b792018-04-29 12:26:10 -0700620 b'"' | b'r' => return Lit::Str(LitStr { token: token }),
David Tolnay7d1d1282018-01-06 16:10:51 -0800621 b'b' => match value::byte(&value, 1) {
David Tolnay94d2b792018-04-29 12:26:10 -0700622 b'"' | b'r' => return Lit::ByteStr(LitByteStr { token: token }),
623 b'\'' => return Lit::Byte(LitByte { token: token }),
David Tolnay7d1d1282018-01-06 16:10:51 -0800624 _ => {}
625 },
David Tolnay94d2b792018-04-29 12:26:10 -0700626 b'\'' => return Lit::Char(LitChar { token: token }),
David Tolnay7d1d1282018-01-06 16:10:51 -0800627 b'0'...b'9' => if number_is_int(&value) {
David Tolnay94d2b792018-04-29 12:26:10 -0700628 return Lit::Int(LitInt { token: token });
David Tolnay7d1d1282018-01-06 16:10:51 -0800629 } else if number_is_float(&value) {
David Tolnay94d2b792018-04-29 12:26:10 -0700630 return Lit::Float(LitFloat { token: token });
David Tolnay7d1d1282018-01-06 16:10:51 -0800631 } else {
632 // number overflow
David Tolnay94d2b792018-04-29 12:26:10 -0700633 return Lit::Verbatim(LitVerbatim { token: token });
David Tolnay7d1d1282018-01-06 16:10:51 -0800634 },
635 _ => if value == "true" || value == "false" {
636 return Lit::Bool(LitBool {
637 value: value == "true",
Alex Crichton9a4dca22018-03-28 06:32:19 -0700638 span: token.span(),
David Tolnay7d1d1282018-01-06 16:10:51 -0800639 });
640 },
641 }
642
643 panic!("Unrecognized literal: {}", value);
644 }
645 }
646
647 fn number_is_int(value: &str) -> bool {
648 if number_is_float(value) {
649 false
650 } else {
651 value::parse_lit_int(value).is_some()
652 }
653 }
654
655 fn number_is_float(value: &str) -> bool {
656 if value.contains('.') {
657 true
658 } else if value.starts_with("0x") || value.ends_with("size") {
659 false
660 } else {
661 value.contains('e') || value.contains('E')
662 }
663 }
664
David Tolnay360efd22018-01-04 23:35:26 -0800665 /// Get the byte at offset idx, or a default of `b'\0'` if we're looking
666 /// past the end of the input buffer.
667 pub fn byte<S: AsRef<[u8]> + ?Sized>(s: &S, idx: usize) -> u8 {
668 let s = s.as_ref();
669 if idx < s.len() {
670 s[idx]
671 } else {
672 0
673 }
674 }
675
676 fn next_chr(s: &str) -> char {
677 s.chars().next().unwrap_or('\0')
678 }
679
680 pub fn parse_lit_str(s: &str) -> String {
681 match byte(s, 0) {
682 b'"' => parse_lit_str_cooked(s),
683 b'r' => parse_lit_str_raw(s),
684 _ => unreachable!(),
685 }
686 }
687
David Tolnay76ebcdd2018-01-05 17:07:26 -0800688 // Clippy false positive
689 // https://github.com/rust-lang-nursery/rust-clippy/issues/2329
690 #[cfg_attr(feature = "cargo-clippy", allow(needless_continue))]
David Tolnay360efd22018-01-04 23:35:26 -0800691 fn parse_lit_str_cooked(mut s: &str) -> String {
692 assert_eq!(byte(s, 0), b'"');
693 s = &s[1..];
694
695 let mut out = String::new();
696 'outer: loop {
697 let ch = match byte(s, 0) {
698 b'"' => break,
699 b'\\' => {
700 let b = byte(s, 1);
701 s = &s[2..];
702 match b {
703 b'x' => {
704 let (byte, rest) = backslash_x(s);
705 s = rest;
706 assert!(byte <= 0x80, "Invalid \\x byte in string literal");
David Tolnay76ebcdd2018-01-05 17:07:26 -0800707 char::from_u32(u32::from(byte)).unwrap()
David Tolnay360efd22018-01-04 23:35:26 -0800708 }
709 b'u' => {
David Tolnay76ebcdd2018-01-05 17:07:26 -0800710 let (chr, rest) = backslash_u(s);
David Tolnay360efd22018-01-04 23:35:26 -0800711 s = rest;
712 chr
713 }
714 b'n' => '\n',
715 b'r' => '\r',
716 b't' => '\t',
717 b'\\' => '\\',
718 b'0' => '\0',
719 b'\'' => '\'',
720 b'"' => '"',
David Tolnay61037c62018-01-05 16:21:03 -0800721 b'\r' | b'\n' => loop {
722 let ch = next_chr(s);
723 if ch.is_whitespace() {
724 s = &s[ch.len_utf8()..];
725 } else {
726 continue 'outer;
David Tolnay360efd22018-01-04 23:35:26 -0800727 }
David Tolnay61037c62018-01-05 16:21:03 -0800728 },
729 b => panic!("unexpected byte {:?} after \\ character in byte literal", b),
David Tolnay360efd22018-01-04 23:35:26 -0800730 }
731 }
732 b'\r' => {
733 assert_eq!(byte(s, 1), b'\n', "Bare CR not allowed in string");
734 s = &s[2..];
735 '\n'
736 }
737 _ => {
738 let ch = next_chr(s);
739 s = &s[ch.len_utf8()..];
740 ch
741 }
742 };
743 out.push(ch);
744 }
745
746 assert_eq!(s, "\"");
747 out
748 }
749
750 fn parse_lit_str_raw(mut s: &str) -> String {
751 assert_eq!(byte(s, 0), b'r');
752 s = &s[1..];
753
754 let mut pounds = 0;
755 while byte(s, pounds) == b'#' {
756 pounds += 1;
757 }
758 assert_eq!(byte(s, pounds), b'"');
759 assert_eq!(byte(s, s.len() - pounds - 1), b'"');
760 for end in s[s.len() - pounds..].bytes() {
761 assert_eq!(end, b'#');
762 }
763
764 s[pounds + 1..s.len() - pounds - 1].to_owned()
765 }
766
767 pub fn parse_lit_byte_str(s: &str) -> Vec<u8> {
768 assert_eq!(byte(s, 0), b'b');
769 match byte(s, 1) {
770 b'"' => parse_lit_byte_str_cooked(s),
771 b'r' => parse_lit_byte_str_raw(s),
772 _ => unreachable!(),
773 }
774 }
775
David Tolnay76ebcdd2018-01-05 17:07:26 -0800776 // Clippy false positive
777 // https://github.com/rust-lang-nursery/rust-clippy/issues/2329
778 #[cfg_attr(feature = "cargo-clippy", allow(needless_continue))]
David Tolnay360efd22018-01-04 23:35:26 -0800779 fn parse_lit_byte_str_cooked(mut s: &str) -> Vec<u8> {
780 assert_eq!(byte(s, 0), b'b');
781 assert_eq!(byte(s, 1), b'"');
782 s = &s[2..];
783
784 // We're going to want to have slices which don't respect codepoint boundaries.
785 let mut s = s.as_bytes();
786
787 let mut out = Vec::new();
788 'outer: loop {
789 let byte = match byte(s, 0) {
790 b'"' => break,
791 b'\\' => {
792 let b = byte(s, 1);
793 s = &s[2..];
794 match b {
795 b'x' => {
796 let (b, rest) = backslash_x(s);
797 s = rest;
798 b
799 }
800 b'n' => b'\n',
801 b'r' => b'\r',
802 b't' => b'\t',
803 b'\\' => b'\\',
804 b'0' => b'\0',
805 b'\'' => b'\'',
806 b'"' => b'"',
David Tolnay61037c62018-01-05 16:21:03 -0800807 b'\r' | b'\n' => loop {
808 let byte = byte(s, 0);
David Tolnay76ebcdd2018-01-05 17:07:26 -0800809 let ch = char::from_u32(u32::from(byte)).unwrap();
David Tolnay61037c62018-01-05 16:21:03 -0800810 if ch.is_whitespace() {
811 s = &s[1..];
812 } else {
813 continue 'outer;
David Tolnay360efd22018-01-04 23:35:26 -0800814 }
David Tolnay61037c62018-01-05 16:21:03 -0800815 },
816 b => panic!("unexpected byte {:?} after \\ character in byte literal", b),
David Tolnay360efd22018-01-04 23:35:26 -0800817 }
818 }
819 b'\r' => {
820 assert_eq!(byte(s, 1), b'\n', "Bare CR not allowed in string");
821 s = &s[2..];
822 b'\n'
823 }
824 b => {
825 s = &s[1..];
826 b
827 }
828 };
829 out.push(byte);
830 }
831
832 assert_eq!(s, b"\"");
833 out
834 }
835
836 fn parse_lit_byte_str_raw(s: &str) -> Vec<u8> {
837 assert_eq!(byte(s, 0), b'b');
838 parse_lit_str_raw(&s[1..]).into_bytes()
839 }
840
841 pub fn parse_lit_byte(s: &str) -> u8 {
842 assert_eq!(byte(s, 0), b'b');
843 assert_eq!(byte(s, 1), b'\'');
844
845 // We're going to want to have slices which don't respect codepoint boundaries.
846 let mut s = s[2..].as_bytes();
847
848 let b = match byte(s, 0) {
849 b'\\' => {
850 let b = byte(s, 1);
851 s = &s[2..];
852 match b {
853 b'x' => {
854 let (b, rest) = backslash_x(s);
855 s = rest;
856 b
857 }
858 b'n' => b'\n',
859 b'r' => b'\r',
860 b't' => b'\t',
861 b'\\' => b'\\',
862 b'0' => b'\0',
863 b'\'' => b'\'',
864 b'"' => b'"',
David Tolnay61037c62018-01-05 16:21:03 -0800865 b => panic!("unexpected byte {:?} after \\ character in byte literal", b),
David Tolnay360efd22018-01-04 23:35:26 -0800866 }
867 }
868 b => {
869 s = &s[1..];
870 b
871 }
872 };
873
874 assert_eq!(byte(s, 0), b'\'');
875 b
876 }
877
878 pub fn parse_lit_char(mut s: &str) -> char {
879 assert_eq!(byte(s, 0), b'\'');
880 s = &s[1..];
881
882 let ch = match byte(s, 0) {
883 b'\\' => {
884 let b = byte(s, 1);
885 s = &s[2..];
886 match b {
887 b'x' => {
888 let (byte, rest) = backslash_x(s);
889 s = rest;
890 assert!(byte <= 0x80, "Invalid \\x byte in string literal");
David Tolnay76ebcdd2018-01-05 17:07:26 -0800891 char::from_u32(u32::from(byte)).unwrap()
David Tolnay360efd22018-01-04 23:35:26 -0800892 }
893 b'u' => {
894 let (chr, rest) = backslash_u(s);
895 s = rest;
896 chr
897 }
898 b'n' => '\n',
899 b'r' => '\r',
900 b't' => '\t',
901 b'\\' => '\\',
902 b'0' => '\0',
903 b'\'' => '\'',
904 b'"' => '"',
David Tolnay61037c62018-01-05 16:21:03 -0800905 b => panic!("unexpected byte {:?} after \\ character in byte literal", b),
David Tolnay360efd22018-01-04 23:35:26 -0800906 }
907 }
908 _ => {
909 let ch = next_chr(s);
910 s = &s[ch.len_utf8()..];
911 ch
912 }
913 };
914 assert_eq!(s, "\'", "Expected end of char literal");
915 ch
916 }
917
918 fn backslash_x<S>(s: &S) -> (u8, &S)
David Tolnay61037c62018-01-05 16:21:03 -0800919 where
920 S: Index<RangeFrom<usize>, Output = S> + AsRef<[u8]> + ?Sized,
David Tolnay360efd22018-01-04 23:35:26 -0800921 {
922 let mut ch = 0;
923 let b0 = byte(s, 0);
924 let b1 = byte(s, 1);
925 ch += 0x10 * match b0 {
926 b'0'...b'9' => b0 - b'0',
927 b'a'...b'f' => 10 + (b0 - b'a'),
928 b'A'...b'F' => 10 + (b0 - b'A'),
929 _ => panic!("unexpected non-hex character after \\x"),
930 };
David Tolnay76ebcdd2018-01-05 17:07:26 -0800931 ch += match b1 {
David Tolnay360efd22018-01-04 23:35:26 -0800932 b'0'...b'9' => b1 - b'0',
933 b'a'...b'f' => 10 + (b1 - b'a'),
934 b'A'...b'F' => 10 + (b1 - b'A'),
935 _ => panic!("unexpected non-hex character after \\x"),
936 };
937 (ch, &s[2..])
938 }
939
940 fn backslash_u(mut s: &str) -> (char, &str) {
941 if byte(s, 0) != b'{' {
942 panic!("expected {{ after \\u");
943 }
944 s = &s[1..];
945
946 let mut ch = 0;
947 for _ in 0..6 {
948 let b = byte(s, 0);
949 match b {
950 b'0'...b'9' => {
951 ch *= 0x10;
David Tolnay76ebcdd2018-01-05 17:07:26 -0800952 ch += u32::from(b - b'0');
David Tolnay360efd22018-01-04 23:35:26 -0800953 s = &s[1..];
954 }
955 b'a'...b'f' => {
956 ch *= 0x10;
David Tolnay76ebcdd2018-01-05 17:07:26 -0800957 ch += u32::from(10 + b - b'a');
David Tolnay360efd22018-01-04 23:35:26 -0800958 s = &s[1..];
959 }
960 b'A'...b'F' => {
961 ch *= 0x10;
David Tolnay76ebcdd2018-01-05 17:07:26 -0800962 ch += u32::from(10 + b - b'A');
David Tolnay360efd22018-01-04 23:35:26 -0800963 s = &s[1..];
964 }
965 b'}' => break,
966 _ => panic!("unexpected non-hex character after \\u"),
967 }
968 }
969 assert!(byte(s, 0) == b'}');
970 s = &s[1..];
971
972 if let Some(ch) = char::from_u32(ch) {
973 (ch, s)
974 } else {
975 panic!("character code {:x} is not a valid unicode character", ch);
976 }
977 }
978
979 pub fn parse_lit_int(mut s: &str) -> Option<u64> {
980 let base = match (byte(s, 0), byte(s, 1)) {
981 (b'0', b'x') => {
982 s = &s[2..];
983 16
984 }
985 (b'0', b'o') => {
986 s = &s[2..];
987 8
988 }
989 (b'0', b'b') => {
990 s = &s[2..];
991 2
992 }
993 (b'0'...b'9', _) => 10,
994 _ => unreachable!(),
995 };
996
997 let mut value = 0u64;
998 loop {
999 let b = byte(s, 0);
1000 let digit = match b {
David Tolnay76ebcdd2018-01-05 17:07:26 -08001001 b'0'...b'9' => u64::from(b - b'0'),
1002 b'a'...b'f' if base > 10 => 10 + u64::from(b - b'a'),
1003 b'A'...b'F' if base > 10 => 10 + u64::from(b - b'A'),
David Tolnay360efd22018-01-04 23:35:26 -08001004 b'_' => {
1005 s = &s[1..];
1006 continue;
1007 }
1008 // NOTE: Looking at a floating point literal, we don't want to
1009 // consider these integers.
1010 b'.' if base == 10 => return None,
1011 b'e' | b'E' if base == 10 => return None,
1012 _ => break,
1013 };
1014
1015 if digit >= base {
1016 panic!("Unexpected digit {:x} out of base range", digit);
1017 }
1018
1019 value = match value.checked_mul(base) {
1020 Some(value) => value,
1021 None => return None,
1022 };
1023 value = match value.checked_add(digit) {
1024 Some(value) => value,
1025 None => return None,
1026 };
1027 s = &s[1..];
1028 }
1029
1030 Some(value)
1031 }
1032
1033 pub fn parse_lit_float(input: &str) -> f64 {
1034 // Rust's floating point literals are very similar to the ones parsed by
1035 // the standard library, except that rust's literals can contain
1036 // ignorable underscores. Let's remove those underscores.
1037 let mut bytes = input.to_owned().into_bytes();
1038 let mut write = 0;
1039 for read in 0..bytes.len() {
1040 if bytes[read] == b'_' {
1041 continue; // Don't increase write
David Tolnay76ebcdd2018-01-05 17:07:26 -08001042 }
1043 if write != read {
David Tolnay360efd22018-01-04 23:35:26 -08001044 let x = bytes[read];
1045 bytes[write] = x;
1046 }
1047 write += 1;
1048 }
1049 bytes.truncate(write);
1050 let input = String::from_utf8(bytes).unwrap();
David Tolnay76ebcdd2018-01-05 17:07:26 -08001051 let end = input.find('f').unwrap_or_else(|| input.len());
David Tolnay360efd22018-01-04 23:35:26 -08001052 input[..end].parse().unwrap()
1053 }
1054
1055 pub fn to_literal(s: &str) -> Literal {
1056 let stream = s.parse::<TokenStream>().unwrap();
Alex Crichton9a4dca22018-03-28 06:32:19 -07001057 match stream.into_iter().next().unwrap() {
1058 TokenTree::Literal(l) => l,
David Tolnay360efd22018-01-04 23:35:26 -08001059 _ => unreachable!(),
David Tolnayf17fd2f2016-10-07 23:38:08 -07001060 }
1061 }
David Tolnayf4bbbd92016-09-23 14:41:55 -07001062}