blob: ac7540829f6942fe885d0a66ebf5cb446ffe59ae [file] [log] [blame]
David Tolnay7aa1c9c2019-01-19 19:53:10 -08001//! A wrapper around the procedural macro API of the compiler's [`proc_macro`]
2//! crate. This library serves three purposes:
Alex Crichtonbabc99e2017-07-05 18:00:29 -07003//!
David Tolnay7aa1c9c2019-01-19 19:53:10 -08004//! [`proc_macro`]: https://doc.rust-lang.org/proc_macro/
Alex Crichtonbabc99e2017-07-05 18:00:29 -07005//!
David Tolnay7aa1c9c2019-01-19 19:53:10 -08006//! - **Bring proc-macro-like functionality to other contexts like build.rs and
7//! main.rs.** Types from `proc_macro` are entirely specific to procedural
8//! macros and cannot ever exist in code outside of a procedural macro.
9//! Meanwhile `proc_macro2` types may exist anywhere including non-macro code.
10//! By developing foundational libraries like [syn] and [quote] against
11//! `proc_macro2` rather than `proc_macro`, the procedural macro ecosystem
12//! becomes easily applicable to many other use cases and we avoid
13//! reimplementing non-macro equivalents of those libraries.
Alex Crichtonbabc99e2017-07-05 18:00:29 -070014//!
David Tolnay7aa1c9c2019-01-19 19:53:10 -080015//! - **Make procedural macros unit testable.** As a consequence of being
16//! specific to procedural macros, nothing that uses `proc_macro` can be
17//! executed from a unit test. In order for helper libraries or components of
18//! a macro to be testable in isolation, they must be implemented using
19//! `proc_macro2`.
Alex Crichton1fd0e8a2018-02-04 21:29:13 -080020//!
David Tolnay7aa1c9c2019-01-19 19:53:10 -080021//! - **Provide the latest and greatest APIs across all compiler versions.**
22//! Procedural macros were first introduced to Rust in 1.15.0 with an
23//! extremely minimal interface. Since then, many improvements have landed to
24//! make macros more flexible and easier to write. This library tracks the
25//! procedural macro API of the most recent stable compiler but employs a
26//! polyfill to provide that API consistently across any compiler since
27//! 1.15.0.
David Tolnay6b46deb2018-04-25 21:22:46 -070028//!
David Tolnay7aa1c9c2019-01-19 19:53:10 -080029//! [syn]: https://github.com/dtolnay/syn
30//! [quote]: https://github.com/dtolnay/quote
David Tolnay6b46deb2018-04-25 21:22:46 -070031//!
David Tolnay7aa1c9c2019-01-19 19:53:10 -080032//! # Usage
33//!
34//! The skeleton of a typical procedural macro typically looks like this:
35//!
36//! ```edition2018
37//! extern crate proc_macro;
38//!
39//! # const IGNORE: &str = stringify! {
40//! #[proc_macro_derive(MyDerive)]
41//! # };
42//! pub fn my_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
43//! let input = proc_macro2::TokenStream::from(input);
44//!
45//! let output: proc_macro2::TokenStream = {
46//! /* transform input */
47//! # input
48//! };
49//!
50//! proc_macro::TokenStream::from(output)
51//! }
52//! ```
53//!
54//! If parsing with [Syn], you'll use [`parse_macro_input!`] instead to
55//! propagate parse errors correctly back to the compiler when parsing fails.
56//!
57//! [`parse_macro_input!`]: https://docs.rs/syn/0.15/syn/macro.parse_macro_input.html
58//!
59//! # Unstable features
60//!
61//! The default feature set of proc-macro2 tracks the most recent stable
62//! compiler API. Functionality in `proc_macro` that is not yet stable is not
63//! exposed by proc-macro2 by default.
64//!
65//! To opt into the additional APIs available in the most recent nightly
66//! compiler, the `procmacro2_semver_exempt` config flag must be passed to
67//! rustc. As usual, we will polyfill those nightly-only APIs all the way back
68//! to Rust 1.15.0. As these are unstable APIs that track the nightly compiler,
69//! minor versions of proc-macro2 may make breaking changes to them at any time.
David Tolnay6b46deb2018-04-25 21:22:46 -070070//!
71//! ```sh
72//! RUSTFLAGS='--cfg procmacro2_semver_exempt' cargo build
73//! ```
74//!
75//! Note that this must not only be done for your crate, but for any crate that
76//! depends on your crate. This infectious nature is intentional, as it serves
77//! as a reminder that you are outside of the normal semver guarantees.
78//!
David Tolnay7aa1c9c2019-01-19 19:53:10 -080079//! Semver exempt methods are marked as such in the proc-macro2 documentation.
Michael Bryan43339962019-06-19 09:04:22 +080080//!
81//! # Thread-Safety
82//!
83//! Most types in this crate are `!Sync` because the underlying compiler
84//! types make use of thread-local memory, meaning they cannot be accessed from
85//! a different thread.
Alex Crichtonbabc99e2017-07-05 18:00:29 -070086
David Tolnay15cc4982018-01-08 08:03:27 -080087// Proc-macro2 types in rustdoc of other crates get linked to here.
David Tolnayf5149212019-05-08 13:39:08 -070088#![doc(html_root_url = "https://docs.rs/proc-macro2/0.4.30")]
David Tolnayb455dd72019-04-28 13:50:51 -070089#![cfg_attr(any(proc_macro_span, super_unstable), feature(proc_macro_span))]
David Tolnay3b1f7d22019-01-28 12:22:11 -080090#![cfg_attr(super_unstable, feature(proc_macro_raw_ident, proc_macro_def_site))]
Alex Crichtoncbec8ec2017-06-02 13:19:33 -070091
Alex Crichton53548482018-08-11 21:54:05 -070092#[cfg(use_proc_macro)]
Alex Crichton44bffbc2017-05-19 17:51:59 -070093extern crate proc_macro;
Alex Crichton44bffbc2017-05-19 17:51:59 -070094
Alex Crichtonf3888432018-05-16 09:11:05 -070095use std::cmp::Ordering;
Alex Crichton44bffbc2017-05-19 17:51:59 -070096use std::fmt;
Alex Crichtonf3888432018-05-16 09:11:05 -070097use std::hash::{Hash, Hasher};
Alex Crichton44bffbc2017-05-19 17:51:59 -070098use std::iter::FromIterator;
Alex Crichtonaf5bad42018-03-27 14:45:10 -070099use std::marker;
David Tolnay9cd3b4c2018-11-11 16:47:32 -0800100#[cfg(procmacro2_semver_exempt)]
101use std::path::PathBuf;
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700102use std::rc::Rc;
103use std::str::FromStr;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700104
David Tolnayb1032662017-05-31 15:52:28 -0700105#[macro_use]
David Tolnayb1032662017-05-31 15:52:28 -0700106mod strnom;
David Tolnayaef075b2019-01-16 16:29:18 -0800107mod fallback;
David Tolnayb1032662017-05-31 15:52:28 -0700108
Alex Crichtonce0904d2018-08-27 17:29:49 -0700109#[cfg(not(wrap_proc_macro))]
David Tolnayaef075b2019-01-16 16:29:18 -0800110use fallback as imp;
111#[path = "wrapper.rs"]
Alex Crichtonce0904d2018-08-27 17:29:49 -0700112#[cfg(wrap_proc_macro)]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700113mod imp;
114
David Tolnay82ba02d2018-05-20 16:22:43 -0700115/// An abstract stream of tokens, or more concretely a sequence of token trees.
116///
117/// This type provides interfaces for iterating over token trees and for
118/// collecting token trees into one stream.
119///
120/// Token stream is both the input and output of `#[proc_macro]`,
121/// `#[proc_macro_attribute]` and `#[proc_macro_derive]` definitions.
David Tolnaycb1b85f2017-06-03 16:40:35 -0700122#[derive(Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700123pub struct TokenStream {
124 inner: imp::TokenStream,
125 _marker: marker::PhantomData<Rc<()>>,
126}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700127
David Tolnay82ba02d2018-05-20 16:22:43 -0700128/// Error returned from `TokenStream::from_str`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700129pub struct LexError {
130 inner: imp::LexError,
131 _marker: marker::PhantomData<Rc<()>>,
132}
133
134impl TokenStream {
135 fn _new(inner: imp::TokenStream) -> TokenStream {
136 TokenStream {
David Tolnayf0814122019-07-19 11:53:55 -0700137 inner,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700138 _marker: marker::PhantomData,
139 }
140 }
141
David Tolnayaef075b2019-01-16 16:29:18 -0800142 fn _new_stable(inner: fallback::TokenStream) -> TokenStream {
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700143 TokenStream {
144 inner: inner.into(),
145 _marker: marker::PhantomData,
146 }
147 }
148
David Tolnay82ba02d2018-05-20 16:22:43 -0700149 /// Returns an empty `TokenStream` containing no token trees.
David Tolnayc3bb4592018-05-28 20:09:44 -0700150 pub fn new() -> TokenStream {
151 TokenStream::_new(imp::TokenStream::new())
152 }
153
154 #[deprecated(since = "0.4.4", note = "please use TokenStream::new")]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700155 pub fn empty() -> TokenStream {
David Tolnayc3bb4592018-05-28 20:09:44 -0700156 TokenStream::new()
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700157 }
158
David Tolnay82ba02d2018-05-20 16:22:43 -0700159 /// Checks if this `TokenStream` is empty.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700160 pub fn is_empty(&self) -> bool {
161 self.inner.is_empty()
162 }
163}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700164
Árpád Goretity4f74b682018-07-14 00:47:51 +0200165/// `TokenStream::default()` returns an empty stream,
166/// i.e. this is equivalent with `TokenStream::new()`.
167impl Default for TokenStream {
168 fn default() -> Self {
169 TokenStream::new()
170 }
171}
172
David Tolnay82ba02d2018-05-20 16:22:43 -0700173/// Attempts to break the string into tokens and parse those tokens into a token
174/// stream.
175///
176/// May fail for a number of reasons, for example, if the string contains
177/// unbalanced delimiters or characters not existing in the language.
178///
179/// NOTE: Some errors may cause panics instead of returning `LexError`. We
180/// reserve the right to change these errors into `LexError`s later.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700181impl FromStr for TokenStream {
182 type Err = LexError;
183
184 fn from_str(src: &str) -> Result<TokenStream, LexError> {
David Tolnayb28f38a2018-03-31 22:02:29 +0200185 let e = src.parse().map_err(|e| LexError {
186 inner: e,
187 _marker: marker::PhantomData,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700188 })?;
189 Ok(TokenStream::_new(e))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700190 }
191}
192
Alex Crichton53548482018-08-11 21:54:05 -0700193#[cfg(use_proc_macro)]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700194impl From<proc_macro::TokenStream> for TokenStream {
195 fn from(inner: proc_macro::TokenStream) -> TokenStream {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700196 TokenStream::_new(inner.into())
Alex Crichton44bffbc2017-05-19 17:51:59 -0700197 }
198}
199
Alex Crichton53548482018-08-11 21:54:05 -0700200#[cfg(use_proc_macro)]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700201impl From<TokenStream> for proc_macro::TokenStream {
202 fn from(inner: TokenStream) -> proc_macro::TokenStream {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700203 inner.inner.into()
Alex Crichton44bffbc2017-05-19 17:51:59 -0700204 }
205}
206
Alex Crichtonf3888432018-05-16 09:11:05 -0700207impl Extend<TokenTree> for TokenStream {
208 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, streams: I) {
209 self.inner.extend(streams)
210 }
211}
212
David Tolnay5c58c532018-08-13 11:33:51 -0700213impl Extend<TokenStream> for TokenStream {
214 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
215 self.inner
216 .extend(streams.into_iter().map(|stream| stream.inner))
217 }
218}
219
David Tolnay82ba02d2018-05-20 16:22:43 -0700220/// Collects a number of token trees into a single stream.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700221impl FromIterator<TokenTree> for TokenStream {
222 fn from_iter<I: IntoIterator<Item = TokenTree>>(streams: I) -> Self {
223 TokenStream::_new(streams.into_iter().collect())
Alex Crichton44bffbc2017-05-19 17:51:59 -0700224 }
225}
Alex Crichton53b00672018-09-06 17:16:10 -0700226impl FromIterator<TokenStream> for TokenStream {
227 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
228 TokenStream::_new(streams.into_iter().map(|i| i.inner).collect())
229 }
230}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700231
David Tolnay82ba02d2018-05-20 16:22:43 -0700232/// Prints the token stream as a string that is supposed to be losslessly
233/// convertible back into the same token stream (modulo spans), except for
234/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
235/// numeric literals.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700236impl fmt::Display for TokenStream {
237 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
238 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700239 }
240}
241
David Tolnay82ba02d2018-05-20 16:22:43 -0700242/// Prints token in a form convenient for debugging.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700243impl fmt::Debug for TokenStream {
244 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
245 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700246 }
247}
248
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700249impl fmt::Debug for LexError {
250 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
251 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700252 }
253}
254
David Tolnay82ba02d2018-05-20 16:22:43 -0700255/// The source file of a given `Span`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700256///
257/// This type is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800258#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500259#[derive(Clone, PartialEq, Eq)]
David Tolnay7e654a82018-11-11 13:33:18 -0800260pub struct SourceFile {
261 inner: imp::SourceFile,
262 _marker: marker::PhantomData<Rc<()>>,
263}
Nika Layzellf8d5f212017-12-11 14:07:02 -0500264
David Tolnay1ebe3972018-01-02 20:14:20 -0800265#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500266impl SourceFile {
David Tolnay7e654a82018-11-11 13:33:18 -0800267 fn _new(inner: imp::SourceFile) -> Self {
268 SourceFile {
David Tolnayf0814122019-07-19 11:53:55 -0700269 inner,
David Tolnay7e654a82018-11-11 13:33:18 -0800270 _marker: marker::PhantomData,
271 }
272 }
273
David Tolnay82ba02d2018-05-20 16:22:43 -0700274 /// Get the path to this source file.
275 ///
276 /// ### Note
277 ///
278 /// If the code span associated with this `SourceFile` was generated by an
279 /// external macro, this may not be an actual path on the filesystem. Use
280 /// [`is_real`] to check.
281 ///
282 /// Also note that even if `is_real` returns `true`, if
283 /// `--remap-path-prefix` was passed on the command line, the path as given
284 /// may not actually be valid.
285 ///
286 /// [`is_real`]: #method.is_real
David Tolnay9cd3b4c2018-11-11 16:47:32 -0800287 pub fn path(&self) -> PathBuf {
David Tolnay7e654a82018-11-11 13:33:18 -0800288 self.inner.path()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500289 }
290
David Tolnay82ba02d2018-05-20 16:22:43 -0700291 /// Returns `true` if this source file is a real source file, and not
292 /// generated by an external macro's expansion.
Nika Layzellf8d5f212017-12-11 14:07:02 -0500293 pub fn is_real(&self) -> bool {
David Tolnay7e654a82018-11-11 13:33:18 -0800294 self.inner.is_real()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500295 }
296}
297
David Tolnay1ebe3972018-01-02 20:14:20 -0800298#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500299impl fmt::Debug for SourceFile {
300 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
David Tolnay7e654a82018-11-11 13:33:18 -0800301 self.inner.fmt(f)
Nika Layzellf8d5f212017-12-11 14:07:02 -0500302 }
303}
304
David Tolnay82ba02d2018-05-20 16:22:43 -0700305/// A line-column pair representing the start or end of a `Span`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700306///
307/// This type is semver exempt and not exposed by default.
David Tolnay3b1f7d22019-01-28 12:22:11 -0800308#[cfg(span_locations)]
David Tolnay9d4fb442019-04-22 16:42:41 -0700309#[derive(Copy, Clone, Debug, PartialEq, Eq)]
Nika Layzell1ecb6ce2017-12-30 14:34:05 -0500310pub struct LineColumn {
David Tolnay82ba02d2018-05-20 16:22:43 -0700311 /// The 1-indexed line in the source file on which the span starts or ends
312 /// (inclusive).
Nika Layzell1ecb6ce2017-12-30 14:34:05 -0500313 pub line: usize,
David Tolnay82ba02d2018-05-20 16:22:43 -0700314 /// The 0-indexed column (in UTF-8 characters) in the source file on which
315 /// the span starts or ends (inclusive).
Nika Layzell1ecb6ce2017-12-30 14:34:05 -0500316 pub column: usize,
317}
Nika Layzellf8d5f212017-12-11 14:07:02 -0500318
David Tolnay82ba02d2018-05-20 16:22:43 -0700319/// A region of source code, along with macro expansion information.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700320#[derive(Copy, Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700321pub struct Span {
322 inner: imp::Span,
323 _marker: marker::PhantomData<Rc<()>>,
324}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700325
Alex Crichton44bffbc2017-05-19 17:51:59 -0700326impl Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700327 fn _new(inner: imp::Span) -> Span {
328 Span {
David Tolnayf0814122019-07-19 11:53:55 -0700329 inner,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700330 _marker: marker::PhantomData,
331 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700332 }
Alex Crichtone6085b72017-11-21 07:24:25 -0800333
David Tolnayaef075b2019-01-16 16:29:18 -0800334 fn _new_stable(inner: fallback::Span) -> Span {
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700335 Span {
336 inner: inner.into(),
337 _marker: marker::PhantomData,
338 }
339 }
340
David Tolnay82ba02d2018-05-20 16:22:43 -0700341 /// The span of the invocation of the current procedural macro.
342 ///
343 /// Identifiers created with this span will be resolved as if they were
344 /// written directly at the macro call location (call-site hygiene) and
345 /// other code at the macro call site will be able to refer to them as well.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700346 pub fn call_site() -> Span {
347 Span::_new(imp::Span::call_site())
348 }
349
David Tolnay82ba02d2018-05-20 16:22:43 -0700350 /// A span that resolves at the macro definition site.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700351 ///
352 /// This method is semver exempt and not exposed by default.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700353 #[cfg(procmacro2_semver_exempt)]
Alex Crichtone6085b72017-11-21 07:24:25 -0800354 pub fn def_site() -> Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700355 Span::_new(imp::Span::def_site())
Alex Crichtone6085b72017-11-21 07:24:25 -0800356 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500357
David Tolnay4e8e3972018-01-05 18:10:22 -0800358 /// Creates a new span with the same line/column information as `self` but
359 /// that resolves symbols as though it were at `other`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700360 ///
361 /// This method is semver exempt and not exposed by default.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700362 #[cfg(procmacro2_semver_exempt)]
David Tolnay4e8e3972018-01-05 18:10:22 -0800363 pub fn resolved_at(&self, other: Span) -> Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700364 Span::_new(self.inner.resolved_at(other.inner))
David Tolnay4e8e3972018-01-05 18:10:22 -0800365 }
366
367 /// Creates a new span with the same name resolution behavior as `self` but
368 /// with the line/column information of `other`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700369 ///
370 /// This method is semver exempt and not exposed by default.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700371 #[cfg(procmacro2_semver_exempt)]
David Tolnay4e8e3972018-01-05 18:10:22 -0800372 pub fn located_at(&self, other: Span) -> Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700373 Span::_new(self.inner.located_at(other.inner))
David Tolnay4e8e3972018-01-05 18:10:22 -0800374 }
375
David Tolnay17eb0702019-01-05 12:23:17 -0800376 /// Convert `proc_macro2::Span` to `proc_macro::Span`.
377 ///
378 /// This method is available when building with a nightly compiler, or when
379 /// building with rustc 1.29+ *without* semver exempt features.
David Tolnayc0425cd2019-01-16 12:13:15 -0800380 ///
381 /// # Panics
382 ///
383 /// Panics if called from outside of a procedural macro. Unlike
384 /// `proc_macro2::Span`, the `proc_macro::Span` type can only exist within
385 /// the context of a procedural macro invocation.
David Tolnay17eb0702019-01-05 12:23:17 -0800386 #[cfg(wrap_proc_macro)]
David Tolnay40bbb1c2019-01-19 19:43:55 -0800387 pub fn unwrap(self) -> proc_macro::Span {
388 self.inner.unwrap()
389 }
390
391 // Soft deprecated. Please use Span::unwrap.
392 #[cfg(wrap_proc_macro)]
393 #[doc(hidden)]
David Tolnay16a17202017-12-31 10:47:24 -0500394 pub fn unstable(self) -> proc_macro::Span {
David Tolnay40bbb1c2019-01-19 19:43:55 -0800395 self.unwrap()
David Tolnay16a17202017-12-31 10:47:24 -0500396 }
397
David Tolnay82ba02d2018-05-20 16:22:43 -0700398 /// The original source file into which this span points.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700399 ///
400 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800401 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500402 pub fn source_file(&self) -> SourceFile {
David Tolnay7e654a82018-11-11 13:33:18 -0800403 SourceFile::_new(self.inner.source_file())
Nika Layzellf8d5f212017-12-11 14:07:02 -0500404 }
405
David Tolnay82ba02d2018-05-20 16:22:43 -0700406 /// Get the starting line/column in the source file for this span.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700407 ///
David Tolnay3b1f7d22019-01-28 12:22:11 -0800408 /// This method requires the `"span-locations"` feature to be enabled.
409 #[cfg(span_locations)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500410 pub fn start(&self) -> LineColumn {
David Tolnayb28f38a2018-03-31 22:02:29 +0200411 let imp::LineColumn { line, column } = self.inner.start();
David Tolnayf0814122019-07-19 11:53:55 -0700412 LineColumn { line, column }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500413 }
414
David Tolnay82ba02d2018-05-20 16:22:43 -0700415 /// Get the ending line/column in the source file for this span.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700416 ///
David Tolnay3b1f7d22019-01-28 12:22:11 -0800417 /// This method requires the `"span-locations"` feature to be enabled.
418 #[cfg(span_locations)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500419 pub fn end(&self) -> LineColumn {
David Tolnayb28f38a2018-03-31 22:02:29 +0200420 let imp::LineColumn { line, column } = self.inner.end();
David Tolnayf0814122019-07-19 11:53:55 -0700421 LineColumn { line, column }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500422 }
423
David Tolnay82ba02d2018-05-20 16:22:43 -0700424 /// Create a new span encompassing `self` and `other`.
425 ///
426 /// Returns `None` if `self` and `other` are from different files.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700427 ///
428 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800429 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500430 pub fn join(&self, other: Span) -> Option<Span> {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700431 self.inner.join(other.inner).map(Span::_new)
432 }
Alex Crichtonb2c94622018-04-04 07:36:41 -0700433
David Tolnay0360cf82019-06-30 13:09:49 -0700434 /// Compares two spans to see if they're equal.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700435 ///
436 /// This method is semver exempt and not exposed by default.
Alex Crichtonb2c94622018-04-04 07:36:41 -0700437 #[cfg(procmacro2_semver_exempt)]
438 pub fn eq(&self, other: &Span) -> bool {
439 self.inner.eq(&other.inner)
440 }
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700441}
442
David Tolnay82ba02d2018-05-20 16:22:43 -0700443/// Prints a span in a form convenient for debugging.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700444impl fmt::Debug for Span {
445 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
446 self.inner.fmt(f)
Nika Layzellf8d5f212017-12-11 14:07:02 -0500447 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700448}
449
David Tolnay82ba02d2018-05-20 16:22:43 -0700450/// A single token or a delimited sequence of token trees (e.g. `[1, (), ..]`).
David Tolnay034205f2018-04-22 16:45:28 -0700451#[derive(Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700452pub enum TokenTree {
David Tolnay82ba02d2018-05-20 16:22:43 -0700453 /// A token stream surrounded by bracket delimiters.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700454 Group(Group),
David Tolnay82ba02d2018-05-20 16:22:43 -0700455 /// An identifier.
Alex Crichtonf3888432018-05-16 09:11:05 -0700456 Ident(Ident),
David Tolnay82ba02d2018-05-20 16:22:43 -0700457 /// A single punctuation character (`+`, `,`, `$`, etc.).
Alex Crichtonf3888432018-05-16 09:11:05 -0700458 Punct(Punct),
David Tolnay82ba02d2018-05-20 16:22:43 -0700459 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700460 Literal(Literal),
Alex Crichton1a7f7622017-07-05 17:47:15 -0700461}
462
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700463impl TokenTree {
David Tolnay82ba02d2018-05-20 16:22:43 -0700464 /// Returns the span of this tree, delegating to the `span` method of
465 /// the contained token or a delimited stream.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700466 pub fn span(&self) -> Span {
467 match *self {
468 TokenTree::Group(ref t) => t.span(),
Alex Crichtonf3888432018-05-16 09:11:05 -0700469 TokenTree::Ident(ref t) => t.span(),
470 TokenTree::Punct(ref t) => t.span(),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700471 TokenTree::Literal(ref t) => t.span(),
472 }
473 }
474
David Tolnay82ba02d2018-05-20 16:22:43 -0700475 /// Configures the span for *only this token*.
476 ///
477 /// Note that if this token is a `Group` then this method will not configure
478 /// the span of each of the internal tokens, this will simply delegate to
479 /// the `set_span` method of each variant.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700480 pub fn set_span(&mut self, span: Span) {
481 match *self {
482 TokenTree::Group(ref mut t) => t.set_span(span),
Alex Crichtonf3888432018-05-16 09:11:05 -0700483 TokenTree::Ident(ref mut t) => t.set_span(span),
484 TokenTree::Punct(ref mut t) => t.set_span(span),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700485 TokenTree::Literal(ref mut t) => t.set_span(span),
486 }
487 }
488}
489
490impl From<Group> for TokenTree {
491 fn from(g: Group) -> TokenTree {
492 TokenTree::Group(g)
493 }
494}
495
Alex Crichtonf3888432018-05-16 09:11:05 -0700496impl From<Ident> for TokenTree {
497 fn from(g: Ident) -> TokenTree {
498 TokenTree::Ident(g)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700499 }
500}
501
Alex Crichtonf3888432018-05-16 09:11:05 -0700502impl From<Punct> for TokenTree {
503 fn from(g: Punct) -> TokenTree {
504 TokenTree::Punct(g)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700505 }
506}
507
508impl From<Literal> for TokenTree {
509 fn from(g: Literal) -> TokenTree {
510 TokenTree::Literal(g)
Alex Crichton1a7f7622017-07-05 17:47:15 -0700511 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700512}
513
David Tolnay82ba02d2018-05-20 16:22:43 -0700514/// Prints the token tree as a string that is supposed to be losslessly
515/// convertible back into the same token tree (modulo spans), except for
516/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
517/// numeric literals.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700518impl fmt::Display for TokenTree {
519 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700520 match *self {
521 TokenTree::Group(ref t) => t.fmt(f),
Alex Crichtonf3888432018-05-16 09:11:05 -0700522 TokenTree::Ident(ref t) => t.fmt(f),
523 TokenTree::Punct(ref t) => t.fmt(f),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700524 TokenTree::Literal(ref t) => t.fmt(f),
525 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700526 }
527}
528
David Tolnay82ba02d2018-05-20 16:22:43 -0700529/// Prints token tree in a form convenient for debugging.
David Tolnay034205f2018-04-22 16:45:28 -0700530impl fmt::Debug for TokenTree {
531 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
532 // Each of these has the name in the struct type in the derived debug,
533 // so don't bother with an extra layer of indirection
534 match *self {
535 TokenTree::Group(ref t) => t.fmt(f),
David Tolnayd8fcdb82018-06-02 15:43:53 -0700536 TokenTree::Ident(ref t) => {
537 let mut debug = f.debug_struct("Ident");
538 debug.field("sym", &format_args!("{}", t));
David Tolnayfd8cdc82019-01-19 19:23:59 -0800539 imp::debug_span_field_if_nontrivial(&mut debug, t.span().inner);
David Tolnayd8fcdb82018-06-02 15:43:53 -0700540 debug.finish()
541 }
Alex Crichtonf3888432018-05-16 09:11:05 -0700542 TokenTree::Punct(ref t) => t.fmt(f),
David Tolnay034205f2018-04-22 16:45:28 -0700543 TokenTree::Literal(ref t) => t.fmt(f),
544 }
545 }
546}
547
David Tolnay82ba02d2018-05-20 16:22:43 -0700548/// A delimited token stream.
549///
550/// A `Group` internally contains a `TokenStream` which is surrounded by
551/// `Delimiter`s.
David Tolnay034205f2018-04-22 16:45:28 -0700552#[derive(Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700553pub struct Group {
David Tolnayf14813f2018-09-08 17:14:07 -0700554 inner: imp::Group,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700555}
556
David Tolnay82ba02d2018-05-20 16:22:43 -0700557/// Describes how a sequence of token trees is delimited.
Michael Layzell5372f4b2017-06-02 10:29:31 -0400558#[derive(Copy, Clone, Debug, Eq, PartialEq)]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700559pub enum Delimiter {
David Tolnay82ba02d2018-05-20 16:22:43 -0700560 /// `( ... )`
Alex Crichton44bffbc2017-05-19 17:51:59 -0700561 Parenthesis,
David Tolnay82ba02d2018-05-20 16:22:43 -0700562 /// `{ ... }`
Alex Crichton44bffbc2017-05-19 17:51:59 -0700563 Brace,
David Tolnay82ba02d2018-05-20 16:22:43 -0700564 /// `[ ... ]`
Alex Crichton44bffbc2017-05-19 17:51:59 -0700565 Bracket,
David Tolnay82ba02d2018-05-20 16:22:43 -0700566 /// `Ø ... Ø`
567 ///
568 /// An implicit delimiter, that may, for example, appear around tokens
569 /// coming from a "macro variable" `$var`. It is important to preserve
570 /// operator priorities in cases like `$var * 3` where `$var` is `1 + 2`.
571 /// Implicit delimiters may not survive roundtrip of a token stream through
572 /// a string.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700573 None,
574}
575
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700576impl Group {
David Tolnayf14813f2018-09-08 17:14:07 -0700577 fn _new(inner: imp::Group) -> Self {
David Tolnayf0814122019-07-19 11:53:55 -0700578 Group { inner }
David Tolnayf14813f2018-09-08 17:14:07 -0700579 }
580
David Tolnayaef075b2019-01-16 16:29:18 -0800581 fn _new_stable(inner: fallback::Group) -> Self {
David Tolnayf14813f2018-09-08 17:14:07 -0700582 Group {
583 inner: inner.into(),
584 }
585 }
586
David Tolnay82ba02d2018-05-20 16:22:43 -0700587 /// Creates a new `Group` with the given delimiter and token stream.
588 ///
589 /// This constructor will set the span for this group to
590 /// `Span::call_site()`. To change the span you can use the `set_span`
591 /// method below.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700592 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
593 Group {
David Tolnayf14813f2018-09-08 17:14:07 -0700594 inner: imp::Group::new(delimiter, stream.inner),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700595 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700596 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700597
David Tolnay82ba02d2018-05-20 16:22:43 -0700598 /// Returns the delimiter of this `Group`
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700599 pub fn delimiter(&self) -> Delimiter {
David Tolnayf14813f2018-09-08 17:14:07 -0700600 self.inner.delimiter()
Alex Crichton44bffbc2017-05-19 17:51:59 -0700601 }
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700602
David Tolnay82ba02d2018-05-20 16:22:43 -0700603 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
604 ///
605 /// Note that the returned token stream does not include the delimiter
606 /// returned above.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700607 pub fn stream(&self) -> TokenStream {
David Tolnayf14813f2018-09-08 17:14:07 -0700608 TokenStream::_new(self.inner.stream())
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700609 }
610
David Tolnay82ba02d2018-05-20 16:22:43 -0700611 /// Returns the span for the delimiters of this token stream, spanning the
612 /// entire `Group`.
David Tolnayf14813f2018-09-08 17:14:07 -0700613 ///
614 /// ```text
615 /// pub fn span(&self) -> Span {
616 /// ^^^^^^^
617 /// ```
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700618 pub fn span(&self) -> Span {
David Tolnayf14813f2018-09-08 17:14:07 -0700619 Span::_new(self.inner.span())
620 }
621
622 /// Returns the span pointing to the opening delimiter of this group.
623 ///
624 /// ```text
625 /// pub fn span_open(&self) -> Span {
626 /// ^
627 /// ```
628 #[cfg(procmacro2_semver_exempt)]
629 pub fn span_open(&self) -> Span {
630 Span::_new(self.inner.span_open())
631 }
632
633 /// Returns the span pointing to the closing delimiter of this group.
634 ///
635 /// ```text
636 /// pub fn span_close(&self) -> Span {
637 /// ^
638 /// ```
639 #[cfg(procmacro2_semver_exempt)]
640 pub fn span_close(&self) -> Span {
641 Span::_new(self.inner.span_close())
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700642 }
643
David Tolnay82ba02d2018-05-20 16:22:43 -0700644 /// Configures the span for this `Group`'s delimiters, but not its internal
645 /// tokens.
646 ///
647 /// This method will **not** set the span of all the internal tokens spanned
648 /// by this group, but rather it will only set the span of the delimiter
649 /// tokens at the level of the `Group`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700650 pub fn set_span(&mut self, span: Span) {
David Tolnayf14813f2018-09-08 17:14:07 -0700651 self.inner.set_span(span.inner)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700652 }
653}
654
David Tolnay82ba02d2018-05-20 16:22:43 -0700655/// Prints the group as a string that should be losslessly convertible back
656/// into the same group (modulo spans), except for possibly `TokenTree::Group`s
657/// with `Delimiter::None` delimiters.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700658impl fmt::Display for Group {
David Tolnayf14813f2018-09-08 17:14:07 -0700659 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
660 fmt::Display::fmt(&self.inner, formatter)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700661 }
662}
663
David Tolnay034205f2018-04-22 16:45:28 -0700664impl fmt::Debug for Group {
David Tolnayf14813f2018-09-08 17:14:07 -0700665 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
666 fmt::Debug::fmt(&self.inner, formatter)
David Tolnay034205f2018-04-22 16:45:28 -0700667 }
668}
669
David Tolnay82ba02d2018-05-20 16:22:43 -0700670/// An `Punct` is an single punctuation character like `+`, `-` or `#`.
671///
672/// Multicharacter operators like `+=` are represented as two instances of
673/// `Punct` with different forms of `Spacing` returned.
Alex Crichtonf3888432018-05-16 09:11:05 -0700674#[derive(Clone)]
675pub struct Punct {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700676 op: char,
677 spacing: Spacing,
678 span: Span,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700679}
680
David Tolnay82ba02d2018-05-20 16:22:43 -0700681/// Whether an `Punct` is followed immediately by another `Punct` or followed by
682/// another token or whitespace.
Lukas Kalbertodteb3f9302017-08-20 18:58:41 +0200683#[derive(Copy, Clone, Debug, Eq, PartialEq)]
Alex Crichton1a7f7622017-07-05 17:47:15 -0700684pub enum Spacing {
David Tolnay82ba02d2018-05-20 16:22:43 -0700685 /// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700686 Alone,
David Tolnay82ba02d2018-05-20 16:22:43 -0700687 /// E.g. `+` is `Joint` in `+=` or `'#`.
688 ///
689 /// Additionally, single quote `'` can join with identifiers to form
690 /// lifetimes `'ident`.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700691 Joint,
692}
693
Alex Crichtonf3888432018-05-16 09:11:05 -0700694impl Punct {
David Tolnay82ba02d2018-05-20 16:22:43 -0700695 /// Creates a new `Punct` from the given character and spacing.
696 ///
697 /// The `ch` argument must be a valid punctuation character permitted by the
698 /// language, otherwise the function will panic.
699 ///
700 /// The returned `Punct` will have the default span of `Span::call_site()`
701 /// which can be further configured with the `set_span` method below.
Alex Crichtonf3888432018-05-16 09:11:05 -0700702 pub fn new(op: char, spacing: Spacing) -> Punct {
703 Punct {
David Tolnayf0814122019-07-19 11:53:55 -0700704 op,
705 spacing,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700706 span: Span::call_site(),
707 }
708 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700709
David Tolnay82ba02d2018-05-20 16:22:43 -0700710 /// Returns the value of this punctuation character as `char`.
Alex Crichtonf3888432018-05-16 09:11:05 -0700711 pub fn as_char(&self) -> char {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700712 self.op
713 }
714
David Tolnay82ba02d2018-05-20 16:22:43 -0700715 /// Returns the spacing of this punctuation character, indicating whether
716 /// it's immediately followed by another `Punct` in the token stream, so
717 /// they can potentially be combined into a multicharacter operator
718 /// (`Joint`), or it's followed by some other token or whitespace (`Alone`)
719 /// so the operator has certainly ended.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700720 pub fn spacing(&self) -> Spacing {
721 self.spacing
722 }
723
David Tolnay82ba02d2018-05-20 16:22:43 -0700724 /// Returns the span for this punctuation character.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700725 pub fn span(&self) -> Span {
726 self.span
727 }
728
David Tolnay82ba02d2018-05-20 16:22:43 -0700729 /// Configure the span for this punctuation character.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700730 pub fn set_span(&mut self, span: Span) {
731 self.span = span;
732 }
733}
734
David Tolnay82ba02d2018-05-20 16:22:43 -0700735/// Prints the punctuation character as a string that should be losslessly
736/// convertible back into the same character.
Alex Crichtonf3888432018-05-16 09:11:05 -0700737impl fmt::Display for Punct {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700738 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
739 self.op.fmt(f)
740 }
741}
742
Alex Crichtonf3888432018-05-16 09:11:05 -0700743impl fmt::Debug for Punct {
David Tolnay034205f2018-04-22 16:45:28 -0700744 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonf3888432018-05-16 09:11:05 -0700745 let mut debug = fmt.debug_struct("Punct");
David Tolnay034205f2018-04-22 16:45:28 -0700746 debug.field("op", &self.op);
747 debug.field("spacing", &self.spacing);
David Tolnayfd8cdc82019-01-19 19:23:59 -0800748 imp::debug_span_field_if_nontrivial(&mut debug, self.span.inner);
David Tolnay034205f2018-04-22 16:45:28 -0700749 debug.finish()
750 }
751}
752
David Tolnay8b71dac2018-05-20 17:07:47 -0700753/// A word of Rust code, which may be a keyword or legal variable name.
754///
755/// An identifier consists of at least one Unicode code point, the first of
756/// which has the XID_Start property and the rest of which have the XID_Continue
757/// property.
758///
759/// - The empty string is not an identifier. Use `Option<Ident>`.
760/// - A lifetime is not an identifier. Use `syn::Lifetime` instead.
761///
762/// An identifier constructed with `Ident::new` is permitted to be a Rust
David Tolnayc239f032018-11-11 12:57:09 -0800763/// keyword, though parsing one through its [`Parse`] implementation rejects
764/// Rust keywords. Use `input.call(Ident::parse_any)` when parsing to match the
David Tolnay8b71dac2018-05-20 17:07:47 -0700765/// behaviour of `Ident::new`.
766///
David Tolnayc239f032018-11-11 12:57:09 -0800767/// [`Parse`]: https://docs.rs/syn/0.15/syn/parse/trait.Parse.html
David Tolnay8b71dac2018-05-20 17:07:47 -0700768///
769/// # Examples
770///
771/// A new ident can be created from a string using the `Ident::new` function.
772/// A span must be provided explicitly which governs the name resolution
773/// behavior of the resulting identifier.
774///
David Tolnay7a964732019-01-19 19:03:20 -0800775/// ```edition2018
David Tolnay8b71dac2018-05-20 17:07:47 -0700776/// use proc_macro2::{Ident, Span};
777///
778/// fn main() {
779/// let call_ident = Ident::new("calligraphy", Span::call_site());
780///
781/// println!("{}", call_ident);
782/// }
783/// ```
784///
785/// An ident can be interpolated into a token stream using the `quote!` macro.
786///
David Tolnay7a964732019-01-19 19:03:20 -0800787/// ```edition2018
David Tolnay8b71dac2018-05-20 17:07:47 -0700788/// use proc_macro2::{Ident, Span};
David Tolnay7a964732019-01-19 19:03:20 -0800789/// use quote::quote;
David Tolnay8b71dac2018-05-20 17:07:47 -0700790///
791/// fn main() {
792/// let ident = Ident::new("demo", Span::call_site());
793///
794/// // Create a variable binding whose name is this ident.
795/// let expanded = quote! { let #ident = 10; };
796///
797/// // Create a variable binding with a slightly different name.
798/// let temp_ident = Ident::new(&format!("new_{}", ident), Span::call_site());
799/// let expanded = quote! { let #temp_ident = 10; };
800/// }
801/// ```
802///
803/// A string representation of the ident is available through the `to_string()`
804/// method.
805///
David Tolnay7a964732019-01-19 19:03:20 -0800806/// ```edition2018
David Tolnay8b71dac2018-05-20 17:07:47 -0700807/// # use proc_macro2::{Ident, Span};
808/// #
809/// # let ident = Ident::new("another_identifier", Span::call_site());
810/// #
811/// // Examine the ident as a string.
812/// let ident_string = ident.to_string();
813/// if ident_string.len() > 60 {
814/// println!("Very long identifier: {}", ident_string)
815/// }
816/// ```
Alex Crichtonf3888432018-05-16 09:11:05 -0700817#[derive(Clone)]
818pub struct Ident {
819 inner: imp::Ident,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700820 _marker: marker::PhantomData<Rc<()>>,
821}
822
Alex Crichtonf3888432018-05-16 09:11:05 -0700823impl Ident {
824 fn _new(inner: imp::Ident) -> Ident {
825 Ident {
David Tolnayf0814122019-07-19 11:53:55 -0700826 inner,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700827 _marker: marker::PhantomData,
828 }
829 }
830
David Tolnay82ba02d2018-05-20 16:22:43 -0700831 /// Creates a new `Ident` with the given `string` as well as the specified
832 /// `span`.
833 ///
834 /// The `string` argument must be a valid identifier permitted by the
835 /// language, otherwise the function will panic.
836 ///
837 /// Note that `span`, currently in rustc, configures the hygiene information
838 /// for this identifier.
839 ///
840 /// As of this time `Span::call_site()` explicitly opts-in to "call-site"
841 /// hygiene meaning that identifiers created with this span will be resolved
842 /// as if they were written directly at the location of the macro call, and
843 /// other code at the macro call site will be able to refer to them as well.
844 ///
845 /// Later spans like `Span::def_site()` will allow to opt-in to
846 /// "definition-site" hygiene meaning that identifiers created with this
847 /// span will be resolved at the location of the macro definition and other
848 /// code at the macro call site will not be able to refer to them.
849 ///
850 /// Due to the current importance of hygiene this constructor, unlike other
851 /// tokens, requires a `Span` to be specified at construction.
David Tolnay8b71dac2018-05-20 17:07:47 -0700852 ///
853 /// # Panics
854 ///
855 /// Panics if the input string is neither a keyword nor a legal variable
David Tolnay219b1d32019-04-22 16:04:11 -0700856 /// name. If you are not sure whether the string contains an identifier and
857 /// need to handle an error case, use
858 /// <a href="https://docs.rs/syn/0.15/syn/fn.parse_str.html"><code
859 /// style="padding-right:0;">syn::parse_str</code></a><code
860 /// style="padding-left:0;">::&lt;Ident&gt;</code>
861 /// rather than `Ident::new`.
Alex Crichtonf3888432018-05-16 09:11:05 -0700862 pub fn new(string: &str, span: Span) -> Ident {
863 Ident::_new(imp::Ident::new(string, span.inner))
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700864 }
865
David Tolnay82ba02d2018-05-20 16:22:43 -0700866 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
David Tolnaya01ca8e2018-06-04 00:55:28 -0700867 ///
868 /// This method is semver exempt and not exposed by default.
Alex Crichtonf3888432018-05-16 09:11:05 -0700869 #[cfg(procmacro2_semver_exempt)]
870 pub fn new_raw(string: &str, span: Span) -> Ident {
871 Ident::_new_raw(string, span)
872 }
873
874 fn _new_raw(string: &str, span: Span) -> Ident {
875 Ident::_new(imp::Ident::new_raw(string, span.inner))
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700876 }
877
David Tolnay82ba02d2018-05-20 16:22:43 -0700878 /// Returns the span of this `Ident`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700879 pub fn span(&self) -> Span {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700880 Span::_new(self.inner.span())
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700881 }
882
David Tolnay82ba02d2018-05-20 16:22:43 -0700883 /// Configures the span of this `Ident`, possibly changing its hygiene
884 /// context.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700885 pub fn set_span(&mut self, span: Span) {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700886 self.inner.set_span(span.inner);
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700887 }
888}
889
Alex Crichtonf3888432018-05-16 09:11:05 -0700890impl PartialEq for Ident {
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700891 fn eq(&self, other: &Ident) -> bool {
David Tolnayc0b0f2e2018-09-02 17:56:08 -0700892 self.inner == other.inner
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700893 }
894}
895
David Tolnayc0bbcc52018-05-18 10:51:04 -0700896impl<T> PartialEq<T> for Ident
897where
898 T: ?Sized + AsRef<str>,
899{
900 fn eq(&self, other: &T) -> bool {
David Tolnayc0b0f2e2018-09-02 17:56:08 -0700901 self.inner == other
David Tolnayc0bbcc52018-05-18 10:51:04 -0700902 }
903}
904
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700905impl Eq for Ident {}
Alex Crichtonf3888432018-05-16 09:11:05 -0700906
907impl PartialOrd for Ident {
908 fn partial_cmp(&self, other: &Ident) -> Option<Ordering> {
909 Some(self.cmp(other))
910 }
911}
912
913impl Ord for Ident {
914 fn cmp(&self, other: &Ident) -> Ordering {
915 self.to_string().cmp(&other.to_string())
916 }
917}
918
919impl Hash for Ident {
920 fn hash<H: Hasher>(&self, hasher: &mut H) {
921 self.to_string().hash(hasher)
922 }
923}
924
David Tolnay82ba02d2018-05-20 16:22:43 -0700925/// Prints the identifier as a string that should be losslessly convertible back
926/// into the same identifier.
Alex Crichtonf3888432018-05-16 09:11:05 -0700927impl fmt::Display for Ident {
928 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
929 self.inner.fmt(f)
930 }
931}
932
933impl fmt::Debug for Ident {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700934 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
935 self.inner.fmt(f)
936 }
937}
938
David Tolnay82ba02d2018-05-20 16:22:43 -0700939/// A literal string (`"hello"`), byte string (`b"hello"`), character (`'a'`),
940/// byte character (`b'a'`), an integer or floating point number with or without
941/// a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
942///
943/// Boolean literals like `true` and `false` do not belong here, they are
944/// `Ident`s.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700945#[derive(Clone)]
946pub struct Literal {
947 inner: imp::Literal,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700948 _marker: marker::PhantomData<Rc<()>>,
949}
950
David Tolnay82ba02d2018-05-20 16:22:43 -0700951macro_rules! suffixed_int_literals {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700952 ($($name:ident => $kind:ident,)*) => ($(
David Tolnay82ba02d2018-05-20 16:22:43 -0700953 /// Creates a new suffixed integer literal with the specified value.
954 ///
955 /// This function will create an integer like `1u32` where the integer
956 /// value specified is the first part of the token and the integral is
957 /// also suffixed at the end. Literals created from negative numbers may
958 /// not survive rountrips through `TokenStream` or strings and may be
959 /// broken into two tokens (`-` and positive literal).
960 ///
961 /// Literals created through this method have the `Span::call_site()`
962 /// span by default, which can be configured with the `set_span` method
963 /// below.
964 pub fn $name(n: $kind) -> Literal {
965 Literal::_new(imp::Literal::$name(n))
966 }
967 )*)
968}
969
970macro_rules! unsuffixed_int_literals {
971 ($($name:ident => $kind:ident,)*) => ($(
972 /// Creates a new unsuffixed integer literal with the specified value.
973 ///
974 /// This function will create an integer like `1` where the integer
975 /// value specified is the first part of the token. No suffix is
976 /// specified on this token, meaning that invocations like
977 /// `Literal::i8_unsuffixed(1)` are equivalent to
978 /// `Literal::u32_unsuffixed(1)`. Literals created from negative numbers
979 /// may not survive rountrips through `TokenStream` or strings and may
980 /// be broken into two tokens (`-` and positive literal).
981 ///
982 /// Literals created through this method have the `Span::call_site()`
983 /// span by default, which can be configured with the `set_span` method
984 /// below.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700985 pub fn $name(n: $kind) -> Literal {
Alex Crichtona914a612018-04-04 07:48:44 -0700986 Literal::_new(imp::Literal::$name(n))
Alex Crichton1a7f7622017-07-05 17:47:15 -0700987 }
988 )*)
989}
990
Alex Crichton852d53d2017-05-19 19:25:08 -0700991impl Literal {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700992 fn _new(inner: imp::Literal) -> Literal {
993 Literal {
David Tolnayf0814122019-07-19 11:53:55 -0700994 inner,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700995 _marker: marker::PhantomData,
996 }
Alex Crichton1a7f7622017-07-05 17:47:15 -0700997 }
998
David Tolnayaef075b2019-01-16 16:29:18 -0800999 fn _new_stable(inner: fallback::Literal) -> Literal {
Alex Crichton30a4e9e2018-04-27 17:02:19 -07001000 Literal {
1001 inner: inner.into(),
1002 _marker: marker::PhantomData,
1003 }
1004 }
1005
David Tolnay82ba02d2018-05-20 16:22:43 -07001006 suffixed_int_literals! {
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001007 u8_suffixed => u8,
1008 u16_suffixed => u16,
1009 u32_suffixed => u32,
1010 u64_suffixed => u64,
David Tolnay1596a8c2019-07-19 11:45:26 -07001011 u128_suffixed => u128,
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001012 usize_suffixed => usize,
1013 i8_suffixed => i8,
1014 i16_suffixed => i16,
1015 i32_suffixed => i32,
1016 i64_suffixed => i64,
Alex Crichton69385662018-11-08 06:30:04 -08001017 i128_suffixed => i128,
David Tolnay1596a8c2019-07-19 11:45:26 -07001018 isize_suffixed => isize,
Alex Crichton69385662018-11-08 06:30:04 -08001019 }
1020
David Tolnay82ba02d2018-05-20 16:22:43 -07001021 unsuffixed_int_literals! {
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001022 u8_unsuffixed => u8,
1023 u16_unsuffixed => u16,
1024 u32_unsuffixed => u32,
1025 u64_unsuffixed => u64,
David Tolnay1596a8c2019-07-19 11:45:26 -07001026 u128_unsuffixed => u128,
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001027 usize_unsuffixed => usize,
1028 i8_unsuffixed => i8,
1029 i16_unsuffixed => i16,
1030 i32_unsuffixed => i32,
1031 i64_unsuffixed => i64,
Alex Crichton69385662018-11-08 06:30:04 -08001032 i128_unsuffixed => i128,
David Tolnay1596a8c2019-07-19 11:45:26 -07001033 isize_unsuffixed => isize,
Alex Crichton69385662018-11-08 06:30:04 -08001034 }
1035
David Tolnaybc3bd3f2019-06-30 13:03:56 -07001036 /// Creates a new unsuffixed floating-point literal.
1037 ///
1038 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1039 /// the float's value is emitted directly into the token but no suffix is
1040 /// used, so it may be inferred to be a `f64` later in the compiler.
1041 /// Literals created from negative numbers may not survive rountrips through
1042 /// `TokenStream` or strings and may be broken into two tokens (`-` and
1043 /// positive literal).
1044 ///
1045 /// # Panics
1046 ///
1047 /// This function requires that the specified float is finite, for example
1048 /// if it is infinity or NaN this function will panic.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001049 pub fn f64_unsuffixed(f: f64) -> Literal {
1050 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -07001051 Literal::_new(imp::Literal::f64_unsuffixed(f))
Alex Crichton1a7f7622017-07-05 17:47:15 -07001052 }
1053
David Tolnaybc3bd3f2019-06-30 13:03:56 -07001054 /// Creates a new suffixed floating-point literal.
1055 ///
1056 /// This constructor will create a literal like `1.0f64` where the value
1057 /// specified is the preceding part of the token and `f64` is the suffix of
1058 /// the token. This token will always be inferred to be an `f64` in the
1059 /// compiler. Literals created from negative numbers may not survive
1060 /// rountrips through `TokenStream` or strings and may be broken into two
1061 /// tokens (`-` and positive literal).
1062 ///
1063 /// # Panics
1064 ///
1065 /// This function requires that the specified float is finite, for example
1066 /// if it is infinity or NaN this function will panic.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001067 pub fn f64_suffixed(f: f64) -> Literal {
1068 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -07001069 Literal::_new(imp::Literal::f64_suffixed(f))
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001070 }
1071
David Tolnay82ba02d2018-05-20 16:22:43 -07001072 /// Creates a new unsuffixed floating-point literal.
1073 ///
1074 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1075 /// the float's value is emitted directly into the token but no suffix is
1076 /// used, so it may be inferred to be a `f64` later in the compiler.
1077 /// Literals created from negative numbers may not survive rountrips through
1078 /// `TokenStream` or strings and may be broken into two tokens (`-` and
1079 /// positive literal).
1080 ///
1081 /// # Panics
1082 ///
1083 /// This function requires that the specified float is finite, for example
1084 /// if it is infinity or NaN this function will panic.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001085 pub fn f32_unsuffixed(f: f32) -> Literal {
1086 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -07001087 Literal::_new(imp::Literal::f32_unsuffixed(f))
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001088 }
1089
David Tolnaybc3bd3f2019-06-30 13:03:56 -07001090 /// Creates a new suffixed floating-point literal.
1091 ///
1092 /// This constructor will create a literal like `1.0f32` where the value
1093 /// specified is the preceding part of the token and `f32` is the suffix of
1094 /// the token. This token will always be inferred to be an `f32` in the
1095 /// compiler. Literals created from negative numbers may not survive
1096 /// rountrips through `TokenStream` or strings and may be broken into two
1097 /// tokens (`-` and positive literal).
1098 ///
1099 /// # Panics
1100 ///
1101 /// This function requires that the specified float is finite, for example
1102 /// if it is infinity or NaN this function will panic.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001103 pub fn f32_suffixed(f: f32) -> Literal {
1104 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -07001105 Literal::_new(imp::Literal::f32_suffixed(f))
Alex Crichton1a7f7622017-07-05 17:47:15 -07001106 }
1107
David Tolnaybc3bd3f2019-06-30 13:03:56 -07001108 /// String literal.
Alex Crichton1a7f7622017-07-05 17:47:15 -07001109 pub fn string(string: &str) -> Literal {
Alex Crichtona914a612018-04-04 07:48:44 -07001110 Literal::_new(imp::Literal::string(string))
Alex Crichton1a7f7622017-07-05 17:47:15 -07001111 }
1112
David Tolnaybc3bd3f2019-06-30 13:03:56 -07001113 /// Character literal.
Alex Crichton1a7f7622017-07-05 17:47:15 -07001114 pub fn character(ch: char) -> Literal {
Alex Crichtona914a612018-04-04 07:48:44 -07001115 Literal::_new(imp::Literal::character(ch))
Alex Crichton76a5cc82017-05-23 07:01:44 -07001116 }
1117
David Tolnaybc3bd3f2019-06-30 13:03:56 -07001118 /// Byte string literal.
Alex Crichton9c2fb0a2017-05-26 08:49:31 -07001119 pub fn byte_string(s: &[u8]) -> Literal {
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001120 Literal::_new(imp::Literal::byte_string(s))
Alex Crichton852d53d2017-05-19 19:25:08 -07001121 }
Alex Crichton76a5cc82017-05-23 07:01:44 -07001122
David Tolnaybc3bd3f2019-06-30 13:03:56 -07001123 /// Returns the span encompassing this literal.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001124 pub fn span(&self) -> Span {
Alex Crichtonb2c94622018-04-04 07:36:41 -07001125 Span::_new(self.inner.span())
Alex Crichton1a7f7622017-07-05 17:47:15 -07001126 }
1127
David Tolnaybc3bd3f2019-06-30 13:03:56 -07001128 /// Configures the span associated for this literal.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001129 pub fn set_span(&mut self, span: Span) {
Alex Crichtonb2c94622018-04-04 07:36:41 -07001130 self.inner.set_span(span.inner);
Alex Crichton31316622017-05-26 12:54:47 -07001131 }
Alex Crichton852d53d2017-05-19 19:25:08 -07001132}
1133
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001134impl fmt::Debug for Literal {
1135 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1136 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001137 }
1138}
David Tolnaycb1b85f2017-06-03 16:40:35 -07001139
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001140impl fmt::Display for Literal {
1141 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1142 self.inner.fmt(f)
1143 }
1144}
1145
David Tolnay82ba02d2018-05-20 16:22:43 -07001146/// Public implementation details for the `TokenStream` type, such as iterators.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001147pub mod token_stream {
1148 use std::fmt;
1149 use std::marker;
1150 use std::rc::Rc;
1151
David Tolnay0f884b12019-07-19 11:59:20 -07001152 pub use crate::TokenStream;
1153 use crate::{imp, TokenTree};
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001154
David Tolnay82ba02d2018-05-20 16:22:43 -07001155 /// An iterator over `TokenStream`'s `TokenTree`s.
1156 ///
1157 /// The iteration is "shallow", e.g. the iterator doesn't recurse into
1158 /// delimited groups, and returns whole groups as token trees.
Isaac van Bakelf6754d32019-05-08 20:21:06 +01001159 #[derive(Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001160 pub struct IntoIter {
1161 inner: imp::TokenTreeIter,
1162 _marker: marker::PhantomData<Rc<()>>,
1163 }
1164
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001165 impl Iterator for IntoIter {
1166 type Item = TokenTree;
1167
1168 fn next(&mut self) -> Option<TokenTree> {
1169 self.inner.next()
1170 }
1171 }
1172
1173 impl fmt::Debug for IntoIter {
1174 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1175 self.inner.fmt(f)
1176 }
1177 }
1178
1179 impl IntoIterator for TokenStream {
1180 type Item = TokenTree;
1181 type IntoIter = IntoIter;
1182
1183 fn into_iter(self) -> IntoIter {
1184 IntoIter {
1185 inner: self.inner.into_iter(),
1186 _marker: marker::PhantomData,
1187 }
1188 }
1189 }
1190}