blob: 9b233d6b4aa969e8de1cd50a686b8b8d56b20cb1 [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.
Alex Crichtonbabc99e2017-07-05 18:00:29 -070080
David Tolnay15cc4982018-01-08 08:03:27 -080081// Proc-macro2 types in rustdoc of other crates get linked to here.
David Tolnaydd1af432019-01-16 12:08:47 -080082#![doc(html_root_url = "https://docs.rs/proc-macro2/0.4.25")]
David Tolnay5a556cf2018-08-12 13:49:39 -070083#![cfg_attr(
Alex Crichtonce0904d2018-08-27 17:29:49 -070084 super_unstable,
xd0096421fd37672018-10-04 16:39:45 +010085 feature(proc_macro_raw_ident, proc_macro_span, proc_macro_def_site)
David Tolnay5a556cf2018-08-12 13:49:39 -070086)]
Alex Crichtoncbec8ec2017-06-02 13:19:33 -070087
Alex Crichton53548482018-08-11 21:54:05 -070088#[cfg(use_proc_macro)]
Alex Crichton44bffbc2017-05-19 17:51:59 -070089extern crate proc_macro;
David Tolnayb1032662017-05-31 15:52:28 -070090extern crate unicode_xid;
Alex Crichton44bffbc2017-05-19 17:51:59 -070091
Alex Crichtonf3888432018-05-16 09:11:05 -070092use std::cmp::Ordering;
Alex Crichton44bffbc2017-05-19 17:51:59 -070093use std::fmt;
Alex Crichtonf3888432018-05-16 09:11:05 -070094use std::hash::{Hash, Hasher};
Alex Crichton44bffbc2017-05-19 17:51:59 -070095use std::iter::FromIterator;
Alex Crichtonaf5bad42018-03-27 14:45:10 -070096use std::marker;
David Tolnay9cd3b4c2018-11-11 16:47:32 -080097#[cfg(procmacro2_semver_exempt)]
98use std::path::PathBuf;
Alex Crichtonaf5bad42018-03-27 14:45:10 -070099use std::rc::Rc;
100use std::str::FromStr;
Alex Crichton44bffbc2017-05-19 17:51:59 -0700101
David Tolnayb1032662017-05-31 15:52:28 -0700102#[macro_use]
David Tolnayb1032662017-05-31 15:52:28 -0700103mod strnom;
David Tolnayaef075b2019-01-16 16:29:18 -0800104mod fallback;
David Tolnayb1032662017-05-31 15:52:28 -0700105
Alex Crichtonce0904d2018-08-27 17:29:49 -0700106#[cfg(not(wrap_proc_macro))]
David Tolnayaef075b2019-01-16 16:29:18 -0800107use fallback as imp;
108#[path = "wrapper.rs"]
Alex Crichtonce0904d2018-08-27 17:29:49 -0700109#[cfg(wrap_proc_macro)]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700110mod imp;
111
David Tolnay82ba02d2018-05-20 16:22:43 -0700112/// An abstract stream of tokens, or more concretely a sequence of token trees.
113///
114/// This type provides interfaces for iterating over token trees and for
115/// collecting token trees into one stream.
116///
117/// Token stream is both the input and output of `#[proc_macro]`,
118/// `#[proc_macro_attribute]` and `#[proc_macro_derive]` definitions.
David Tolnaycb1b85f2017-06-03 16:40:35 -0700119#[derive(Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700120pub struct TokenStream {
121 inner: imp::TokenStream,
122 _marker: marker::PhantomData<Rc<()>>,
123}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700124
David Tolnay82ba02d2018-05-20 16:22:43 -0700125/// Error returned from `TokenStream::from_str`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700126pub struct LexError {
127 inner: imp::LexError,
128 _marker: marker::PhantomData<Rc<()>>,
129}
130
131impl TokenStream {
132 fn _new(inner: imp::TokenStream) -> TokenStream {
133 TokenStream {
134 inner: inner,
135 _marker: marker::PhantomData,
136 }
137 }
138
David Tolnayaef075b2019-01-16 16:29:18 -0800139 fn _new_stable(inner: fallback::TokenStream) -> TokenStream {
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700140 TokenStream {
141 inner: inner.into(),
142 _marker: marker::PhantomData,
143 }
144 }
145
David Tolnay82ba02d2018-05-20 16:22:43 -0700146 /// Returns an empty `TokenStream` containing no token trees.
David Tolnayc3bb4592018-05-28 20:09:44 -0700147 pub fn new() -> TokenStream {
148 TokenStream::_new(imp::TokenStream::new())
149 }
150
151 #[deprecated(since = "0.4.4", note = "please use TokenStream::new")]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700152 pub fn empty() -> TokenStream {
David Tolnayc3bb4592018-05-28 20:09:44 -0700153 TokenStream::new()
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700154 }
155
David Tolnay82ba02d2018-05-20 16:22:43 -0700156 /// Checks if this `TokenStream` is empty.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700157 pub fn is_empty(&self) -> bool {
158 self.inner.is_empty()
159 }
160}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700161
Árpád Goretity4f74b682018-07-14 00:47:51 +0200162/// `TokenStream::default()` returns an empty stream,
163/// i.e. this is equivalent with `TokenStream::new()`.
164impl Default for TokenStream {
165 fn default() -> Self {
166 TokenStream::new()
167 }
168}
169
David Tolnay82ba02d2018-05-20 16:22:43 -0700170/// Attempts to break the string into tokens and parse those tokens into a token
171/// stream.
172///
173/// May fail for a number of reasons, for example, if the string contains
174/// unbalanced delimiters or characters not existing in the language.
175///
176/// NOTE: Some errors may cause panics instead of returning `LexError`. We
177/// reserve the right to change these errors into `LexError`s later.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700178impl FromStr for TokenStream {
179 type Err = LexError;
180
181 fn from_str(src: &str) -> Result<TokenStream, LexError> {
David Tolnayb28f38a2018-03-31 22:02:29 +0200182 let e = src.parse().map_err(|e| LexError {
183 inner: e,
184 _marker: marker::PhantomData,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700185 })?;
186 Ok(TokenStream::_new(e))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700187 }
188}
189
Alex Crichton53548482018-08-11 21:54:05 -0700190#[cfg(use_proc_macro)]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700191impl From<proc_macro::TokenStream> for TokenStream {
192 fn from(inner: proc_macro::TokenStream) -> TokenStream {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700193 TokenStream::_new(inner.into())
Alex Crichton44bffbc2017-05-19 17:51:59 -0700194 }
195}
196
Alex Crichton53548482018-08-11 21:54:05 -0700197#[cfg(use_proc_macro)]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700198impl From<TokenStream> for proc_macro::TokenStream {
199 fn from(inner: TokenStream) -> proc_macro::TokenStream {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700200 inner.inner.into()
Alex Crichton44bffbc2017-05-19 17:51:59 -0700201 }
202}
203
Alex Crichtonf3888432018-05-16 09:11:05 -0700204impl Extend<TokenTree> for TokenStream {
205 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, streams: I) {
206 self.inner.extend(streams)
207 }
208}
209
David Tolnay5c58c532018-08-13 11:33:51 -0700210impl Extend<TokenStream> for TokenStream {
211 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
212 self.inner
213 .extend(streams.into_iter().map(|stream| stream.inner))
214 }
215}
216
David Tolnay82ba02d2018-05-20 16:22:43 -0700217/// Collects a number of token trees into a single stream.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700218impl FromIterator<TokenTree> for TokenStream {
219 fn from_iter<I: IntoIterator<Item = TokenTree>>(streams: I) -> Self {
220 TokenStream::_new(streams.into_iter().collect())
Alex Crichton44bffbc2017-05-19 17:51:59 -0700221 }
222}
Alex Crichton53b00672018-09-06 17:16:10 -0700223impl FromIterator<TokenStream> for TokenStream {
224 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
225 TokenStream::_new(streams.into_iter().map(|i| i.inner).collect())
226 }
227}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700228
David Tolnay82ba02d2018-05-20 16:22:43 -0700229/// Prints the token stream as a string that is supposed to be losslessly
230/// convertible back into the same token stream (modulo spans), except for
231/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
232/// numeric literals.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700233impl fmt::Display for TokenStream {
234 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
235 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700236 }
237}
238
David Tolnay82ba02d2018-05-20 16:22:43 -0700239/// Prints token in a form convenient for debugging.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700240impl fmt::Debug for TokenStream {
241 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
242 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700243 }
244}
245
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700246impl fmt::Debug for LexError {
247 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
248 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700249 }
250}
251
David Tolnay82ba02d2018-05-20 16:22:43 -0700252/// The source file of a given `Span`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700253///
254/// This type is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800255#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500256#[derive(Clone, PartialEq, Eq)]
David Tolnay7e654a82018-11-11 13:33:18 -0800257pub struct SourceFile {
258 inner: imp::SourceFile,
259 _marker: marker::PhantomData<Rc<()>>,
260}
Nika Layzellf8d5f212017-12-11 14:07:02 -0500261
David Tolnay1ebe3972018-01-02 20:14:20 -0800262#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500263impl SourceFile {
David Tolnay7e654a82018-11-11 13:33:18 -0800264 fn _new(inner: imp::SourceFile) -> Self {
265 SourceFile {
266 inner: inner,
267 _marker: marker::PhantomData,
268 }
269 }
270
David Tolnay82ba02d2018-05-20 16:22:43 -0700271 /// Get the path to this source file.
272 ///
273 /// ### Note
274 ///
275 /// If the code span associated with this `SourceFile` was generated by an
276 /// external macro, this may not be an actual path on the filesystem. Use
277 /// [`is_real`] to check.
278 ///
279 /// Also note that even if `is_real` returns `true`, if
280 /// `--remap-path-prefix` was passed on the command line, the path as given
281 /// may not actually be valid.
282 ///
283 /// [`is_real`]: #method.is_real
David Tolnay9cd3b4c2018-11-11 16:47:32 -0800284 pub fn path(&self) -> PathBuf {
David Tolnay7e654a82018-11-11 13:33:18 -0800285 self.inner.path()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500286 }
287
David Tolnay82ba02d2018-05-20 16:22:43 -0700288 /// Returns `true` if this source file is a real source file, and not
289 /// generated by an external macro's expansion.
Nika Layzellf8d5f212017-12-11 14:07:02 -0500290 pub fn is_real(&self) -> bool {
David Tolnay7e654a82018-11-11 13:33:18 -0800291 self.inner.is_real()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500292 }
293}
294
David Tolnay1ebe3972018-01-02 20:14:20 -0800295#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500296impl fmt::Debug for SourceFile {
297 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
David Tolnay7e654a82018-11-11 13:33:18 -0800298 self.inner.fmt(f)
Nika Layzellf8d5f212017-12-11 14:07:02 -0500299 }
300}
301
David Tolnay82ba02d2018-05-20 16:22:43 -0700302/// A line-column pair representing the start or end of a `Span`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700303///
304/// This type is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800305#[cfg(procmacro2_semver_exempt)]
Nika Layzell1ecb6ce2017-12-30 14:34:05 -0500306pub struct LineColumn {
David Tolnay82ba02d2018-05-20 16:22:43 -0700307 /// The 1-indexed line in the source file on which the span starts or ends
308 /// (inclusive).
Nika Layzell1ecb6ce2017-12-30 14:34:05 -0500309 pub line: usize,
David Tolnay82ba02d2018-05-20 16:22:43 -0700310 /// The 0-indexed column (in UTF-8 characters) in the source file on which
311 /// the span starts or ends (inclusive).
Nika Layzell1ecb6ce2017-12-30 14:34:05 -0500312 pub column: usize,
313}
Nika Layzellf8d5f212017-12-11 14:07:02 -0500314
David Tolnay82ba02d2018-05-20 16:22:43 -0700315/// A region of source code, along with macro expansion information.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700316#[derive(Copy, Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700317pub struct Span {
318 inner: imp::Span,
319 _marker: marker::PhantomData<Rc<()>>,
320}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700321
Alex Crichton44bffbc2017-05-19 17:51:59 -0700322impl Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700323 fn _new(inner: imp::Span) -> Span {
324 Span {
325 inner: inner,
326 _marker: marker::PhantomData,
327 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700328 }
Alex Crichtone6085b72017-11-21 07:24:25 -0800329
David Tolnayaef075b2019-01-16 16:29:18 -0800330 fn _new_stable(inner: fallback::Span) -> Span {
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700331 Span {
332 inner: inner.into(),
333 _marker: marker::PhantomData,
334 }
335 }
336
David Tolnay82ba02d2018-05-20 16:22:43 -0700337 /// The span of the invocation of the current procedural macro.
338 ///
339 /// Identifiers created with this span will be resolved as if they were
340 /// written directly at the macro call location (call-site hygiene) and
341 /// other code at the macro call site will be able to refer to them as well.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700342 pub fn call_site() -> Span {
343 Span::_new(imp::Span::call_site())
344 }
345
David Tolnay82ba02d2018-05-20 16:22:43 -0700346 /// A span that resolves at the macro definition site.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700347 ///
348 /// This method is semver exempt and not exposed by default.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700349 #[cfg(procmacro2_semver_exempt)]
Alex Crichtone6085b72017-11-21 07:24:25 -0800350 pub fn def_site() -> Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700351 Span::_new(imp::Span::def_site())
Alex Crichtone6085b72017-11-21 07:24:25 -0800352 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500353
David Tolnay4e8e3972018-01-05 18:10:22 -0800354 /// Creates a new span with the same line/column information as `self` but
355 /// that resolves symbols as though it were at `other`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700356 ///
357 /// This method is semver exempt and not exposed by default.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700358 #[cfg(procmacro2_semver_exempt)]
David Tolnay4e8e3972018-01-05 18:10:22 -0800359 pub fn resolved_at(&self, other: Span) -> Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700360 Span::_new(self.inner.resolved_at(other.inner))
David Tolnay4e8e3972018-01-05 18:10:22 -0800361 }
362
363 /// Creates a new span with the same name resolution behavior as `self` but
364 /// with the line/column information of `other`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700365 ///
366 /// This method is semver exempt and not exposed by default.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700367 #[cfg(procmacro2_semver_exempt)]
David Tolnay4e8e3972018-01-05 18:10:22 -0800368 pub fn located_at(&self, other: Span) -> Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700369 Span::_new(self.inner.located_at(other.inner))
David Tolnay4e8e3972018-01-05 18:10:22 -0800370 }
371
David Tolnay17eb0702019-01-05 12:23:17 -0800372 /// Convert `proc_macro2::Span` to `proc_macro::Span`.
373 ///
374 /// This method is available when building with a nightly compiler, or when
375 /// building with rustc 1.29+ *without* semver exempt features.
David Tolnayc0425cd2019-01-16 12:13:15 -0800376 ///
377 /// # Panics
378 ///
379 /// Panics if called from outside of a procedural macro. Unlike
380 /// `proc_macro2::Span`, the `proc_macro::Span` type can only exist within
381 /// the context of a procedural macro invocation.
David Tolnay17eb0702019-01-05 12:23:17 -0800382 #[cfg(wrap_proc_macro)]
David Tolnay16a17202017-12-31 10:47:24 -0500383 pub fn unstable(self) -> proc_macro::Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700384 self.inner.unstable()
David Tolnay16a17202017-12-31 10:47:24 -0500385 }
386
David Tolnay82ba02d2018-05-20 16:22:43 -0700387 /// The original source file into which this span points.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700388 ///
389 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800390 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500391 pub fn source_file(&self) -> SourceFile {
David Tolnay7e654a82018-11-11 13:33:18 -0800392 SourceFile::_new(self.inner.source_file())
Nika Layzellf8d5f212017-12-11 14:07:02 -0500393 }
394
David Tolnay82ba02d2018-05-20 16:22:43 -0700395 /// Get the starting line/column in the source file for this span.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700396 ///
397 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800398 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500399 pub fn start(&self) -> LineColumn {
David Tolnayb28f38a2018-03-31 22:02:29 +0200400 let imp::LineColumn { line, column } = self.inner.start();
401 LineColumn {
402 line: line,
403 column: column,
404 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500405 }
406
David Tolnay82ba02d2018-05-20 16:22:43 -0700407 /// Get the ending line/column in the source file for this span.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700408 ///
409 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800410 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500411 pub fn end(&self) -> LineColumn {
David Tolnayb28f38a2018-03-31 22:02:29 +0200412 let imp::LineColumn { line, column } = self.inner.end();
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 /// Create a new span encompassing `self` and `other`.
420 ///
421 /// Returns `None` if `self` and `other` are from different files.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700422 ///
423 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800424 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500425 pub fn join(&self, other: Span) -> Option<Span> {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700426 self.inner.join(other.inner).map(Span::_new)
427 }
Alex Crichtonb2c94622018-04-04 07:36:41 -0700428
David Tolnay82ba02d2018-05-20 16:22:43 -0700429 /// Compares to spans to see if they're equal.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700430 ///
431 /// This method is semver exempt and not exposed by default.
Alex Crichtonb2c94622018-04-04 07:36:41 -0700432 #[cfg(procmacro2_semver_exempt)]
433 pub fn eq(&self, other: &Span) -> bool {
434 self.inner.eq(&other.inner)
435 }
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700436}
437
David Tolnay82ba02d2018-05-20 16:22:43 -0700438/// Prints a span in a form convenient for debugging.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700439impl fmt::Debug for Span {
440 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
441 self.inner.fmt(f)
Nika Layzellf8d5f212017-12-11 14:07:02 -0500442 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700443}
444
David Tolnay82ba02d2018-05-20 16:22:43 -0700445/// A single token or a delimited sequence of token trees (e.g. `[1, (), ..]`).
David Tolnay034205f2018-04-22 16:45:28 -0700446#[derive(Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700447pub enum TokenTree {
David Tolnay82ba02d2018-05-20 16:22:43 -0700448 /// A token stream surrounded by bracket delimiters.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700449 Group(Group),
David Tolnay82ba02d2018-05-20 16:22:43 -0700450 /// An identifier.
Alex Crichtonf3888432018-05-16 09:11:05 -0700451 Ident(Ident),
David Tolnay82ba02d2018-05-20 16:22:43 -0700452 /// A single punctuation character (`+`, `,`, `$`, etc.).
Alex Crichtonf3888432018-05-16 09:11:05 -0700453 Punct(Punct),
David Tolnay82ba02d2018-05-20 16:22:43 -0700454 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700455 Literal(Literal),
Alex Crichton1a7f7622017-07-05 17:47:15 -0700456}
457
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700458impl TokenTree {
David Tolnay82ba02d2018-05-20 16:22:43 -0700459 /// Returns the span of this tree, delegating to the `span` method of
460 /// the contained token or a delimited stream.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700461 pub fn span(&self) -> Span {
462 match *self {
463 TokenTree::Group(ref t) => t.span(),
Alex Crichtonf3888432018-05-16 09:11:05 -0700464 TokenTree::Ident(ref t) => t.span(),
465 TokenTree::Punct(ref t) => t.span(),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700466 TokenTree::Literal(ref t) => t.span(),
467 }
468 }
469
David Tolnay82ba02d2018-05-20 16:22:43 -0700470 /// Configures the span for *only this token*.
471 ///
472 /// Note that if this token is a `Group` then this method will not configure
473 /// the span of each of the internal tokens, this will simply delegate to
474 /// the `set_span` method of each variant.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700475 pub fn set_span(&mut self, span: Span) {
476 match *self {
477 TokenTree::Group(ref mut t) => t.set_span(span),
Alex Crichtonf3888432018-05-16 09:11:05 -0700478 TokenTree::Ident(ref mut t) => t.set_span(span),
479 TokenTree::Punct(ref mut t) => t.set_span(span),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700480 TokenTree::Literal(ref mut t) => t.set_span(span),
481 }
482 }
483}
484
485impl From<Group> for TokenTree {
486 fn from(g: Group) -> TokenTree {
487 TokenTree::Group(g)
488 }
489}
490
Alex Crichtonf3888432018-05-16 09:11:05 -0700491impl From<Ident> for TokenTree {
492 fn from(g: Ident) -> TokenTree {
493 TokenTree::Ident(g)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700494 }
495}
496
Alex Crichtonf3888432018-05-16 09:11:05 -0700497impl From<Punct> for TokenTree {
498 fn from(g: Punct) -> TokenTree {
499 TokenTree::Punct(g)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700500 }
501}
502
503impl From<Literal> for TokenTree {
504 fn from(g: Literal) -> TokenTree {
505 TokenTree::Literal(g)
Alex Crichton1a7f7622017-07-05 17:47:15 -0700506 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700507}
508
David Tolnay82ba02d2018-05-20 16:22:43 -0700509/// Prints the token tree as a string that is supposed to be losslessly
510/// convertible back into the same token tree (modulo spans), except for
511/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
512/// numeric literals.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700513impl fmt::Display for TokenTree {
514 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700515 match *self {
516 TokenTree::Group(ref t) => t.fmt(f),
Alex Crichtonf3888432018-05-16 09:11:05 -0700517 TokenTree::Ident(ref t) => t.fmt(f),
518 TokenTree::Punct(ref t) => t.fmt(f),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700519 TokenTree::Literal(ref t) => t.fmt(f),
520 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700521 }
522}
523
David Tolnay82ba02d2018-05-20 16:22:43 -0700524/// Prints token tree in a form convenient for debugging.
David Tolnay034205f2018-04-22 16:45:28 -0700525impl fmt::Debug for TokenTree {
526 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
527 // Each of these has the name in the struct type in the derived debug,
528 // so don't bother with an extra layer of indirection
529 match *self {
530 TokenTree::Group(ref t) => t.fmt(f),
David Tolnayd8fcdb82018-06-02 15:43:53 -0700531 TokenTree::Ident(ref t) => {
532 let mut debug = f.debug_struct("Ident");
533 debug.field("sym", &format_args!("{}", t));
David Tolnayfd8cdc82019-01-19 19:23:59 -0800534 imp::debug_span_field_if_nontrivial(&mut debug, t.span().inner);
David Tolnayd8fcdb82018-06-02 15:43:53 -0700535 debug.finish()
536 }
Alex Crichtonf3888432018-05-16 09:11:05 -0700537 TokenTree::Punct(ref t) => t.fmt(f),
David Tolnay034205f2018-04-22 16:45:28 -0700538 TokenTree::Literal(ref t) => t.fmt(f),
539 }
540 }
541}
542
David Tolnay82ba02d2018-05-20 16:22:43 -0700543/// A delimited token stream.
544///
545/// A `Group` internally contains a `TokenStream` which is surrounded by
546/// `Delimiter`s.
David Tolnay034205f2018-04-22 16:45:28 -0700547#[derive(Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700548pub struct Group {
David Tolnayf14813f2018-09-08 17:14:07 -0700549 inner: imp::Group,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700550}
551
David Tolnay82ba02d2018-05-20 16:22:43 -0700552/// Describes how a sequence of token trees is delimited.
Michael Layzell5372f4b2017-06-02 10:29:31 -0400553#[derive(Copy, Clone, Debug, Eq, PartialEq)]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700554pub enum Delimiter {
David Tolnay82ba02d2018-05-20 16:22:43 -0700555 /// `( ... )`
Alex Crichton44bffbc2017-05-19 17:51:59 -0700556 Parenthesis,
David Tolnay82ba02d2018-05-20 16:22:43 -0700557 /// `{ ... }`
Alex Crichton44bffbc2017-05-19 17:51:59 -0700558 Brace,
David Tolnay82ba02d2018-05-20 16:22:43 -0700559 /// `[ ... ]`
Alex Crichton44bffbc2017-05-19 17:51:59 -0700560 Bracket,
David Tolnay82ba02d2018-05-20 16:22:43 -0700561 /// `Ø ... Ø`
562 ///
563 /// An implicit delimiter, that may, for example, appear around tokens
564 /// coming from a "macro variable" `$var`. It is important to preserve
565 /// operator priorities in cases like `$var * 3` where `$var` is `1 + 2`.
566 /// Implicit delimiters may not survive roundtrip of a token stream through
567 /// a string.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700568 None,
569}
570
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700571impl Group {
David Tolnayf14813f2018-09-08 17:14:07 -0700572 fn _new(inner: imp::Group) -> Self {
David Tolnay4453fcc2019-01-16 12:15:01 -0800573 Group { inner: inner }
David Tolnayf14813f2018-09-08 17:14:07 -0700574 }
575
David Tolnayaef075b2019-01-16 16:29:18 -0800576 fn _new_stable(inner: fallback::Group) -> Self {
David Tolnayf14813f2018-09-08 17:14:07 -0700577 Group {
578 inner: inner.into(),
579 }
580 }
581
David Tolnay82ba02d2018-05-20 16:22:43 -0700582 /// Creates a new `Group` with the given delimiter and token stream.
583 ///
584 /// This constructor will set the span for this group to
585 /// `Span::call_site()`. To change the span you can use the `set_span`
586 /// method below.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700587 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
588 Group {
David Tolnayf14813f2018-09-08 17:14:07 -0700589 inner: imp::Group::new(delimiter, stream.inner),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700590 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700591 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700592
David Tolnay82ba02d2018-05-20 16:22:43 -0700593 /// Returns the delimiter of this `Group`
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700594 pub fn delimiter(&self) -> Delimiter {
David Tolnayf14813f2018-09-08 17:14:07 -0700595 self.inner.delimiter()
Alex Crichton44bffbc2017-05-19 17:51:59 -0700596 }
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700597
David Tolnay82ba02d2018-05-20 16:22:43 -0700598 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
599 ///
600 /// Note that the returned token stream does not include the delimiter
601 /// returned above.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700602 pub fn stream(&self) -> TokenStream {
David Tolnayf14813f2018-09-08 17:14:07 -0700603 TokenStream::_new(self.inner.stream())
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700604 }
605
David Tolnay82ba02d2018-05-20 16:22:43 -0700606 /// Returns the span for the delimiters of this token stream, spanning the
607 /// entire `Group`.
David Tolnayf14813f2018-09-08 17:14:07 -0700608 ///
609 /// ```text
610 /// pub fn span(&self) -> Span {
611 /// ^^^^^^^
612 /// ```
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700613 pub fn span(&self) -> Span {
David Tolnayf14813f2018-09-08 17:14:07 -0700614 Span::_new(self.inner.span())
615 }
616
617 /// Returns the span pointing to the opening delimiter of this group.
618 ///
619 /// ```text
620 /// pub fn span_open(&self) -> Span {
621 /// ^
622 /// ```
623 #[cfg(procmacro2_semver_exempt)]
624 pub fn span_open(&self) -> Span {
625 Span::_new(self.inner.span_open())
626 }
627
628 /// Returns the span pointing to the closing delimiter of this group.
629 ///
630 /// ```text
631 /// pub fn span_close(&self) -> Span {
632 /// ^
633 /// ```
634 #[cfg(procmacro2_semver_exempt)]
635 pub fn span_close(&self) -> Span {
636 Span::_new(self.inner.span_close())
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700637 }
638
David Tolnay82ba02d2018-05-20 16:22:43 -0700639 /// Configures the span for this `Group`'s delimiters, but not its internal
640 /// tokens.
641 ///
642 /// This method will **not** set the span of all the internal tokens spanned
643 /// by this group, but rather it will only set the span of the delimiter
644 /// tokens at the level of the `Group`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700645 pub fn set_span(&mut self, span: Span) {
David Tolnayf14813f2018-09-08 17:14:07 -0700646 self.inner.set_span(span.inner)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700647 }
648}
649
David Tolnay82ba02d2018-05-20 16:22:43 -0700650/// Prints the group as a string that should be losslessly convertible back
651/// into the same group (modulo spans), except for possibly `TokenTree::Group`s
652/// with `Delimiter::None` delimiters.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700653impl fmt::Display for Group {
David Tolnayf14813f2018-09-08 17:14:07 -0700654 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
655 fmt::Display::fmt(&self.inner, formatter)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700656 }
657}
658
David Tolnay034205f2018-04-22 16:45:28 -0700659impl fmt::Debug for Group {
David Tolnayf14813f2018-09-08 17:14:07 -0700660 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
661 fmt::Debug::fmt(&self.inner, formatter)
David Tolnay034205f2018-04-22 16:45:28 -0700662 }
663}
664
David Tolnay82ba02d2018-05-20 16:22:43 -0700665/// An `Punct` is an single punctuation character like `+`, `-` or `#`.
666///
667/// Multicharacter operators like `+=` are represented as two instances of
668/// `Punct` with different forms of `Spacing` returned.
Alex Crichtonf3888432018-05-16 09:11:05 -0700669#[derive(Clone)]
670pub struct Punct {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700671 op: char,
672 spacing: Spacing,
673 span: Span,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700674}
675
David Tolnay82ba02d2018-05-20 16:22:43 -0700676/// Whether an `Punct` is followed immediately by another `Punct` or followed by
677/// another token or whitespace.
Lukas Kalbertodteb3f9302017-08-20 18:58:41 +0200678#[derive(Copy, Clone, Debug, Eq, PartialEq)]
Alex Crichton1a7f7622017-07-05 17:47:15 -0700679pub enum Spacing {
David Tolnay82ba02d2018-05-20 16:22:43 -0700680 /// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700681 Alone,
David Tolnay82ba02d2018-05-20 16:22:43 -0700682 /// E.g. `+` is `Joint` in `+=` or `'#`.
683 ///
684 /// Additionally, single quote `'` can join with identifiers to form
685 /// lifetimes `'ident`.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700686 Joint,
687}
688
Alex Crichtonf3888432018-05-16 09:11:05 -0700689impl Punct {
David Tolnay82ba02d2018-05-20 16:22:43 -0700690 /// Creates a new `Punct` from the given character and spacing.
691 ///
692 /// The `ch` argument must be a valid punctuation character permitted by the
693 /// language, otherwise the function will panic.
694 ///
695 /// The returned `Punct` will have the default span of `Span::call_site()`
696 /// which can be further configured with the `set_span` method below.
Alex Crichtonf3888432018-05-16 09:11:05 -0700697 pub fn new(op: char, spacing: Spacing) -> Punct {
698 Punct {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700699 op: op,
700 spacing: spacing,
701 span: Span::call_site(),
702 }
703 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700704
David Tolnay82ba02d2018-05-20 16:22:43 -0700705 /// Returns the value of this punctuation character as `char`.
Alex Crichtonf3888432018-05-16 09:11:05 -0700706 pub fn as_char(&self) -> char {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700707 self.op
708 }
709
David Tolnay82ba02d2018-05-20 16:22:43 -0700710 /// Returns the spacing of this punctuation character, indicating whether
711 /// it's immediately followed by another `Punct` in the token stream, so
712 /// they can potentially be combined into a multicharacter operator
713 /// (`Joint`), or it's followed by some other token or whitespace (`Alone`)
714 /// so the operator has certainly ended.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700715 pub fn spacing(&self) -> Spacing {
716 self.spacing
717 }
718
David Tolnay82ba02d2018-05-20 16:22:43 -0700719 /// Returns the span for this punctuation character.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700720 pub fn span(&self) -> Span {
721 self.span
722 }
723
David Tolnay82ba02d2018-05-20 16:22:43 -0700724 /// Configure the span for this punctuation character.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700725 pub fn set_span(&mut self, span: Span) {
726 self.span = span;
727 }
728}
729
David Tolnay82ba02d2018-05-20 16:22:43 -0700730/// Prints the punctuation character as a string that should be losslessly
731/// convertible back into the same character.
Alex Crichtonf3888432018-05-16 09:11:05 -0700732impl fmt::Display for Punct {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700733 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
734 self.op.fmt(f)
735 }
736}
737
Alex Crichtonf3888432018-05-16 09:11:05 -0700738impl fmt::Debug for Punct {
David Tolnay034205f2018-04-22 16:45:28 -0700739 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonf3888432018-05-16 09:11:05 -0700740 let mut debug = fmt.debug_struct("Punct");
David Tolnay034205f2018-04-22 16:45:28 -0700741 debug.field("op", &self.op);
742 debug.field("spacing", &self.spacing);
David Tolnayfd8cdc82019-01-19 19:23:59 -0800743 imp::debug_span_field_if_nontrivial(&mut debug, self.span.inner);
David Tolnay034205f2018-04-22 16:45:28 -0700744 debug.finish()
745 }
746}
747
David Tolnay8b71dac2018-05-20 17:07:47 -0700748/// A word of Rust code, which may be a keyword or legal variable name.
749///
750/// An identifier consists of at least one Unicode code point, the first of
751/// which has the XID_Start property and the rest of which have the XID_Continue
752/// property.
753///
754/// - The empty string is not an identifier. Use `Option<Ident>`.
755/// - A lifetime is not an identifier. Use `syn::Lifetime` instead.
756///
757/// An identifier constructed with `Ident::new` is permitted to be a Rust
David Tolnayc239f032018-11-11 12:57:09 -0800758/// keyword, though parsing one through its [`Parse`] implementation rejects
759/// Rust keywords. Use `input.call(Ident::parse_any)` when parsing to match the
David Tolnay8b71dac2018-05-20 17:07:47 -0700760/// behaviour of `Ident::new`.
761///
David Tolnayc239f032018-11-11 12:57:09 -0800762/// [`Parse`]: https://docs.rs/syn/0.15/syn/parse/trait.Parse.html
David Tolnay8b71dac2018-05-20 17:07:47 -0700763///
764/// # Examples
765///
766/// A new ident can be created from a string using the `Ident::new` function.
767/// A span must be provided explicitly which governs the name resolution
768/// behavior of the resulting identifier.
769///
David Tolnay7a964732019-01-19 19:03:20 -0800770/// ```edition2018
David Tolnay8b71dac2018-05-20 17:07:47 -0700771/// use proc_macro2::{Ident, Span};
772///
773/// fn main() {
774/// let call_ident = Ident::new("calligraphy", Span::call_site());
775///
776/// println!("{}", call_ident);
777/// }
778/// ```
779///
780/// An ident can be interpolated into a token stream using the `quote!` macro.
781///
David Tolnay7a964732019-01-19 19:03:20 -0800782/// ```edition2018
David Tolnay8b71dac2018-05-20 17:07:47 -0700783/// use proc_macro2::{Ident, Span};
David Tolnay7a964732019-01-19 19:03:20 -0800784/// use quote::quote;
David Tolnay8b71dac2018-05-20 17:07:47 -0700785///
786/// fn main() {
787/// let ident = Ident::new("demo", Span::call_site());
788///
789/// // Create a variable binding whose name is this ident.
790/// let expanded = quote! { let #ident = 10; };
791///
792/// // Create a variable binding with a slightly different name.
793/// let temp_ident = Ident::new(&format!("new_{}", ident), Span::call_site());
794/// let expanded = quote! { let #temp_ident = 10; };
795/// }
796/// ```
797///
798/// A string representation of the ident is available through the `to_string()`
799/// method.
800///
David Tolnay7a964732019-01-19 19:03:20 -0800801/// ```edition2018
David Tolnay8b71dac2018-05-20 17:07:47 -0700802/// # use proc_macro2::{Ident, Span};
803/// #
804/// # let ident = Ident::new("another_identifier", Span::call_site());
805/// #
806/// // Examine the ident as a string.
807/// let ident_string = ident.to_string();
808/// if ident_string.len() > 60 {
809/// println!("Very long identifier: {}", ident_string)
810/// }
811/// ```
Alex Crichtonf3888432018-05-16 09:11:05 -0700812#[derive(Clone)]
813pub struct Ident {
814 inner: imp::Ident,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700815 _marker: marker::PhantomData<Rc<()>>,
816}
817
Alex Crichtonf3888432018-05-16 09:11:05 -0700818impl Ident {
819 fn _new(inner: imp::Ident) -> Ident {
820 Ident {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700821 inner: inner,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700822 _marker: marker::PhantomData,
823 }
824 }
825
David Tolnay82ba02d2018-05-20 16:22:43 -0700826 /// Creates a new `Ident` with the given `string` as well as the specified
827 /// `span`.
828 ///
829 /// The `string` argument must be a valid identifier permitted by the
830 /// language, otherwise the function will panic.
831 ///
832 /// Note that `span`, currently in rustc, configures the hygiene information
833 /// for this identifier.
834 ///
835 /// As of this time `Span::call_site()` explicitly opts-in to "call-site"
836 /// hygiene meaning that identifiers created with this span will be resolved
837 /// as if they were written directly at the location of the macro call, and
838 /// other code at the macro call site will be able to refer to them as well.
839 ///
840 /// Later spans like `Span::def_site()` will allow to opt-in to
841 /// "definition-site" hygiene meaning that identifiers created with this
842 /// span will be resolved at the location of the macro definition and other
843 /// code at the macro call site will not be able to refer to them.
844 ///
845 /// Due to the current importance of hygiene this constructor, unlike other
846 /// tokens, requires a `Span` to be specified at construction.
David Tolnay8b71dac2018-05-20 17:07:47 -0700847 ///
848 /// # Panics
849 ///
850 /// Panics if the input string is neither a keyword nor a legal variable
851 /// name.
Alex Crichtonf3888432018-05-16 09:11:05 -0700852 pub fn new(string: &str, span: Span) -> Ident {
853 Ident::_new(imp::Ident::new(string, span.inner))
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700854 }
855
David Tolnay82ba02d2018-05-20 16:22:43 -0700856 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
David Tolnaya01ca8e2018-06-04 00:55:28 -0700857 ///
858 /// This method is semver exempt and not exposed by default.
Alex Crichtonf3888432018-05-16 09:11:05 -0700859 #[cfg(procmacro2_semver_exempt)]
860 pub fn new_raw(string: &str, span: Span) -> Ident {
861 Ident::_new_raw(string, span)
862 }
863
864 fn _new_raw(string: &str, span: Span) -> Ident {
865 Ident::_new(imp::Ident::new_raw(string, span.inner))
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700866 }
867
David Tolnay82ba02d2018-05-20 16:22:43 -0700868 /// Returns the span of this `Ident`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700869 pub fn span(&self) -> Span {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700870 Span::_new(self.inner.span())
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700871 }
872
David Tolnay82ba02d2018-05-20 16:22:43 -0700873 /// Configures the span of this `Ident`, possibly changing its hygiene
874 /// context.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700875 pub fn set_span(&mut self, span: Span) {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700876 self.inner.set_span(span.inner);
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700877 }
878}
879
Alex Crichtonf3888432018-05-16 09:11:05 -0700880impl PartialEq for Ident {
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700881 fn eq(&self, other: &Ident) -> bool {
David Tolnayc0b0f2e2018-09-02 17:56:08 -0700882 self.inner == other.inner
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700883 }
884}
885
David Tolnayc0bbcc52018-05-18 10:51:04 -0700886impl<T> PartialEq<T> for Ident
887where
888 T: ?Sized + AsRef<str>,
889{
890 fn eq(&self, other: &T) -> bool {
David Tolnayc0b0f2e2018-09-02 17:56:08 -0700891 self.inner == other
David Tolnayc0bbcc52018-05-18 10:51:04 -0700892 }
893}
894
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700895impl Eq for Ident {}
Alex Crichtonf3888432018-05-16 09:11:05 -0700896
897impl PartialOrd for Ident {
898 fn partial_cmp(&self, other: &Ident) -> Option<Ordering> {
899 Some(self.cmp(other))
900 }
901}
902
903impl Ord for Ident {
904 fn cmp(&self, other: &Ident) -> Ordering {
905 self.to_string().cmp(&other.to_string())
906 }
907}
908
909impl Hash for Ident {
910 fn hash<H: Hasher>(&self, hasher: &mut H) {
911 self.to_string().hash(hasher)
912 }
913}
914
David Tolnay82ba02d2018-05-20 16:22:43 -0700915/// Prints the identifier as a string that should be losslessly convertible back
916/// into the same identifier.
Alex Crichtonf3888432018-05-16 09:11:05 -0700917impl fmt::Display for Ident {
918 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
919 self.inner.fmt(f)
920 }
921}
922
923impl fmt::Debug for Ident {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700924 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
925 self.inner.fmt(f)
926 }
927}
928
David Tolnay82ba02d2018-05-20 16:22:43 -0700929/// A literal string (`"hello"`), byte string (`b"hello"`), character (`'a'`),
930/// byte character (`b'a'`), an integer or floating point number with or without
931/// a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
932///
933/// Boolean literals like `true` and `false` do not belong here, they are
934/// `Ident`s.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700935#[derive(Clone)]
936pub struct Literal {
937 inner: imp::Literal,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700938 _marker: marker::PhantomData<Rc<()>>,
939}
940
David Tolnay82ba02d2018-05-20 16:22:43 -0700941macro_rules! suffixed_int_literals {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700942 ($($name:ident => $kind:ident,)*) => ($(
David Tolnay82ba02d2018-05-20 16:22:43 -0700943 /// Creates a new suffixed integer literal with the specified value.
944 ///
945 /// This function will create an integer like `1u32` where the integer
946 /// value specified is the first part of the token and the integral is
947 /// also suffixed at the end. Literals created from negative numbers may
948 /// not survive rountrips through `TokenStream` or strings and may be
949 /// broken into two tokens (`-` and positive literal).
950 ///
951 /// Literals created through this method have the `Span::call_site()`
952 /// span by default, which can be configured with the `set_span` method
953 /// below.
954 pub fn $name(n: $kind) -> Literal {
955 Literal::_new(imp::Literal::$name(n))
956 }
957 )*)
958}
959
960macro_rules! unsuffixed_int_literals {
961 ($($name:ident => $kind:ident,)*) => ($(
962 /// Creates a new unsuffixed integer literal with the specified value.
963 ///
964 /// This function will create an integer like `1` where the integer
965 /// value specified is the first part of the token. No suffix is
966 /// specified on this token, meaning that invocations like
967 /// `Literal::i8_unsuffixed(1)` are equivalent to
968 /// `Literal::u32_unsuffixed(1)`. Literals created from negative numbers
969 /// may not survive rountrips through `TokenStream` or strings and may
970 /// be broken into two tokens (`-` and positive literal).
971 ///
972 /// Literals created through this method have the `Span::call_site()`
973 /// span by default, which can be configured with the `set_span` method
974 /// below.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700975 pub fn $name(n: $kind) -> Literal {
Alex Crichtona914a612018-04-04 07:48:44 -0700976 Literal::_new(imp::Literal::$name(n))
Alex Crichton1a7f7622017-07-05 17:47:15 -0700977 }
978 )*)
979}
980
Alex Crichton852d53d2017-05-19 19:25:08 -0700981impl Literal {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700982 fn _new(inner: imp::Literal) -> Literal {
983 Literal {
984 inner: inner,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700985 _marker: marker::PhantomData,
986 }
Alex Crichton1a7f7622017-07-05 17:47:15 -0700987 }
988
David Tolnayaef075b2019-01-16 16:29:18 -0800989 fn _new_stable(inner: fallback::Literal) -> Literal {
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700990 Literal {
991 inner: inner.into(),
992 _marker: marker::PhantomData,
993 }
994 }
995
David Tolnay82ba02d2018-05-20 16:22:43 -0700996 suffixed_int_literals! {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700997 u8_suffixed => u8,
998 u16_suffixed => u16,
999 u32_suffixed => u32,
1000 u64_suffixed => u64,
1001 usize_suffixed => usize,
1002 i8_suffixed => i8,
1003 i16_suffixed => i16,
1004 i32_suffixed => i32,
1005 i64_suffixed => i64,
1006 isize_suffixed => isize,
David Tolnay82ba02d2018-05-20 16:22:43 -07001007 }
Alex Crichton1a7f7622017-07-05 17:47:15 -07001008
Alex Crichton69385662018-11-08 06:30:04 -08001009 #[cfg(u128)]
1010 suffixed_int_literals! {
1011 u128_suffixed => u128,
1012 i128_suffixed => i128,
1013 }
1014
David Tolnay82ba02d2018-05-20 16:22:43 -07001015 unsuffixed_int_literals! {
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001016 u8_unsuffixed => u8,
1017 u16_unsuffixed => u16,
1018 u32_unsuffixed => u32,
1019 u64_unsuffixed => u64,
1020 usize_unsuffixed => usize,
1021 i8_unsuffixed => i8,
1022 i16_unsuffixed => i16,
1023 i32_unsuffixed => i32,
1024 i64_unsuffixed => i64,
1025 isize_unsuffixed => isize,
Alex Crichton1a7f7622017-07-05 17:47:15 -07001026 }
1027
Alex Crichton69385662018-11-08 06:30:04 -08001028 #[cfg(u128)]
1029 unsuffixed_int_literals! {
1030 u128_unsuffixed => u128,
1031 i128_unsuffixed => i128,
1032 }
1033
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001034 pub fn f64_unsuffixed(f: f64) -> Literal {
1035 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -07001036 Literal::_new(imp::Literal::f64_unsuffixed(f))
Alex Crichton1a7f7622017-07-05 17:47:15 -07001037 }
1038
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001039 pub fn f64_suffixed(f: f64) -> Literal {
1040 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -07001041 Literal::_new(imp::Literal::f64_suffixed(f))
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001042 }
1043
David Tolnay82ba02d2018-05-20 16:22:43 -07001044 /// Creates a new unsuffixed floating-point literal.
1045 ///
1046 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1047 /// the float's value is emitted directly into the token but no suffix is
1048 /// used, so it may be inferred to be a `f64` later in the compiler.
1049 /// Literals created from negative numbers may not survive rountrips through
1050 /// `TokenStream` or strings and may be broken into two tokens (`-` and
1051 /// positive literal).
1052 ///
1053 /// # Panics
1054 ///
1055 /// This function requires that the specified float is finite, for example
1056 /// if it is infinity or NaN this function will panic.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001057 pub fn f32_unsuffixed(f: f32) -> Literal {
1058 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -07001059 Literal::_new(imp::Literal::f32_unsuffixed(f))
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001060 }
1061
1062 pub fn f32_suffixed(f: f32) -> Literal {
1063 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -07001064 Literal::_new(imp::Literal::f32_suffixed(f))
Alex Crichton1a7f7622017-07-05 17:47:15 -07001065 }
1066
1067 pub fn string(string: &str) -> Literal {
Alex Crichtona914a612018-04-04 07:48:44 -07001068 Literal::_new(imp::Literal::string(string))
Alex Crichton1a7f7622017-07-05 17:47:15 -07001069 }
1070
1071 pub fn character(ch: char) -> Literal {
Alex Crichtona914a612018-04-04 07:48:44 -07001072 Literal::_new(imp::Literal::character(ch))
Alex Crichton76a5cc82017-05-23 07:01:44 -07001073 }
1074
Alex Crichton9c2fb0a2017-05-26 08:49:31 -07001075 pub fn byte_string(s: &[u8]) -> Literal {
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001076 Literal::_new(imp::Literal::byte_string(s))
Alex Crichton852d53d2017-05-19 19:25:08 -07001077 }
Alex Crichton76a5cc82017-05-23 07:01:44 -07001078
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001079 pub fn span(&self) -> Span {
Alex Crichtonb2c94622018-04-04 07:36:41 -07001080 Span::_new(self.inner.span())
Alex Crichton1a7f7622017-07-05 17:47:15 -07001081 }
1082
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001083 pub fn set_span(&mut self, span: Span) {
Alex Crichtonb2c94622018-04-04 07:36:41 -07001084 self.inner.set_span(span.inner);
Alex Crichton31316622017-05-26 12:54:47 -07001085 }
Alex Crichton852d53d2017-05-19 19:25:08 -07001086}
1087
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001088impl fmt::Debug for Literal {
1089 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1090 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001091 }
1092}
David Tolnaycb1b85f2017-06-03 16:40:35 -07001093
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001094impl fmt::Display for Literal {
1095 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1096 self.inner.fmt(f)
1097 }
1098}
1099
David Tolnay82ba02d2018-05-20 16:22:43 -07001100/// Public implementation details for the `TokenStream` type, such as iterators.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001101pub mod token_stream {
1102 use std::fmt;
1103 use std::marker;
1104 use std::rc::Rc;
1105
David Tolnay48ea5042018-04-23 19:17:35 -07001106 use imp;
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001107 pub use TokenStream;
David Tolnayb28f38a2018-03-31 22:02:29 +02001108 use TokenTree;
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001109
David Tolnay82ba02d2018-05-20 16:22:43 -07001110 /// An iterator over `TokenStream`'s `TokenTree`s.
1111 ///
1112 /// The iteration is "shallow", e.g. the iterator doesn't recurse into
1113 /// delimited groups, and returns whole groups as token trees.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001114 pub struct IntoIter {
1115 inner: imp::TokenTreeIter,
1116 _marker: marker::PhantomData<Rc<()>>,
1117 }
1118
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001119 impl Iterator for IntoIter {
1120 type Item = TokenTree;
1121
1122 fn next(&mut self) -> Option<TokenTree> {
1123 self.inner.next()
1124 }
1125 }
1126
1127 impl fmt::Debug for IntoIter {
1128 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1129 self.inner.fmt(f)
1130 }
1131 }
1132
1133 impl IntoIterator for TokenStream {
1134 type Item = TokenTree;
1135 type IntoIter = IntoIter;
1136
1137 fn into_iter(self) -> IntoIter {
1138 IntoIter {
1139 inner: self.inner.into_iter(),
1140 _marker: marker::PhantomData,
1141 }
1142 }
1143 }
1144}