blob: 597048d89dc0c41bcb25f1fc3b524c6834405378 [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() {
David Tolnay9e0e8332018-08-30 17:48:48 -0700442 Some((lit, rest)) => Ok((Lit::new(lit), rest)),
David Tolnay4fb71232018-08-25 23:14:50 -0400443 _ => match cursor.ident() {
444 Some((ident, rest)) => Ok((
445 Lit::Bool(LitBool {
446 value: if ident == "true" {
447 true
448 } else if ident == "false" {
449 false
450 } else {
451 return parse_error();
452 },
453 span: ident.span(),
454 }),
455 rest,
456 )),
457 _ => parse_error(),
458 },
David Tolnay7037c9b2018-01-23 09:34:09 -0800459 }
David Tolnay4fb71232018-08-25 23:14:50 -0400460 })
Sergio Benitez5680d6a2017-12-29 11:20:29 -0800461 }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700462 }
David Tolnay360efd22018-01-04 23:35:26 -0800463
David Tolnaya7d69fc2018-08-26 13:30:24 -0400464 impl Parse for LitStr {
465 fn parse(input: ParseStream) -> Result<Self> {
466 let head = input.fork();
467 match input.parse()? {
468 Lit::Str(lit) => Ok(lit),
469 _ => Err(head.error("expected string literal")),
470 }
471 }
472 }
David Tolnay360efd22018-01-04 23:35:26 -0800473
David Tolnaya7d69fc2018-08-26 13:30:24 -0400474 impl Parse for LitByteStr {
475 fn parse(input: ParseStream) -> Result<Self> {
476 let head = input.fork();
477 match input.parse()? {
478 Lit::ByteStr(lit) => Ok(lit),
479 _ => Err(head.error("expected byte string literal")),
480 }
481 }
482 }
David Tolnay360efd22018-01-04 23:35:26 -0800483
David Tolnaya7d69fc2018-08-26 13:30:24 -0400484 impl Parse for LitByte {
485 fn parse(input: ParseStream) -> Result<Self> {
486 let head = input.fork();
487 match input.parse()? {
488 Lit::Byte(lit) => Ok(lit),
489 _ => Err(head.error("expected byte literal")),
490 }
491 }
492 }
David Tolnay360efd22018-01-04 23:35:26 -0800493
David Tolnaya7d69fc2018-08-26 13:30:24 -0400494 impl Parse for LitChar {
495 fn parse(input: ParseStream) -> Result<Self> {
496 let head = input.fork();
497 match input.parse()? {
498 Lit::Char(lit) => Ok(lit),
499 _ => Err(head.error("expected character literal")),
500 }
501 }
502 }
David Tolnay360efd22018-01-04 23:35:26 -0800503
David Tolnaya7d69fc2018-08-26 13:30:24 -0400504 impl Parse for LitInt {
505 fn parse(input: ParseStream) -> Result<Self> {
506 let head = input.fork();
507 match input.parse()? {
508 Lit::Int(lit) => Ok(lit),
509 _ => Err(head.error("expected integer literal")),
510 }
511 }
512 }
David Tolnay360efd22018-01-04 23:35:26 -0800513
David Tolnaya7d69fc2018-08-26 13:30:24 -0400514 impl Parse for LitFloat {
515 fn parse(input: ParseStream) -> Result<Self> {
516 let head = input.fork();
517 match input.parse()? {
518 Lit::Float(lit) => Ok(lit),
519 _ => Err(head.error("expected floating point literal")),
520 }
521 }
522 }
David Tolnay360efd22018-01-04 23:35:26 -0800523
David Tolnaya7d69fc2018-08-26 13:30:24 -0400524 impl Parse for LitBool {
525 fn parse(input: ParseStream) -> Result<Self> {
526 let head = input.fork();
527 match input.parse()? {
528 Lit::Bool(lit) => Ok(lit),
529 _ => Err(head.error("expected boolean literal")),
530 }
531 }
532 }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700533}
534
535#[cfg(feature = "printing")]
536mod printing {
537 use super::*;
Alex Crichtona74a1c82018-05-16 10:20:44 -0700538 use proc_macro2::TokenStream;
David Tolnay65fb5662018-05-20 20:02:28 -0700539 use quote::{ToTokens, TokenStreamExt};
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700540
David Tolnay360efd22018-01-04 23:35:26 -0800541 impl ToTokens for LitStr {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700542 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700543 self.token.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800544 }
545 }
546
547 impl ToTokens for LitByteStr {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700548 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700549 self.token.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800550 }
551 }
552
553 impl ToTokens for LitByte {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700554 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700555 self.token.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800556 }
557 }
558
559 impl ToTokens for LitChar {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700560 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700561 self.token.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800562 }
563 }
564
565 impl ToTokens for LitInt {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700566 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700567 self.token.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800568 }
569 }
570
571 impl ToTokens for LitFloat {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700572 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700573 self.token.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800574 }
575 }
576
577 impl ToTokens for LitBool {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700578 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700579 let s = if self.value { "true" } else { "false" };
Alex Crichtona74a1c82018-05-16 10:20:44 -0700580 tokens.append(Ident::new(s, self.span));
David Tolnay360efd22018-01-04 23:35:26 -0800581 }
582 }
583
584 impl ToTokens for LitVerbatim {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700585 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700586 self.token.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800587 }
588 }
589}
590
591mod value {
592 use super::*;
David Tolnay94d2b792018-04-29 12:26:10 -0700593 use proc_macro2::TokenStream;
David Tolnay360efd22018-01-04 23:35:26 -0800594 use std::char;
595 use std::ops::{Index, RangeFrom};
David Tolnay360efd22018-01-04 23:35:26 -0800596
David Tolnay7d1d1282018-01-06 16:10:51 -0800597 impl Lit {
David Tolnay780292d2018-01-22 23:26:44 -0800598 /// Interpret a Syn literal from a proc-macro2 literal.
599 ///
600 /// Not all proc-macro2 literals are valid Syn literals. In particular,
601 /// doc comments are considered by proc-macro2 to be literals but in Syn
602 /// they are [`Attribute`].
603 ///
604 /// [`Attribute`]: struct.Attribute.html
605 ///
606 /// # Panics
607 ///
608 /// Panics if the input is a doc comment literal.
Alex Crichton9a4dca22018-03-28 06:32:19 -0700609 pub fn new(token: Literal) -> Self {
David Tolnay7d1d1282018-01-06 16:10:51 -0800610 let value = token.to_string();
611
612 match value::byte(&value, 0) {
David Tolnay94d2b792018-04-29 12:26:10 -0700613 b'"' | b'r' => return Lit::Str(LitStr { token: token }),
David Tolnay7d1d1282018-01-06 16:10:51 -0800614 b'b' => match value::byte(&value, 1) {
David Tolnay94d2b792018-04-29 12:26:10 -0700615 b'"' | b'r' => return Lit::ByteStr(LitByteStr { token: token }),
616 b'\'' => return Lit::Byte(LitByte { token: token }),
David Tolnay7d1d1282018-01-06 16:10:51 -0800617 _ => {}
618 },
David Tolnay94d2b792018-04-29 12:26:10 -0700619 b'\'' => return Lit::Char(LitChar { token: token }),
David Tolnay7d1d1282018-01-06 16:10:51 -0800620 b'0'...b'9' => if number_is_int(&value) {
David Tolnay94d2b792018-04-29 12:26:10 -0700621 return Lit::Int(LitInt { token: token });
David Tolnay7d1d1282018-01-06 16:10:51 -0800622 } else if number_is_float(&value) {
David Tolnay94d2b792018-04-29 12:26:10 -0700623 return Lit::Float(LitFloat { token: token });
David Tolnay7d1d1282018-01-06 16:10:51 -0800624 } else {
625 // number overflow
David Tolnay94d2b792018-04-29 12:26:10 -0700626 return Lit::Verbatim(LitVerbatim { token: token });
David Tolnay7d1d1282018-01-06 16:10:51 -0800627 },
628 _ => if value == "true" || value == "false" {
629 return Lit::Bool(LitBool {
630 value: value == "true",
Alex Crichton9a4dca22018-03-28 06:32:19 -0700631 span: token.span(),
David Tolnay7d1d1282018-01-06 16:10:51 -0800632 });
633 },
634 }
635
636 panic!("Unrecognized literal: {}", value);
637 }
638 }
639
640 fn number_is_int(value: &str) -> bool {
641 if number_is_float(value) {
642 false
643 } else {
644 value::parse_lit_int(value).is_some()
645 }
646 }
647
648 fn number_is_float(value: &str) -> bool {
649 if value.contains('.') {
650 true
651 } else if value.starts_with("0x") || value.ends_with("size") {
652 false
653 } else {
654 value.contains('e') || value.contains('E')
655 }
656 }
657
David Tolnay360efd22018-01-04 23:35:26 -0800658 /// Get the byte at offset idx, or a default of `b'\0'` if we're looking
659 /// past the end of the input buffer.
660 pub fn byte<S: AsRef<[u8]> + ?Sized>(s: &S, idx: usize) -> u8 {
661 let s = s.as_ref();
662 if idx < s.len() {
663 s[idx]
664 } else {
665 0
666 }
667 }
668
669 fn next_chr(s: &str) -> char {
670 s.chars().next().unwrap_or('\0')
671 }
672
673 pub fn parse_lit_str(s: &str) -> String {
674 match byte(s, 0) {
675 b'"' => parse_lit_str_cooked(s),
676 b'r' => parse_lit_str_raw(s),
677 _ => unreachable!(),
678 }
679 }
680
David Tolnay76ebcdd2018-01-05 17:07:26 -0800681 // Clippy false positive
682 // https://github.com/rust-lang-nursery/rust-clippy/issues/2329
683 #[cfg_attr(feature = "cargo-clippy", allow(needless_continue))]
David Tolnay360efd22018-01-04 23:35:26 -0800684 fn parse_lit_str_cooked(mut s: &str) -> String {
685 assert_eq!(byte(s, 0), b'"');
686 s = &s[1..];
687
688 let mut out = String::new();
689 'outer: loop {
690 let ch = match byte(s, 0) {
691 b'"' => break,
692 b'\\' => {
693 let b = byte(s, 1);
694 s = &s[2..];
695 match b {
696 b'x' => {
697 let (byte, rest) = backslash_x(s);
698 s = rest;
699 assert!(byte <= 0x80, "Invalid \\x byte in string literal");
David Tolnay76ebcdd2018-01-05 17:07:26 -0800700 char::from_u32(u32::from(byte)).unwrap()
David Tolnay360efd22018-01-04 23:35:26 -0800701 }
702 b'u' => {
David Tolnay76ebcdd2018-01-05 17:07:26 -0800703 let (chr, rest) = backslash_u(s);
David Tolnay360efd22018-01-04 23:35:26 -0800704 s = rest;
705 chr
706 }
707 b'n' => '\n',
708 b'r' => '\r',
709 b't' => '\t',
710 b'\\' => '\\',
711 b'0' => '\0',
712 b'\'' => '\'',
713 b'"' => '"',
David Tolnay61037c62018-01-05 16:21:03 -0800714 b'\r' | b'\n' => loop {
715 let ch = next_chr(s);
716 if ch.is_whitespace() {
717 s = &s[ch.len_utf8()..];
718 } else {
719 continue 'outer;
David Tolnay360efd22018-01-04 23:35:26 -0800720 }
David Tolnay61037c62018-01-05 16:21:03 -0800721 },
722 b => panic!("unexpected byte {:?} after \\ character in byte literal", b),
David Tolnay360efd22018-01-04 23:35:26 -0800723 }
724 }
725 b'\r' => {
726 assert_eq!(byte(s, 1), b'\n', "Bare CR not allowed in string");
727 s = &s[2..];
728 '\n'
729 }
730 _ => {
731 let ch = next_chr(s);
732 s = &s[ch.len_utf8()..];
733 ch
734 }
735 };
736 out.push(ch);
737 }
738
739 assert_eq!(s, "\"");
740 out
741 }
742
743 fn parse_lit_str_raw(mut s: &str) -> String {
744 assert_eq!(byte(s, 0), b'r');
745 s = &s[1..];
746
747 let mut pounds = 0;
748 while byte(s, pounds) == b'#' {
749 pounds += 1;
750 }
751 assert_eq!(byte(s, pounds), b'"');
752 assert_eq!(byte(s, s.len() - pounds - 1), b'"');
753 for end in s[s.len() - pounds..].bytes() {
754 assert_eq!(end, b'#');
755 }
756
757 s[pounds + 1..s.len() - pounds - 1].to_owned()
758 }
759
760 pub fn parse_lit_byte_str(s: &str) -> Vec<u8> {
761 assert_eq!(byte(s, 0), b'b');
762 match byte(s, 1) {
763 b'"' => parse_lit_byte_str_cooked(s),
764 b'r' => parse_lit_byte_str_raw(s),
765 _ => unreachable!(),
766 }
767 }
768
David Tolnay76ebcdd2018-01-05 17:07:26 -0800769 // Clippy false positive
770 // https://github.com/rust-lang-nursery/rust-clippy/issues/2329
771 #[cfg_attr(feature = "cargo-clippy", allow(needless_continue))]
David Tolnay360efd22018-01-04 23:35:26 -0800772 fn parse_lit_byte_str_cooked(mut s: &str) -> Vec<u8> {
773 assert_eq!(byte(s, 0), b'b');
774 assert_eq!(byte(s, 1), b'"');
775 s = &s[2..];
776
777 // We're going to want to have slices which don't respect codepoint boundaries.
778 let mut s = s.as_bytes();
779
780 let mut out = Vec::new();
781 'outer: loop {
782 let byte = match byte(s, 0) {
783 b'"' => break,
784 b'\\' => {
785 let b = byte(s, 1);
786 s = &s[2..];
787 match b {
788 b'x' => {
789 let (b, rest) = backslash_x(s);
790 s = rest;
791 b
792 }
793 b'n' => b'\n',
794 b'r' => b'\r',
795 b't' => b'\t',
796 b'\\' => b'\\',
797 b'0' => b'\0',
798 b'\'' => b'\'',
799 b'"' => b'"',
David Tolnay61037c62018-01-05 16:21:03 -0800800 b'\r' | b'\n' => loop {
801 let byte = byte(s, 0);
David Tolnay76ebcdd2018-01-05 17:07:26 -0800802 let ch = char::from_u32(u32::from(byte)).unwrap();
David Tolnay61037c62018-01-05 16:21:03 -0800803 if ch.is_whitespace() {
804 s = &s[1..];
805 } else {
806 continue 'outer;
David Tolnay360efd22018-01-04 23:35:26 -0800807 }
David Tolnay61037c62018-01-05 16:21:03 -0800808 },
809 b => panic!("unexpected byte {:?} after \\ character in byte literal", b),
David Tolnay360efd22018-01-04 23:35:26 -0800810 }
811 }
812 b'\r' => {
813 assert_eq!(byte(s, 1), b'\n', "Bare CR not allowed in string");
814 s = &s[2..];
815 b'\n'
816 }
817 b => {
818 s = &s[1..];
819 b
820 }
821 };
822 out.push(byte);
823 }
824
825 assert_eq!(s, b"\"");
826 out
827 }
828
829 fn parse_lit_byte_str_raw(s: &str) -> Vec<u8> {
830 assert_eq!(byte(s, 0), b'b');
831 parse_lit_str_raw(&s[1..]).into_bytes()
832 }
833
834 pub fn parse_lit_byte(s: &str) -> u8 {
835 assert_eq!(byte(s, 0), b'b');
836 assert_eq!(byte(s, 1), b'\'');
837
838 // We're going to want to have slices which don't respect codepoint boundaries.
839 let mut s = s[2..].as_bytes();
840
841 let b = match byte(s, 0) {
842 b'\\' => {
843 let b = byte(s, 1);
844 s = &s[2..];
845 match b {
846 b'x' => {
847 let (b, rest) = backslash_x(s);
848 s = rest;
849 b
850 }
851 b'n' => b'\n',
852 b'r' => b'\r',
853 b't' => b'\t',
854 b'\\' => b'\\',
855 b'0' => b'\0',
856 b'\'' => b'\'',
857 b'"' => b'"',
David Tolnay61037c62018-01-05 16:21:03 -0800858 b => panic!("unexpected byte {:?} after \\ character in byte literal", b),
David Tolnay360efd22018-01-04 23:35:26 -0800859 }
860 }
861 b => {
862 s = &s[1..];
863 b
864 }
865 };
866
867 assert_eq!(byte(s, 0), b'\'');
868 b
869 }
870
871 pub fn parse_lit_char(mut s: &str) -> char {
872 assert_eq!(byte(s, 0), b'\'');
873 s = &s[1..];
874
875 let ch = match byte(s, 0) {
876 b'\\' => {
877 let b = byte(s, 1);
878 s = &s[2..];
879 match b {
880 b'x' => {
881 let (byte, rest) = backslash_x(s);
882 s = rest;
883 assert!(byte <= 0x80, "Invalid \\x byte in string literal");
David Tolnay76ebcdd2018-01-05 17:07:26 -0800884 char::from_u32(u32::from(byte)).unwrap()
David Tolnay360efd22018-01-04 23:35:26 -0800885 }
886 b'u' => {
887 let (chr, rest) = backslash_u(s);
888 s = rest;
889 chr
890 }
891 b'n' => '\n',
892 b'r' => '\r',
893 b't' => '\t',
894 b'\\' => '\\',
895 b'0' => '\0',
896 b'\'' => '\'',
897 b'"' => '"',
David Tolnay61037c62018-01-05 16:21:03 -0800898 b => panic!("unexpected byte {:?} after \\ character in byte literal", b),
David Tolnay360efd22018-01-04 23:35:26 -0800899 }
900 }
901 _ => {
902 let ch = next_chr(s);
903 s = &s[ch.len_utf8()..];
904 ch
905 }
906 };
907 assert_eq!(s, "\'", "Expected end of char literal");
908 ch
909 }
910
911 fn backslash_x<S>(s: &S) -> (u8, &S)
David Tolnay61037c62018-01-05 16:21:03 -0800912 where
913 S: Index<RangeFrom<usize>, Output = S> + AsRef<[u8]> + ?Sized,
David Tolnay360efd22018-01-04 23:35:26 -0800914 {
915 let mut ch = 0;
916 let b0 = byte(s, 0);
917 let b1 = byte(s, 1);
918 ch += 0x10 * match b0 {
919 b'0'...b'9' => b0 - b'0',
920 b'a'...b'f' => 10 + (b0 - b'a'),
921 b'A'...b'F' => 10 + (b0 - b'A'),
922 _ => panic!("unexpected non-hex character after \\x"),
923 };
David Tolnay76ebcdd2018-01-05 17:07:26 -0800924 ch += match b1 {
David Tolnay360efd22018-01-04 23:35:26 -0800925 b'0'...b'9' => b1 - b'0',
926 b'a'...b'f' => 10 + (b1 - b'a'),
927 b'A'...b'F' => 10 + (b1 - b'A'),
928 _ => panic!("unexpected non-hex character after \\x"),
929 };
930 (ch, &s[2..])
931 }
932
933 fn backslash_u(mut s: &str) -> (char, &str) {
934 if byte(s, 0) != b'{' {
935 panic!("expected {{ after \\u");
936 }
937 s = &s[1..];
938
939 let mut ch = 0;
940 for _ in 0..6 {
941 let b = byte(s, 0);
942 match b {
943 b'0'...b'9' => {
944 ch *= 0x10;
David Tolnay76ebcdd2018-01-05 17:07:26 -0800945 ch += u32::from(b - b'0');
David Tolnay360efd22018-01-04 23:35:26 -0800946 s = &s[1..];
947 }
948 b'a'...b'f' => {
949 ch *= 0x10;
David Tolnay76ebcdd2018-01-05 17:07:26 -0800950 ch += u32::from(10 + b - b'a');
David Tolnay360efd22018-01-04 23:35:26 -0800951 s = &s[1..];
952 }
953 b'A'...b'F' => {
954 ch *= 0x10;
David Tolnay76ebcdd2018-01-05 17:07:26 -0800955 ch += u32::from(10 + b - b'A');
David Tolnay360efd22018-01-04 23:35:26 -0800956 s = &s[1..];
957 }
958 b'}' => break,
959 _ => panic!("unexpected non-hex character after \\u"),
960 }
961 }
962 assert!(byte(s, 0) == b'}');
963 s = &s[1..];
964
965 if let Some(ch) = char::from_u32(ch) {
966 (ch, s)
967 } else {
968 panic!("character code {:x} is not a valid unicode character", ch);
969 }
970 }
971
972 pub fn parse_lit_int(mut s: &str) -> Option<u64> {
973 let base = match (byte(s, 0), byte(s, 1)) {
974 (b'0', b'x') => {
975 s = &s[2..];
976 16
977 }
978 (b'0', b'o') => {
979 s = &s[2..];
980 8
981 }
982 (b'0', b'b') => {
983 s = &s[2..];
984 2
985 }
986 (b'0'...b'9', _) => 10,
987 _ => unreachable!(),
988 };
989
990 let mut value = 0u64;
991 loop {
992 let b = byte(s, 0);
993 let digit = match b {
David Tolnay76ebcdd2018-01-05 17:07:26 -0800994 b'0'...b'9' => u64::from(b - b'0'),
995 b'a'...b'f' if base > 10 => 10 + u64::from(b - b'a'),
996 b'A'...b'F' if base > 10 => 10 + u64::from(b - b'A'),
David Tolnay360efd22018-01-04 23:35:26 -0800997 b'_' => {
998 s = &s[1..];
999 continue;
1000 }
1001 // NOTE: Looking at a floating point literal, we don't want to
1002 // consider these integers.
1003 b'.' if base == 10 => return None,
1004 b'e' | b'E' if base == 10 => return None,
1005 _ => break,
1006 };
1007
1008 if digit >= base {
1009 panic!("Unexpected digit {:x} out of base range", digit);
1010 }
1011
1012 value = match value.checked_mul(base) {
1013 Some(value) => value,
1014 None => return None,
1015 };
1016 value = match value.checked_add(digit) {
1017 Some(value) => value,
1018 None => return None,
1019 };
1020 s = &s[1..];
1021 }
1022
1023 Some(value)
1024 }
1025
1026 pub fn parse_lit_float(input: &str) -> f64 {
1027 // Rust's floating point literals are very similar to the ones parsed by
1028 // the standard library, except that rust's literals can contain
1029 // ignorable underscores. Let's remove those underscores.
1030 let mut bytes = input.to_owned().into_bytes();
1031 let mut write = 0;
1032 for read in 0..bytes.len() {
1033 if bytes[read] == b'_' {
1034 continue; // Don't increase write
David Tolnay76ebcdd2018-01-05 17:07:26 -08001035 }
1036 if write != read {
David Tolnay360efd22018-01-04 23:35:26 -08001037 let x = bytes[read];
1038 bytes[write] = x;
1039 }
1040 write += 1;
1041 }
1042 bytes.truncate(write);
1043 let input = String::from_utf8(bytes).unwrap();
David Tolnay76ebcdd2018-01-05 17:07:26 -08001044 let end = input.find('f').unwrap_or_else(|| input.len());
David Tolnay360efd22018-01-04 23:35:26 -08001045 input[..end].parse().unwrap()
1046 }
1047
1048 pub fn to_literal(s: &str) -> Literal {
1049 let stream = s.parse::<TokenStream>().unwrap();
Alex Crichton9a4dca22018-03-28 06:32:19 -07001050 match stream.into_iter().next().unwrap() {
1051 TokenTree::Literal(l) => l,
David Tolnay360efd22018-01-04 23:35:26 -08001052 _ => unreachable!(),
David Tolnayf17fd2f2016-10-07 23:38:08 -07001053 }
1054 }
David Tolnayf4bbbd92016-09-23 14:41:55 -07001055}