blob: 21a5cbdea8131a785e58a41523cd6c7c89fb03b1 [file] [log] [blame]
David Tolnayf733f7e2016-11-25 10:36:25 -08001use std::borrow::Cow;
Alex Crichtonccbb45d2017-05-23 10:58:24 -07002use std::cmp::Ordering;
David Tolnay42f50292016-09-04 13:54:21 -07003use std::fmt::{self, Display};
Alex Crichtonccbb45d2017-05-23 10:58:24 -07004use std::hash::{Hash, Hasher};
David Tolnay42f50292016-09-04 13:54:21 -07005
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -07006use proc_macro2::Term;
David Tolnay570695e2017-06-03 16:15:13 -07007use unicode_xid::UnicodeXID;
Alex Crichtonccbb45d2017-05-23 10:58:24 -07008
David Tolnay98942562017-12-26 21:24:35 -05009use proc_macro2::Span;
Alex Crichtonccbb45d2017-05-23 10:58:24 -070010
David Tolnay570695e2017-06-03 16:15:13 -070011/// A word of Rust code, such as a keyword or variable name.
12///
13/// An identifier consists of at least one Unicode code point, the first of
14/// which has the XID_Start property and the rest of which have the XID_Continue
15/// property. An underscore may be used as the first character as long as it is
16/// not the only character.
17///
18/// - The empty string is not an identifier. Use `Option<Ident>`.
19/// - An underscore by itself is not an identifier. Use
David Tolnayf8db7ba2017-11-11 22:52:16 -080020/// `Token![_]` instead.
David Tolnay570695e2017-06-03 16:15:13 -070021/// - A lifetime is not an identifier. Use `syn::Lifetime` instead.
22///
23/// An identifier constructed with `Ident::new` is permitted to be a Rust
Mikko Rantanena87ac032017-10-30 08:19:00 +020024/// keyword, though parsing input with [`parse`], [`parse_str`] or
25/// [`parse_tokens`] rejects Rust keywords.
26///
27/// [`parse`]: fn.parse.html
28/// [`parse_str`]: fn.parse_str.html
29/// [`parse_tokens`]: fn.parse_tokens.html
30///
31/// # Examples
32///
33/// A new ident can be created from a string using the `Ident::from` function.
34///
35/// ```rust
36/// extern crate syn;
37/// use syn::Ident;
38/// #
39/// # fn main() {
40///
41/// let ident = Ident::from("another_identifier");
42///
43/// # }
44/// ```
45///
46/// When the ident is used in Macros 1.1 output, it needs to be turned into
47/// a token stream. This is easy to do using the `quote!` macro from the `quote`
48/// crate.
49///
50/// ```rust
51/// # #[macro_use]
52/// # extern crate quote;
53/// # extern crate syn;
54/// # use syn::Ident;
55/// # fn main() {
56/// # let ident = Ident::from("another_identifier");
57/// #
58/// // Create tokens using the ident.
59/// let expanded = quote! { let #ident = 10; };
60///
61/// // Derive a new ident from the existing one.
62/// let temp_ident = Ident::from(format!("new_{}", ident));
63/// let expanded = quote! { let $temp_ident = 10; };
64///
65/// # }
66/// ```
67///
68/// If `syn` is used to parse existing Rust source code, it is often useful to
69/// convert the `Ident` to a more generic string data type at some point. The
70/// methods `as_ref()` and `to_string()` achieve this.
David Tolnay51382052017-12-27 13:46:21 -050071///
Mikko Rantanena87ac032017-10-30 08:19:00 +020072/// ```rust
73/// # use syn::Ident;
74/// # let ident = Ident::from("another_identifier");
75/// #
76/// // Examine the ident as a &str.
77/// let ident_str = ident.as_ref();
78/// if ident_str.len() > 60 {
79/// println!("Very long identifier: {}", ident_str)
80/// }
81///
82/// // Create a String from the ident.
83/// let ident_string = ident.to_string();
84/// give_away(ident_string);
85///
86/// fn give_away(s: String) { /* ... */ }
87/// ```
David Tolnay570695e2017-06-03 16:15:13 -070088#[derive(Copy, Clone, Debug)]
Alex Crichtonccbb45d2017-05-23 10:58:24 -070089pub struct Ident {
David Tolnay73c98de2017-12-31 15:56:56 -050090 term: Term,
Alex Crichtonccbb45d2017-05-23 10:58:24 -070091 pub span: Span,
92}
David Tolnay42f50292016-09-04 13:54:21 -070093
94impl Ident {
Mikko Rantanena87ac032017-10-30 08:19:00 +020095 /// Creates a new `Ident` from the structured items. This is mainly used
96 /// by the parser to create `Ident`s from existing Rust source code.
97 ///
98 /// Creating new `Ident`s programmatically is easier with `Ident::from`.
David Tolnayeb771d72017-12-27 22:11:06 -050099 pub fn new(s: &str, span: Span) -> Self {
David Tolnay570695e2017-06-03 16:15:13 -0700100 if s.is_empty() {
101 panic!("ident is not allowed to be empty; use Option<Ident>");
102 }
103
104 if s.starts_with('\'') {
105 panic!("ident is not allowed to be a lifetime; use syn::Lifetime");
106 }
107
108 if s == "_" {
David Tolnay32954ef2017-12-26 22:43:16 -0500109 panic!("`_` is not a valid ident; use syn::token::Underscore");
David Tolnay570695e2017-06-03 16:15:13 -0700110 }
111
David Tolnay14982012017-12-29 00:49:51 -0500112 if s.bytes().all(|digit| digit >= b'0' && digit <= b'9') {
113 panic!("ident cannot be a number, use syn::Index instead");
114 }
115
David Tolnay570695e2017-06-03 16:15:13 -0700116 fn xid_ok(s: &str) -> bool {
117 let mut chars = s.chars();
118 let first = chars.next().unwrap();
119 if !(UnicodeXID::is_xid_start(first) || first == '_') {
120 return false;
121 }
122 for ch in chars {
123 if !UnicodeXID::is_xid_continue(ch) {
124 return false;
125 }
126 }
127 true
128 }
129
David Tolnay14982012017-12-29 00:49:51 -0500130 if !xid_ok(s) {
David Tolnay570695e2017-06-03 16:15:13 -0700131 panic!("{:?} is not a valid ident", s);
132 }
133
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700134 Ident {
David Tolnay73c98de2017-12-31 15:56:56 -0500135 term: Term::intern(s),
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700136 span: span,
137 }
David Tolnay42f50292016-09-04 13:54:21 -0700138 }
139}
140
141impl<'a> From<&'a str> for Ident {
142 fn from(s: &str) -> Self {
David Tolnayeb771d72017-12-27 22:11:06 -0500143 Ident::new(s, Span::default())
David Tolnay42f50292016-09-04 13:54:21 -0700144 }
145}
146
David Tolnayf8db7ba2017-11-11 22:52:16 -0800147impl From<Token![self]> for Ident {
148 fn from(tok: Token![self]) -> Self {
David Tolnayeb771d72017-12-27 22:11:06 -0500149 Ident::new("self", tok.0)
Alex Crichton954046c2017-05-30 21:49:42 -0700150 }
151}
152
David Tolnayf8db7ba2017-11-11 22:52:16 -0800153impl From<Token![Self]> for Ident {
154 fn from(tok: Token![Self]) -> Self {
David Tolnayeb771d72017-12-27 22:11:06 -0500155 Ident::new("Self", tok.0)
Alex Crichton954046c2017-05-30 21:49:42 -0700156 }
157}
158
David Tolnayf8db7ba2017-11-11 22:52:16 -0800159impl From<Token![super]> for Ident {
160 fn from(tok: Token![super]) -> Self {
David Tolnayeb771d72017-12-27 22:11:06 -0500161 Ident::new("super", tok.0)
Alex Crichton954046c2017-05-30 21:49:42 -0700162 }
163}
164
David Tolnaydfc6df72017-12-25 23:44:08 -0500165impl From<Token![crate]> for Ident {
166 fn from(tok: Token![crate]) -> Self {
David Tolnayeb771d72017-12-27 22:11:06 -0500167 Ident::new("crate", tok.0)
David Tolnaydfc6df72017-12-25 23:44:08 -0500168 }
169}
170
David Tolnayf733f7e2016-11-25 10:36:25 -0800171impl<'a> From<Cow<'a, str>> for Ident {
172 fn from(s: Cow<'a, str>) -> Self {
David Tolnayeb771d72017-12-27 22:11:06 -0500173 Ident::new(&s, Span::default())
David Tolnayf733f7e2016-11-25 10:36:25 -0800174 }
175}
176
David Tolnay42f50292016-09-04 13:54:21 -0700177impl From<String> for Ident {
178 fn from(s: String) -> Self {
David Tolnayeb771d72017-12-27 22:11:06 -0500179 Ident::new(&s, Span::default())
David Tolnay42f50292016-09-04 13:54:21 -0700180 }
181}
182
David Tolnay26469072016-09-04 13:59:48 -0700183impl AsRef<str> for Ident {
184 fn as_ref(&self) -> &str {
David Tolnay73c98de2017-12-31 15:56:56 -0500185 self.term.as_str()
David Tolnay42f50292016-09-04 13:54:21 -0700186 }
187}
188
189impl Display for Ident {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700190 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
David Tolnay73c98de2017-12-31 15:56:56 -0500191 self.term.as_str().fmt(formatter)
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700192 }
193}
194
David Tolnaydaaf7742016-10-03 11:11:43 -0700195impl<T: ?Sized> PartialEq<T> for Ident
David Tolnay51382052017-12-27 13:46:21 -0500196where
197 T: AsRef<str>,
David Tolnaydaaf7742016-10-03 11:11:43 -0700198{
David Tolnay55337722016-09-11 12:58:56 -0700199 fn eq(&self, other: &T) -> bool {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700200 self.as_ref() == other.as_ref()
201 }
202}
203
204impl Eq for Ident {}
205
206impl PartialOrd for Ident {
207 fn partial_cmp(&self, other: &Ident) -> Option<Ordering> {
208 Some(self.cmp(other))
209 }
210}
211
212impl Ord for Ident {
213 fn cmp(&self, other: &Ident) -> Ordering {
214 self.as_ref().cmp(other.as_ref())
215 }
216}
217
218impl Hash for Ident {
219 fn hash<H: Hasher>(&self, h: &mut H) {
David Tolnay85b69a42017-12-27 20:43:10 -0500220 self.as_ref().hash(h);
David Tolnay55337722016-09-11 12:58:56 -0700221 }
David Tolnayb79ee962016-09-04 09:39:20 -0700222}
223
David Tolnay86eca752016-09-04 11:26:41 -0700224#[cfg(feature = "parsing")]
David Tolnay9d8f1972016-09-04 11:58:48 -0700225pub mod parsing {
226 use super::*;
David Tolnayc5ab8c62017-12-26 16:43:39 -0500227 use synom::Synom;
228 use cursor::Cursor;
David Tolnay203557a2017-12-27 23:59:33 -0500229 use parse_error;
230 use synom::PResult;
David Tolnay9d8f1972016-09-04 11:58:48 -0700231
Alex Crichton954046c2017-05-30 21:49:42 -0700232 impl Synom for Ident {
Michael Layzell92639a52017-06-01 00:07:44 -0400233 fn parse(input: Cursor) -> PResult<Self> {
David Tolnay65729482017-12-31 16:14:50 -0500234 let (span, term, rest) = match input.term() {
David Tolnay73c98de2017-12-31 15:56:56 -0500235 Some(term) => term,
Michael Layzell92639a52017-06-01 00:07:44 -0400236 _ => return parse_error(),
Alex Crichton954046c2017-05-30 21:49:42 -0700237 };
David Tolnay73c98de2017-12-31 15:56:56 -0500238 if term.as_str().starts_with('\'') {
Michael Layzell92639a52017-06-01 00:07:44 -0400239 return parse_error();
Alex Crichton954046c2017-05-30 21:49:42 -0700240 }
David Tolnay73c98de2017-12-31 15:56:56 -0500241 match term.as_str() {
Michael Layzell416724e2017-05-24 21:12:34 -0400242 // From https://doc.rust-lang.org/grammar.html#keywords
David Tolnay51382052017-12-27 13:46:21 -0500243 "abstract" | "alignof" | "as" | "become" | "box" | "break" | "const"
244 | "continue" | "crate" | "do" | "else" | "enum" | "extern" | "false" | "final"
245 | "fn" | "for" | "if" | "impl" | "in" | "let" | "loop" | "macro" | "match"
246 | "mod" | "move" | "mut" | "offsetof" | "override" | "priv" | "proc" | "pub"
247 | "pure" | "ref" | "return" | "Self" | "self" | "sizeof" | "static" | "struct"
248 | "super" | "trait" | "true" | "type" | "typeof" | "unsafe" | "unsized" | "use"
249 | "virtual" | "where" | "while" | "yield" => return parse_error(),
Alex Crichton954046c2017-05-30 21:49:42 -0700250 _ => {}
Michael Layzell416724e2017-05-24 21:12:34 -0400251 }
Alex Crichton954046c2017-05-30 21:49:42 -0700252
David Tolnay51382052017-12-27 13:46:21 -0500253 Ok((
254 rest,
255 Ident {
256 span: span,
David Tolnay73c98de2017-12-31 15:56:56 -0500257 term: term,
David Tolnay51382052017-12-27 13:46:21 -0500258 },
259 ))
Alex Crichton954046c2017-05-30 21:49:42 -0700260 }
261
262 fn description() -> Option<&'static str> {
263 Some("identifier")
David Tolnay05f462f2016-10-24 22:19:42 -0700264 }
265 }
David Tolnayb79ee962016-09-04 09:39:20 -0700266}
David Tolnay26469072016-09-04 13:59:48 -0700267
268#[cfg(feature = "printing")]
269mod printing {
270 use super::*;
David Tolnay51382052017-12-27 13:46:21 -0500271 use quote::{ToTokens, Tokens};
272 use proc_macro2::{TokenNode, TokenTree};
David Tolnay26469072016-09-04 13:59:48 -0700273
274 impl ToTokens for Ident {
275 fn to_tokens(&self, tokens: &mut Tokens) {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700276 tokens.append(TokenTree {
David Tolnay98942562017-12-26 21:24:35 -0500277 span: self.span,
David Tolnay73c98de2017-12-31 15:56:56 -0500278 kind: TokenNode::Term(self.term),
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700279 })
David Tolnay26469072016-09-04 13:59:48 -0700280 }
281 }
282}