blob: 81aa2a997ea689194b0be03fc927f7d0b1233262 [file] [log] [blame]
David Tolnay4fb71232018-08-25 23:14:50 -04001#[cfg(feature = "parsing")]
David Tolnay719ad5a2018-09-02 18:01:15 -07002use buffer::Cursor;
3#[cfg(feature = "parsing")]
David Tolnay4fb71232018-08-25 23:14:50 -04004use lookahead;
David Tolnayf07b3342018-09-01 11:58:11 -07005#[cfg(feature = "parsing")]
6use parse::{Parse, ParseStream, Result};
David Tolnay719ad5a2018-09-02 18:01:15 -07007#[cfg(feature = "parsing")]
8use token::Token;
David Tolnay4fb71232018-08-25 23:14:50 -04009
10pub use proc_macro2::Ident;
11
12#[cfg(feature = "parsing")]
13#[doc(hidden)]
14#[allow(non_snake_case)]
15pub fn Ident(marker: lookahead::TokenMarker) -> Ident {
16 match marker {}
17}
David Tolnayf07b3342018-09-01 11:58:11 -070018
19#[cfg(feature = "parsing")]
David Tolnay719ad5a2018-09-02 18:01:15 -070020fn accept_as_ident(ident: &Ident) -> bool {
21 match ident.to_string().as_str() {
22 "_"
23 // Based on https://doc.rust-lang.org/grammar.html#keywords
24 // and https://github.com/rust-lang/rfcs/blob/master/text/2421-unreservations-2018.md
25 | "abstract" | "as" | "become" | "box" | "break" | "const"
26 | "continue" | "crate" | "do" | "else" | "enum" | "extern" | "false" | "final"
27 | "fn" | "for" | "if" | "impl" | "in" | "let" | "loop" | "macro" | "match"
28 | "mod" | "move" | "mut" | "override" | "priv" | "proc" | "pub"
29 | "ref" | "return" | "Self" | "self" | "static" | "struct"
30 | "super" | "trait" | "true" | "type" | "typeof" | "unsafe" | "unsized" | "use"
31 | "virtual" | "where" | "while" | "yield" => false,
32 _ => true,
33 }
34}
35
36#[cfg(feature = "parsing")]
David Tolnayf07b3342018-09-01 11:58:11 -070037impl Parse for Ident {
38 fn parse(input: ParseStream) -> Result<Self> {
39 input.step(|cursor| {
40 if let Some((ident, rest)) = cursor.ident() {
David Tolnay719ad5a2018-09-02 18:01:15 -070041 if accept_as_ident(&ident) {
42 return Ok((ident, rest));
David Tolnayf07b3342018-09-01 11:58:11 -070043 }
44 }
45 Err(cursor.error("expected identifier"))
46 })
47 }
48}
David Tolnayd3c93d52018-09-01 18:26:05 -070049
David Tolnay719ad5a2018-09-02 18:01:15 -070050#[cfg(feature = "parsing")]
51impl Token for Ident {
52 fn peek(cursor: Cursor) -> bool {
53 if let Some((ident, _rest)) = cursor.ident() {
54 accept_as_ident(&ident)
55 } else {
56 false
57 }
58 }
59
60 fn display() -> &'static str {
61 "identifier"
62 }
63}
64
David Tolnayd3c93d52018-09-01 18:26:05 -070065macro_rules! ident_from_token {
66 ($token:ident) => {
67 impl From<Token![$token]> for Ident {
68 fn from(token: Token![$token]) -> Ident {
69 Ident::new(stringify!($token), token.span)
70 }
71 }
72 };
73}
74
75ident_from_token!(self);
76ident_from_token!(Self);
77ident_from_token!(super);
78ident_from_token!(crate);
79ident_from_token!(extern);
David Tolnayd72b6452018-09-01 18:27:54 -070080
81impl From<Token![_]> for Ident {
82 fn from(token: Token![_]) -> Ident {
83 Ident::new("_", token.spans[0])
84 }
85}