blob: 4c897a669bd695afb3937e8c80c87d4d7dad1a58 [file] [log] [blame]
David Tolnay55535012018-01-05 16:39:23 -08001// Copyright 2018 Syn Developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
David Tolnayf733f7e2016-11-25 10:36:25 -08009use std::borrow::Cow;
Alex Crichtonccbb45d2017-05-23 10:58:24 -070010use std::cmp::Ordering;
David Tolnay42f50292016-09-04 13:54:21 -070011use std::fmt::{self, Display};
Alex Crichtonccbb45d2017-05-23 10:58:24 -070012use std::hash::{Hash, Hasher};
David Tolnay42f50292016-09-04 13:54:21 -070013
Alex Crichtonf9e8f1a2017-07-05 18:20:44 -070014use proc_macro2::Term;
David Tolnay570695e2017-06-03 16:15:13 -070015use unicode_xid::UnicodeXID;
Alex Crichtonccbb45d2017-05-23 10:58:24 -070016
David Tolnay98942562017-12-26 21:24:35 -050017use proc_macro2::Span;
Alex Crichtonccbb45d2017-05-23 10:58:24 -070018
David Tolnay570695e2017-06-03 16:15:13 -070019/// A word of Rust code, such as a keyword or variable name.
20///
21/// An identifier consists of at least one Unicode code point, the first of
22/// which has the XID_Start property and the rest of which have the XID_Continue
23/// property. An underscore may be used as the first character as long as it is
24/// not the only character.
25///
26/// - The empty string is not an identifier. Use `Option<Ident>`.
27/// - An underscore by itself is not an identifier. Use
David Tolnayf8db7ba2017-11-11 22:52:16 -080028/// `Token![_]` instead.
David Tolnay570695e2017-06-03 16:15:13 -070029/// - A lifetime is not an identifier. Use `syn::Lifetime` instead.
30///
31/// An identifier constructed with `Ident::new` is permitted to be a Rust
David Tolnay1cf80912017-12-31 18:35:12 -050032/// keyword, though parsing one through its [`Synom`] implementation rejects
33/// Rust keywords.
Mikko Rantanena87ac032017-10-30 08:19:00 +020034///
David Tolnay1cf80912017-12-31 18:35:12 -050035/// [`Synom`]: synom/trait.Synom.html
Mikko Rantanena87ac032017-10-30 08:19:00 +020036///
37/// # Examples
38///
39/// A new ident can be created from a string using the `Ident::from` function.
40///
41/// ```rust
42/// extern crate syn;
43/// use syn::Ident;
44/// #
45/// # fn main() {
46///
47/// let ident = Ident::from("another_identifier");
48///
49/// # }
50/// ```
51///
52/// When the ident is used in Macros 1.1 output, it needs to be turned into
53/// a token stream. This is easy to do using the `quote!` macro from the `quote`
54/// crate.
55///
56/// ```rust
57/// # #[macro_use]
58/// # extern crate quote;
59/// # extern crate syn;
60/// # use syn::Ident;
61/// # fn main() {
62/// # let ident = Ident::from("another_identifier");
63/// #
64/// // Create tokens using the ident.
65/// let expanded = quote! { let #ident = 10; };
66///
67/// // Derive a new ident from the existing one.
68/// let temp_ident = Ident::from(format!("new_{}", ident));
69/// let expanded = quote! { let $temp_ident = 10; };
70///
71/// # }
72/// ```
73///
74/// If `syn` is used to parse existing Rust source code, it is often useful to
75/// convert the `Ident` to a more generic string data type at some point. The
76/// methods `as_ref()` and `to_string()` achieve this.
David Tolnay51382052017-12-27 13:46:21 -050077///
Mikko Rantanena87ac032017-10-30 08:19:00 +020078/// ```rust
79/// # use syn::Ident;
80/// # let ident = Ident::from("another_identifier");
81/// #
82/// // Examine the ident as a &str.
83/// let ident_str = ident.as_ref();
84/// if ident_str.len() > 60 {
85/// println!("Very long identifier: {}", ident_str)
86/// }
87///
88/// // Create a String from the ident.
89/// let ident_string = ident.to_string();
90/// give_away(ident_string);
91///
92/// fn give_away(s: String) { /* ... */ }
93/// ```
David Tolnay570695e2017-06-03 16:15:13 -070094#[derive(Copy, Clone, Debug)]
Alex Crichtonccbb45d2017-05-23 10:58:24 -070095pub struct Ident {
David Tolnay73c98de2017-12-31 15:56:56 -050096 term: Term,
Alex Crichtonccbb45d2017-05-23 10:58:24 -070097 pub span: Span,
98}
David Tolnay42f50292016-09-04 13:54:21 -070099
100impl Ident {
Mikko Rantanena87ac032017-10-30 08:19:00 +0200101 /// Creates a new `Ident` from the structured items. This is mainly used
102 /// by the parser to create `Ident`s from existing Rust source code.
103 ///
104 /// Creating new `Ident`s programmatically is easier with `Ident::from`.
David Tolnayeb771d72017-12-27 22:11:06 -0500105 pub fn new(s: &str, span: Span) -> Self {
David Tolnay570695e2017-06-03 16:15:13 -0700106 if s.is_empty() {
107 panic!("ident is not allowed to be empty; use Option<Ident>");
108 }
109
110 if s.starts_with('\'') {
111 panic!("ident is not allowed to be a lifetime; use syn::Lifetime");
112 }
113
114 if s == "_" {
David Tolnay32954ef2017-12-26 22:43:16 -0500115 panic!("`_` is not a valid ident; use syn::token::Underscore");
David Tolnay570695e2017-06-03 16:15:13 -0700116 }
117
David Tolnay14982012017-12-29 00:49:51 -0500118 if s.bytes().all(|digit| digit >= b'0' && digit <= b'9') {
119 panic!("ident cannot be a number, use syn::Index instead");
120 }
121
David Tolnay570695e2017-06-03 16:15:13 -0700122 fn xid_ok(s: &str) -> bool {
123 let mut chars = s.chars();
124 let first = chars.next().unwrap();
125 if !(UnicodeXID::is_xid_start(first) || first == '_') {
126 return false;
127 }
128 for ch in chars {
129 if !UnicodeXID::is_xid_continue(ch) {
130 return false;
131 }
132 }
133 true
134 }
135
David Tolnay14982012017-12-29 00:49:51 -0500136 if !xid_ok(s) {
David Tolnay570695e2017-06-03 16:15:13 -0700137 panic!("{:?} is not a valid ident", s);
138 }
139
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700140 Ident {
David Tolnay73c98de2017-12-31 15:56:56 -0500141 term: Term::intern(s),
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700142 span: span,
143 }
David Tolnay42f50292016-09-04 13:54:21 -0700144 }
145}
146
147impl<'a> From<&'a str> for Ident {
148 fn from(s: &str) -> Self {
David Tolnay66bb8d52018-01-08 08:22:31 -0800149 Ident::new(s, Span::def_site())
David Tolnay42f50292016-09-04 13:54:21 -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![Self]> for Ident {
160 fn from(tok: Token![Self]) -> Self {
David Tolnayeb771d72017-12-27 22:11:06 -0500161 Ident::new("Self", tok.0)
Alex Crichton954046c2017-05-30 21:49:42 -0700162 }
163}
164
David Tolnayf8db7ba2017-11-11 22:52:16 -0800165impl From<Token![super]> for Ident {
166 fn from(tok: Token![super]) -> Self {
David Tolnayeb771d72017-12-27 22:11:06 -0500167 Ident::new("super", tok.0)
Alex Crichton954046c2017-05-30 21:49:42 -0700168 }
169}
170
David Tolnaydfc6df72017-12-25 23:44:08 -0500171impl From<Token![crate]> for Ident {
172 fn from(tok: Token![crate]) -> Self {
David Tolnayeb771d72017-12-27 22:11:06 -0500173 Ident::new("crate", tok.0)
David Tolnaydfc6df72017-12-25 23:44:08 -0500174 }
175}
176
David Tolnayf733f7e2016-11-25 10:36:25 -0800177impl<'a> From<Cow<'a, str>> for Ident {
178 fn from(s: Cow<'a, str>) -> Self {
David Tolnay66bb8d52018-01-08 08:22:31 -0800179 Ident::new(&s, Span::def_site())
David Tolnayf733f7e2016-11-25 10:36:25 -0800180 }
181}
182
David Tolnay42f50292016-09-04 13:54:21 -0700183impl From<String> for Ident {
184 fn from(s: String) -> Self {
David Tolnay66bb8d52018-01-08 08:22:31 -0800185 Ident::new(&s, Span::def_site())
David Tolnay42f50292016-09-04 13:54:21 -0700186 }
187}
188
David Tolnay26469072016-09-04 13:59:48 -0700189impl AsRef<str> for Ident {
190 fn as_ref(&self) -> &str {
David Tolnay73c98de2017-12-31 15:56:56 -0500191 self.term.as_str()
David Tolnay42f50292016-09-04 13:54:21 -0700192 }
193}
194
195impl Display for Ident {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700196 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
David Tolnay73c98de2017-12-31 15:56:56 -0500197 self.term.as_str().fmt(formatter)
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700198 }
199}
200
David Tolnaydaaf7742016-10-03 11:11:43 -0700201impl<T: ?Sized> PartialEq<T> for Ident
David Tolnay51382052017-12-27 13:46:21 -0500202where
203 T: AsRef<str>,
David Tolnaydaaf7742016-10-03 11:11:43 -0700204{
David Tolnay55337722016-09-11 12:58:56 -0700205 fn eq(&self, other: &T) -> bool {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700206 self.as_ref() == other.as_ref()
207 }
208}
209
210impl Eq for Ident {}
211
212impl PartialOrd for Ident {
213 fn partial_cmp(&self, other: &Ident) -> Option<Ordering> {
214 Some(self.cmp(other))
215 }
216}
217
218impl Ord for Ident {
219 fn cmp(&self, other: &Ident) -> Ordering {
220 self.as_ref().cmp(other.as_ref())
221 }
222}
223
224impl Hash for Ident {
225 fn hash<H: Hasher>(&self, h: &mut H) {
David Tolnay85b69a42017-12-27 20:43:10 -0500226 self.as_ref().hash(h);
David Tolnay55337722016-09-11 12:58:56 -0700227 }
David Tolnayb79ee962016-09-04 09:39:20 -0700228}
229
David Tolnay86eca752016-09-04 11:26:41 -0700230#[cfg(feature = "parsing")]
David Tolnay9d8f1972016-09-04 11:58:48 -0700231pub mod parsing {
232 use super::*;
David Tolnayc5ab8c62017-12-26 16:43:39 -0500233 use synom::Synom;
David Tolnaydfc886b2018-01-06 08:03:09 -0800234 use buffer::Cursor;
David Tolnay203557a2017-12-27 23:59:33 -0500235 use parse_error;
236 use synom::PResult;
David Tolnay9d8f1972016-09-04 11:58:48 -0700237
Alex Crichton954046c2017-05-30 21:49:42 -0700238 impl Synom for Ident {
Michael Layzell92639a52017-06-01 00:07:44 -0400239 fn parse(input: Cursor) -> PResult<Self> {
David Tolnay65729482017-12-31 16:14:50 -0500240 let (span, term, rest) = match input.term() {
David Tolnay73c98de2017-12-31 15:56:56 -0500241 Some(term) => term,
Michael Layzell92639a52017-06-01 00:07:44 -0400242 _ => return parse_error(),
Alex Crichton954046c2017-05-30 21:49:42 -0700243 };
David Tolnay73c98de2017-12-31 15:56:56 -0500244 if term.as_str().starts_with('\'') {
Michael Layzell92639a52017-06-01 00:07:44 -0400245 return parse_error();
Alex Crichton954046c2017-05-30 21:49:42 -0700246 }
David Tolnay73c98de2017-12-31 15:56:56 -0500247 match term.as_str() {
Michael Layzell416724e2017-05-24 21:12:34 -0400248 // From https://doc.rust-lang.org/grammar.html#keywords
David Tolnay51382052017-12-27 13:46:21 -0500249 "abstract" | "alignof" | "as" | "become" | "box" | "break" | "const"
250 | "continue" | "crate" | "do" | "else" | "enum" | "extern" | "false" | "final"
251 | "fn" | "for" | "if" | "impl" | "in" | "let" | "loop" | "macro" | "match"
252 | "mod" | "move" | "mut" | "offsetof" | "override" | "priv" | "proc" | "pub"
253 | "pure" | "ref" | "return" | "Self" | "self" | "sizeof" | "static" | "struct"
254 | "super" | "trait" | "true" | "type" | "typeof" | "unsafe" | "unsized" | "use"
255 | "virtual" | "where" | "while" | "yield" => return parse_error(),
Alex Crichton954046c2017-05-30 21:49:42 -0700256 _ => {}
Michael Layzell416724e2017-05-24 21:12:34 -0400257 }
Alex Crichton954046c2017-05-30 21:49:42 -0700258
David Tolnay51382052017-12-27 13:46:21 -0500259 Ok((
David Tolnay51382052017-12-27 13:46:21 -0500260 Ident {
261 span: span,
David Tolnay73c98de2017-12-31 15:56:56 -0500262 term: term,
David Tolnay51382052017-12-27 13:46:21 -0500263 },
David Tolnayf4aa6b42017-12-31 16:40:33 -0500264 rest,
David Tolnay51382052017-12-27 13:46:21 -0500265 ))
Alex Crichton954046c2017-05-30 21:49:42 -0700266 }
267
268 fn description() -> Option<&'static str> {
269 Some("identifier")
David Tolnay05f462f2016-10-24 22:19:42 -0700270 }
271 }
David Tolnayb79ee962016-09-04 09:39:20 -0700272}
David Tolnay26469072016-09-04 13:59:48 -0700273
274#[cfg(feature = "printing")]
275mod printing {
276 use super::*;
David Tolnay51382052017-12-27 13:46:21 -0500277 use quote::{ToTokens, Tokens};
278 use proc_macro2::{TokenNode, TokenTree};
David Tolnay26469072016-09-04 13:59:48 -0700279
280 impl ToTokens for Ident {
281 fn to_tokens(&self, tokens: &mut Tokens) {
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700282 tokens.append(TokenTree {
David Tolnay98942562017-12-26 21:24:35 -0500283 span: self.span,
David Tolnay73c98de2017-12-31 15:56:56 -0500284 kind: TokenNode::Term(self.term),
Alex Crichtonccbb45d2017-05-23 10:58:24 -0700285 })
David Tolnay26469072016-09-04 13:59:48 -0700286 }
287 }
288}