1#[cfg(feature = "parsing")]
2use crate::buffer::Cursor;
3#[cfg(feature = "parsing")]
4use crate::lookahead;
5#[cfg(feature = "parsing")]
6use crate::parse::{Parse, ParseStream, Result};
7#[cfg(feature = "parsing")]
8use crate::token::Token;
9
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}
18
19#[cfg(feature = "parsing")]
20fn 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 // and https://github.com/rust-lang/rfcs/blob/master/text/2420-unreserve-proc.md
26 "abstract" | "as" | "become" | "box" | "break" | "const" | "continue" |
27 "crate" | "do" | "else" | "enum" | "extern" | "false" | "final" | "fn" |
28 "for" | "if" | "impl" | "in" | "let" | "loop" | "macro" | "match" |
29 "mod" | "move" | "mut" | "override" | "priv" | "pub" | "ref" |
30 "return" | "Self" | "self" | "static" | "struct" | "super" | "trait" |
31 "true" | "type" | "typeof" | "unsafe" | "unsized" | "use" | "virtual" |
32 "where" | "while" | "yield" => false,
33 _ => true,
34 }
35}
36
37#[cfg(feature = "parsing")]
38#[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))]
39impl Parse for Ident {
40 fn parse(input: ParseStream) -> Result<Self> {
41 input.step(|cursor: StepCursor<'_, '_>| {
42 if let Some((ident: Ident, rest: Cursor<'_>)) = cursor.ident() {
43 if accept_as_ident(&ident) {
44 return Ok((ident, rest));
45 }
46 }
47 Err(cursor.error(message:"expected identifier"))
48 })
49 }
50}
51
52#[cfg(feature = "parsing")]
53impl Token for Ident {
54 fn peek(cursor: Cursor) -> bool {
55 if let Some((ident: Ident, _rest: Cursor<'_>)) = cursor.ident() {
56 accept_as_ident(&ident)
57 } else {
58 false
59 }
60 }
61
62 fn display() -> &'static str {
63 "identifier"
64 }
65}
66
67macro_rules! ident_from_token {
68 ($token:ident) => {
69 impl From<Token![$token]> for Ident {
70 fn from(token: Token![$token]) -> Ident {
71 Ident::new(stringify!($token), token.span)
72 }
73 }
74 };
75}
76
77ident_from_token!(self);
78ident_from_token!(Self);
79ident_from_token!(super);
80ident_from_token!(crate);
81ident_from_token!(extern);
82
83impl From<Token![_]> for Ident {
84 fn from(token: Token![_]) -> Ident {
85 Ident::new(string:"_", token.span)
86 }
87}
88
89pub fn xid_ok(symbol: &str) -> bool {
90 let mut chars: Chars<'_> = symbol.chars();
91 let first: char = chars.next().unwrap();
92 if !(first == '_' || unicode_ident::is_xid_start(ch:first)) {
93 return false;
94 }
95 for ch: char in chars {
96 if !unicode_ident::is_xid_continue(ch) {
97 return false;
98 }
99 }
100 true
101}
102