blob: bba6e1caed71d927d3359161450ecae3f17ebc11 [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
David Tolnay1cf80912017-12-31 18:35:12 -050024/// keyword, though parsing one through its [`Synom`] implementation rejects
25/// Rust keywords.
Mikko Rantanena87ac032017-10-30 08:19:00 +020026///
David Tolnay1cf80912017-12-31 18:35:12 -050027/// [`Synom`]: synom/trait.Synom.html
Mikko Rantanena87ac032017-10-30 08:19:00 +020028///
29/// # Examples
30///
31/// A new ident can be created from a string using the `Ident::from` function.
32///
33/// ```rust
34/// extern crate syn;
35/// use syn::Ident;
36/// #
37/// # fn main() {
38///
39/// let ident = Ident::from("another_identifier");
40///
41/// # }
42/// ```
43///
44/// When the ident is used in Macros 1.1 output, it needs to be turned into
45/// a token stream. This is easy to do using the `quote!` macro from the `quote`
46/// crate.
47///
48/// ```rust
49/// # #[macro_use]
50/// # extern crate quote;
51/// # extern crate syn;
52/// # use syn::Ident;
53/// # fn main() {
54/// # let ident = Ident::from("another_identifier");
55/// #
56/// // Create tokens using the ident.
57/// let expanded = quote! { let #ident = 10; };
58///
59/// // Derive a new ident from the existing one.
60/// let temp_ident = Ident::from(format!("new_{}", ident));
61/// let expanded = quote! { let $temp_ident = 10; };
62///
63/// # }
64/// ```
65///
66/// If `syn` is used to parse existing Rust source code, it is often useful to
67/// convert the `Ident` to a more generic string data type at some point. The
68/// methods `as_ref()` and `to_string()` achieve this.
David Tolnay51382052017-12-27 13:46:21 -050069///
Mikko Rantanena87ac032017-10-30 08:19:00 +020070/// ```rust
71/// # use syn::Ident;
72/// # let ident = Ident::from("another_identifier");
73/// #
74/// // Examine the ident as a &str.
75/// let ident_str = ident.as_ref();
76/// if ident_str.len() > 60 {
77/// println!("Very long identifier: {}", ident_str)
78/// }
79///
80/// // Create a String from the ident.
81/// let ident_string = ident.to_string();
82/// give_away(ident_string);
83///
84/// fn give_away(s: String) { /* ... */ }
85/// ```
David Tolnay570695e2017-06-03 16:15:13 -070086#[derive(Copy, Clone, Debug)]
Alex Crichtonccbb45d2017-05-23 10:58:24 -070087pub struct Ident {
David Tolnay73c98de2017-12-31 15:56:56 -050088 term: Term,
Alex Crichtonccbb45d2017-05-23 10:58:24 -070089 pub span: Span,
90}
David Tolnay42f50292016-09-04 13:54:21 -070091
92impl Ident {
Mikko Rantanena87ac032017-10-30 08:19:00 +020093 /// Creates a new `Ident` from the structured items. This is mainly used
94 /// by the parser to create `Ident`s from existing Rust source code.
95 ///
96 /// Creating new `Ident`s programmatically is easier with `Ident::from`.
David Tolnayeb771d72017-12-27 22:11:06 -050097 pub fn new(s: &str, span: Span) -> Self {
David Tolnay570695e2017-06-03 16:15:13 -070098 if s.is_empty() {
99 panic!("ident is not allowed to be empty; use Option<Ident>");
100 }
101
102 if s.starts_with('\'') {
103 panic!("ident is not allowed to be a lifetime; use syn::Lifetime");
104 }
105
106 if s == "_" {
David Tolnay32954ef2017-12-26 22:43:16 -0500107 panic!("`_` is not a valid ident; use syn::token::Underscore");
David Tolnay570695e2017-06-03 16:15:13 -0700108 }
109
David Tolnay14982012017-12-29 00:49:51 -0500110 if s.bytes().all(|digit| digit >= b'0' && digit <= b'9') {
111 panic!("ident cannot be a number, use syn::Index instead");
112 }
113
David Tolnay570695e2017-06-03 16:15:13 -0700114 fn xid_ok(s: &str) -> bool {
115 let mut chars = s.chars();
116 let first = chars.next().unwrap();
117 if !(UnicodeXID::is_xid_start(first) || first == '_') {
118 return false;
119 }
120 for ch in chars {
121 if !UnicodeXID::is_xid_continue(ch) {
122 return false;
123 }
124 }
125 true
126 }
127
David Tolnay14982012017-12-29 00:49:51 -0500128 if !xid_ok(s) {
David Tolnay570695e2017-06-03 16:15:13 -0700129 panic!("{:?} is not a valid ident", s);
130 }
131
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700132 Ident {
David Tolnay73c98de2017-12-31 15:56:56 -0500133 term: Term::intern(s),
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700134 span: span,
135 }
David Tolnay42f50292016-09-04 13:54:21 -0700136 }
137}
138
139impl<'a> From<&'a str> for Ident {
140 fn from(s: &str) -> Self {
David Tolnayeb771d72017-12-27 22:11:06 -0500141 Ident::new(s, Span::default())
David Tolnay42f50292016-09-04 13:54:21 -0700142 }
143}
144
David Tolnayf8db7ba2017-11-11 22:52:16 -0800145impl From<Token![self]> for Ident {
146 fn from(tok: Token![self]) -> Self {
David Tolnayeb771d72017-12-27 22:11:06 -0500147 Ident::new("self", tok.0)
Alex Crichton954046c2017-05-30 21:49:42 -0700148 }
149}
150
David Tolnayf8db7ba2017-11-11 22:52:16 -0800151impl From<Token![Self]> for Ident {
152 fn from(tok: Token![Self]) -> Self {
David Tolnayeb771d72017-12-27 22:11:06 -0500153 Ident::new("Self", tok.0)
Alex Crichton954046c2017-05-30 21:49:42 -0700154 }
155}
156
David Tolnayf8db7ba2017-11-11 22:52:16 -0800157impl From<Token![super]> for Ident {
158 fn from(tok: Token![super]) -> Self {
David Tolnayeb771d72017-12-27 22:11:06 -0500159 Ident::new("super", tok.0)
Alex Crichton954046c2017-05-30 21:49:42 -0700160 }
161}
162
David Tolnaydfc6df72017-12-25 23:44:08 -0500163impl From<Token![crate]> for Ident {
164 fn from(tok: Token![crate]) -> Self {
David Tolnayeb771d72017-12-27 22:11:06 -0500165 Ident::new("crate", tok.0)
David Tolnaydfc6df72017-12-25 23:44:08 -0500166 }
167}
168
David Tolnayf733f7e2016-11-25 10:36:25 -0800169impl<'a> From<Cow<'a, str>> for Ident {
170 fn from(s: Cow<'a, str>) -> Self {
David Tolnayeb771d72017-12-27 22:11:06 -0500171 Ident::new(&s, Span::default())
David Tolnayf733f7e2016-11-25 10:36:25 -0800172 }
173}
174
David Tolnay42f50292016-09-04 13:54:21 -0700175impl From<String> for Ident {
176 fn from(s: String) -> Self {
David Tolnayeb771d72017-12-27 22:11:06 -0500177 Ident::new(&s, Span::default())
David Tolnay42f50292016-09-04 13:54:21 -0700178 }
179}
180
David Tolnay26469072016-09-04 13:59:48 -0700181impl AsRef<str> for Ident {
182 fn as_ref(&self) -> &str {
David Tolnay73c98de2017-12-31 15:56:56 -0500183 self.term.as_str()
David Tolnay42f50292016-09-04 13:54:21 -0700184 }
185}
186
187impl Display for Ident {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700188 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
David Tolnay73c98de2017-12-31 15:56:56 -0500189 self.term.as_str().fmt(formatter)
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700190 }
191}
192
David Tolnaydaaf7742016-10-03 11:11:43 -0700193impl<T: ?Sized> PartialEq<T> for Ident
David Tolnay51382052017-12-27 13:46:21 -0500194where
195 T: AsRef<str>,
David Tolnaydaaf7742016-10-03 11:11:43 -0700196{
David Tolnay55337722016-09-11 12:58:56 -0700197 fn eq(&self, other: &T) -> bool {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700198 self.as_ref() == other.as_ref()
199 }
200}
201
202impl Eq for Ident {}
203
204impl PartialOrd for Ident {
205 fn partial_cmp(&self, other: &Ident) -> Option<Ordering> {
206 Some(self.cmp(other))
207 }
208}
209
210impl Ord for Ident {
211 fn cmp(&self, other: &Ident) -> Ordering {
212 self.as_ref().cmp(other.as_ref())
213 }
214}
215
216impl Hash for Ident {
217 fn hash<H: Hasher>(&self, h: &mut H) {
David Tolnay85b69a42017-12-27 20:43:10 -0500218 self.as_ref().hash(h);
David Tolnay55337722016-09-11 12:58:56 -0700219 }
David Tolnayb79ee962016-09-04 09:39:20 -0700220}
221
David Tolnay86eca752016-09-04 11:26:41 -0700222#[cfg(feature = "parsing")]
David Tolnay9d8f1972016-09-04 11:58:48 -0700223pub mod parsing {
224 use super::*;
David Tolnayc5ab8c62017-12-26 16:43:39 -0500225 use synom::Synom;
226 use cursor::Cursor;
David Tolnay203557a2017-12-27 23:59:33 -0500227 use parse_error;
228 use synom::PResult;
David Tolnay9d8f1972016-09-04 11:58:48 -0700229
Alex Crichton954046c2017-05-30 21:49:42 -0700230 impl Synom for Ident {
Michael Layzell92639a52017-06-01 00:07:44 -0400231 fn parse(input: Cursor) -> PResult<Self> {
David Tolnay65729482017-12-31 16:14:50 -0500232 let (span, term, rest) = match input.term() {
David Tolnay73c98de2017-12-31 15:56:56 -0500233 Some(term) => term,
Michael Layzell92639a52017-06-01 00:07:44 -0400234 _ => return parse_error(),
Alex Crichton954046c2017-05-30 21:49:42 -0700235 };
David Tolnay73c98de2017-12-31 15:56:56 -0500236 if term.as_str().starts_with('\'') {
Michael Layzell92639a52017-06-01 00:07:44 -0400237 return parse_error();
Alex Crichton954046c2017-05-30 21:49:42 -0700238 }
David Tolnay73c98de2017-12-31 15:56:56 -0500239 match term.as_str() {
Michael Layzell416724e2017-05-24 21:12:34 -0400240 // From https://doc.rust-lang.org/grammar.html#keywords
David Tolnay51382052017-12-27 13:46:21 -0500241 "abstract" | "alignof" | "as" | "become" | "box" | "break" | "const"
242 | "continue" | "crate" | "do" | "else" | "enum" | "extern" | "false" | "final"
243 | "fn" | "for" | "if" | "impl" | "in" | "let" | "loop" | "macro" | "match"
244 | "mod" | "move" | "mut" | "offsetof" | "override" | "priv" | "proc" | "pub"
245 | "pure" | "ref" | "return" | "Self" | "self" | "sizeof" | "static" | "struct"
246 | "super" | "trait" | "true" | "type" | "typeof" | "unsafe" | "unsized" | "use"
247 | "virtual" | "where" | "while" | "yield" => return parse_error(),
Alex Crichton954046c2017-05-30 21:49:42 -0700248 _ => {}
Michael Layzell416724e2017-05-24 21:12:34 -0400249 }
Alex Crichton954046c2017-05-30 21:49:42 -0700250
David Tolnay51382052017-12-27 13:46:21 -0500251 Ok((
David Tolnay51382052017-12-27 13:46:21 -0500252 Ident {
253 span: span,
David Tolnay73c98de2017-12-31 15:56:56 -0500254 term: term,
David Tolnay51382052017-12-27 13:46:21 -0500255 },
David Tolnayf4aa6b42017-12-31 16:40:33 -0500256 rest,
David Tolnay51382052017-12-27 13:46:21 -0500257 ))
Alex Crichton954046c2017-05-30 21:49:42 -0700258 }
259
260 fn description() -> Option<&'static str> {
261 Some("identifier")
David Tolnay05f462f2016-10-24 22:19:42 -0700262 }
263 }
David Tolnayb79ee962016-09-04 09:39:20 -0700264}
David Tolnay26469072016-09-04 13:59:48 -0700265
266#[cfg(feature = "printing")]
267mod printing {
268 use super::*;
David Tolnay51382052017-12-27 13:46:21 -0500269 use quote::{ToTokens, Tokens};
270 use proc_macro2::{TokenNode, TokenTree};
David Tolnay26469072016-09-04 13:59:48 -0700271
272 impl ToTokens for Ident {
273 fn to_tokens(&self, tokens: &mut Tokens) {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700274 tokens.append(TokenTree {
David Tolnay98942562017-12-26 21:24:35 -0500275 span: self.span,
David Tolnay73c98de2017-12-31 15:56:56 -0500276 kind: TokenNode::Term(self.term),
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700277 })
David Tolnay26469072016-09-04 13:59:48 -0700278 }
279 }
280}