blob: 908ff8944d98750ef407cfe84d32aa9fa171ce78 [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 Tolnayad4b2472018-08-25 08:25:24 -040018use {Error, Synom};
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;
27
David Tolnay360efd22018-01-04 23:35:26 -080028ast_enum_of_structs! {
David Tolnayabf5c2e2018-01-06 23:30:04 -080029 /// A Rust literal such as a string or integer or boolean.
David Tolnay614a0142018-01-07 10:25:43 -080030 ///
David Tolnay461d98e2018-01-07 11:07:19 -080031 /// *This type is available if Syn is built with the `"derive"` or `"full"`
32 /// feature.*
33 ///
David Tolnay614a0142018-01-07 10:25:43 -080034 /// # Syntax tree enum
35 ///
36 /// This type is a [syntax tree enum].
37 ///
38 /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums
David Tolnay360efd22018-01-04 23:35:26 -080039 pub enum Lit {
David Tolnayabf5c2e2018-01-06 23:30:04 -080040 /// A UTF-8 string literal: `"foo"`.
David Tolnay461d98e2018-01-07 11:07:19 -080041 ///
42 /// *This type is available if Syn is built with the `"derive"` or
43 /// `"full"` feature.*
David Tolnay360efd22018-01-04 23:35:26 -080044 pub Str(LitStr #manual_extra_traits {
45 token: Literal,
David Tolnay360efd22018-01-04 23:35:26 -080046 }),
Alex Crichtonccbb45d2017-05-23 10:58:24 -070047
David Tolnayabf5c2e2018-01-06 23:30:04 -080048 /// A byte string literal: `b"foo"`.
David Tolnay461d98e2018-01-07 11:07:19 -080049 ///
50 /// *This type is available if Syn is built with the `"derive"` or
51 /// `"full"` feature.*
David Tolnay360efd22018-01-04 23:35:26 -080052 pub ByteStr(LitByteStr #manual_extra_traits {
53 token: Literal,
David Tolnay360efd22018-01-04 23:35:26 -080054 }),
55
David Tolnayabf5c2e2018-01-06 23:30:04 -080056 /// A byte literal: `b'f'`.
David Tolnay461d98e2018-01-07 11:07:19 -080057 ///
58 /// *This type is available if Syn is built with the `"derive"` or
59 /// `"full"` feature.*
David Tolnay360efd22018-01-04 23:35:26 -080060 pub Byte(LitByte #manual_extra_traits {
61 token: Literal,
David Tolnay360efd22018-01-04 23:35:26 -080062 }),
63
David Tolnayabf5c2e2018-01-06 23:30:04 -080064 /// A character literal: `'a'`.
David Tolnay461d98e2018-01-07 11:07:19 -080065 ///
66 /// *This type is available if Syn is built with the `"derive"` or
67 /// `"full"` feature.*
David Tolnay360efd22018-01-04 23:35:26 -080068 pub Char(LitChar #manual_extra_traits {
69 token: Literal,
David Tolnay360efd22018-01-04 23:35:26 -080070 }),
71
David Tolnayabf5c2e2018-01-06 23:30:04 -080072 /// An integer literal: `1` or `1u16`.
David Tolnay360efd22018-01-04 23:35:26 -080073 ///
74 /// Holds up to 64 bits of data. Use `LitVerbatim` for any larger
75 /// integer literal.
David Tolnay461d98e2018-01-07 11:07:19 -080076 ///
77 /// *This type is available if Syn is built with the `"derive"` or
78 /// `"full"` feature.*
David Tolnay360efd22018-01-04 23:35:26 -080079 pub Int(LitInt #manual_extra_traits {
80 token: Literal,
David Tolnay360efd22018-01-04 23:35:26 -080081 }),
82
David Tolnayabf5c2e2018-01-06 23:30:04 -080083 /// A floating point literal: `1f64` or `1.0e10f64`.
David Tolnay360efd22018-01-04 23:35:26 -080084 ///
85 /// Must be finite. May not be infinte or NaN.
David Tolnay461d98e2018-01-07 11:07:19 -080086 ///
87 /// *This type is available if Syn is built with the `"derive"` or
88 /// `"full"` feature.*
David Tolnay360efd22018-01-04 23:35:26 -080089 pub Float(LitFloat #manual_extra_traits {
90 token: Literal,
David Tolnay360efd22018-01-04 23:35:26 -080091 }),
92
David Tolnayabf5c2e2018-01-06 23:30:04 -080093 /// A boolean literal: `true` or `false`.
David Tolnay461d98e2018-01-07 11:07:19 -080094 ///
95 /// *This type is available if Syn is built with the `"derive"` or
96 /// `"full"` feature.*
David Tolnay360efd22018-01-04 23:35:26 -080097 pub Bool(LitBool #manual_extra_traits {
98 pub value: bool,
99 pub span: Span,
100 }),
101
David Tolnayabf5c2e2018-01-06 23:30:04 -0800102 /// A raw token literal not interpreted by Syn, possibly because it
103 /// represents an integer larger than 64 bits.
David Tolnay461d98e2018-01-07 11:07:19 -0800104 ///
105 /// *This type is available if Syn is built with the `"derive"` or
106 /// `"full"` feature.*
David Tolnay360efd22018-01-04 23:35:26 -0800107 pub Verbatim(LitVerbatim #manual_extra_traits {
108 pub token: Literal,
David Tolnay360efd22018-01-04 23:35:26 -0800109 }),
110 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700111}
112
David Tolnay360efd22018-01-04 23:35:26 -0800113impl LitStr {
114 pub fn new(value: &str, span: Span) -> Self {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700115 let mut lit = Literal::string(value);
116 lit.set_span(span);
David Tolnay94d2b792018-04-29 12:26:10 -0700117 LitStr { token: lit }
David Tolnay360efd22018-01-04 23:35:26 -0800118 }
119
120 pub fn value(&self) -> String {
121 value::parse_lit_str(&self.token.to_string())
122 }
David Tolnayd53ac2b2018-01-27 19:00:06 -0800123
124 /// Parse a syntax tree node from the content of this string literal.
125 ///
126 /// All spans in the syntax tree will point to the span of this `LitStr`.
127 #[cfg(feature = "parsing")]
David Tolnayad4b2472018-08-25 08:25:24 -0400128 pub fn parse<T: Synom>(&self) -> Result<T, Error> {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700129 use proc_macro2::Group;
130
David Tolnayd53ac2b2018-01-27 19:00:06 -0800131 // Parse string literal into a token stream with every span equal to the
132 // original literal's span.
David Tolnayad4b2472018-08-25 08:25:24 -0400133 fn spanned_tokens(s: &LitStr) -> Result<TokenStream, Error> {
David Tolnayd53ac2b2018-01-27 19:00:06 -0800134 let stream = ::parse_str(&s.value())?;
Alex Crichton9a4dca22018-03-28 06:32:19 -0700135 Ok(respan_token_stream(stream, s.span()))
David Tolnayd53ac2b2018-01-27 19:00:06 -0800136 }
137
138 // Token stream with every span replaced by the given one.
139 fn respan_token_stream(stream: TokenStream, span: Span) -> TokenStream {
David Tolnay94d2b792018-04-29 12:26:10 -0700140 stream
141 .into_iter()
142 .map(|token| respan_token_tree(token, span))
143 .collect()
David Tolnayd53ac2b2018-01-27 19:00:06 -0800144 }
145
146 // Token tree with every span replaced by the given one.
Alex Crichton9a4dca22018-03-28 06:32:19 -0700147 fn respan_token_tree(mut token: TokenTree, span: Span) -> TokenTree {
148 match token {
149 TokenTree::Group(ref mut g) => {
150 let stream = respan_token_stream(g.stream().clone(), span);
151 *g = Group::new(g.delimiter(), stream);
152 g.set_span(span);
153 }
154 ref mut other => other.set_span(span),
David Tolnayd53ac2b2018-01-27 19:00:06 -0800155 }
Alex Crichton9a4dca22018-03-28 06:32:19 -0700156 token
David Tolnayd53ac2b2018-01-27 19:00:06 -0800157 }
158
159 spanned_tokens(self).and_then(::parse2)
160 }
Alex Crichton9a4dca22018-03-28 06:32:19 -0700161
162 pub fn span(&self) -> Span {
163 self.token.span()
164 }
165
166 pub fn set_span(&mut self, span: Span) {
167 self.token.set_span(span)
168 }
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700169}
170
David Tolnay360efd22018-01-04 23:35:26 -0800171impl LitByteStr {
172 pub fn new(value: &[u8], span: Span) -> Self {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700173 let mut token = Literal::byte_string(value);
174 token.set_span(span);
175 LitByteStr { token: token }
David Tolnay360efd22018-01-04 23:35:26 -0800176 }
177
178 pub fn value(&self) -> Vec<u8> {
179 value::parse_lit_byte_str(&self.token.to_string())
180 }
Alex Crichton9a4dca22018-03-28 06:32:19 -0700181
182 pub fn span(&self) -> Span {
183 self.token.span()
184 }
185
186 pub fn set_span(&mut self, span: Span) {
187 self.token.set_span(span)
188 }
David Tolnay360efd22018-01-04 23:35:26 -0800189}
190
191impl LitByte {
192 pub fn new(value: u8, span: Span) -> Self {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700193 let mut token = Literal::u8_suffixed(value);
194 token.set_span(span);
195 LitByte { token: token }
David Tolnay360efd22018-01-04 23:35:26 -0800196 }
197
198 pub fn value(&self) -> u8 {
199 value::parse_lit_byte(&self.token.to_string())
200 }
Alex Crichton9a4dca22018-03-28 06:32:19 -0700201
202 pub fn span(&self) -> Span {
203 self.token.span()
204 }
205
206 pub fn set_span(&mut self, span: Span) {
207 self.token.set_span(span)
208 }
David Tolnay360efd22018-01-04 23:35:26 -0800209}
210
211impl LitChar {
212 pub fn new(value: char, span: Span) -> Self {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700213 let mut token = Literal::character(value);
214 token.set_span(span);
215 LitChar { token: token }
David Tolnay360efd22018-01-04 23:35:26 -0800216 }
217
218 pub fn value(&self) -> char {
219 value::parse_lit_char(&self.token.to_string())
220 }
Alex Crichton9a4dca22018-03-28 06:32:19 -0700221
222 pub fn span(&self) -> Span {
223 self.token.span()
224 }
225
226 pub fn set_span(&mut self, span: Span) {
227 self.token.set_span(span)
228 }
David Tolnay360efd22018-01-04 23:35:26 -0800229}
230
231impl LitInt {
232 pub fn new(value: u64, suffix: IntSuffix, span: Span) -> Self {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700233 let mut token = match suffix {
234 IntSuffix::Isize => Literal::isize_suffixed(value as isize),
235 IntSuffix::I8 => Literal::i8_suffixed(value as i8),
236 IntSuffix::I16 => Literal::i16_suffixed(value as i16),
237 IntSuffix::I32 => Literal::i32_suffixed(value as i32),
238 IntSuffix::I64 => Literal::i64_suffixed(value as i64),
239 IntSuffix::I128 => value::to_literal(&format!("{}i128", value)),
240 IntSuffix::Usize => Literal::usize_suffixed(value as usize),
241 IntSuffix::U8 => Literal::u8_suffixed(value as u8),
242 IntSuffix::U16 => Literal::u16_suffixed(value as u16),
243 IntSuffix::U32 => Literal::u32_suffixed(value as u32),
244 IntSuffix::U64 => Literal::u64_suffixed(value),
245 IntSuffix::U128 => value::to_literal(&format!("{}u128", value)),
246 IntSuffix::None => Literal::u64_unsuffixed(value),
247 };
248 token.set_span(span);
249 LitInt { token: token }
David Tolnay360efd22018-01-04 23:35:26 -0800250 }
251
252 pub fn value(&self) -> u64 {
253 value::parse_lit_int(&self.token.to_string()).unwrap()
254 }
255
256 pub fn suffix(&self) -> IntSuffix {
257 let value = self.token.to_string();
258 for (s, suffix) in vec![
259 ("i8", IntSuffix::I8),
260 ("i16", IntSuffix::I16),
261 ("i32", IntSuffix::I32),
262 ("i64", IntSuffix::I64),
263 ("i128", IntSuffix::I128),
264 ("isize", IntSuffix::Isize),
265 ("u8", IntSuffix::U8),
266 ("u16", IntSuffix::U16),
267 ("u32", IntSuffix::U32),
268 ("u64", IntSuffix::U64),
269 ("u128", IntSuffix::U128),
270 ("usize", IntSuffix::Usize),
271 ] {
272 if value.ends_with(s) {
273 return suffix;
274 }
275 }
276 IntSuffix::None
277 }
Alex Crichton9a4dca22018-03-28 06:32:19 -0700278
279 pub fn span(&self) -> Span {
280 self.token.span()
281 }
282
283 pub fn set_span(&mut self, span: Span) {
284 self.token.set_span(span)
285 }
David Tolnay360efd22018-01-04 23:35:26 -0800286}
287
288impl LitFloat {
289 pub fn new(value: f64, suffix: FloatSuffix, span: Span) -> Self {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700290 let mut token = match suffix {
291 FloatSuffix::F32 => Literal::f32_suffixed(value as f32),
292 FloatSuffix::F64 => Literal::f64_suffixed(value),
293 FloatSuffix::None => Literal::f64_unsuffixed(value),
294 };
295 token.set_span(span);
296 LitFloat { token: token }
David Tolnay360efd22018-01-04 23:35:26 -0800297 }
298
299 pub fn value(&self) -> f64 {
300 value::parse_lit_float(&self.token.to_string())
301 }
302
303 pub fn suffix(&self) -> FloatSuffix {
304 let value = self.token.to_string();
David Tolnay61037c62018-01-05 16:21:03 -0800305 for (s, suffix) in vec![("f32", FloatSuffix::F32), ("f64", FloatSuffix::F64)] {
David Tolnay360efd22018-01-04 23:35:26 -0800306 if value.ends_with(s) {
307 return suffix;
308 }
309 }
310 FloatSuffix::None
311 }
Alex Crichton9a4dca22018-03-28 06:32:19 -0700312
313 pub fn span(&self) -> Span {
314 self.token.span()
315 }
316
317 pub fn set_span(&mut self, span: Span) {
318 self.token.set_span(span)
319 }
David Tolnay360efd22018-01-04 23:35:26 -0800320}
321
322macro_rules! lit_extra_traits {
323 ($ty:ident, $field:ident) => {
324 #[cfg(feature = "extra-traits")]
325 impl Eq for $ty {}
326
327 #[cfg(feature = "extra-traits")]
328 impl PartialEq for $ty {
329 fn eq(&self, other: &Self) -> bool {
330 self.$field.to_string() == other.$field.to_string()
331 }
332 }
333
334 #[cfg(feature = "extra-traits")]
335 impl Hash for $ty {
336 fn hash<H>(&self, state: &mut H)
337 where
338 H: Hasher,
339 {
340 self.$field.to_string().hash(state);
341 }
David Tolnay9c76bcb2017-12-26 23:14:59 -0500342 }
David Tolnay94d2b792018-04-29 12:26:10 -0700343 };
David Tolnayf4bbbd92016-09-23 14:41:55 -0700344}
345
Alex Crichton9a4dca22018-03-28 06:32:19 -0700346impl LitVerbatim {
347 pub fn span(&self) -> Span {
348 self.token.span()
349 }
350
351 pub fn set_span(&mut self, span: Span) {
352 self.token.set_span(span)
353 }
354}
355
David Tolnay360efd22018-01-04 23:35:26 -0800356lit_extra_traits!(LitStr, token);
357lit_extra_traits!(LitByteStr, token);
358lit_extra_traits!(LitByte, token);
359lit_extra_traits!(LitChar, token);
360lit_extra_traits!(LitInt, token);
361lit_extra_traits!(LitFloat, token);
362lit_extra_traits!(LitBool, value);
363lit_extra_traits!(LitVerbatim, token);
364
365ast_enum! {
David Tolnay05658502018-01-07 09:56:37 -0800366 /// The style of a string literal, either plain quoted or a raw string like
David Tolnayabf5c2e2018-01-06 23:30:04 -0800367 /// `r##"data"##`.
David Tolnay461d98e2018-01-07 11:07:19 -0800368 ///
369 /// *This type is available if Syn is built with the `"derive"` or `"full"`
370 /// feature.*
David Tolnay360efd22018-01-04 23:35:26 -0800371 pub enum StrStyle #no_visit {
David Tolnayabf5c2e2018-01-06 23:30:04 -0800372 /// An ordinary string like `"data"`.
David Tolnay360efd22018-01-04 23:35:26 -0800373 Cooked,
David Tolnayabf5c2e2018-01-06 23:30:04 -0800374 /// A raw string like `r##"data"##`.
David Tolnay360efd22018-01-04 23:35:26 -0800375 ///
376 /// The unsigned integer is the number of `#` symbols used.
377 Raw(usize),
Alex Crichton62a0a592017-05-22 13:58:53 -0700378 }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700379}
380
David Tolnay360efd22018-01-04 23:35:26 -0800381ast_enum! {
David Tolnayabf5c2e2018-01-06 23:30:04 -0800382 /// The suffix on an integer literal if any, like the `u8` in `127u8`.
David Tolnay461d98e2018-01-07 11:07:19 -0800383 ///
384 /// *This type is available if Syn is built with the `"derive"` or `"full"`
385 /// feature.*
David Tolnay360efd22018-01-04 23:35:26 -0800386 pub enum IntSuffix #no_visit {
387 I8,
388 I16,
389 I32,
390 I64,
391 I128,
392 Isize,
393 U8,
394 U16,
395 U32,
396 U64,
397 U128,
398 Usize,
399 None,
Pascal Hertleif36342c52016-10-19 10:31:42 +0200400 }
401}
402
David Tolnay360efd22018-01-04 23:35:26 -0800403ast_enum! {
David Tolnayabf5c2e2018-01-06 23:30:04 -0800404 /// The suffix on a floating point literal if any, like the `f32` in
405 /// `1.0f32`.
David Tolnay461d98e2018-01-07 11:07:19 -0800406 ///
407 /// *This type is available if Syn is built with the `"derive"` or `"full"`
408 /// feature.*
David Tolnay360efd22018-01-04 23:35:26 -0800409 pub enum FloatSuffix #no_visit {
410 F32,
411 F64,
412 None,
Alex Crichton2e0229c2017-05-23 09:34:50 -0700413 }
David Tolnay5fe14fc2017-01-27 16:22:08 -0800414}
415
416#[cfg(feature = "parsing")]
David Tolnay4fb71232018-08-25 23:14:50 -0400417#[doc(hidden)]
418#[allow(non_snake_case)]
419pub fn Lit(marker: lookahead::TokenMarker) -> Lit {
420 match marker {}
421}
422
423#[cfg(feature = "parsing")]
David Tolnayf4bbbd92016-09-23 14:41:55 -0700424pub mod parsing {
425 use super::*;
David Tolnay4fb71232018-08-25 23:14:50 -0400426 use parse::{Parse, ParseStream, Result};
David Tolnay203557a2017-12-27 23:59:33 -0500427 use parse_error;
David Tolnayf4bbbd92016-09-23 14:41:55 -0700428
David Tolnay4fb71232018-08-25 23:14:50 -0400429 impl Parse for Lit {
430 fn parse(input: ParseStream) -> Result<Self> {
431 input.step_cursor(|cursor| {
432 match cursor.literal() {
433 Some((lit, rest)) => {
434 if lit.to_string().starts_with('/') {
435 // Doc comment literal which is not a Syn literal
436 parse_error()
437 } else {
438 Ok((Lit::new(lit), rest))
439 }
David Tolnay7037c9b2018-01-23 09:34:09 -0800440 }
David Tolnay4fb71232018-08-25 23:14:50 -0400441 _ => 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 parse_error();
450 },
451 span: ident.span(),
452 }),
453 rest,
454 )),
455 _ => parse_error(),
456 },
David Tolnay7037c9b2018-01-23 09:34:09 -0800457 }
David Tolnay4fb71232018-08-25 23:14:50 -0400458 })
Sergio Benitez5680d6a2017-12-29 11:20:29 -0800459 }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700460 }
David Tolnay360efd22018-01-04 23:35:26 -0800461
David Tolnaya7d69fc2018-08-26 13:30:24 -0400462 impl Parse for LitStr {
463 fn parse(input: ParseStream) -> Result<Self> {
464 let head = input.fork();
465 match input.parse()? {
466 Lit::Str(lit) => Ok(lit),
467 _ => Err(head.error("expected string literal")),
468 }
469 }
470 }
David Tolnay360efd22018-01-04 23:35:26 -0800471
David Tolnaya7d69fc2018-08-26 13:30:24 -0400472 impl Parse for LitByteStr {
473 fn parse(input: ParseStream) -> Result<Self> {
474 let head = input.fork();
475 match input.parse()? {
476 Lit::ByteStr(lit) => Ok(lit),
477 _ => Err(head.error("expected byte string literal")),
478 }
479 }
480 }
David Tolnay360efd22018-01-04 23:35:26 -0800481
David Tolnaya7d69fc2018-08-26 13:30:24 -0400482 impl Parse for LitByte {
483 fn parse(input: ParseStream) -> Result<Self> {
484 let head = input.fork();
485 match input.parse()? {
486 Lit::Byte(lit) => Ok(lit),
487 _ => Err(head.error("expected byte literal")),
488 }
489 }
490 }
David Tolnay360efd22018-01-04 23:35:26 -0800491
David Tolnaya7d69fc2018-08-26 13:30:24 -0400492 impl Parse for LitChar {
493 fn parse(input: ParseStream) -> Result<Self> {
494 let head = input.fork();
495 match input.parse()? {
496 Lit::Char(lit) => Ok(lit),
497 _ => Err(head.error("expected character literal")),
498 }
499 }
500 }
David Tolnay360efd22018-01-04 23:35:26 -0800501
David Tolnaya7d69fc2018-08-26 13:30:24 -0400502 impl Parse for LitInt {
503 fn parse(input: ParseStream) -> Result<Self> {
504 let head = input.fork();
505 match input.parse()? {
506 Lit::Int(lit) => Ok(lit),
507 _ => Err(head.error("expected integer literal")),
508 }
509 }
510 }
David Tolnay360efd22018-01-04 23:35:26 -0800511
David Tolnaya7d69fc2018-08-26 13:30:24 -0400512 impl Parse for LitFloat {
513 fn parse(input: ParseStream) -> Result<Self> {
514 let head = input.fork();
515 match input.parse()? {
516 Lit::Float(lit) => Ok(lit),
517 _ => Err(head.error("expected floating point literal")),
518 }
519 }
520 }
David Tolnay360efd22018-01-04 23:35:26 -0800521
David Tolnaya7d69fc2018-08-26 13:30:24 -0400522 impl Parse for LitBool {
523 fn parse(input: ParseStream) -> Result<Self> {
524 let head = input.fork();
525 match input.parse()? {
526 Lit::Bool(lit) => Ok(lit),
527 _ => Err(head.error("expected boolean literal")),
528 }
529 }
530 }
David Tolnayf4bbbd92016-09-23 14:41:55 -0700531}
532
533#[cfg(feature = "printing")]
534mod printing {
535 use super::*;
Alex Crichtona74a1c82018-05-16 10:20:44 -0700536 use proc_macro2::TokenStream;
David Tolnay65fb5662018-05-20 20:02:28 -0700537 use quote::{ToTokens, TokenStreamExt};
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700538
David Tolnay360efd22018-01-04 23:35:26 -0800539 impl ToTokens for LitStr {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700540 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700541 self.token.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800542 }
543 }
544
545 impl ToTokens for LitByteStr {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700546 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700547 self.token.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800548 }
549 }
550
551 impl ToTokens for LitByte {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700552 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700553 self.token.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800554 }
555 }
556
557 impl ToTokens for LitChar {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700558 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700559 self.token.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800560 }
561 }
562
563 impl ToTokens for LitInt {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700564 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700565 self.token.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800566 }
567 }
568
569 impl ToTokens for LitFloat {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700570 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700571 self.token.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800572 }
573 }
574
575 impl ToTokens for LitBool {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700576 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700577 let s = if self.value { "true" } else { "false" };
Alex Crichtona74a1c82018-05-16 10:20:44 -0700578 tokens.append(Ident::new(s, self.span));
David Tolnay360efd22018-01-04 23:35:26 -0800579 }
580 }
581
582 impl ToTokens for LitVerbatim {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700583 fn to_tokens(&self, tokens: &mut TokenStream) {
Alex Crichton9a4dca22018-03-28 06:32:19 -0700584 self.token.to_tokens(tokens);
David Tolnay360efd22018-01-04 23:35:26 -0800585 }
586 }
587}
588
589mod value {
590 use super::*;
David Tolnay94d2b792018-04-29 12:26:10 -0700591 use proc_macro2::TokenStream;
David Tolnay360efd22018-01-04 23:35:26 -0800592 use std::char;
593 use std::ops::{Index, RangeFrom};
David Tolnay360efd22018-01-04 23:35:26 -0800594
David Tolnay7d1d1282018-01-06 16:10:51 -0800595 impl Lit {
David Tolnay780292d2018-01-22 23:26:44 -0800596 /// Interpret a Syn literal from a proc-macro2 literal.
597 ///
598 /// Not all proc-macro2 literals are valid Syn literals. In particular,
599 /// doc comments are considered by proc-macro2 to be literals but in Syn
600 /// they are [`Attribute`].
601 ///
602 /// [`Attribute`]: struct.Attribute.html
603 ///
604 /// # Panics
605 ///
606 /// Panics if the input is a doc comment literal.
Alex Crichton9a4dca22018-03-28 06:32:19 -0700607 pub fn new(token: Literal) -> Self {
David Tolnay7d1d1282018-01-06 16:10:51 -0800608 let value = token.to_string();
609
610 match value::byte(&value, 0) {
David Tolnay94d2b792018-04-29 12:26:10 -0700611 b'"' | b'r' => return Lit::Str(LitStr { token: token }),
David Tolnay7d1d1282018-01-06 16:10:51 -0800612 b'b' => match value::byte(&value, 1) {
David Tolnay94d2b792018-04-29 12:26:10 -0700613 b'"' | b'r' => return Lit::ByteStr(LitByteStr { token: token }),
614 b'\'' => return Lit::Byte(LitByte { token: token }),
David Tolnay7d1d1282018-01-06 16:10:51 -0800615 _ => {}
616 },
David Tolnay94d2b792018-04-29 12:26:10 -0700617 b'\'' => return Lit::Char(LitChar { token: token }),
David Tolnay7d1d1282018-01-06 16:10:51 -0800618 b'0'...b'9' => if number_is_int(&value) {
David Tolnay94d2b792018-04-29 12:26:10 -0700619 return Lit::Int(LitInt { token: token });
David Tolnay7d1d1282018-01-06 16:10:51 -0800620 } else if number_is_float(&value) {
David Tolnay94d2b792018-04-29 12:26:10 -0700621 return Lit::Float(LitFloat { token: token });
David Tolnay7d1d1282018-01-06 16:10:51 -0800622 } else {
623 // number overflow
David Tolnay94d2b792018-04-29 12:26:10 -0700624 return Lit::Verbatim(LitVerbatim { token: token });
David Tolnay7d1d1282018-01-06 16:10:51 -0800625 },
626 _ => if value == "true" || value == "false" {
627 return Lit::Bool(LitBool {
628 value: value == "true",
Alex Crichton9a4dca22018-03-28 06:32:19 -0700629 span: token.span(),
David Tolnay7d1d1282018-01-06 16:10:51 -0800630 });
631 },
632 }
633
634 panic!("Unrecognized literal: {}", value);
635 }
636 }
637
638 fn number_is_int(value: &str) -> bool {
639 if number_is_float(value) {
640 false
641 } else {
642 value::parse_lit_int(value).is_some()
643 }
644 }
645
646 fn number_is_float(value: &str) -> bool {
647 if value.contains('.') {
648 true
649 } else if value.starts_with("0x") || value.ends_with("size") {
650 false
651 } else {
652 value.contains('e') || value.contains('E')
653 }
654 }
655
David Tolnay360efd22018-01-04 23:35:26 -0800656 /// Get the byte at offset idx, or a default of `b'\0'` if we're looking
657 /// past the end of the input buffer.
658 pub fn byte<S: AsRef<[u8]> + ?Sized>(s: &S, idx: usize) -> u8 {
659 let s = s.as_ref();
660 if idx < s.len() {
661 s[idx]
662 } else {
663 0
664 }
665 }
666
667 fn next_chr(s: &str) -> char {
668 s.chars().next().unwrap_or('\0')
669 }
670
671 pub fn parse_lit_str(s: &str) -> String {
672 match byte(s, 0) {
673 b'"' => parse_lit_str_cooked(s),
674 b'r' => parse_lit_str_raw(s),
675 _ => unreachable!(),
676 }
677 }
678
David Tolnay76ebcdd2018-01-05 17:07:26 -0800679 // Clippy false positive
680 // https://github.com/rust-lang-nursery/rust-clippy/issues/2329
681 #[cfg_attr(feature = "cargo-clippy", allow(needless_continue))]
David Tolnay360efd22018-01-04 23:35:26 -0800682 fn parse_lit_str_cooked(mut s: &str) -> String {
683 assert_eq!(byte(s, 0), b'"');
684 s = &s[1..];
685
686 let mut out = String::new();
687 'outer: loop {
688 let ch = match byte(s, 0) {
689 b'"' => break,
690 b'\\' => {
691 let b = byte(s, 1);
692 s = &s[2..];
693 match b {
694 b'x' => {
695 let (byte, rest) = backslash_x(s);
696 s = rest;
697 assert!(byte <= 0x80, "Invalid \\x byte in string literal");
David Tolnay76ebcdd2018-01-05 17:07:26 -0800698 char::from_u32(u32::from(byte)).unwrap()
David Tolnay360efd22018-01-04 23:35:26 -0800699 }
700 b'u' => {
David Tolnay76ebcdd2018-01-05 17:07:26 -0800701 let (chr, rest) = backslash_u(s);
David Tolnay360efd22018-01-04 23:35:26 -0800702 s = rest;
703 chr
704 }
705 b'n' => '\n',
706 b'r' => '\r',
707 b't' => '\t',
708 b'\\' => '\\',
709 b'0' => '\0',
710 b'\'' => '\'',
711 b'"' => '"',
David Tolnay61037c62018-01-05 16:21:03 -0800712 b'\r' | b'\n' => loop {
713 let ch = next_chr(s);
714 if ch.is_whitespace() {
715 s = &s[ch.len_utf8()..];
716 } else {
717 continue 'outer;
David Tolnay360efd22018-01-04 23:35:26 -0800718 }
David Tolnay61037c62018-01-05 16:21:03 -0800719 },
720 b => panic!("unexpected byte {:?} after \\ character in byte literal", b),
David Tolnay360efd22018-01-04 23:35:26 -0800721 }
722 }
723 b'\r' => {
724 assert_eq!(byte(s, 1), b'\n', "Bare CR not allowed in string");
725 s = &s[2..];
726 '\n'
727 }
728 _ => {
729 let ch = next_chr(s);
730 s = &s[ch.len_utf8()..];
731 ch
732 }
733 };
734 out.push(ch);
735 }
736
737 assert_eq!(s, "\"");
738 out
739 }
740
741 fn parse_lit_str_raw(mut s: &str) -> String {
742 assert_eq!(byte(s, 0), b'r');
743 s = &s[1..];
744
745 let mut pounds = 0;
746 while byte(s, pounds) == b'#' {
747 pounds += 1;
748 }
749 assert_eq!(byte(s, pounds), b'"');
750 assert_eq!(byte(s, s.len() - pounds - 1), b'"');
751 for end in s[s.len() - pounds..].bytes() {
752 assert_eq!(end, b'#');
753 }
754
755 s[pounds + 1..s.len() - pounds - 1].to_owned()
756 }
757
758 pub fn parse_lit_byte_str(s: &str) -> Vec<u8> {
759 assert_eq!(byte(s, 0), b'b');
760 match byte(s, 1) {
761 b'"' => parse_lit_byte_str_cooked(s),
762 b'r' => parse_lit_byte_str_raw(s),
763 _ => unreachable!(),
764 }
765 }
766
David Tolnay76ebcdd2018-01-05 17:07:26 -0800767 // Clippy false positive
768 // https://github.com/rust-lang-nursery/rust-clippy/issues/2329
769 #[cfg_attr(feature = "cargo-clippy", allow(needless_continue))]
David Tolnay360efd22018-01-04 23:35:26 -0800770 fn parse_lit_byte_str_cooked(mut s: &str) -> Vec<u8> {
771 assert_eq!(byte(s, 0), b'b');
772 assert_eq!(byte(s, 1), b'"');
773 s = &s[2..];
774
775 // We're going to want to have slices which don't respect codepoint boundaries.
776 let mut s = s.as_bytes();
777
778 let mut out = Vec::new();
779 'outer: loop {
780 let byte = match byte(s, 0) {
781 b'"' => break,
782 b'\\' => {
783 let b = byte(s, 1);
784 s = &s[2..];
785 match b {
786 b'x' => {
787 let (b, rest) = backslash_x(s);
788 s = rest;
789 b
790 }
791 b'n' => b'\n',
792 b'r' => b'\r',
793 b't' => b'\t',
794 b'\\' => b'\\',
795 b'0' => b'\0',
796 b'\'' => b'\'',
797 b'"' => b'"',
David Tolnay61037c62018-01-05 16:21:03 -0800798 b'\r' | b'\n' => loop {
799 let byte = byte(s, 0);
David Tolnay76ebcdd2018-01-05 17:07:26 -0800800 let ch = char::from_u32(u32::from(byte)).unwrap();
David Tolnay61037c62018-01-05 16:21:03 -0800801 if ch.is_whitespace() {
802 s = &s[1..];
803 } else {
804 continue 'outer;
David Tolnay360efd22018-01-04 23:35:26 -0800805 }
David Tolnay61037c62018-01-05 16:21:03 -0800806 },
807 b => panic!("unexpected byte {:?} after \\ character in byte literal", b),
David Tolnay360efd22018-01-04 23:35:26 -0800808 }
809 }
810 b'\r' => {
811 assert_eq!(byte(s, 1), b'\n', "Bare CR not allowed in string");
812 s = &s[2..];
813 b'\n'
814 }
815 b => {
816 s = &s[1..];
817 b
818 }
819 };
820 out.push(byte);
821 }
822
823 assert_eq!(s, b"\"");
824 out
825 }
826
827 fn parse_lit_byte_str_raw(s: &str) -> Vec<u8> {
828 assert_eq!(byte(s, 0), b'b');
829 parse_lit_str_raw(&s[1..]).into_bytes()
830 }
831
832 pub fn parse_lit_byte(s: &str) -> u8 {
833 assert_eq!(byte(s, 0), b'b');
834 assert_eq!(byte(s, 1), b'\'');
835
836 // We're going to want to have slices which don't respect codepoint boundaries.
837 let mut s = s[2..].as_bytes();
838
839 let b = match byte(s, 0) {
840 b'\\' => {
841 let b = byte(s, 1);
842 s = &s[2..];
843 match b {
844 b'x' => {
845 let (b, rest) = backslash_x(s);
846 s = rest;
847 b
848 }
849 b'n' => b'\n',
850 b'r' => b'\r',
851 b't' => b'\t',
852 b'\\' => b'\\',
853 b'0' => b'\0',
854 b'\'' => b'\'',
855 b'"' => b'"',
David Tolnay61037c62018-01-05 16:21:03 -0800856 b => panic!("unexpected byte {:?} after \\ character in byte literal", b),
David Tolnay360efd22018-01-04 23:35:26 -0800857 }
858 }
859 b => {
860 s = &s[1..];
861 b
862 }
863 };
864
865 assert_eq!(byte(s, 0), b'\'');
866 b
867 }
868
869 pub fn parse_lit_char(mut s: &str) -> char {
870 assert_eq!(byte(s, 0), b'\'');
871 s = &s[1..];
872
873 let ch = match byte(s, 0) {
874 b'\\' => {
875 let b = byte(s, 1);
876 s = &s[2..];
877 match b {
878 b'x' => {
879 let (byte, rest) = backslash_x(s);
880 s = rest;
881 assert!(byte <= 0x80, "Invalid \\x byte in string literal");
David Tolnay76ebcdd2018-01-05 17:07:26 -0800882 char::from_u32(u32::from(byte)).unwrap()
David Tolnay360efd22018-01-04 23:35:26 -0800883 }
884 b'u' => {
885 let (chr, rest) = backslash_u(s);
886 s = rest;
887 chr
888 }
889 b'n' => '\n',
890 b'r' => '\r',
891 b't' => '\t',
892 b'\\' => '\\',
893 b'0' => '\0',
894 b'\'' => '\'',
895 b'"' => '"',
David Tolnay61037c62018-01-05 16:21:03 -0800896 b => panic!("unexpected byte {:?} after \\ character in byte literal", b),
David Tolnay360efd22018-01-04 23:35:26 -0800897 }
898 }
899 _ => {
900 let ch = next_chr(s);
901 s = &s[ch.len_utf8()..];
902 ch
903 }
904 };
905 assert_eq!(s, "\'", "Expected end of char literal");
906 ch
907 }
908
909 fn backslash_x<S>(s: &S) -> (u8, &S)
David Tolnay61037c62018-01-05 16:21:03 -0800910 where
911 S: Index<RangeFrom<usize>, Output = S> + AsRef<[u8]> + ?Sized,
David Tolnay360efd22018-01-04 23:35:26 -0800912 {
913 let mut ch = 0;
914 let b0 = byte(s, 0);
915 let b1 = byte(s, 1);
916 ch += 0x10 * match b0 {
917 b'0'...b'9' => b0 - b'0',
918 b'a'...b'f' => 10 + (b0 - b'a'),
919 b'A'...b'F' => 10 + (b0 - b'A'),
920 _ => panic!("unexpected non-hex character after \\x"),
921 };
David Tolnay76ebcdd2018-01-05 17:07:26 -0800922 ch += match b1 {
David Tolnay360efd22018-01-04 23:35:26 -0800923 b'0'...b'9' => b1 - b'0',
924 b'a'...b'f' => 10 + (b1 - b'a'),
925 b'A'...b'F' => 10 + (b1 - b'A'),
926 _ => panic!("unexpected non-hex character after \\x"),
927 };
928 (ch, &s[2..])
929 }
930
931 fn backslash_u(mut s: &str) -> (char, &str) {
932 if byte(s, 0) != b'{' {
933 panic!("expected {{ after \\u");
934 }
935 s = &s[1..];
936
937 let mut ch = 0;
938 for _ in 0..6 {
939 let b = byte(s, 0);
940 match b {
941 b'0'...b'9' => {
942 ch *= 0x10;
David Tolnay76ebcdd2018-01-05 17:07:26 -0800943 ch += u32::from(b - b'0');
David Tolnay360efd22018-01-04 23:35:26 -0800944 s = &s[1..];
945 }
946 b'a'...b'f' => {
947 ch *= 0x10;
David Tolnay76ebcdd2018-01-05 17:07:26 -0800948 ch += u32::from(10 + b - b'a');
David Tolnay360efd22018-01-04 23:35:26 -0800949 s = &s[1..];
950 }
951 b'A'...b'F' => {
952 ch *= 0x10;
David Tolnay76ebcdd2018-01-05 17:07:26 -0800953 ch += u32::from(10 + b - b'A');
David Tolnay360efd22018-01-04 23:35:26 -0800954 s = &s[1..];
955 }
956 b'}' => break,
957 _ => panic!("unexpected non-hex character after \\u"),
958 }
959 }
960 assert!(byte(s, 0) == b'}');
961 s = &s[1..];
962
963 if let Some(ch) = char::from_u32(ch) {
964 (ch, s)
965 } else {
966 panic!("character code {:x} is not a valid unicode character", ch);
967 }
968 }
969
970 pub fn parse_lit_int(mut s: &str) -> Option<u64> {
971 let base = match (byte(s, 0), byte(s, 1)) {
972 (b'0', b'x') => {
973 s = &s[2..];
974 16
975 }
976 (b'0', b'o') => {
977 s = &s[2..];
978 8
979 }
980 (b'0', b'b') => {
981 s = &s[2..];
982 2
983 }
984 (b'0'...b'9', _) => 10,
985 _ => unreachable!(),
986 };
987
988 let mut value = 0u64;
989 loop {
990 let b = byte(s, 0);
991 let digit = match b {
David Tolnay76ebcdd2018-01-05 17:07:26 -0800992 b'0'...b'9' => u64::from(b - b'0'),
993 b'a'...b'f' if base > 10 => 10 + u64::from(b - b'a'),
994 b'A'...b'F' if base > 10 => 10 + u64::from(b - b'A'),
David Tolnay360efd22018-01-04 23:35:26 -0800995 b'_' => {
996 s = &s[1..];
997 continue;
998 }
999 // NOTE: Looking at a floating point literal, we don't want to
1000 // consider these integers.
1001 b'.' if base == 10 => return None,
1002 b'e' | b'E' if base == 10 => return None,
1003 _ => break,
1004 };
1005
1006 if digit >= base {
1007 panic!("Unexpected digit {:x} out of base range", digit);
1008 }
1009
1010 value = match value.checked_mul(base) {
1011 Some(value) => value,
1012 None => return None,
1013 };
1014 value = match value.checked_add(digit) {
1015 Some(value) => value,
1016 None => return None,
1017 };
1018 s = &s[1..];
1019 }
1020
1021 Some(value)
1022 }
1023
1024 pub fn parse_lit_float(input: &str) -> f64 {
1025 // Rust's floating point literals are very similar to the ones parsed by
1026 // the standard library, except that rust's literals can contain
1027 // ignorable underscores. Let's remove those underscores.
1028 let mut bytes = input.to_owned().into_bytes();
1029 let mut write = 0;
1030 for read in 0..bytes.len() {
1031 if bytes[read] == b'_' {
1032 continue; // Don't increase write
David Tolnay76ebcdd2018-01-05 17:07:26 -08001033 }
1034 if write != read {
David Tolnay360efd22018-01-04 23:35:26 -08001035 let x = bytes[read];
1036 bytes[write] = x;
1037 }
1038 write += 1;
1039 }
1040 bytes.truncate(write);
1041 let input = String::from_utf8(bytes).unwrap();
David Tolnay76ebcdd2018-01-05 17:07:26 -08001042 let end = input.find('f').unwrap_or_else(|| input.len());
David Tolnay360efd22018-01-04 23:35:26 -08001043 input[..end].parse().unwrap()
1044 }
1045
1046 pub fn to_literal(s: &str) -> Literal {
1047 let stream = s.parse::<TokenStream>().unwrap();
Alex Crichton9a4dca22018-03-28 06:32:19 -07001048 match stream.into_iter().next().unwrap() {
1049 TokenTree::Literal(l) => l,
David Tolnay360efd22018-01-04 23:35:26 -08001050 _ => unreachable!(),
David Tolnayf17fd2f2016-10-07 23:38:08 -07001051 }
1052 }
David Tolnayf4bbbd92016-09-23 14:41:55 -07001053}