blob: 63b0ad6f720e61511ebfed7c4d170f68a6800ff6 [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;
David Tolnayb1032662017-05-31 15:52:28 -070094extern crate unicode_xid;
Alex Crichton44bffbc2017-05-19 17:51:59 -070095
Alex Crichtonf3888432018-05-16 09:11:05 -070096use std::cmp::Ordering;
Alex Crichton44bffbc2017-05-19 17:51:59 -070097use std::fmt;
Alex Crichtonf3888432018-05-16 09:11:05 -070098use std::hash::{Hash, Hasher};
Alex Crichton44bffbc2017-05-19 17:51:59 -070099use std::iter::FromIterator;
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700100use std::marker;
David Tolnay9cd3b4c2018-11-11 16:47:32 -0800101#[cfg(procmacro2_semver_exempt)]
102use std::path::PathBuf;
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700103use std::rc::Rc;
104use std::str::FromStr;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700105
David Tolnayb1032662017-05-31 15:52:28 -0700106#[macro_use]
David Tolnayb1032662017-05-31 15:52:28 -0700107mod strnom;
David Tolnayaef075b2019-01-16 16:29:18 -0800108mod fallback;
David Tolnayb1032662017-05-31 15:52:28 -0700109
Alex Crichtonce0904d2018-08-27 17:29:49 -0700110#[cfg(not(wrap_proc_macro))]
David Tolnayaef075b2019-01-16 16:29:18 -0800111use fallback as imp;
112#[path = "wrapper.rs"]
Alex Crichtonce0904d2018-08-27 17:29:49 -0700113#[cfg(wrap_proc_macro)]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700114mod imp;
115
David Tolnay82ba02d2018-05-20 16:22:43 -0700116/// An abstract stream of tokens, or more concretely a sequence of token trees.
117///
118/// This type provides interfaces for iterating over token trees and for
119/// collecting token trees into one stream.
120///
121/// Token stream is both the input and output of `#[proc_macro]`,
122/// `#[proc_macro_attribute]` and `#[proc_macro_derive]` definitions.
David Tolnaycb1b85f2017-06-03 16:40:35 -0700123#[derive(Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700124pub struct TokenStream {
125 inner: imp::TokenStream,
126 _marker: marker::PhantomData<Rc<()>>,
127}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700128
David Tolnay82ba02d2018-05-20 16:22:43 -0700129/// Error returned from `TokenStream::from_str`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700130pub struct LexError {
131 inner: imp::LexError,
132 _marker: marker::PhantomData<Rc<()>>,
133}
134
135impl TokenStream {
136 fn _new(inner: imp::TokenStream) -> TokenStream {
137 TokenStream {
138 inner: inner,
139 _marker: marker::PhantomData,
140 }
141 }
142
David Tolnayaef075b2019-01-16 16:29:18 -0800143 fn _new_stable(inner: fallback::TokenStream) -> TokenStream {
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700144 TokenStream {
145 inner: inner.into(),
146 _marker: marker::PhantomData,
147 }
148 }
149
David Tolnay82ba02d2018-05-20 16:22:43 -0700150 /// Returns an empty `TokenStream` containing no token trees.
David Tolnayc3bb4592018-05-28 20:09:44 -0700151 pub fn new() -> TokenStream {
152 TokenStream::_new(imp::TokenStream::new())
153 }
154
155 #[deprecated(since = "0.4.4", note = "please use TokenStream::new")]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700156 pub fn empty() -> TokenStream {
David Tolnayc3bb4592018-05-28 20:09:44 -0700157 TokenStream::new()
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700158 }
159
David Tolnay82ba02d2018-05-20 16:22:43 -0700160 /// Checks if this `TokenStream` is empty.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700161 pub fn is_empty(&self) -> bool {
162 self.inner.is_empty()
163 }
164}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700165
Árpád Goretity4f74b682018-07-14 00:47:51 +0200166/// `TokenStream::default()` returns an empty stream,
167/// i.e. this is equivalent with `TokenStream::new()`.
168impl Default for TokenStream {
169 fn default() -> Self {
170 TokenStream::new()
171 }
172}
173
David Tolnay82ba02d2018-05-20 16:22:43 -0700174/// Attempts to break the string into tokens and parse those tokens into a token
175/// stream.
176///
177/// May fail for a number of reasons, for example, if the string contains
178/// unbalanced delimiters or characters not existing in the language.
179///
180/// NOTE: Some errors may cause panics instead of returning `LexError`. We
181/// reserve the right to change these errors into `LexError`s later.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700182impl FromStr for TokenStream {
183 type Err = LexError;
184
185 fn from_str(src: &str) -> Result<TokenStream, LexError> {
David Tolnayb28f38a2018-03-31 22:02:29 +0200186 let e = src.parse().map_err(|e| LexError {
187 inner: e,
188 _marker: marker::PhantomData,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700189 })?;
190 Ok(TokenStream::_new(e))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700191 }
192}
193
Alex Crichton53548482018-08-11 21:54:05 -0700194#[cfg(use_proc_macro)]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700195impl From<proc_macro::TokenStream> for TokenStream {
196 fn from(inner: proc_macro::TokenStream) -> TokenStream {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700197 TokenStream::_new(inner.into())
Alex Crichton44bffbc2017-05-19 17:51:59 -0700198 }
199}
200
Alex Crichton53548482018-08-11 21:54:05 -0700201#[cfg(use_proc_macro)]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700202impl From<TokenStream> for proc_macro::TokenStream {
203 fn from(inner: TokenStream) -> proc_macro::TokenStream {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700204 inner.inner.into()
Alex Crichton44bffbc2017-05-19 17:51:59 -0700205 }
206}
207
Alex Crichtonf3888432018-05-16 09:11:05 -0700208impl Extend<TokenTree> for TokenStream {
209 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, streams: I) {
210 self.inner.extend(streams)
211 }
212}
213
David Tolnay5c58c532018-08-13 11:33:51 -0700214impl Extend<TokenStream> for TokenStream {
215 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
216 self.inner
217 .extend(streams.into_iter().map(|stream| stream.inner))
218 }
219}
220
David Tolnay82ba02d2018-05-20 16:22:43 -0700221/// Collects a number of token trees into a single stream.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700222impl FromIterator<TokenTree> for TokenStream {
223 fn from_iter<I: IntoIterator<Item = TokenTree>>(streams: I) -> Self {
224 TokenStream::_new(streams.into_iter().collect())
Alex Crichton44bffbc2017-05-19 17:51:59 -0700225 }
226}
Alex Crichton53b00672018-09-06 17:16:10 -0700227impl FromIterator<TokenStream> for TokenStream {
228 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
229 TokenStream::_new(streams.into_iter().map(|i| i.inner).collect())
230 }
231}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700232
David Tolnay82ba02d2018-05-20 16:22:43 -0700233/// Prints the token stream as a string that is supposed to be losslessly
234/// convertible back into the same token stream (modulo spans), except for
235/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
236/// numeric literals.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700237impl fmt::Display for TokenStream {
238 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
239 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700240 }
241}
242
David Tolnay82ba02d2018-05-20 16:22:43 -0700243/// Prints token in a form convenient for debugging.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700244impl fmt::Debug for TokenStream {
245 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
246 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700247 }
248}
249
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700250impl fmt::Debug for LexError {
251 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
252 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700253 }
254}
255
David Tolnay82ba02d2018-05-20 16:22:43 -0700256/// The source file of a given `Span`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700257///
258/// This type is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800259#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500260#[derive(Clone, PartialEq, Eq)]
David Tolnay7e654a82018-11-11 13:33:18 -0800261pub struct SourceFile {
262 inner: imp::SourceFile,
263 _marker: marker::PhantomData<Rc<()>>,
264}
Nika Layzellf8d5f212017-12-11 14:07:02 -0500265
David Tolnay1ebe3972018-01-02 20:14:20 -0800266#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500267impl SourceFile {
David Tolnay7e654a82018-11-11 13:33:18 -0800268 fn _new(inner: imp::SourceFile) -> Self {
269 SourceFile {
270 inner: inner,
271 _marker: marker::PhantomData,
272 }
273 }
274
David Tolnay82ba02d2018-05-20 16:22:43 -0700275 /// Get the path to this source file.
276 ///
277 /// ### Note
278 ///
279 /// If the code span associated with this `SourceFile` was generated by an
280 /// external macro, this may not be an actual path on the filesystem. Use
281 /// [`is_real`] to check.
282 ///
283 /// Also note that even if `is_real` returns `true`, if
284 /// `--remap-path-prefix` was passed on the command line, the path as given
285 /// may not actually be valid.
286 ///
287 /// [`is_real`]: #method.is_real
David Tolnay9cd3b4c2018-11-11 16:47:32 -0800288 pub fn path(&self) -> PathBuf {
David Tolnay7e654a82018-11-11 13:33:18 -0800289 self.inner.path()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500290 }
291
David Tolnay82ba02d2018-05-20 16:22:43 -0700292 /// Returns `true` if this source file is a real source file, and not
293 /// generated by an external macro's expansion.
Nika Layzellf8d5f212017-12-11 14:07:02 -0500294 pub fn is_real(&self) -> bool {
David Tolnay7e654a82018-11-11 13:33:18 -0800295 self.inner.is_real()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500296 }
297}
298
David Tolnay1ebe3972018-01-02 20:14:20 -0800299#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500300impl fmt::Debug for SourceFile {
301 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
David Tolnay7e654a82018-11-11 13:33:18 -0800302 self.inner.fmt(f)
Nika Layzellf8d5f212017-12-11 14:07:02 -0500303 }
304}
305
David Tolnay82ba02d2018-05-20 16:22:43 -0700306/// A line-column pair representing the start or end of a `Span`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700307///
308/// This type is semver exempt and not exposed by default.
David Tolnay3b1f7d22019-01-28 12:22:11 -0800309#[cfg(span_locations)]
David Tolnay9d4fb442019-04-22 16:42:41 -0700310#[derive(Copy, Clone, Debug, PartialEq, Eq)]
Nika Layzell1ecb6ce2017-12-30 14:34:05 -0500311pub struct LineColumn {
David Tolnay82ba02d2018-05-20 16:22:43 -0700312 /// The 1-indexed line in the source file on which the span starts or ends
313 /// (inclusive).
Nika Layzell1ecb6ce2017-12-30 14:34:05 -0500314 pub line: usize,
David Tolnay82ba02d2018-05-20 16:22:43 -0700315 /// The 0-indexed column (in UTF-8 characters) in the source file on which
316 /// the span starts or ends (inclusive).
Nika Layzell1ecb6ce2017-12-30 14:34:05 -0500317 pub column: usize,
318}
Nika Layzellf8d5f212017-12-11 14:07:02 -0500319
David Tolnay82ba02d2018-05-20 16:22:43 -0700320/// A region of source code, along with macro expansion information.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700321#[derive(Copy, Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700322pub struct Span {
323 inner: imp::Span,
324 _marker: marker::PhantomData<Rc<()>>,
325}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700326
Alex Crichton44bffbc2017-05-19 17:51:59 -0700327impl Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700328 fn _new(inner: imp::Span) -> Span {
329 Span {
330 inner: inner,
331 _marker: marker::PhantomData,
332 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700333 }
Alex Crichtone6085b72017-11-21 07:24:25 -0800334
David Tolnayaef075b2019-01-16 16:29:18 -0800335 fn _new_stable(inner: fallback::Span) -> Span {
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700336 Span {
337 inner: inner.into(),
338 _marker: marker::PhantomData,
339 }
340 }
341
David Tolnay82ba02d2018-05-20 16:22:43 -0700342 /// The span of the invocation of the current procedural macro.
343 ///
344 /// Identifiers created with this span will be resolved as if they were
345 /// written directly at the macro call location (call-site hygiene) and
346 /// other code at the macro call site will be able to refer to them as well.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700347 pub fn call_site() -> Span {
348 Span::_new(imp::Span::call_site())
349 }
350
David Tolnay82ba02d2018-05-20 16:22:43 -0700351 /// A span that resolves at the macro definition site.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700352 ///
353 /// This method is semver exempt and not exposed by default.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700354 #[cfg(procmacro2_semver_exempt)]
Alex Crichtone6085b72017-11-21 07:24:25 -0800355 pub fn def_site() -> Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700356 Span::_new(imp::Span::def_site())
Alex Crichtone6085b72017-11-21 07:24:25 -0800357 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500358
David Tolnay4e8e3972018-01-05 18:10:22 -0800359 /// Creates a new span with the same line/column information as `self` but
360 /// that resolves symbols as though it were at `other`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700361 ///
362 /// This method is semver exempt and not exposed by default.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700363 #[cfg(procmacro2_semver_exempt)]
David Tolnay4e8e3972018-01-05 18:10:22 -0800364 pub fn resolved_at(&self, other: Span) -> Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700365 Span::_new(self.inner.resolved_at(other.inner))
David Tolnay4e8e3972018-01-05 18:10:22 -0800366 }
367
368 /// Creates a new span with the same name resolution behavior as `self` but
369 /// with the line/column information of `other`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700370 ///
371 /// This method is semver exempt and not exposed by default.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700372 #[cfg(procmacro2_semver_exempt)]
David Tolnay4e8e3972018-01-05 18:10:22 -0800373 pub fn located_at(&self, other: Span) -> Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700374 Span::_new(self.inner.located_at(other.inner))
David Tolnay4e8e3972018-01-05 18:10:22 -0800375 }
376
David Tolnay17eb0702019-01-05 12:23:17 -0800377 /// Convert `proc_macro2::Span` to `proc_macro::Span`.
378 ///
379 /// This method is available when building with a nightly compiler, or when
380 /// building with rustc 1.29+ *without* semver exempt features.
David Tolnayc0425cd2019-01-16 12:13:15 -0800381 ///
382 /// # Panics
383 ///
384 /// Panics if called from outside of a procedural macro. Unlike
385 /// `proc_macro2::Span`, the `proc_macro::Span` type can only exist within
386 /// the context of a procedural macro invocation.
David Tolnay17eb0702019-01-05 12:23:17 -0800387 #[cfg(wrap_proc_macro)]
David Tolnay40bbb1c2019-01-19 19:43:55 -0800388 pub fn unwrap(self) -> proc_macro::Span {
389 self.inner.unwrap()
390 }
391
392 // Soft deprecated. Please use Span::unwrap.
393 #[cfg(wrap_proc_macro)]
394 #[doc(hidden)]
David Tolnay16a17202017-12-31 10:47:24 -0500395 pub fn unstable(self) -> proc_macro::Span {
David Tolnay40bbb1c2019-01-19 19:43:55 -0800396 self.unwrap()
David Tolnay16a17202017-12-31 10:47:24 -0500397 }
398
David Tolnay82ba02d2018-05-20 16:22:43 -0700399 /// The original source file into which this span points.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700400 ///
401 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800402 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500403 pub fn source_file(&self) -> SourceFile {
David Tolnay7e654a82018-11-11 13:33:18 -0800404 SourceFile::_new(self.inner.source_file())
Nika Layzellf8d5f212017-12-11 14:07:02 -0500405 }
406
David Tolnay82ba02d2018-05-20 16:22:43 -0700407 /// Get the starting line/column in the source file for this span.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700408 ///
David Tolnay3b1f7d22019-01-28 12:22:11 -0800409 /// This method requires the `"span-locations"` feature to be enabled.
410 #[cfg(span_locations)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500411 pub fn start(&self) -> LineColumn {
David Tolnayb28f38a2018-03-31 22:02:29 +0200412 let imp::LineColumn { line, column } = self.inner.start();
413 LineColumn {
414 line: line,
415 column: column,
416 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500417 }
418
David Tolnay82ba02d2018-05-20 16:22:43 -0700419 /// Get the ending line/column in the source file for this span.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700420 ///
David Tolnay3b1f7d22019-01-28 12:22:11 -0800421 /// This method requires the `"span-locations"` feature to be enabled.
422 #[cfg(span_locations)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500423 pub fn end(&self) -> LineColumn {
David Tolnayb28f38a2018-03-31 22:02:29 +0200424 let imp::LineColumn { line, column } = self.inner.end();
425 LineColumn {
426 line: line,
427 column: column,
428 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500429 }
430
David Tolnay82ba02d2018-05-20 16:22:43 -0700431 /// Create a new span encompassing `self` and `other`.
432 ///
433 /// Returns `None` if `self` and `other` are from different files.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700434 ///
435 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800436 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500437 pub fn join(&self, other: Span) -> Option<Span> {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700438 self.inner.join(other.inner).map(Span::_new)
439 }
Alex Crichtonb2c94622018-04-04 07:36:41 -0700440
David Tolnay82ba02d2018-05-20 16:22:43 -0700441 /// Compares to spans to see if they're equal.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700442 ///
443 /// This method is semver exempt and not exposed by default.
Alex Crichtonb2c94622018-04-04 07:36:41 -0700444 #[cfg(procmacro2_semver_exempt)]
445 pub fn eq(&self, other: &Span) -> bool {
446 self.inner.eq(&other.inner)
447 }
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700448}
449
David Tolnay82ba02d2018-05-20 16:22:43 -0700450/// Prints a span in a form convenient for debugging.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700451impl fmt::Debug for Span {
452 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
453 self.inner.fmt(f)
Nika Layzellf8d5f212017-12-11 14:07:02 -0500454 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700455}
456
David Tolnay82ba02d2018-05-20 16:22:43 -0700457/// A single token or a delimited sequence of token trees (e.g. `[1, (), ..]`).
David Tolnay034205f2018-04-22 16:45:28 -0700458#[derive(Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700459pub enum TokenTree {
David Tolnay82ba02d2018-05-20 16:22:43 -0700460 /// A token stream surrounded by bracket delimiters.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700461 Group(Group),
David Tolnay82ba02d2018-05-20 16:22:43 -0700462 /// An identifier.
Alex Crichtonf3888432018-05-16 09:11:05 -0700463 Ident(Ident),
David Tolnay82ba02d2018-05-20 16:22:43 -0700464 /// A single punctuation character (`+`, `,`, `$`, etc.).
Alex Crichtonf3888432018-05-16 09:11:05 -0700465 Punct(Punct),
David Tolnay82ba02d2018-05-20 16:22:43 -0700466 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700467 Literal(Literal),
Alex Crichton1a7f7622017-07-05 17:47:15 -0700468}
469
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700470impl TokenTree {
David Tolnay82ba02d2018-05-20 16:22:43 -0700471 /// Returns the span of this tree, delegating to the `span` method of
472 /// the contained token or a delimited stream.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700473 pub fn span(&self) -> Span {
474 match *self {
475 TokenTree::Group(ref t) => t.span(),
Alex Crichtonf3888432018-05-16 09:11:05 -0700476 TokenTree::Ident(ref t) => t.span(),
477 TokenTree::Punct(ref t) => t.span(),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700478 TokenTree::Literal(ref t) => t.span(),
479 }
480 }
481
David Tolnay82ba02d2018-05-20 16:22:43 -0700482 /// Configures the span for *only this token*.
483 ///
484 /// Note that if this token is a `Group` then this method will not configure
485 /// the span of each of the internal tokens, this will simply delegate to
486 /// the `set_span` method of each variant.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700487 pub fn set_span(&mut self, span: Span) {
488 match *self {
489 TokenTree::Group(ref mut t) => t.set_span(span),
Alex Crichtonf3888432018-05-16 09:11:05 -0700490 TokenTree::Ident(ref mut t) => t.set_span(span),
491 TokenTree::Punct(ref mut t) => t.set_span(span),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700492 TokenTree::Literal(ref mut t) => t.set_span(span),
493 }
494 }
495}
496
497impl From<Group> for TokenTree {
498 fn from(g: Group) -> TokenTree {
499 TokenTree::Group(g)
500 }
501}
502
Alex Crichtonf3888432018-05-16 09:11:05 -0700503impl From<Ident> for TokenTree {
504 fn from(g: Ident) -> TokenTree {
505 TokenTree::Ident(g)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700506 }
507}
508
Alex Crichtonf3888432018-05-16 09:11:05 -0700509impl From<Punct> for TokenTree {
510 fn from(g: Punct) -> TokenTree {
511 TokenTree::Punct(g)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700512 }
513}
514
515impl From<Literal> for TokenTree {
516 fn from(g: Literal) -> TokenTree {
517 TokenTree::Literal(g)
Alex Crichton1a7f7622017-07-05 17:47:15 -0700518 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700519}
520
David Tolnay82ba02d2018-05-20 16:22:43 -0700521/// Prints the token tree as a string that is supposed to be losslessly
522/// convertible back into the same token tree (modulo spans), except for
523/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
524/// numeric literals.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700525impl fmt::Display for TokenTree {
526 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700527 match *self {
528 TokenTree::Group(ref t) => t.fmt(f),
Alex Crichtonf3888432018-05-16 09:11:05 -0700529 TokenTree::Ident(ref t) => t.fmt(f),
530 TokenTree::Punct(ref t) => t.fmt(f),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700531 TokenTree::Literal(ref t) => t.fmt(f),
532 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700533 }
534}
535
David Tolnay82ba02d2018-05-20 16:22:43 -0700536/// Prints token tree in a form convenient for debugging.
David Tolnay034205f2018-04-22 16:45:28 -0700537impl fmt::Debug for TokenTree {
538 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
539 // Each of these has the name in the struct type in the derived debug,
540 // so don't bother with an extra layer of indirection
541 match *self {
542 TokenTree::Group(ref t) => t.fmt(f),
David Tolnayd8fcdb82018-06-02 15:43:53 -0700543 TokenTree::Ident(ref t) => {
544 let mut debug = f.debug_struct("Ident");
545 debug.field("sym", &format_args!("{}", t));
David Tolnayfd8cdc82019-01-19 19:23:59 -0800546 imp::debug_span_field_if_nontrivial(&mut debug, t.span().inner);
David Tolnayd8fcdb82018-06-02 15:43:53 -0700547 debug.finish()
548 }
Alex Crichtonf3888432018-05-16 09:11:05 -0700549 TokenTree::Punct(ref t) => t.fmt(f),
David Tolnay034205f2018-04-22 16:45:28 -0700550 TokenTree::Literal(ref t) => t.fmt(f),
551 }
552 }
553}
554
David Tolnay82ba02d2018-05-20 16:22:43 -0700555/// A delimited token stream.
556///
557/// A `Group` internally contains a `TokenStream` which is surrounded by
558/// `Delimiter`s.
David Tolnay034205f2018-04-22 16:45:28 -0700559#[derive(Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700560pub struct Group {
David Tolnayf14813f2018-09-08 17:14:07 -0700561 inner: imp::Group,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700562}
563
David Tolnay82ba02d2018-05-20 16:22:43 -0700564/// Describes how a sequence of token trees is delimited.
Michael Layzell5372f4b2017-06-02 10:29:31 -0400565#[derive(Copy, Clone, Debug, Eq, PartialEq)]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700566pub enum Delimiter {
David Tolnay82ba02d2018-05-20 16:22:43 -0700567 /// `( ... )`
Alex Crichton44bffbc2017-05-19 17:51:59 -0700568 Parenthesis,
David Tolnay82ba02d2018-05-20 16:22:43 -0700569 /// `{ ... }`
Alex Crichton44bffbc2017-05-19 17:51:59 -0700570 Brace,
David Tolnay82ba02d2018-05-20 16:22:43 -0700571 /// `[ ... ]`
Alex Crichton44bffbc2017-05-19 17:51:59 -0700572 Bracket,
David Tolnay82ba02d2018-05-20 16:22:43 -0700573 /// `Ø ... Ø`
574 ///
575 /// An implicit delimiter, that may, for example, appear around tokens
576 /// coming from a "macro variable" `$var`. It is important to preserve
577 /// operator priorities in cases like `$var * 3` where `$var` is `1 + 2`.
578 /// Implicit delimiters may not survive roundtrip of a token stream through
579 /// a string.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700580 None,
581}
582
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700583impl Group {
David Tolnayf14813f2018-09-08 17:14:07 -0700584 fn _new(inner: imp::Group) -> Self {
David Tolnay4453fcc2019-01-16 12:15:01 -0800585 Group { inner: inner }
David Tolnayf14813f2018-09-08 17:14:07 -0700586 }
587
David Tolnayaef075b2019-01-16 16:29:18 -0800588 fn _new_stable(inner: fallback::Group) -> Self {
David Tolnayf14813f2018-09-08 17:14:07 -0700589 Group {
590 inner: inner.into(),
591 }
592 }
593
David Tolnay82ba02d2018-05-20 16:22:43 -0700594 /// Creates a new `Group` with the given delimiter and token stream.
595 ///
596 /// This constructor will set the span for this group to
597 /// `Span::call_site()`. To change the span you can use the `set_span`
598 /// method below.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700599 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
600 Group {
David Tolnayf14813f2018-09-08 17:14:07 -0700601 inner: imp::Group::new(delimiter, stream.inner),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700602 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700603 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700604
David Tolnay82ba02d2018-05-20 16:22:43 -0700605 /// Returns the delimiter of this `Group`
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700606 pub fn delimiter(&self) -> Delimiter {
David Tolnayf14813f2018-09-08 17:14:07 -0700607 self.inner.delimiter()
Alex Crichton44bffbc2017-05-19 17:51:59 -0700608 }
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700609
David Tolnay82ba02d2018-05-20 16:22:43 -0700610 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
611 ///
612 /// Note that the returned token stream does not include the delimiter
613 /// returned above.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700614 pub fn stream(&self) -> TokenStream {
David Tolnayf14813f2018-09-08 17:14:07 -0700615 TokenStream::_new(self.inner.stream())
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700616 }
617
David Tolnay82ba02d2018-05-20 16:22:43 -0700618 /// Returns the span for the delimiters of this token stream, spanning the
619 /// entire `Group`.
David Tolnayf14813f2018-09-08 17:14:07 -0700620 ///
621 /// ```text
622 /// pub fn span(&self) -> Span {
623 /// ^^^^^^^
624 /// ```
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700625 pub fn span(&self) -> Span {
David Tolnayf14813f2018-09-08 17:14:07 -0700626 Span::_new(self.inner.span())
627 }
628
629 /// Returns the span pointing to the opening delimiter of this group.
630 ///
631 /// ```text
632 /// pub fn span_open(&self) -> Span {
633 /// ^
634 /// ```
635 #[cfg(procmacro2_semver_exempt)]
636 pub fn span_open(&self) -> Span {
637 Span::_new(self.inner.span_open())
638 }
639
640 /// Returns the span pointing to the closing delimiter of this group.
641 ///
642 /// ```text
643 /// pub fn span_close(&self) -> Span {
644 /// ^
645 /// ```
646 #[cfg(procmacro2_semver_exempt)]
647 pub fn span_close(&self) -> Span {
648 Span::_new(self.inner.span_close())
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700649 }
650
David Tolnay82ba02d2018-05-20 16:22:43 -0700651 /// Configures the span for this `Group`'s delimiters, but not its internal
652 /// tokens.
653 ///
654 /// This method will **not** set the span of all the internal tokens spanned
655 /// by this group, but rather it will only set the span of the delimiter
656 /// tokens at the level of the `Group`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700657 pub fn set_span(&mut self, span: Span) {
David Tolnayf14813f2018-09-08 17:14:07 -0700658 self.inner.set_span(span.inner)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700659 }
660}
661
David Tolnay82ba02d2018-05-20 16:22:43 -0700662/// Prints the group as a string that should be losslessly convertible back
663/// into the same group (modulo spans), except for possibly `TokenTree::Group`s
664/// with `Delimiter::None` delimiters.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700665impl fmt::Display for Group {
David Tolnayf14813f2018-09-08 17:14:07 -0700666 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
667 fmt::Display::fmt(&self.inner, formatter)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700668 }
669}
670
David Tolnay034205f2018-04-22 16:45:28 -0700671impl fmt::Debug for Group {
David Tolnayf14813f2018-09-08 17:14:07 -0700672 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
673 fmt::Debug::fmt(&self.inner, formatter)
David Tolnay034205f2018-04-22 16:45:28 -0700674 }
675}
676
David Tolnay82ba02d2018-05-20 16:22:43 -0700677/// An `Punct` is an single punctuation character like `+`, `-` or `#`.
678///
679/// Multicharacter operators like `+=` are represented as two instances of
680/// `Punct` with different forms of `Spacing` returned.
Alex Crichtonf3888432018-05-16 09:11:05 -0700681#[derive(Clone)]
682pub struct Punct {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700683 op: char,
684 spacing: Spacing,
685 span: Span,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700686}
687
David Tolnay82ba02d2018-05-20 16:22:43 -0700688/// Whether an `Punct` is followed immediately by another `Punct` or followed by
689/// another token or whitespace.
Lukas Kalbertodteb3f9302017-08-20 18:58:41 +0200690#[derive(Copy, Clone, Debug, Eq, PartialEq)]
Alex Crichton1a7f7622017-07-05 17:47:15 -0700691pub enum Spacing {
David Tolnay82ba02d2018-05-20 16:22:43 -0700692 /// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700693 Alone,
David Tolnay82ba02d2018-05-20 16:22:43 -0700694 /// E.g. `+` is `Joint` in `+=` or `'#`.
695 ///
696 /// Additionally, single quote `'` can join with identifiers to form
697 /// lifetimes `'ident`.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700698 Joint,
699}
700
Alex Crichtonf3888432018-05-16 09:11:05 -0700701impl Punct {
David Tolnay82ba02d2018-05-20 16:22:43 -0700702 /// Creates a new `Punct` from the given character and spacing.
703 ///
704 /// The `ch` argument must be a valid punctuation character permitted by the
705 /// language, otherwise the function will panic.
706 ///
707 /// The returned `Punct` will have the default span of `Span::call_site()`
708 /// which can be further configured with the `set_span` method below.
Alex Crichtonf3888432018-05-16 09:11:05 -0700709 pub fn new(op: char, spacing: Spacing) -> Punct {
710 Punct {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700711 op: op,
712 spacing: spacing,
713 span: Span::call_site(),
714 }
715 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700716
David Tolnay82ba02d2018-05-20 16:22:43 -0700717 /// Returns the value of this punctuation character as `char`.
Alex Crichtonf3888432018-05-16 09:11:05 -0700718 pub fn as_char(&self) -> char {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700719 self.op
720 }
721
David Tolnay82ba02d2018-05-20 16:22:43 -0700722 /// Returns the spacing of this punctuation character, indicating whether
723 /// it's immediately followed by another `Punct` in the token stream, so
724 /// they can potentially be combined into a multicharacter operator
725 /// (`Joint`), or it's followed by some other token or whitespace (`Alone`)
726 /// so the operator has certainly ended.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700727 pub fn spacing(&self) -> Spacing {
728 self.spacing
729 }
730
David Tolnay82ba02d2018-05-20 16:22:43 -0700731 /// Returns the span for this punctuation character.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700732 pub fn span(&self) -> Span {
733 self.span
734 }
735
David Tolnay82ba02d2018-05-20 16:22:43 -0700736 /// Configure the span for this punctuation character.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700737 pub fn set_span(&mut self, span: Span) {
738 self.span = span;
739 }
740}
741
David Tolnay82ba02d2018-05-20 16:22:43 -0700742/// Prints the punctuation character as a string that should be losslessly
743/// convertible back into the same character.
Alex Crichtonf3888432018-05-16 09:11:05 -0700744impl fmt::Display for Punct {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700745 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
746 self.op.fmt(f)
747 }
748}
749
Alex Crichtonf3888432018-05-16 09:11:05 -0700750impl fmt::Debug for Punct {
David Tolnay034205f2018-04-22 16:45:28 -0700751 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonf3888432018-05-16 09:11:05 -0700752 let mut debug = fmt.debug_struct("Punct");
David Tolnay034205f2018-04-22 16:45:28 -0700753 debug.field("op", &self.op);
754 debug.field("spacing", &self.spacing);
David Tolnayfd8cdc82019-01-19 19:23:59 -0800755 imp::debug_span_field_if_nontrivial(&mut debug, self.span.inner);
David Tolnay034205f2018-04-22 16:45:28 -0700756 debug.finish()
757 }
758}
759
David Tolnay8b71dac2018-05-20 17:07:47 -0700760/// A word of Rust code, which may be a keyword or legal variable name.
761///
762/// An identifier consists of at least one Unicode code point, the first of
763/// which has the XID_Start property and the rest of which have the XID_Continue
764/// property.
765///
766/// - The empty string is not an identifier. Use `Option<Ident>`.
767/// - A lifetime is not an identifier. Use `syn::Lifetime` instead.
768///
769/// An identifier constructed with `Ident::new` is permitted to be a Rust
David Tolnayc239f032018-11-11 12:57:09 -0800770/// keyword, though parsing one through its [`Parse`] implementation rejects
771/// Rust keywords. Use `input.call(Ident::parse_any)` when parsing to match the
David Tolnay8b71dac2018-05-20 17:07:47 -0700772/// behaviour of `Ident::new`.
773///
David Tolnayc239f032018-11-11 12:57:09 -0800774/// [`Parse`]: https://docs.rs/syn/0.15/syn/parse/trait.Parse.html
David Tolnay8b71dac2018-05-20 17:07:47 -0700775///
776/// # Examples
777///
778/// A new ident can be created from a string using the `Ident::new` function.
779/// A span must be provided explicitly which governs the name resolution
780/// behavior of the resulting identifier.
781///
David Tolnay7a964732019-01-19 19:03:20 -0800782/// ```edition2018
David Tolnay8b71dac2018-05-20 17:07:47 -0700783/// use proc_macro2::{Ident, Span};
784///
785/// fn main() {
786/// let call_ident = Ident::new("calligraphy", Span::call_site());
787///
788/// println!("{}", call_ident);
789/// }
790/// ```
791///
792/// An ident can be interpolated into a token stream using the `quote!` macro.
793///
David Tolnay7a964732019-01-19 19:03:20 -0800794/// ```edition2018
David Tolnay8b71dac2018-05-20 17:07:47 -0700795/// use proc_macro2::{Ident, Span};
David Tolnay7a964732019-01-19 19:03:20 -0800796/// use quote::quote;
David Tolnay8b71dac2018-05-20 17:07:47 -0700797///
798/// fn main() {
799/// let ident = Ident::new("demo", Span::call_site());
800///
801/// // Create a variable binding whose name is this ident.
802/// let expanded = quote! { let #ident = 10; };
803///
804/// // Create a variable binding with a slightly different name.
805/// let temp_ident = Ident::new(&format!("new_{}", ident), Span::call_site());
806/// let expanded = quote! { let #temp_ident = 10; };
807/// }
808/// ```
809///
810/// A string representation of the ident is available through the `to_string()`
811/// method.
812///
David Tolnay7a964732019-01-19 19:03:20 -0800813/// ```edition2018
David Tolnay8b71dac2018-05-20 17:07:47 -0700814/// # use proc_macro2::{Ident, Span};
815/// #
816/// # let ident = Ident::new("another_identifier", Span::call_site());
817/// #
818/// // Examine the ident as a string.
819/// let ident_string = ident.to_string();
820/// if ident_string.len() > 60 {
821/// println!("Very long identifier: {}", ident_string)
822/// }
823/// ```
Alex Crichtonf3888432018-05-16 09:11:05 -0700824#[derive(Clone)]
825pub struct Ident {
826 inner: imp::Ident,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700827 _marker: marker::PhantomData<Rc<()>>,
828}
829
Alex Crichtonf3888432018-05-16 09:11:05 -0700830impl Ident {
831 fn _new(inner: imp::Ident) -> Ident {
832 Ident {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700833 inner: inner,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700834 _marker: marker::PhantomData,
835 }
836 }
837
David Tolnay82ba02d2018-05-20 16:22:43 -0700838 /// Creates a new `Ident` with the given `string` as well as the specified
839 /// `span`.
840 ///
841 /// The `string` argument must be a valid identifier permitted by the
842 /// language, otherwise the function will panic.
843 ///
844 /// Note that `span`, currently in rustc, configures the hygiene information
845 /// for this identifier.
846 ///
847 /// As of this time `Span::call_site()` explicitly opts-in to "call-site"
848 /// hygiene meaning that identifiers created with this span will be resolved
849 /// as if they were written directly at the location of the macro call, and
850 /// other code at the macro call site will be able to refer to them as well.
851 ///
852 /// Later spans like `Span::def_site()` will allow to opt-in to
853 /// "definition-site" hygiene meaning that identifiers created with this
854 /// span will be resolved at the location of the macro definition and other
855 /// code at the macro call site will not be able to refer to them.
856 ///
857 /// Due to the current importance of hygiene this constructor, unlike other
858 /// tokens, requires a `Span` to be specified at construction.
David Tolnay8b71dac2018-05-20 17:07:47 -0700859 ///
860 /// # Panics
861 ///
862 /// Panics if the input string is neither a keyword nor a legal variable
David Tolnay219b1d32019-04-22 16:04:11 -0700863 /// name. If you are not sure whether the string contains an identifier and
864 /// need to handle an error case, use
865 /// <a href="https://docs.rs/syn/0.15/syn/fn.parse_str.html"><code
866 /// style="padding-right:0;">syn::parse_str</code></a><code
867 /// style="padding-left:0;">::&lt;Ident&gt;</code>
868 /// rather than `Ident::new`.
Alex Crichtonf3888432018-05-16 09:11:05 -0700869 pub fn new(string: &str, span: Span) -> Ident {
870 Ident::_new(imp::Ident::new(string, span.inner))
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700871 }
872
David Tolnay82ba02d2018-05-20 16:22:43 -0700873 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
David Tolnaya01ca8e2018-06-04 00:55:28 -0700874 ///
875 /// This method is semver exempt and not exposed by default.
Alex Crichtonf3888432018-05-16 09:11:05 -0700876 #[cfg(procmacro2_semver_exempt)]
877 pub fn new_raw(string: &str, span: Span) -> Ident {
878 Ident::_new_raw(string, span)
879 }
880
881 fn _new_raw(string: &str, span: Span) -> Ident {
882 Ident::_new(imp::Ident::new_raw(string, span.inner))
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700883 }
884
David Tolnay82ba02d2018-05-20 16:22:43 -0700885 /// Returns the span of this `Ident`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700886 pub fn span(&self) -> Span {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700887 Span::_new(self.inner.span())
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700888 }
889
David Tolnay82ba02d2018-05-20 16:22:43 -0700890 /// Configures the span of this `Ident`, possibly changing its hygiene
891 /// context.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700892 pub fn set_span(&mut self, span: Span) {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700893 self.inner.set_span(span.inner);
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700894 }
895}
896
Alex Crichtonf3888432018-05-16 09:11:05 -0700897impl PartialEq for Ident {
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700898 fn eq(&self, other: &Ident) -> bool {
David Tolnayc0b0f2e2018-09-02 17:56:08 -0700899 self.inner == other.inner
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700900 }
901}
902
David Tolnayc0bbcc52018-05-18 10:51:04 -0700903impl<T> PartialEq<T> for Ident
904where
905 T: ?Sized + AsRef<str>,
906{
907 fn eq(&self, other: &T) -> bool {
David Tolnayc0b0f2e2018-09-02 17:56:08 -0700908 self.inner == other
David Tolnayc0bbcc52018-05-18 10:51:04 -0700909 }
910}
911
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700912impl Eq for Ident {}
Alex Crichtonf3888432018-05-16 09:11:05 -0700913
914impl PartialOrd for Ident {
915 fn partial_cmp(&self, other: &Ident) -> Option<Ordering> {
916 Some(self.cmp(other))
917 }
918}
919
920impl Ord for Ident {
921 fn cmp(&self, other: &Ident) -> Ordering {
922 self.to_string().cmp(&other.to_string())
923 }
924}
925
926impl Hash for Ident {
927 fn hash<H: Hasher>(&self, hasher: &mut H) {
928 self.to_string().hash(hasher)
929 }
930}
931
David Tolnay82ba02d2018-05-20 16:22:43 -0700932/// Prints the identifier as a string that should be losslessly convertible back
933/// into the same identifier.
Alex Crichtonf3888432018-05-16 09:11:05 -0700934impl fmt::Display for Ident {
935 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
936 self.inner.fmt(f)
937 }
938}
939
940impl fmt::Debug for Ident {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700941 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
942 self.inner.fmt(f)
943 }
944}
945
David Tolnay82ba02d2018-05-20 16:22:43 -0700946/// A literal string (`"hello"`), byte string (`b"hello"`), character (`'a'`),
947/// byte character (`b'a'`), an integer or floating point number with or without
948/// a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
949///
950/// Boolean literals like `true` and `false` do not belong here, they are
951/// `Ident`s.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700952#[derive(Clone)]
953pub struct Literal {
954 inner: imp::Literal,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700955 _marker: marker::PhantomData<Rc<()>>,
956}
957
David Tolnay82ba02d2018-05-20 16:22:43 -0700958macro_rules! suffixed_int_literals {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700959 ($($name:ident => $kind:ident,)*) => ($(
David Tolnay82ba02d2018-05-20 16:22:43 -0700960 /// Creates a new suffixed integer literal with the specified value.
961 ///
962 /// This function will create an integer like `1u32` where the integer
963 /// value specified is the first part of the token and the integral is
964 /// also suffixed at the end. Literals created from negative numbers may
965 /// not survive rountrips through `TokenStream` or strings and may be
966 /// broken into two tokens (`-` and positive literal).
967 ///
968 /// Literals created through this method have the `Span::call_site()`
969 /// span by default, which can be configured with the `set_span` method
970 /// below.
971 pub fn $name(n: $kind) -> Literal {
972 Literal::_new(imp::Literal::$name(n))
973 }
974 )*)
975}
976
977macro_rules! unsuffixed_int_literals {
978 ($($name:ident => $kind:ident,)*) => ($(
979 /// Creates a new unsuffixed integer literal with the specified value.
980 ///
981 /// This function will create an integer like `1` where the integer
982 /// value specified is the first part of the token. No suffix is
983 /// specified on this token, meaning that invocations like
984 /// `Literal::i8_unsuffixed(1)` are equivalent to
985 /// `Literal::u32_unsuffixed(1)`. Literals created from negative numbers
986 /// may not survive rountrips through `TokenStream` or strings and may
987 /// be broken into two tokens (`-` and positive literal).
988 ///
989 /// Literals created through this method have the `Span::call_site()`
990 /// span by default, which can be configured with the `set_span` method
991 /// below.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700992 pub fn $name(n: $kind) -> Literal {
Alex Crichtona914a612018-04-04 07:48:44 -0700993 Literal::_new(imp::Literal::$name(n))
Alex Crichton1a7f7622017-07-05 17:47:15 -0700994 }
995 )*)
996}
997
Alex Crichton852d53d2017-05-19 19:25:08 -0700998impl Literal {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700999 fn _new(inner: imp::Literal) -> Literal {
1000 Literal {
1001 inner: inner,
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001002 _marker: marker::PhantomData,
1003 }
Alex Crichton1a7f7622017-07-05 17:47:15 -07001004 }
1005
David Tolnayaef075b2019-01-16 16:29:18 -08001006 fn _new_stable(inner: fallback::Literal) -> Literal {
Alex Crichton30a4e9e2018-04-27 17:02:19 -07001007 Literal {
1008 inner: inner.into(),
1009 _marker: marker::PhantomData,
1010 }
1011 }
1012
David Tolnay82ba02d2018-05-20 16:22:43 -07001013 suffixed_int_literals! {
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001014 u8_suffixed => u8,
1015 u16_suffixed => u16,
1016 u32_suffixed => u32,
1017 u64_suffixed => u64,
1018 usize_suffixed => usize,
1019 i8_suffixed => i8,
1020 i16_suffixed => i16,
1021 i32_suffixed => i32,
1022 i64_suffixed => i64,
1023 isize_suffixed => isize,
David Tolnay82ba02d2018-05-20 16:22:43 -07001024 }
Alex Crichton1a7f7622017-07-05 17:47:15 -07001025
Alex Crichton69385662018-11-08 06:30:04 -08001026 #[cfg(u128)]
1027 suffixed_int_literals! {
1028 u128_suffixed => u128,
1029 i128_suffixed => i128,
1030 }
1031
David Tolnay82ba02d2018-05-20 16:22:43 -07001032 unsuffixed_int_literals! {
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001033 u8_unsuffixed => u8,
1034 u16_unsuffixed => u16,
1035 u32_unsuffixed => u32,
1036 u64_unsuffixed => u64,
1037 usize_unsuffixed => usize,
1038 i8_unsuffixed => i8,
1039 i16_unsuffixed => i16,
1040 i32_unsuffixed => i32,
1041 i64_unsuffixed => i64,
1042 isize_unsuffixed => isize,
Alex Crichton1a7f7622017-07-05 17:47:15 -07001043 }
1044
Alex Crichton69385662018-11-08 06:30:04 -08001045 #[cfg(u128)]
1046 unsuffixed_int_literals! {
1047 u128_unsuffixed => u128,
1048 i128_unsuffixed => i128,
1049 }
1050
David Tolnaybc3bd3f2019-06-30 13:03:56 -07001051 /// Creates a new unsuffixed floating-point literal.
1052 ///
1053 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1054 /// the float's value is emitted directly into the token but no suffix is
1055 /// used, so it may be inferred to be a `f64` later in the compiler.
1056 /// Literals created from negative numbers may not survive rountrips through
1057 /// `TokenStream` or strings and may be broken into two tokens (`-` and
1058 /// positive literal).
1059 ///
1060 /// # Panics
1061 ///
1062 /// This function requires that the specified float is finite, for example
1063 /// if it is infinity or NaN this function will panic.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001064 pub fn f64_unsuffixed(f: f64) -> Literal {
1065 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -07001066 Literal::_new(imp::Literal::f64_unsuffixed(f))
Alex Crichton1a7f7622017-07-05 17:47:15 -07001067 }
1068
David Tolnaybc3bd3f2019-06-30 13:03:56 -07001069 /// Creates a new suffixed floating-point literal.
1070 ///
1071 /// This constructor will create a literal like `1.0f64` where the value
1072 /// specified is the preceding part of the token and `f64` is the suffix of
1073 /// the token. This token will always be inferred to be an `f64` in the
1074 /// compiler. Literals created from negative numbers may not survive
1075 /// rountrips through `TokenStream` or strings and may be broken into two
1076 /// tokens (`-` and positive literal).
1077 ///
1078 /// # Panics
1079 ///
1080 /// This function requires that the specified float is finite, for example
1081 /// if it is infinity or NaN this function will panic.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001082 pub fn f64_suffixed(f: f64) -> Literal {
1083 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -07001084 Literal::_new(imp::Literal::f64_suffixed(f))
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001085 }
1086
David Tolnay82ba02d2018-05-20 16:22:43 -07001087 /// Creates a new unsuffixed floating-point literal.
1088 ///
1089 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1090 /// the float's value is emitted directly into the token but no suffix is
1091 /// used, so it may be inferred to be a `f64` later in the compiler.
1092 /// Literals created from negative numbers may not survive rountrips through
1093 /// `TokenStream` or strings and may be broken into two tokens (`-` and
1094 /// positive literal).
1095 ///
1096 /// # Panics
1097 ///
1098 /// This function requires that the specified float is finite, for example
1099 /// if it is infinity or NaN this function will panic.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001100 pub fn f32_unsuffixed(f: f32) -> Literal {
1101 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -07001102 Literal::_new(imp::Literal::f32_unsuffixed(f))
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001103 }
1104
David Tolnaybc3bd3f2019-06-30 13:03:56 -07001105 /// Creates a new suffixed floating-point literal.
1106 ///
1107 /// This constructor will create a literal like `1.0f32` where the value
1108 /// specified is the preceding part of the token and `f32` is the suffix of
1109 /// the token. This token will always be inferred to be an `f32` in the
1110 /// compiler. Literals created from negative numbers may not survive
1111 /// rountrips through `TokenStream` or strings and may be broken into two
1112 /// tokens (`-` and positive literal).
1113 ///
1114 /// # Panics
1115 ///
1116 /// This function requires that the specified float is finite, for example
1117 /// if it is infinity or NaN this function will panic.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001118 pub fn f32_suffixed(f: f32) -> Literal {
1119 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -07001120 Literal::_new(imp::Literal::f32_suffixed(f))
Alex Crichton1a7f7622017-07-05 17:47:15 -07001121 }
1122
David Tolnaybc3bd3f2019-06-30 13:03:56 -07001123 /// String literal.
Alex Crichton1a7f7622017-07-05 17:47:15 -07001124 pub fn string(string: &str) -> Literal {
Alex Crichtona914a612018-04-04 07:48:44 -07001125 Literal::_new(imp::Literal::string(string))
Alex Crichton1a7f7622017-07-05 17:47:15 -07001126 }
1127
David Tolnaybc3bd3f2019-06-30 13:03:56 -07001128 /// Character literal.
Alex Crichton1a7f7622017-07-05 17:47:15 -07001129 pub fn character(ch: char) -> Literal {
Alex Crichtona914a612018-04-04 07:48:44 -07001130 Literal::_new(imp::Literal::character(ch))
Alex Crichton76a5cc82017-05-23 07:01:44 -07001131 }
1132
David Tolnaybc3bd3f2019-06-30 13:03:56 -07001133 /// Byte string literal.
Alex Crichton9c2fb0a2017-05-26 08:49:31 -07001134 pub fn byte_string(s: &[u8]) -> Literal {
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001135 Literal::_new(imp::Literal::byte_string(s))
Alex Crichton852d53d2017-05-19 19:25:08 -07001136 }
Alex Crichton76a5cc82017-05-23 07:01:44 -07001137
David Tolnaybc3bd3f2019-06-30 13:03:56 -07001138 /// Returns the span encompassing this literal.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001139 pub fn span(&self) -> Span {
Alex Crichtonb2c94622018-04-04 07:36:41 -07001140 Span::_new(self.inner.span())
Alex Crichton1a7f7622017-07-05 17:47:15 -07001141 }
1142
David Tolnaybc3bd3f2019-06-30 13:03:56 -07001143 /// Configures the span associated for this literal.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001144 pub fn set_span(&mut self, span: Span) {
Alex Crichtonb2c94622018-04-04 07:36:41 -07001145 self.inner.set_span(span.inner);
Alex Crichton31316622017-05-26 12:54:47 -07001146 }
Alex Crichton852d53d2017-05-19 19:25:08 -07001147}
1148
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001149impl fmt::Debug for Literal {
1150 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1151 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001152 }
1153}
David Tolnaycb1b85f2017-06-03 16:40:35 -07001154
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001155impl fmt::Display for Literal {
1156 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1157 self.inner.fmt(f)
1158 }
1159}
1160
David Tolnay82ba02d2018-05-20 16:22:43 -07001161/// Public implementation details for the `TokenStream` type, such as iterators.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001162pub mod token_stream {
1163 use std::fmt;
1164 use std::marker;
1165 use std::rc::Rc;
1166
David Tolnay48ea5042018-04-23 19:17:35 -07001167 use imp;
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001168 pub use TokenStream;
David Tolnayb28f38a2018-03-31 22:02:29 +02001169 use TokenTree;
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001170
David Tolnay82ba02d2018-05-20 16:22:43 -07001171 /// An iterator over `TokenStream`'s `TokenTree`s.
1172 ///
1173 /// The iteration is "shallow", e.g. the iterator doesn't recurse into
1174 /// delimited groups, and returns whole groups as token trees.
Isaac van Bakelf6754d32019-05-08 20:21:06 +01001175 #[derive(Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001176 pub struct IntoIter {
1177 inner: imp::TokenTreeIter,
1178 _marker: marker::PhantomData<Rc<()>>,
1179 }
1180
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001181 impl Iterator for IntoIter {
1182 type Item = TokenTree;
1183
1184 fn next(&mut self) -> Option<TokenTree> {
1185 self.inner.next()
1186 }
1187 }
1188
1189 impl fmt::Debug for IntoIter {
1190 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1191 self.inner.fmt(f)
1192 }
1193 }
1194
1195 impl IntoIterator for TokenStream {
1196 type Item = TokenTree;
1197 type IntoIter = IntoIter;
1198
1199 fn into_iter(self) -> IntoIter {
1200 IntoIter {
1201 inner: self.inner.into_iter(),
1202 _marker: marker::PhantomData,
1203 }
1204 }
1205 }
1206}