blob: 784e456a796e830debfb33b0ae18f891af2a136d [file] [log] [blame]
Alex Crichton1fd0e8a2018-02-04 21:29:13 -08001//! A "shim crate" intended to multiplex the [`proc_macro`] API on to stable
2//! Rust.
Alex Crichtonbabc99e2017-07-05 18:00:29 -07003//!
4//! Procedural macros in Rust operate over the upstream
Alex Crichton1fd0e8a2018-02-04 21:29:13 -08005//! [`proc_macro::TokenStream`][ts] type. This type currently is quite
6//! conservative and exposed no internal implementation details. Nightly
7//! compilers, however, contain a much richer interface. This richer interface
8//! allows fine-grained inspection of the token stream which avoids
9//! stringification/re-lexing and also preserves span information.
Alex Crichtonbabc99e2017-07-05 18:00:29 -070010//!
Alex Crichton1fd0e8a2018-02-04 21:29:13 -080011//! The upcoming APIs added to [`proc_macro`] upstream are the foundation for
Alex Crichtonbabc99e2017-07-05 18:00:29 -070012//! productive procedural macros in the ecosystem. To help prepare the ecosystem
13//! for using them this crate serves to both compile on stable and nightly and
14//! mirrors the API-to-be. The intention is that procedural macros which switch
15//! to use this crate will be trivially able to switch to the upstream
16//! `proc_macro` crate once its API stabilizes.
17//!
David Tolnayd66ecf62018-01-02 20:05:42 -080018//! In the meantime this crate also has a `nightly` Cargo feature which
Alex Crichton1fd0e8a2018-02-04 21:29:13 -080019//! enables it to reimplement itself with the unstable API of [`proc_macro`].
Alex Crichtonbabc99e2017-07-05 18:00:29 -070020//! This'll allow immediate usage of the beneficial upstream API, particularly
21//! around preserving span information.
Alex Crichton1fd0e8a2018-02-04 21:29:13 -080022//!
David Tolnay6b46deb2018-04-25 21:22:46 -070023//! # Unstable Features
24//!
25//! `proc-macro2` supports exporting some methods from `proc_macro` which are
26//! currently highly unstable, and may not be stabilized in the first pass of
27//! `proc_macro` stabilizations. These features are not exported by default.
28//! Minor versions of `proc-macro2` may make breaking changes to them at any
29//! time.
30//!
31//! To enable these features, the `procmacro2_semver_exempt` config flag must be
32//! passed to rustc.
33//!
34//! ```sh
35//! RUSTFLAGS='--cfg procmacro2_semver_exempt' cargo build
36//! ```
37//!
38//! Note that this must not only be done for your crate, but for any crate that
39//! depends on your crate. This infectious nature is intentional, as it serves
40//! as a reminder that you are outside of the normal semver guarantees.
41//!
Alex Crichton1fd0e8a2018-02-04 21:29:13 -080042//! [`proc_macro`]: https://doc.rust-lang.org/proc_macro/
43//! [ts]: https://doc.rust-lang.org/proc_macro/struct.TokenStream.html
Alex Crichtonbabc99e2017-07-05 18:00:29 -070044
David Tolnay15cc4982018-01-08 08:03:27 -080045// Proc-macro2 types in rustdoc of other crates get linked to here.
David Tolnay102ee292018-11-11 15:27:31 -080046#![doc(html_root_url = "https://docs.rs/proc-macro2/0.4.23")]
David Tolnay5a556cf2018-08-12 13:49:39 -070047#![cfg_attr(
Alex Crichtonce0904d2018-08-27 17:29:49 -070048 super_unstable,
xd0096421fd37672018-10-04 16:39:45 +010049 feature(proc_macro_raw_ident, proc_macro_span, proc_macro_def_site)
David Tolnay5a556cf2018-08-12 13:49:39 -070050)]
Alex Crichtoncbec8ec2017-06-02 13:19:33 -070051
Alex Crichton53548482018-08-11 21:54:05 -070052#[cfg(use_proc_macro)]
Alex Crichton44bffbc2017-05-19 17:51:59 -070053extern crate proc_macro;
David Tolnayb1032662017-05-31 15:52:28 -070054extern crate unicode_xid;
Alex Crichton44bffbc2017-05-19 17:51:59 -070055
Alex Crichtonf3888432018-05-16 09:11:05 -070056use std::cmp::Ordering;
Alex Crichton44bffbc2017-05-19 17:51:59 -070057use std::fmt;
Alex Crichtonf3888432018-05-16 09:11:05 -070058use std::hash::{Hash, Hasher};
Alex Crichton44bffbc2017-05-19 17:51:59 -070059use std::iter::FromIterator;
Alex Crichtonaf5bad42018-03-27 14:45:10 -070060use std::marker;
61use std::rc::Rc;
62use std::str::FromStr;
Alex Crichton44bffbc2017-05-19 17:51:59 -070063
David Tolnayb1032662017-05-31 15:52:28 -070064#[macro_use]
David Tolnayb1032662017-05-31 15:52:28 -070065mod strnom;
Alex Crichton30a4e9e2018-04-27 17:02:19 -070066mod stable;
David Tolnayb1032662017-05-31 15:52:28 -070067
Alex Crichtonce0904d2018-08-27 17:29:49 -070068#[cfg(not(wrap_proc_macro))]
Alex Crichton30a4e9e2018-04-27 17:02:19 -070069use stable as imp;
Alex Crichtonb15c6352017-05-19 19:36:36 -070070#[path = "unstable.rs"]
Alex Crichtonce0904d2018-08-27 17:29:49 -070071#[cfg(wrap_proc_macro)]
Alex Crichton44bffbc2017-05-19 17:51:59 -070072mod imp;
73
David Tolnay82ba02d2018-05-20 16:22:43 -070074/// An abstract stream of tokens, or more concretely a sequence of token trees.
75///
76/// This type provides interfaces for iterating over token trees and for
77/// collecting token trees into one stream.
78///
79/// Token stream is both the input and output of `#[proc_macro]`,
80/// `#[proc_macro_attribute]` and `#[proc_macro_derive]` definitions.
David Tolnaycb1b85f2017-06-03 16:40:35 -070081#[derive(Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -070082pub struct TokenStream {
83 inner: imp::TokenStream,
84 _marker: marker::PhantomData<Rc<()>>,
85}
Alex Crichton44bffbc2017-05-19 17:51:59 -070086
David Tolnay82ba02d2018-05-20 16:22:43 -070087/// Error returned from `TokenStream::from_str`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -070088pub struct LexError {
89 inner: imp::LexError,
90 _marker: marker::PhantomData<Rc<()>>,
91}
92
93impl TokenStream {
94 fn _new(inner: imp::TokenStream) -> TokenStream {
95 TokenStream {
96 inner: inner,
97 _marker: marker::PhantomData,
98 }
99 }
100
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700101 fn _new_stable(inner: stable::TokenStream) -> TokenStream {
102 TokenStream {
103 inner: inner.into(),
104 _marker: marker::PhantomData,
105 }
106 }
107
David Tolnay82ba02d2018-05-20 16:22:43 -0700108 /// Returns an empty `TokenStream` containing no token trees.
David Tolnayc3bb4592018-05-28 20:09:44 -0700109 pub fn new() -> TokenStream {
110 TokenStream::_new(imp::TokenStream::new())
111 }
112
113 #[deprecated(since = "0.4.4", note = "please use TokenStream::new")]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700114 pub fn empty() -> TokenStream {
David Tolnayc3bb4592018-05-28 20:09:44 -0700115 TokenStream::new()
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700116 }
117
David Tolnay82ba02d2018-05-20 16:22:43 -0700118 /// Checks if this `TokenStream` is empty.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700119 pub fn is_empty(&self) -> bool {
120 self.inner.is_empty()
121 }
122}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700123
Árpád Goretity4f74b682018-07-14 00:47:51 +0200124/// `TokenStream::default()` returns an empty stream,
125/// i.e. this is equivalent with `TokenStream::new()`.
126impl Default for TokenStream {
127 fn default() -> Self {
128 TokenStream::new()
129 }
130}
131
David Tolnay82ba02d2018-05-20 16:22:43 -0700132/// Attempts to break the string into tokens and parse those tokens into a token
133/// stream.
134///
135/// May fail for a number of reasons, for example, if the string contains
136/// unbalanced delimiters or characters not existing in the language.
137///
138/// NOTE: Some errors may cause panics instead of returning `LexError`. We
139/// reserve the right to change these errors into `LexError`s later.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700140impl FromStr for TokenStream {
141 type Err = LexError;
142
143 fn from_str(src: &str) -> Result<TokenStream, LexError> {
David Tolnayb28f38a2018-03-31 22:02:29 +0200144 let e = src.parse().map_err(|e| LexError {
145 inner: e,
146 _marker: marker::PhantomData,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700147 })?;
148 Ok(TokenStream::_new(e))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700149 }
150}
151
Alex Crichton53548482018-08-11 21:54:05 -0700152#[cfg(use_proc_macro)]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700153impl From<proc_macro::TokenStream> for TokenStream {
154 fn from(inner: proc_macro::TokenStream) -> TokenStream {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700155 TokenStream::_new(inner.into())
Alex Crichton44bffbc2017-05-19 17:51:59 -0700156 }
157}
158
Alex Crichton53548482018-08-11 21:54:05 -0700159#[cfg(use_proc_macro)]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700160impl From<TokenStream> for proc_macro::TokenStream {
161 fn from(inner: TokenStream) -> proc_macro::TokenStream {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700162 inner.inner.into()
Alex Crichton44bffbc2017-05-19 17:51:59 -0700163 }
164}
165
Alex Crichtonf3888432018-05-16 09:11:05 -0700166impl Extend<TokenTree> for TokenStream {
167 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, streams: I) {
168 self.inner.extend(streams)
169 }
170}
171
David Tolnay5c58c532018-08-13 11:33:51 -0700172impl Extend<TokenStream> for TokenStream {
173 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
174 self.inner
175 .extend(streams.into_iter().map(|stream| stream.inner))
176 }
177}
178
David Tolnay82ba02d2018-05-20 16:22:43 -0700179/// Collects a number of token trees into a single stream.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700180impl FromIterator<TokenTree> for TokenStream {
181 fn from_iter<I: IntoIterator<Item = TokenTree>>(streams: I) -> Self {
182 TokenStream::_new(streams.into_iter().collect())
Alex Crichton44bffbc2017-05-19 17:51:59 -0700183 }
184}
Alex Crichton53b00672018-09-06 17:16:10 -0700185impl FromIterator<TokenStream> for TokenStream {
186 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
187 TokenStream::_new(streams.into_iter().map(|i| i.inner).collect())
188 }
189}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700190
David Tolnay82ba02d2018-05-20 16:22:43 -0700191/// Prints the token stream as a string that is supposed to be losslessly
192/// convertible back into the same token stream (modulo spans), except for
193/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
194/// numeric literals.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700195impl fmt::Display for TokenStream {
196 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
197 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700198 }
199}
200
David Tolnay82ba02d2018-05-20 16:22:43 -0700201/// Prints token in a form convenient for debugging.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700202impl fmt::Debug for TokenStream {
203 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
204 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700205 }
206}
207
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700208impl fmt::Debug for LexError {
209 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
210 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700211 }
212}
213
Nika Layzellb35a9a32017-12-30 14:34:35 -0500214// Returned by reference, so we can't easily wrap it.
David Tolnay1ebe3972018-01-02 20:14:20 -0800215#[cfg(procmacro2_semver_exempt)]
Nika Layzellb35a9a32017-12-30 14:34:35 -0500216pub use imp::FileName;
217
David Tolnay82ba02d2018-05-20 16:22:43 -0700218/// The source file of a given `Span`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700219///
220/// This type is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800221#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500222#[derive(Clone, PartialEq, Eq)]
David Tolnay7e654a82018-11-11 13:33:18 -0800223pub struct SourceFile {
224 inner: imp::SourceFile,
225 _marker: marker::PhantomData<Rc<()>>,
226}
Nika Layzellf8d5f212017-12-11 14:07:02 -0500227
David Tolnay1ebe3972018-01-02 20:14:20 -0800228#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500229impl SourceFile {
David Tolnay7e654a82018-11-11 13:33:18 -0800230 fn _new(inner: imp::SourceFile) -> Self {
231 SourceFile {
232 inner: inner,
233 _marker: marker::PhantomData,
234 }
235 }
236
David Tolnay82ba02d2018-05-20 16:22:43 -0700237 /// Get the path to this source file.
238 ///
239 /// ### Note
240 ///
241 /// If the code span associated with this `SourceFile` was generated by an
242 /// external macro, this may not be an actual path on the filesystem. Use
243 /// [`is_real`] to check.
244 ///
245 /// Also note that even if `is_real` returns `true`, if
246 /// `--remap-path-prefix` was passed on the command line, the path as given
247 /// may not actually be valid.
248 ///
249 /// [`is_real`]: #method.is_real
Nika Layzellb35a9a32017-12-30 14:34:35 -0500250 pub fn path(&self) -> &FileName {
David Tolnay7e654a82018-11-11 13:33:18 -0800251 self.inner.path()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500252 }
253
David Tolnay82ba02d2018-05-20 16:22:43 -0700254 /// Returns `true` if this source file is a real source file, and not
255 /// generated by an external macro's expansion.
Nika Layzellf8d5f212017-12-11 14:07:02 -0500256 pub fn is_real(&self) -> bool {
David Tolnay7e654a82018-11-11 13:33:18 -0800257 self.inner.is_real()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500258 }
259}
260
David Tolnay1ebe3972018-01-02 20:14:20 -0800261#[cfg(procmacro2_semver_exempt)]
Nika Layzellb35a9a32017-12-30 14:34:35 -0500262impl AsRef<FileName> for SourceFile {
263 fn as_ref(&self) -> &FileName {
David Tolnay7e654a82018-11-11 13:33:18 -0800264 self.inner.path()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500265 }
266}
267
David Tolnay1ebe3972018-01-02 20:14:20 -0800268#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500269impl fmt::Debug for SourceFile {
270 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
David Tolnay7e654a82018-11-11 13:33:18 -0800271 self.inner.fmt(f)
Nika Layzellf8d5f212017-12-11 14:07:02 -0500272 }
273}
274
David Tolnay82ba02d2018-05-20 16:22:43 -0700275/// A line-column pair representing the start or end of a `Span`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700276///
277/// This type is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800278#[cfg(procmacro2_semver_exempt)]
Nika Layzell1ecb6ce2017-12-30 14:34:05 -0500279pub struct LineColumn {
David Tolnay82ba02d2018-05-20 16:22:43 -0700280 /// The 1-indexed line in the source file on which the span starts or ends
281 /// (inclusive).
Nika Layzell1ecb6ce2017-12-30 14:34:05 -0500282 pub line: usize,
David Tolnay82ba02d2018-05-20 16:22:43 -0700283 /// The 0-indexed column (in UTF-8 characters) in the source file on which
284 /// the span starts or ends (inclusive).
Nika Layzell1ecb6ce2017-12-30 14:34:05 -0500285 pub column: usize,
286}
Nika Layzellf8d5f212017-12-11 14:07:02 -0500287
David Tolnay82ba02d2018-05-20 16:22:43 -0700288/// A region of source code, along with macro expansion information.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700289#[derive(Copy, Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700290pub struct Span {
291 inner: imp::Span,
292 _marker: marker::PhantomData<Rc<()>>,
293}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700294
Alex Crichton44bffbc2017-05-19 17:51:59 -0700295impl Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700296 fn _new(inner: imp::Span) -> Span {
297 Span {
298 inner: inner,
299 _marker: marker::PhantomData,
300 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700301 }
Alex Crichtone6085b72017-11-21 07:24:25 -0800302
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700303 fn _new_stable(inner: stable::Span) -> Span {
304 Span {
305 inner: inner.into(),
306 _marker: marker::PhantomData,
307 }
308 }
309
David Tolnay82ba02d2018-05-20 16:22:43 -0700310 /// The span of the invocation of the current procedural macro.
311 ///
312 /// Identifiers created with this span will be resolved as if they were
313 /// written directly at the macro call location (call-site hygiene) and
314 /// other code at the macro call site will be able to refer to them as well.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700315 pub fn call_site() -> Span {
316 Span::_new(imp::Span::call_site())
317 }
318
David Tolnay82ba02d2018-05-20 16:22:43 -0700319 /// A span that resolves at the macro definition site.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700320 ///
321 /// This method is semver exempt and not exposed by default.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700322 #[cfg(procmacro2_semver_exempt)]
Alex Crichtone6085b72017-11-21 07:24:25 -0800323 pub fn def_site() -> Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700324 Span::_new(imp::Span::def_site())
Alex Crichtone6085b72017-11-21 07:24:25 -0800325 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500326
David Tolnay4e8e3972018-01-05 18:10:22 -0800327 /// Creates a new span with the same line/column information as `self` but
328 /// that resolves symbols as though it were at `other`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700329 ///
330 /// This method is semver exempt and not exposed by default.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700331 #[cfg(procmacro2_semver_exempt)]
David Tolnay4e8e3972018-01-05 18:10:22 -0800332 pub fn resolved_at(&self, other: Span) -> Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700333 Span::_new(self.inner.resolved_at(other.inner))
David Tolnay4e8e3972018-01-05 18:10:22 -0800334 }
335
336 /// Creates a new span with the same name resolution behavior as `self` but
337 /// with the line/column information of `other`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700338 ///
339 /// This method is semver exempt and not exposed by default.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700340 #[cfg(procmacro2_semver_exempt)]
David Tolnay4e8e3972018-01-05 18:10:22 -0800341 pub fn located_at(&self, other: Span) -> Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700342 Span::_new(self.inner.located_at(other.inner))
David Tolnay4e8e3972018-01-05 18:10:22 -0800343 }
344
David Tolnayd66ecf62018-01-02 20:05:42 -0800345 /// This method is only available when the `"nightly"` feature is enabled.
Sergio Benitez4a232822018-08-28 17:06:22 -0700346 #[doc(hidden)]
347 #[cfg(any(feature = "nightly", super_unstable))]
David Tolnay16a17202017-12-31 10:47:24 -0500348 pub fn unstable(self) -> proc_macro::Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700349 self.inner.unstable()
David Tolnay16a17202017-12-31 10:47:24 -0500350 }
351
David Tolnay82ba02d2018-05-20 16:22:43 -0700352 /// The original source file into which this span points.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700353 ///
354 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800355 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500356 pub fn source_file(&self) -> SourceFile {
David Tolnay7e654a82018-11-11 13:33:18 -0800357 SourceFile::_new(self.inner.source_file())
Nika Layzellf8d5f212017-12-11 14:07:02 -0500358 }
359
David Tolnay82ba02d2018-05-20 16:22:43 -0700360 /// Get the starting line/column in the source file for this span.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700361 ///
362 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800363 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500364 pub fn start(&self) -> LineColumn {
David Tolnayb28f38a2018-03-31 22:02:29 +0200365 let imp::LineColumn { line, column } = self.inner.start();
366 LineColumn {
367 line: line,
368 column: column,
369 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500370 }
371
David Tolnay82ba02d2018-05-20 16:22:43 -0700372 /// Get the ending line/column in the source file for this span.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700373 ///
374 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800375 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500376 pub fn end(&self) -> LineColumn {
David Tolnayb28f38a2018-03-31 22:02:29 +0200377 let imp::LineColumn { line, column } = self.inner.end();
378 LineColumn {
379 line: line,
380 column: column,
381 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500382 }
383
David Tolnay82ba02d2018-05-20 16:22:43 -0700384 /// Create a new span encompassing `self` and `other`.
385 ///
386 /// Returns `None` if `self` and `other` are from different files.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700387 ///
388 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800389 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500390 pub fn join(&self, other: Span) -> Option<Span> {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700391 self.inner.join(other.inner).map(Span::_new)
392 }
Alex Crichtonb2c94622018-04-04 07:36:41 -0700393
David Tolnay82ba02d2018-05-20 16:22:43 -0700394 /// Compares to spans to see if they're equal.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700395 ///
396 /// This method is semver exempt and not exposed by default.
Alex Crichtonb2c94622018-04-04 07:36:41 -0700397 #[cfg(procmacro2_semver_exempt)]
398 pub fn eq(&self, other: &Span) -> bool {
399 self.inner.eq(&other.inner)
400 }
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700401}
402
David Tolnay82ba02d2018-05-20 16:22:43 -0700403/// Prints a span in a form convenient for debugging.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700404impl fmt::Debug for Span {
405 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
406 self.inner.fmt(f)
Nika Layzellf8d5f212017-12-11 14:07:02 -0500407 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700408}
409
David Tolnay82ba02d2018-05-20 16:22:43 -0700410/// A single token or a delimited sequence of token trees (e.g. `[1, (), ..]`).
David Tolnay034205f2018-04-22 16:45:28 -0700411#[derive(Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700412pub enum TokenTree {
David Tolnay82ba02d2018-05-20 16:22:43 -0700413 /// A token stream surrounded by bracket delimiters.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700414 Group(Group),
David Tolnay82ba02d2018-05-20 16:22:43 -0700415 /// An identifier.
Alex Crichtonf3888432018-05-16 09:11:05 -0700416 Ident(Ident),
David Tolnay82ba02d2018-05-20 16:22:43 -0700417 /// A single punctuation character (`+`, `,`, `$`, etc.).
Alex Crichtonf3888432018-05-16 09:11:05 -0700418 Punct(Punct),
David Tolnay82ba02d2018-05-20 16:22:43 -0700419 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700420 Literal(Literal),
Alex Crichton1a7f7622017-07-05 17:47:15 -0700421}
422
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700423impl TokenTree {
David Tolnay82ba02d2018-05-20 16:22:43 -0700424 /// Returns the span of this tree, delegating to the `span` method of
425 /// the contained token or a delimited stream.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700426 pub fn span(&self) -> Span {
427 match *self {
428 TokenTree::Group(ref t) => t.span(),
Alex Crichtonf3888432018-05-16 09:11:05 -0700429 TokenTree::Ident(ref t) => t.span(),
430 TokenTree::Punct(ref t) => t.span(),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700431 TokenTree::Literal(ref t) => t.span(),
432 }
433 }
434
David Tolnay82ba02d2018-05-20 16:22:43 -0700435 /// Configures the span for *only this token*.
436 ///
437 /// Note that if this token is a `Group` then this method will not configure
438 /// the span of each of the internal tokens, this will simply delegate to
439 /// the `set_span` method of each variant.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700440 pub fn set_span(&mut self, span: Span) {
441 match *self {
442 TokenTree::Group(ref mut t) => t.set_span(span),
Alex Crichtonf3888432018-05-16 09:11:05 -0700443 TokenTree::Ident(ref mut t) => t.set_span(span),
444 TokenTree::Punct(ref mut t) => t.set_span(span),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700445 TokenTree::Literal(ref mut t) => t.set_span(span),
446 }
447 }
448}
449
450impl From<Group> for TokenTree {
451 fn from(g: Group) -> TokenTree {
452 TokenTree::Group(g)
453 }
454}
455
Alex Crichtonf3888432018-05-16 09:11:05 -0700456impl From<Ident> for TokenTree {
457 fn from(g: Ident) -> TokenTree {
458 TokenTree::Ident(g)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700459 }
460}
461
Alex Crichtonf3888432018-05-16 09:11:05 -0700462impl From<Punct> for TokenTree {
463 fn from(g: Punct) -> TokenTree {
464 TokenTree::Punct(g)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700465 }
466}
467
468impl From<Literal> for TokenTree {
469 fn from(g: Literal) -> TokenTree {
470 TokenTree::Literal(g)
Alex Crichton1a7f7622017-07-05 17:47:15 -0700471 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700472}
473
David Tolnay82ba02d2018-05-20 16:22:43 -0700474/// Prints the token tree as a string that is supposed to be losslessly
475/// convertible back into the same token tree (modulo spans), except for
476/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
477/// numeric literals.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700478impl fmt::Display for TokenTree {
479 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700480 match *self {
481 TokenTree::Group(ref t) => t.fmt(f),
Alex Crichtonf3888432018-05-16 09:11:05 -0700482 TokenTree::Ident(ref t) => t.fmt(f),
483 TokenTree::Punct(ref t) => t.fmt(f),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700484 TokenTree::Literal(ref t) => t.fmt(f),
485 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700486 }
487}
488
David Tolnay82ba02d2018-05-20 16:22:43 -0700489/// Prints token tree in a form convenient for debugging.
David Tolnay034205f2018-04-22 16:45:28 -0700490impl fmt::Debug for TokenTree {
491 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
492 // Each of these has the name in the struct type in the derived debug,
493 // so don't bother with an extra layer of indirection
494 match *self {
495 TokenTree::Group(ref t) => t.fmt(f),
David Tolnayd8fcdb82018-06-02 15:43:53 -0700496 TokenTree::Ident(ref t) => {
497 let mut debug = f.debug_struct("Ident");
498 debug.field("sym", &format_args!("{}", t));
499 #[cfg(any(feature = "nightly", procmacro2_semver_exempt))]
500 debug.field("span", &t.span());
501 debug.finish()
502 }
Alex Crichtonf3888432018-05-16 09:11:05 -0700503 TokenTree::Punct(ref t) => t.fmt(f),
David Tolnay034205f2018-04-22 16:45:28 -0700504 TokenTree::Literal(ref t) => t.fmt(f),
505 }
506 }
507}
508
David Tolnay82ba02d2018-05-20 16:22:43 -0700509/// A delimited token stream.
510///
511/// A `Group` internally contains a `TokenStream` which is surrounded by
512/// `Delimiter`s.
David Tolnay034205f2018-04-22 16:45:28 -0700513#[derive(Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700514pub struct Group {
David Tolnayf14813f2018-09-08 17:14:07 -0700515 inner: imp::Group,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700516}
517
David Tolnay82ba02d2018-05-20 16:22:43 -0700518/// Describes how a sequence of token trees is delimited.
Michael Layzell5372f4b2017-06-02 10:29:31 -0400519#[derive(Copy, Clone, Debug, Eq, PartialEq)]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700520pub enum Delimiter {
David Tolnay82ba02d2018-05-20 16:22:43 -0700521 /// `( ... )`
Alex Crichton44bffbc2017-05-19 17:51:59 -0700522 Parenthesis,
David Tolnay82ba02d2018-05-20 16:22:43 -0700523 /// `{ ... }`
Alex Crichton44bffbc2017-05-19 17:51:59 -0700524 Brace,
David Tolnay82ba02d2018-05-20 16:22:43 -0700525 /// `[ ... ]`
Alex Crichton44bffbc2017-05-19 17:51:59 -0700526 Bracket,
David Tolnay82ba02d2018-05-20 16:22:43 -0700527 /// `Ø ... Ø`
528 ///
529 /// An implicit delimiter, that may, for example, appear around tokens
530 /// coming from a "macro variable" `$var`. It is important to preserve
531 /// operator priorities in cases like `$var * 3` where `$var` is `1 + 2`.
532 /// Implicit delimiters may not survive roundtrip of a token stream through
533 /// a string.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700534 None,
535}
536
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700537impl Group {
David Tolnayf14813f2018-09-08 17:14:07 -0700538 fn _new(inner: imp::Group) -> Self {
539 Group {
540 inner: inner,
541 }
542 }
543
544 fn _new_stable(inner: stable::Group) -> Self {
545 Group {
546 inner: inner.into(),
547 }
548 }
549
David Tolnay82ba02d2018-05-20 16:22:43 -0700550 /// Creates a new `Group` with the given delimiter and token stream.
551 ///
552 /// This constructor will set the span for this group to
553 /// `Span::call_site()`. To change the span you can use the `set_span`
554 /// method below.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700555 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
556 Group {
David Tolnayf14813f2018-09-08 17:14:07 -0700557 inner: imp::Group::new(delimiter, stream.inner),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700558 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700559 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700560
David Tolnay82ba02d2018-05-20 16:22:43 -0700561 /// Returns the delimiter of this `Group`
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700562 pub fn delimiter(&self) -> Delimiter {
David Tolnayf14813f2018-09-08 17:14:07 -0700563 self.inner.delimiter()
Alex Crichton44bffbc2017-05-19 17:51:59 -0700564 }
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700565
David Tolnay82ba02d2018-05-20 16:22:43 -0700566 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
567 ///
568 /// Note that the returned token stream does not include the delimiter
569 /// returned above.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700570 pub fn stream(&self) -> TokenStream {
David Tolnayf14813f2018-09-08 17:14:07 -0700571 TokenStream::_new(self.inner.stream())
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700572 }
573
David Tolnay82ba02d2018-05-20 16:22:43 -0700574 /// Returns the span for the delimiters of this token stream, spanning the
575 /// entire `Group`.
David Tolnayf14813f2018-09-08 17:14:07 -0700576 ///
577 /// ```text
578 /// pub fn span(&self) -> Span {
579 /// ^^^^^^^
580 /// ```
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700581 pub fn span(&self) -> Span {
David Tolnayf14813f2018-09-08 17:14:07 -0700582 Span::_new(self.inner.span())
583 }
584
585 /// Returns the span pointing to the opening delimiter of this group.
586 ///
587 /// ```text
588 /// pub fn span_open(&self) -> Span {
589 /// ^
590 /// ```
591 #[cfg(procmacro2_semver_exempt)]
592 pub fn span_open(&self) -> Span {
593 Span::_new(self.inner.span_open())
594 }
595
596 /// Returns the span pointing to the closing delimiter of this group.
597 ///
598 /// ```text
599 /// pub fn span_close(&self) -> Span {
600 /// ^
601 /// ```
602 #[cfg(procmacro2_semver_exempt)]
603 pub fn span_close(&self) -> Span {
604 Span::_new(self.inner.span_close())
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700605 }
606
David Tolnay82ba02d2018-05-20 16:22:43 -0700607 /// Configures the span for this `Group`'s delimiters, but not its internal
608 /// tokens.
609 ///
610 /// This method will **not** set the span of all the internal tokens spanned
611 /// by this group, but rather it will only set the span of the delimiter
612 /// tokens at the level of the `Group`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700613 pub fn set_span(&mut self, span: Span) {
David Tolnayf14813f2018-09-08 17:14:07 -0700614 self.inner.set_span(span.inner)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700615 }
616}
617
David Tolnay82ba02d2018-05-20 16:22:43 -0700618/// Prints the group as a string that should be losslessly convertible back
619/// into the same group (modulo spans), except for possibly `TokenTree::Group`s
620/// with `Delimiter::None` delimiters.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700621impl fmt::Display for Group {
David Tolnayf14813f2018-09-08 17:14:07 -0700622 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
623 fmt::Display::fmt(&self.inner, formatter)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700624 }
625}
626
David Tolnay034205f2018-04-22 16:45:28 -0700627impl fmt::Debug for Group {
David Tolnayf14813f2018-09-08 17:14:07 -0700628 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
629 fmt::Debug::fmt(&self.inner, formatter)
David Tolnay034205f2018-04-22 16:45:28 -0700630 }
631}
632
David Tolnay82ba02d2018-05-20 16:22:43 -0700633/// An `Punct` is an single punctuation character like `+`, `-` or `#`.
634///
635/// Multicharacter operators like `+=` are represented as two instances of
636/// `Punct` with different forms of `Spacing` returned.
Alex Crichtonf3888432018-05-16 09:11:05 -0700637#[derive(Clone)]
638pub struct Punct {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700639 op: char,
640 spacing: Spacing,
641 span: Span,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700642}
643
David Tolnay82ba02d2018-05-20 16:22:43 -0700644/// Whether an `Punct` is followed immediately by another `Punct` or followed by
645/// another token or whitespace.
Lukas Kalbertodteb3f9302017-08-20 18:58:41 +0200646#[derive(Copy, Clone, Debug, Eq, PartialEq)]
Alex Crichton1a7f7622017-07-05 17:47:15 -0700647pub enum Spacing {
David Tolnay82ba02d2018-05-20 16:22:43 -0700648 /// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700649 Alone,
David Tolnay82ba02d2018-05-20 16:22:43 -0700650 /// E.g. `+` is `Joint` in `+=` or `'#`.
651 ///
652 /// Additionally, single quote `'` can join with identifiers to form
653 /// lifetimes `'ident`.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700654 Joint,
655}
656
Alex Crichtonf3888432018-05-16 09:11:05 -0700657impl Punct {
David Tolnay82ba02d2018-05-20 16:22:43 -0700658 /// Creates a new `Punct` from the given character and spacing.
659 ///
660 /// The `ch` argument must be a valid punctuation character permitted by the
661 /// language, otherwise the function will panic.
662 ///
663 /// The returned `Punct` will have the default span of `Span::call_site()`
664 /// which can be further configured with the `set_span` method below.
Alex Crichtonf3888432018-05-16 09:11:05 -0700665 pub fn new(op: char, spacing: Spacing) -> Punct {
666 Punct {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700667 op: op,
668 spacing: spacing,
669 span: Span::call_site(),
670 }
671 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700672
David Tolnay82ba02d2018-05-20 16:22:43 -0700673 /// Returns the value of this punctuation character as `char`.
Alex Crichtonf3888432018-05-16 09:11:05 -0700674 pub fn as_char(&self) -> char {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700675 self.op
676 }
677
David Tolnay82ba02d2018-05-20 16:22:43 -0700678 /// Returns the spacing of this punctuation character, indicating whether
679 /// it's immediately followed by another `Punct` in the token stream, so
680 /// they can potentially be combined into a multicharacter operator
681 /// (`Joint`), or it's followed by some other token or whitespace (`Alone`)
682 /// so the operator has certainly ended.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700683 pub fn spacing(&self) -> Spacing {
684 self.spacing
685 }
686
David Tolnay82ba02d2018-05-20 16:22:43 -0700687 /// Returns the span for this punctuation character.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700688 pub fn span(&self) -> Span {
689 self.span
690 }
691
David Tolnay82ba02d2018-05-20 16:22:43 -0700692 /// Configure the span for this punctuation character.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700693 pub fn set_span(&mut self, span: Span) {
694 self.span = span;
695 }
696}
697
David Tolnay82ba02d2018-05-20 16:22:43 -0700698/// Prints the punctuation character as a string that should be losslessly
699/// convertible back into the same character.
Alex Crichtonf3888432018-05-16 09:11:05 -0700700impl fmt::Display for Punct {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700701 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
702 self.op.fmt(f)
703 }
704}
705
Alex Crichtonf3888432018-05-16 09:11:05 -0700706impl fmt::Debug for Punct {
David Tolnay034205f2018-04-22 16:45:28 -0700707 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonf3888432018-05-16 09:11:05 -0700708 let mut debug = fmt.debug_struct("Punct");
David Tolnay034205f2018-04-22 16:45:28 -0700709 debug.field("op", &self.op);
710 debug.field("spacing", &self.spacing);
711 #[cfg(procmacro2_semver_exempt)]
712 debug.field("span", &self.span);
713 debug.finish()
714 }
715}
716
David Tolnay8b71dac2018-05-20 17:07:47 -0700717/// A word of Rust code, which may be a keyword or legal variable name.
718///
719/// An identifier consists of at least one Unicode code point, the first of
720/// which has the XID_Start property and the rest of which have the XID_Continue
721/// property.
722///
723/// - The empty string is not an identifier. Use `Option<Ident>`.
724/// - A lifetime is not an identifier. Use `syn::Lifetime` instead.
725///
726/// An identifier constructed with `Ident::new` is permitted to be a Rust
David Tolnayc239f032018-11-11 12:57:09 -0800727/// keyword, though parsing one through its [`Parse`] implementation rejects
728/// Rust keywords. Use `input.call(Ident::parse_any)` when parsing to match the
David Tolnay8b71dac2018-05-20 17:07:47 -0700729/// behaviour of `Ident::new`.
730///
David Tolnayc239f032018-11-11 12:57:09 -0800731/// [`Parse`]: https://docs.rs/syn/0.15/syn/parse/trait.Parse.html
David Tolnay8b71dac2018-05-20 17:07:47 -0700732///
733/// # Examples
734///
735/// A new ident can be created from a string using the `Ident::new` function.
736/// A span must be provided explicitly which governs the name resolution
737/// behavior of the resulting identifier.
738///
739/// ```rust
740/// extern crate proc_macro2;
741///
742/// use proc_macro2::{Ident, Span};
743///
744/// fn main() {
745/// let call_ident = Ident::new("calligraphy", Span::call_site());
746///
747/// println!("{}", call_ident);
748/// }
749/// ```
750///
751/// An ident can be interpolated into a token stream using the `quote!` macro.
752///
753/// ```rust
754/// #[macro_use]
755/// extern crate quote;
756///
757/// extern crate proc_macro2;
758///
759/// use proc_macro2::{Ident, Span};
760///
761/// fn main() {
762/// let ident = Ident::new("demo", Span::call_site());
763///
764/// // Create a variable binding whose name is this ident.
765/// let expanded = quote! { let #ident = 10; };
766///
767/// // Create a variable binding with a slightly different name.
768/// let temp_ident = Ident::new(&format!("new_{}", ident), Span::call_site());
769/// let expanded = quote! { let #temp_ident = 10; };
770/// }
771/// ```
772///
773/// A string representation of the ident is available through the `to_string()`
774/// method.
775///
776/// ```rust
777/// # extern crate proc_macro2;
778/// #
779/// # use proc_macro2::{Ident, Span};
780/// #
781/// # let ident = Ident::new("another_identifier", Span::call_site());
782/// #
783/// // Examine the ident as a string.
784/// let ident_string = ident.to_string();
785/// if ident_string.len() > 60 {
786/// println!("Very long identifier: {}", ident_string)
787/// }
788/// ```
Alex Crichtonf3888432018-05-16 09:11:05 -0700789#[derive(Clone)]
790pub struct Ident {
791 inner: imp::Ident,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700792 _marker: marker::PhantomData<Rc<()>>,
793}
794
Alex Crichtonf3888432018-05-16 09:11:05 -0700795impl Ident {
796 fn _new(inner: imp::Ident) -> Ident {
797 Ident {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700798 inner: inner,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700799 _marker: marker::PhantomData,
800 }
801 }
802
David Tolnay82ba02d2018-05-20 16:22:43 -0700803 /// Creates a new `Ident` with the given `string` as well as the specified
804 /// `span`.
805 ///
806 /// The `string` argument must be a valid identifier permitted by the
807 /// language, otherwise the function will panic.
808 ///
809 /// Note that `span`, currently in rustc, configures the hygiene information
810 /// for this identifier.
811 ///
812 /// As of this time `Span::call_site()` explicitly opts-in to "call-site"
813 /// hygiene meaning that identifiers created with this span will be resolved
814 /// as if they were written directly at the location of the macro call, and
815 /// other code at the macro call site will be able to refer to them as well.
816 ///
817 /// Later spans like `Span::def_site()` will allow to opt-in to
818 /// "definition-site" hygiene meaning that identifiers created with this
819 /// span will be resolved at the location of the macro definition and other
820 /// code at the macro call site will not be able to refer to them.
821 ///
822 /// Due to the current importance of hygiene this constructor, unlike other
823 /// tokens, requires a `Span` to be specified at construction.
David Tolnay8b71dac2018-05-20 17:07:47 -0700824 ///
825 /// # Panics
826 ///
827 /// Panics if the input string is neither a keyword nor a legal variable
828 /// name.
Alex Crichtonf3888432018-05-16 09:11:05 -0700829 pub fn new(string: &str, span: Span) -> Ident {
830 Ident::_new(imp::Ident::new(string, span.inner))
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700831 }
832
David Tolnay82ba02d2018-05-20 16:22:43 -0700833 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
David Tolnaya01ca8e2018-06-04 00:55:28 -0700834 ///
835 /// This method is semver exempt and not exposed by default.
Alex Crichtonf3888432018-05-16 09:11:05 -0700836 #[cfg(procmacro2_semver_exempt)]
837 pub fn new_raw(string: &str, span: Span) -> Ident {
838 Ident::_new_raw(string, span)
839 }
840
841 fn _new_raw(string: &str, span: Span) -> Ident {
842 Ident::_new(imp::Ident::new_raw(string, span.inner))
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700843 }
844
David Tolnay82ba02d2018-05-20 16:22:43 -0700845 /// Returns the span of this `Ident`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700846 pub fn span(&self) -> Span {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700847 Span::_new(self.inner.span())
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700848 }
849
David Tolnay82ba02d2018-05-20 16:22:43 -0700850 /// Configures the span of this `Ident`, possibly changing its hygiene
851 /// context.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700852 pub fn set_span(&mut self, span: Span) {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700853 self.inner.set_span(span.inner);
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700854 }
855}
856
Alex Crichtonf3888432018-05-16 09:11:05 -0700857impl PartialEq for Ident {
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700858 fn eq(&self, other: &Ident) -> bool {
David Tolnayc0b0f2e2018-09-02 17:56:08 -0700859 self.inner == other.inner
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700860 }
861}
862
David Tolnayc0bbcc52018-05-18 10:51:04 -0700863impl<T> PartialEq<T> for Ident
864where
865 T: ?Sized + AsRef<str>,
866{
867 fn eq(&self, other: &T) -> bool {
David Tolnayc0b0f2e2018-09-02 17:56:08 -0700868 self.inner == other
David Tolnayc0bbcc52018-05-18 10:51:04 -0700869 }
870}
871
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700872impl Eq for Ident {}
Alex Crichtonf3888432018-05-16 09:11:05 -0700873
874impl PartialOrd for Ident {
875 fn partial_cmp(&self, other: &Ident) -> Option<Ordering> {
876 Some(self.cmp(other))
877 }
878}
879
880impl Ord for Ident {
881 fn cmp(&self, other: &Ident) -> Ordering {
882 self.to_string().cmp(&other.to_string())
883 }
884}
885
886impl Hash for Ident {
887 fn hash<H: Hasher>(&self, hasher: &mut H) {
888 self.to_string().hash(hasher)
889 }
890}
891
David Tolnay82ba02d2018-05-20 16:22:43 -0700892/// Prints the identifier as a string that should be losslessly convertible back
893/// into the same identifier.
Alex Crichtonf3888432018-05-16 09:11:05 -0700894impl fmt::Display for Ident {
895 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
896 self.inner.fmt(f)
897 }
898}
899
900impl fmt::Debug for Ident {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700901 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
902 self.inner.fmt(f)
903 }
904}
905
David Tolnay82ba02d2018-05-20 16:22:43 -0700906/// A literal string (`"hello"`), byte string (`b"hello"`), character (`'a'`),
907/// byte character (`b'a'`), an integer or floating point number with or without
908/// a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
909///
910/// Boolean literals like `true` and `false` do not belong here, they are
911/// `Ident`s.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700912#[derive(Clone)]
913pub struct Literal {
914 inner: imp::Literal,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700915 _marker: marker::PhantomData<Rc<()>>,
916}
917
David Tolnay82ba02d2018-05-20 16:22:43 -0700918macro_rules! suffixed_int_literals {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700919 ($($name:ident => $kind:ident,)*) => ($(
David Tolnay82ba02d2018-05-20 16:22:43 -0700920 /// Creates a new suffixed integer literal with the specified value.
921 ///
922 /// This function will create an integer like `1u32` where the integer
923 /// value specified is the first part of the token and the integral is
924 /// also suffixed at the end. Literals created from negative numbers may
925 /// not survive rountrips through `TokenStream` or strings and may be
926 /// broken into two tokens (`-` and positive literal).
927 ///
928 /// Literals created through this method have the `Span::call_site()`
929 /// span by default, which can be configured with the `set_span` method
930 /// below.
931 pub fn $name(n: $kind) -> Literal {
932 Literal::_new(imp::Literal::$name(n))
933 }
934 )*)
935}
936
937macro_rules! unsuffixed_int_literals {
938 ($($name:ident => $kind:ident,)*) => ($(
939 /// Creates a new unsuffixed integer literal with the specified value.
940 ///
941 /// This function will create an integer like `1` where the integer
942 /// value specified is the first part of the token. No suffix is
943 /// specified on this token, meaning that invocations like
944 /// `Literal::i8_unsuffixed(1)` are equivalent to
945 /// `Literal::u32_unsuffixed(1)`. Literals created from negative numbers
946 /// may not survive rountrips through `TokenStream` or strings and may
947 /// be broken into two tokens (`-` and positive literal).
948 ///
949 /// Literals created through this method have the `Span::call_site()`
950 /// span by default, which can be configured with the `set_span` method
951 /// below.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700952 pub fn $name(n: $kind) -> Literal {
Alex Crichtona914a612018-04-04 07:48:44 -0700953 Literal::_new(imp::Literal::$name(n))
Alex Crichton1a7f7622017-07-05 17:47:15 -0700954 }
955 )*)
956}
957
Alex Crichton852d53d2017-05-19 19:25:08 -0700958impl Literal {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700959 fn _new(inner: imp::Literal) -> Literal {
960 Literal {
961 inner: inner,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700962 _marker: marker::PhantomData,
963 }
Alex Crichton1a7f7622017-07-05 17:47:15 -0700964 }
965
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700966 fn _new_stable(inner: stable::Literal) -> Literal {
967 Literal {
968 inner: inner.into(),
969 _marker: marker::PhantomData,
970 }
971 }
972
David Tolnay82ba02d2018-05-20 16:22:43 -0700973 suffixed_int_literals! {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700974 u8_suffixed => u8,
975 u16_suffixed => u16,
976 u32_suffixed => u32,
977 u64_suffixed => u64,
978 usize_suffixed => usize,
979 i8_suffixed => i8,
980 i16_suffixed => i16,
981 i32_suffixed => i32,
982 i64_suffixed => i64,
983 isize_suffixed => isize,
David Tolnay82ba02d2018-05-20 16:22:43 -0700984 }
Alex Crichton1a7f7622017-07-05 17:47:15 -0700985
Alex Crichton69385662018-11-08 06:30:04 -0800986 #[cfg(u128)]
987 suffixed_int_literals! {
988 u128_suffixed => u128,
989 i128_suffixed => i128,
990 }
991
David Tolnay82ba02d2018-05-20 16:22:43 -0700992 unsuffixed_int_literals! {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700993 u8_unsuffixed => u8,
994 u16_unsuffixed => u16,
995 u32_unsuffixed => u32,
996 u64_unsuffixed => u64,
997 usize_unsuffixed => usize,
998 i8_unsuffixed => i8,
999 i16_unsuffixed => i16,
1000 i32_unsuffixed => i32,
1001 i64_unsuffixed => i64,
1002 isize_unsuffixed => isize,
Alex Crichton1a7f7622017-07-05 17:47:15 -07001003 }
1004
Alex Crichton69385662018-11-08 06:30:04 -08001005 #[cfg(u128)]
1006 unsuffixed_int_literals! {
1007 u128_unsuffixed => u128,
1008 i128_unsuffixed => i128,
1009 }
1010
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001011 pub fn f64_unsuffixed(f: f64) -> Literal {
1012 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -07001013 Literal::_new(imp::Literal::f64_unsuffixed(f))
Alex Crichton1a7f7622017-07-05 17:47:15 -07001014 }
1015
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001016 pub fn f64_suffixed(f: f64) -> Literal {
1017 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -07001018 Literal::_new(imp::Literal::f64_suffixed(f))
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001019 }
1020
David Tolnay82ba02d2018-05-20 16:22:43 -07001021 /// Creates a new unsuffixed floating-point literal.
1022 ///
1023 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1024 /// the float's value is emitted directly into the token but no suffix is
1025 /// used, so it may be inferred to be a `f64` later in the compiler.
1026 /// Literals created from negative numbers may not survive rountrips through
1027 /// `TokenStream` or strings and may be broken into two tokens (`-` and
1028 /// positive literal).
1029 ///
1030 /// # Panics
1031 ///
1032 /// This function requires that the specified float is finite, for example
1033 /// if it is infinity or NaN this function will panic.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001034 pub fn f32_unsuffixed(f: f32) -> Literal {
1035 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -07001036 Literal::_new(imp::Literal::f32_unsuffixed(f))
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001037 }
1038
1039 pub fn f32_suffixed(f: f32) -> Literal {
1040 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -07001041 Literal::_new(imp::Literal::f32_suffixed(f))
Alex Crichton1a7f7622017-07-05 17:47:15 -07001042 }
1043
1044 pub fn string(string: &str) -> Literal {
Alex Crichtona914a612018-04-04 07:48:44 -07001045 Literal::_new(imp::Literal::string(string))
Alex Crichton1a7f7622017-07-05 17:47:15 -07001046 }
1047
1048 pub fn character(ch: char) -> Literal {
Alex Crichtona914a612018-04-04 07:48:44 -07001049 Literal::_new(imp::Literal::character(ch))
Alex Crichton76a5cc82017-05-23 07:01:44 -07001050 }
1051
Alex Crichton9c2fb0a2017-05-26 08:49:31 -07001052 pub fn byte_string(s: &[u8]) -> Literal {
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001053 Literal::_new(imp::Literal::byte_string(s))
Alex Crichton852d53d2017-05-19 19:25:08 -07001054 }
Alex Crichton76a5cc82017-05-23 07:01:44 -07001055
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001056 pub fn span(&self) -> Span {
Alex Crichtonb2c94622018-04-04 07:36:41 -07001057 Span::_new(self.inner.span())
Alex Crichton1a7f7622017-07-05 17:47:15 -07001058 }
1059
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001060 pub fn set_span(&mut self, span: Span) {
Alex Crichtonb2c94622018-04-04 07:36:41 -07001061 self.inner.set_span(span.inner);
Alex Crichton31316622017-05-26 12:54:47 -07001062 }
Alex Crichton852d53d2017-05-19 19:25:08 -07001063}
1064
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001065impl fmt::Debug for Literal {
1066 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1067 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001068 }
1069}
David Tolnaycb1b85f2017-06-03 16:40:35 -07001070
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001071impl fmt::Display for Literal {
1072 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1073 self.inner.fmt(f)
1074 }
1075}
1076
David Tolnay82ba02d2018-05-20 16:22:43 -07001077/// Public implementation details for the `TokenStream` type, such as iterators.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001078pub mod token_stream {
1079 use std::fmt;
1080 use std::marker;
1081 use std::rc::Rc;
1082
David Tolnay48ea5042018-04-23 19:17:35 -07001083 use imp;
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001084 pub use TokenStream;
David Tolnayb28f38a2018-03-31 22:02:29 +02001085 use TokenTree;
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001086
David Tolnay82ba02d2018-05-20 16:22:43 -07001087 /// An iterator over `TokenStream`'s `TokenTree`s.
1088 ///
1089 /// The iteration is "shallow", e.g. the iterator doesn't recurse into
1090 /// delimited groups, and returns whole groups as token trees.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001091 pub struct IntoIter {
1092 inner: imp::TokenTreeIter,
1093 _marker: marker::PhantomData<Rc<()>>,
1094 }
1095
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001096 impl Iterator for IntoIter {
1097 type Item = TokenTree;
1098
1099 fn next(&mut self) -> Option<TokenTree> {
1100 self.inner.next()
1101 }
1102 }
1103
1104 impl fmt::Debug for IntoIter {
1105 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1106 self.inner.fmt(f)
1107 }
1108 }
1109
1110 impl IntoIterator for TokenStream {
1111 type Item = TokenTree;
1112 type IntoIter = IntoIter;
1113
1114 fn into_iter(self) -> IntoIter {
1115 IntoIter {
1116 inner: self.inner.into_iter(),
1117 _marker: marker::PhantomData,
1118 }
1119 }
1120 }
1121}