David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 1 | #[cfg(feature = "parsing")] |
| 2 | use lookahead; |
David Tolnay | f07b334 | 2018-09-01 11:58:11 -0700 | [diff] [blame] | 3 | #[cfg(feature = "parsing")] |
| 4 | use parse::{Parse, ParseStream, Result}; |
David Tolnay | 4fb7123 | 2018-08-25 23:14:50 -0400 | [diff] [blame] | 5 | |
| 6 | pub use proc_macro2::Ident; |
| 7 | |
| 8 | #[cfg(feature = "parsing")] |
| 9 | #[doc(hidden)] |
| 10 | #[allow(non_snake_case)] |
| 11 | pub fn Ident(marker: lookahead::TokenMarker) -> Ident { |
| 12 | match marker {} |
| 13 | } |
David Tolnay | f07b334 | 2018-09-01 11:58:11 -0700 | [diff] [blame] | 14 | |
| 15 | #[cfg(feature = "parsing")] |
| 16 | impl Parse for Ident { |
| 17 | fn parse(input: ParseStream) -> Result<Self> { |
| 18 | input.step(|cursor| { |
| 19 | if let Some((ident, rest)) = cursor.ident() { |
| 20 | match ident.to_string().as_str() { |
| 21 | "_" |
| 22 | // Based on https://doc.rust-lang.org/grammar.html#keywords |
| 23 | // and https://github.com/rust-lang/rfcs/blob/master/text/2421-unreservations-2018.md |
| 24 | | "abstract" | "as" | "become" | "box" | "break" | "const" |
| 25 | | "continue" | "crate" | "do" | "else" | "enum" | "extern" | "false" | "final" |
| 26 | | "fn" | "for" | "if" | "impl" | "in" | "let" | "loop" | "macro" | "match" |
| 27 | | "mod" | "move" | "mut" | "override" | "priv" | "proc" | "pub" |
| 28 | | "ref" | "return" | "Self" | "self" | "static" | "struct" |
| 29 | | "super" | "trait" | "true" | "type" | "typeof" | "unsafe" | "unsized" | "use" |
| 30 | | "virtual" | "where" | "while" | "yield" => {} |
| 31 | _ => return Ok((ident, rest)), |
| 32 | } |
| 33 | } |
| 34 | Err(cursor.error("expected identifier")) |
| 35 | }) |
| 36 | } |
| 37 | } |
David Tolnay | d3c93d5 | 2018-09-01 18:26:05 -0700 | [diff] [blame] | 38 | |
| 39 | macro_rules! ident_from_token { |
| 40 | ($token:ident) => { |
| 41 | impl From<Token![$token]> for Ident { |
| 42 | fn from(token: Token![$token]) -> Ident { |
| 43 | Ident::new(stringify!($token), token.span) |
| 44 | } |
| 45 | } |
| 46 | }; |
| 47 | } |
| 48 | |
| 49 | ident_from_token!(self); |
| 50 | ident_from_token!(Self); |
| 51 | ident_from_token!(super); |
| 52 | ident_from_token!(crate); |
| 53 | ident_from_token!(extern); |
David Tolnay | d72b645 | 2018-09-01 18:27:54 -0700 | [diff] [blame^] | 54 | |
| 55 | impl From<Token![_]> for Ident { |
| 56 | fn from(token: Token![_]) -> Ident { |
| 57 | Ident::new("_", token.spans[0]) |
| 58 | } |
| 59 | } |