blob: 4f8f59d047b4e41cbd8b09f5d6a1f0f4a8a7c32b [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;
David Tolnay9cd3b4c2018-11-11 16:47:32 -080061#[cfg(procmacro2_semver_exempt)]
62use std::path::PathBuf;
Alex Crichtonaf5bad42018-03-27 14:45:10 -070063use std::rc::Rc;
64use std::str::FromStr;
Alex Crichton44bffbc2017-05-19 17:51:59 -070065
David Tolnayb1032662017-05-31 15:52:28 -070066#[macro_use]
David Tolnayb1032662017-05-31 15:52:28 -070067mod strnom;
Alex Crichton30a4e9e2018-04-27 17:02:19 -070068mod stable;
David Tolnayb1032662017-05-31 15:52:28 -070069
Alex Crichtonce0904d2018-08-27 17:29:49 -070070#[cfg(not(wrap_proc_macro))]
Alex Crichton30a4e9e2018-04-27 17:02:19 -070071use stable as imp;
Alex Crichtonb15c6352017-05-19 19:36:36 -070072#[path = "unstable.rs"]
Alex Crichtonce0904d2018-08-27 17:29:49 -070073#[cfg(wrap_proc_macro)]
Alex Crichton44bffbc2017-05-19 17:51:59 -070074mod imp;
75
David Tolnay82ba02d2018-05-20 16:22:43 -070076/// An abstract stream of tokens, or more concretely a sequence of token trees.
77///
78/// This type provides interfaces for iterating over token trees and for
79/// collecting token trees into one stream.
80///
81/// Token stream is both the input and output of `#[proc_macro]`,
82/// `#[proc_macro_attribute]` and `#[proc_macro_derive]` definitions.
David Tolnaycb1b85f2017-06-03 16:40:35 -070083#[derive(Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -070084pub struct TokenStream {
85 inner: imp::TokenStream,
86 _marker: marker::PhantomData<Rc<()>>,
87}
Alex Crichton44bffbc2017-05-19 17:51:59 -070088
David Tolnay82ba02d2018-05-20 16:22:43 -070089/// Error returned from `TokenStream::from_str`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -070090pub struct LexError {
91 inner: imp::LexError,
92 _marker: marker::PhantomData<Rc<()>>,
93}
94
95impl TokenStream {
96 fn _new(inner: imp::TokenStream) -> TokenStream {
97 TokenStream {
98 inner: inner,
99 _marker: marker::PhantomData,
100 }
101 }
102
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700103 fn _new_stable(inner: stable::TokenStream) -> TokenStream {
104 TokenStream {
105 inner: inner.into(),
106 _marker: marker::PhantomData,
107 }
108 }
109
David Tolnay82ba02d2018-05-20 16:22:43 -0700110 /// Returns an empty `TokenStream` containing no token trees.
David Tolnayc3bb4592018-05-28 20:09:44 -0700111 pub fn new() -> TokenStream {
112 TokenStream::_new(imp::TokenStream::new())
113 }
114
115 #[deprecated(since = "0.4.4", note = "please use TokenStream::new")]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700116 pub fn empty() -> TokenStream {
David Tolnayc3bb4592018-05-28 20:09:44 -0700117 TokenStream::new()
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700118 }
119
David Tolnay82ba02d2018-05-20 16:22:43 -0700120 /// Checks if this `TokenStream` is empty.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700121 pub fn is_empty(&self) -> bool {
122 self.inner.is_empty()
123 }
124}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700125
Árpád Goretity4f74b682018-07-14 00:47:51 +0200126/// `TokenStream::default()` returns an empty stream,
127/// i.e. this is equivalent with `TokenStream::new()`.
128impl Default for TokenStream {
129 fn default() -> Self {
130 TokenStream::new()
131 }
132}
133
David Tolnay82ba02d2018-05-20 16:22:43 -0700134/// Attempts to break the string into tokens and parse those tokens into a token
135/// stream.
136///
137/// May fail for a number of reasons, for example, if the string contains
138/// unbalanced delimiters or characters not existing in the language.
139///
140/// NOTE: Some errors may cause panics instead of returning `LexError`. We
141/// reserve the right to change these errors into `LexError`s later.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700142impl FromStr for TokenStream {
143 type Err = LexError;
144
145 fn from_str(src: &str) -> Result<TokenStream, LexError> {
David Tolnayb28f38a2018-03-31 22:02:29 +0200146 let e = src.parse().map_err(|e| LexError {
147 inner: e,
148 _marker: marker::PhantomData,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700149 })?;
150 Ok(TokenStream::_new(e))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700151 }
152}
153
Alex Crichton53548482018-08-11 21:54:05 -0700154#[cfg(use_proc_macro)]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700155impl From<proc_macro::TokenStream> for TokenStream {
156 fn from(inner: proc_macro::TokenStream) -> TokenStream {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700157 TokenStream::_new(inner.into())
Alex Crichton44bffbc2017-05-19 17:51:59 -0700158 }
159}
160
Alex Crichton53548482018-08-11 21:54:05 -0700161#[cfg(use_proc_macro)]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700162impl From<TokenStream> for proc_macro::TokenStream {
163 fn from(inner: TokenStream) -> proc_macro::TokenStream {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700164 inner.inner.into()
Alex Crichton44bffbc2017-05-19 17:51:59 -0700165 }
166}
167
Alex Crichtonf3888432018-05-16 09:11:05 -0700168impl Extend<TokenTree> for TokenStream {
169 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, streams: I) {
170 self.inner.extend(streams)
171 }
172}
173
David Tolnay5c58c532018-08-13 11:33:51 -0700174impl Extend<TokenStream> for TokenStream {
175 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
176 self.inner
177 .extend(streams.into_iter().map(|stream| stream.inner))
178 }
179}
180
David Tolnay82ba02d2018-05-20 16:22:43 -0700181/// Collects a number of token trees into a single stream.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700182impl FromIterator<TokenTree> for TokenStream {
183 fn from_iter<I: IntoIterator<Item = TokenTree>>(streams: I) -> Self {
184 TokenStream::_new(streams.into_iter().collect())
Alex Crichton44bffbc2017-05-19 17:51:59 -0700185 }
186}
Alex Crichton53b00672018-09-06 17:16:10 -0700187impl FromIterator<TokenStream> for TokenStream {
188 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
189 TokenStream::_new(streams.into_iter().map(|i| i.inner).collect())
190 }
191}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700192
David Tolnay82ba02d2018-05-20 16:22:43 -0700193/// Prints the token stream as a string that is supposed to be losslessly
194/// convertible back into the same token stream (modulo spans), except for
195/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
196/// numeric literals.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700197impl fmt::Display for TokenStream {
198 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
199 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700200 }
201}
202
David Tolnay82ba02d2018-05-20 16:22:43 -0700203/// Prints token in a form convenient for debugging.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700204impl fmt::Debug for TokenStream {
205 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
206 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700207 }
208}
209
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700210impl fmt::Debug for LexError {
211 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
212 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700213 }
214}
215
David Tolnay82ba02d2018-05-20 16:22:43 -0700216/// The source file of a given `Span`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700217///
218/// This type is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800219#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500220#[derive(Clone, PartialEq, Eq)]
221pub struct SourceFile(imp::SourceFile);
222
David Tolnay1ebe3972018-01-02 20:14:20 -0800223#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500224impl SourceFile {
David Tolnay82ba02d2018-05-20 16:22:43 -0700225 /// Get the path to this source file.
226 ///
227 /// ### Note
228 ///
229 /// If the code span associated with this `SourceFile` was generated by an
230 /// external macro, this may not be an actual path on the filesystem. Use
231 /// [`is_real`] to check.
232 ///
233 /// Also note that even if `is_real` returns `true`, if
234 /// `--remap-path-prefix` was passed on the command line, the path as given
235 /// may not actually be valid.
236 ///
237 /// [`is_real`]: #method.is_real
David Tolnay9cd3b4c2018-11-11 16:47:32 -0800238 pub fn path(&self) -> PathBuf {
Nika Layzellb35a9a32017-12-30 14:34:35 -0500239 self.0.path()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500240 }
241
David Tolnay82ba02d2018-05-20 16:22:43 -0700242 /// Returns `true` if this source file is a real source file, and not
243 /// generated by an external macro's expansion.
Nika Layzellf8d5f212017-12-11 14:07:02 -0500244 pub fn is_real(&self) -> bool {
245 self.0.is_real()
246 }
247}
248
David Tolnay1ebe3972018-01-02 20:14:20 -0800249#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500250impl fmt::Debug for SourceFile {
251 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
252 self.0.fmt(f)
253 }
254}
255
David Tolnay82ba02d2018-05-20 16:22:43 -0700256/// A line-column pair representing the start or end of a `Span`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700257///
258/// This type is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800259#[cfg(procmacro2_semver_exempt)]
Nika Layzell1ecb6ce2017-12-30 14:34:05 -0500260pub struct LineColumn {
David Tolnay82ba02d2018-05-20 16:22:43 -0700261 /// The 1-indexed line in the source file on which the span starts or ends
262 /// (inclusive).
Nika Layzell1ecb6ce2017-12-30 14:34:05 -0500263 pub line: usize,
David Tolnay82ba02d2018-05-20 16:22:43 -0700264 /// The 0-indexed column (in UTF-8 characters) in the source file on which
265 /// the span starts or ends (inclusive).
Nika Layzell1ecb6ce2017-12-30 14:34:05 -0500266 pub column: usize,
267}
Nika Layzellf8d5f212017-12-11 14:07:02 -0500268
David Tolnay82ba02d2018-05-20 16:22:43 -0700269/// A region of source code, along with macro expansion information.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700270#[derive(Copy, Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700271pub struct Span {
272 inner: imp::Span,
273 _marker: marker::PhantomData<Rc<()>>,
274}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700275
Alex Crichton44bffbc2017-05-19 17:51:59 -0700276impl Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700277 fn _new(inner: imp::Span) -> Span {
278 Span {
279 inner: inner,
280 _marker: marker::PhantomData,
281 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700282 }
Alex Crichtone6085b72017-11-21 07:24:25 -0800283
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700284 fn _new_stable(inner: stable::Span) -> Span {
285 Span {
286 inner: inner.into(),
287 _marker: marker::PhantomData,
288 }
289 }
290
David Tolnay82ba02d2018-05-20 16:22:43 -0700291 /// The span of the invocation of the current procedural macro.
292 ///
293 /// Identifiers created with this span will be resolved as if they were
294 /// written directly at the macro call location (call-site hygiene) and
295 /// other code at the macro call site will be able to refer to them as well.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700296 pub fn call_site() -> Span {
297 Span::_new(imp::Span::call_site())
298 }
299
David Tolnay82ba02d2018-05-20 16:22:43 -0700300 /// A span that resolves at the macro definition site.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700301 ///
302 /// This method is semver exempt and not exposed by default.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700303 #[cfg(procmacro2_semver_exempt)]
Alex Crichtone6085b72017-11-21 07:24:25 -0800304 pub fn def_site() -> Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700305 Span::_new(imp::Span::def_site())
Alex Crichtone6085b72017-11-21 07:24:25 -0800306 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500307
David Tolnay4e8e3972018-01-05 18:10:22 -0800308 /// Creates a new span with the same line/column information as `self` but
309 /// that resolves symbols as though it were at `other`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700310 ///
311 /// This method is semver exempt and not exposed by default.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700312 #[cfg(procmacro2_semver_exempt)]
David Tolnay4e8e3972018-01-05 18:10:22 -0800313 pub fn resolved_at(&self, other: Span) -> Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700314 Span::_new(self.inner.resolved_at(other.inner))
David Tolnay4e8e3972018-01-05 18:10:22 -0800315 }
316
317 /// Creates a new span with the same name resolution behavior as `self` but
318 /// with the line/column information of `other`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700319 ///
320 /// This method is semver exempt and not exposed by default.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700321 #[cfg(procmacro2_semver_exempt)]
David Tolnay4e8e3972018-01-05 18:10:22 -0800322 pub fn located_at(&self, other: Span) -> Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700323 Span::_new(self.inner.located_at(other.inner))
David Tolnay4e8e3972018-01-05 18:10:22 -0800324 }
325
David Tolnayd66ecf62018-01-02 20:05:42 -0800326 /// This method is only available when the `"nightly"` feature is enabled.
Sergio Benitez4a232822018-08-28 17:06:22 -0700327 #[doc(hidden)]
328 #[cfg(any(feature = "nightly", super_unstable))]
David Tolnay16a17202017-12-31 10:47:24 -0500329 pub fn unstable(self) -> proc_macro::Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700330 self.inner.unstable()
David Tolnay16a17202017-12-31 10:47:24 -0500331 }
332
David Tolnay82ba02d2018-05-20 16:22:43 -0700333 /// The original source file into which this span points.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700334 ///
335 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800336 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500337 pub fn source_file(&self) -> SourceFile {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700338 SourceFile(self.inner.source_file())
Nika Layzellf8d5f212017-12-11 14:07:02 -0500339 }
340
David Tolnay82ba02d2018-05-20 16:22:43 -0700341 /// Get the starting line/column in the source file for this span.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700342 ///
343 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800344 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500345 pub fn start(&self) -> LineColumn {
David Tolnayb28f38a2018-03-31 22:02:29 +0200346 let imp::LineColumn { line, column } = self.inner.start();
347 LineColumn {
348 line: line,
349 column: column,
350 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500351 }
352
David Tolnay82ba02d2018-05-20 16:22:43 -0700353 /// Get the ending line/column in the source file for this span.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700354 ///
355 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800356 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500357 pub fn end(&self) -> LineColumn {
David Tolnayb28f38a2018-03-31 22:02:29 +0200358 let imp::LineColumn { line, column } = self.inner.end();
359 LineColumn {
360 line: line,
361 column: column,
362 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500363 }
364
David Tolnay82ba02d2018-05-20 16:22:43 -0700365 /// Create a new span encompassing `self` and `other`.
366 ///
367 /// Returns `None` if `self` and `other` are from different files.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700368 ///
369 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800370 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500371 pub fn join(&self, other: Span) -> Option<Span> {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700372 self.inner.join(other.inner).map(Span::_new)
373 }
Alex Crichtonb2c94622018-04-04 07:36:41 -0700374
David Tolnay82ba02d2018-05-20 16:22:43 -0700375 /// Compares to spans to see if they're equal.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700376 ///
377 /// This method is semver exempt and not exposed by default.
Alex Crichtonb2c94622018-04-04 07:36:41 -0700378 #[cfg(procmacro2_semver_exempt)]
379 pub fn eq(&self, other: &Span) -> bool {
380 self.inner.eq(&other.inner)
381 }
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700382}
383
David Tolnay82ba02d2018-05-20 16:22:43 -0700384/// Prints a span in a form convenient for debugging.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700385impl fmt::Debug for Span {
386 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
387 self.inner.fmt(f)
Nika Layzellf8d5f212017-12-11 14:07:02 -0500388 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700389}
390
David Tolnay82ba02d2018-05-20 16:22:43 -0700391/// A single token or a delimited sequence of token trees (e.g. `[1, (), ..]`).
David Tolnay034205f2018-04-22 16:45:28 -0700392#[derive(Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700393pub enum TokenTree {
David Tolnay82ba02d2018-05-20 16:22:43 -0700394 /// A token stream surrounded by bracket delimiters.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700395 Group(Group),
David Tolnay82ba02d2018-05-20 16:22:43 -0700396 /// An identifier.
Alex Crichtonf3888432018-05-16 09:11:05 -0700397 Ident(Ident),
David Tolnay82ba02d2018-05-20 16:22:43 -0700398 /// A single punctuation character (`+`, `,`, `$`, etc.).
Alex Crichtonf3888432018-05-16 09:11:05 -0700399 Punct(Punct),
David Tolnay82ba02d2018-05-20 16:22:43 -0700400 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700401 Literal(Literal),
Alex Crichton1a7f7622017-07-05 17:47:15 -0700402}
403
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700404impl TokenTree {
David Tolnay82ba02d2018-05-20 16:22:43 -0700405 /// Returns the span of this tree, delegating to the `span` method of
406 /// the contained token or a delimited stream.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700407 pub fn span(&self) -> Span {
408 match *self {
409 TokenTree::Group(ref t) => t.span(),
Alex Crichtonf3888432018-05-16 09:11:05 -0700410 TokenTree::Ident(ref t) => t.span(),
411 TokenTree::Punct(ref t) => t.span(),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700412 TokenTree::Literal(ref t) => t.span(),
413 }
414 }
415
David Tolnay82ba02d2018-05-20 16:22:43 -0700416 /// Configures the span for *only this token*.
417 ///
418 /// Note that if this token is a `Group` then this method will not configure
419 /// the span of each of the internal tokens, this will simply delegate to
420 /// the `set_span` method of each variant.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700421 pub fn set_span(&mut self, span: Span) {
422 match *self {
423 TokenTree::Group(ref mut t) => t.set_span(span),
Alex Crichtonf3888432018-05-16 09:11:05 -0700424 TokenTree::Ident(ref mut t) => t.set_span(span),
425 TokenTree::Punct(ref mut t) => t.set_span(span),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700426 TokenTree::Literal(ref mut t) => t.set_span(span),
427 }
428 }
429}
430
431impl From<Group> for TokenTree {
432 fn from(g: Group) -> TokenTree {
433 TokenTree::Group(g)
434 }
435}
436
Alex Crichtonf3888432018-05-16 09:11:05 -0700437impl From<Ident> for TokenTree {
438 fn from(g: Ident) -> TokenTree {
439 TokenTree::Ident(g)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700440 }
441}
442
Alex Crichtonf3888432018-05-16 09:11:05 -0700443impl From<Punct> for TokenTree {
444 fn from(g: Punct) -> TokenTree {
445 TokenTree::Punct(g)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700446 }
447}
448
449impl From<Literal> for TokenTree {
450 fn from(g: Literal) -> TokenTree {
451 TokenTree::Literal(g)
Alex Crichton1a7f7622017-07-05 17:47:15 -0700452 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700453}
454
David Tolnay82ba02d2018-05-20 16:22:43 -0700455/// Prints the token tree as a string that is supposed to be losslessly
456/// convertible back into the same token tree (modulo spans), except for
457/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
458/// numeric literals.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700459impl fmt::Display for TokenTree {
460 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700461 match *self {
462 TokenTree::Group(ref t) => t.fmt(f),
Alex Crichtonf3888432018-05-16 09:11:05 -0700463 TokenTree::Ident(ref t) => t.fmt(f),
464 TokenTree::Punct(ref t) => t.fmt(f),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700465 TokenTree::Literal(ref t) => t.fmt(f),
466 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700467 }
468}
469
David Tolnay82ba02d2018-05-20 16:22:43 -0700470/// Prints token tree in a form convenient for debugging.
David Tolnay034205f2018-04-22 16:45:28 -0700471impl fmt::Debug for TokenTree {
472 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
473 // Each of these has the name in the struct type in the derived debug,
474 // so don't bother with an extra layer of indirection
475 match *self {
476 TokenTree::Group(ref t) => t.fmt(f),
David Tolnayd8fcdb82018-06-02 15:43:53 -0700477 TokenTree::Ident(ref t) => {
478 let mut debug = f.debug_struct("Ident");
479 debug.field("sym", &format_args!("{}", t));
480 #[cfg(any(feature = "nightly", procmacro2_semver_exempt))]
481 debug.field("span", &t.span());
482 debug.finish()
483 }
Alex Crichtonf3888432018-05-16 09:11:05 -0700484 TokenTree::Punct(ref t) => t.fmt(f),
David Tolnay034205f2018-04-22 16:45:28 -0700485 TokenTree::Literal(ref t) => t.fmt(f),
486 }
487 }
488}
489
David Tolnay82ba02d2018-05-20 16:22:43 -0700490/// A delimited token stream.
491///
492/// A `Group` internally contains a `TokenStream` which is surrounded by
493/// `Delimiter`s.
David Tolnay034205f2018-04-22 16:45:28 -0700494#[derive(Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700495pub struct Group {
David Tolnayf14813f2018-09-08 17:14:07 -0700496 inner: imp::Group,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700497}
498
David Tolnay82ba02d2018-05-20 16:22:43 -0700499/// Describes how a sequence of token trees is delimited.
Michael Layzell5372f4b2017-06-02 10:29:31 -0400500#[derive(Copy, Clone, Debug, Eq, PartialEq)]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700501pub enum Delimiter {
David Tolnay82ba02d2018-05-20 16:22:43 -0700502 /// `( ... )`
Alex Crichton44bffbc2017-05-19 17:51:59 -0700503 Parenthesis,
David Tolnay82ba02d2018-05-20 16:22:43 -0700504 /// `{ ... }`
Alex Crichton44bffbc2017-05-19 17:51:59 -0700505 Brace,
David Tolnay82ba02d2018-05-20 16:22:43 -0700506 /// `[ ... ]`
Alex Crichton44bffbc2017-05-19 17:51:59 -0700507 Bracket,
David Tolnay82ba02d2018-05-20 16:22:43 -0700508 /// `Ø ... Ø`
509 ///
510 /// An implicit delimiter, that may, for example, appear around tokens
511 /// coming from a "macro variable" `$var`. It is important to preserve
512 /// operator priorities in cases like `$var * 3` where `$var` is `1 + 2`.
513 /// Implicit delimiters may not survive roundtrip of a token stream through
514 /// a string.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700515 None,
516}
517
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700518impl Group {
David Tolnayf14813f2018-09-08 17:14:07 -0700519 fn _new(inner: imp::Group) -> Self {
520 Group {
521 inner: inner,
522 }
523 }
524
525 fn _new_stable(inner: stable::Group) -> Self {
526 Group {
527 inner: inner.into(),
528 }
529 }
530
David Tolnay82ba02d2018-05-20 16:22:43 -0700531 /// Creates a new `Group` with the given delimiter and token stream.
532 ///
533 /// This constructor will set the span for this group to
534 /// `Span::call_site()`. To change the span you can use the `set_span`
535 /// method below.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700536 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
537 Group {
David Tolnayf14813f2018-09-08 17:14:07 -0700538 inner: imp::Group::new(delimiter, stream.inner),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700539 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700540 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700541
David Tolnay82ba02d2018-05-20 16:22:43 -0700542 /// Returns the delimiter of this `Group`
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700543 pub fn delimiter(&self) -> Delimiter {
David Tolnayf14813f2018-09-08 17:14:07 -0700544 self.inner.delimiter()
Alex Crichton44bffbc2017-05-19 17:51:59 -0700545 }
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700546
David Tolnay82ba02d2018-05-20 16:22:43 -0700547 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
548 ///
549 /// Note that the returned token stream does not include the delimiter
550 /// returned above.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700551 pub fn stream(&self) -> TokenStream {
David Tolnayf14813f2018-09-08 17:14:07 -0700552 TokenStream::_new(self.inner.stream())
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700553 }
554
David Tolnay82ba02d2018-05-20 16:22:43 -0700555 /// Returns the span for the delimiters of this token stream, spanning the
556 /// entire `Group`.
David Tolnayf14813f2018-09-08 17:14:07 -0700557 ///
558 /// ```text
559 /// pub fn span(&self) -> Span {
560 /// ^^^^^^^
561 /// ```
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700562 pub fn span(&self) -> Span {
David Tolnayf14813f2018-09-08 17:14:07 -0700563 Span::_new(self.inner.span())
564 }
565
566 /// Returns the span pointing to the opening delimiter of this group.
567 ///
568 /// ```text
569 /// pub fn span_open(&self) -> Span {
570 /// ^
571 /// ```
572 #[cfg(procmacro2_semver_exempt)]
573 pub fn span_open(&self) -> Span {
574 Span::_new(self.inner.span_open())
575 }
576
577 /// Returns the span pointing to the closing delimiter of this group.
578 ///
579 /// ```text
580 /// pub fn span_close(&self) -> Span {
581 /// ^
582 /// ```
583 #[cfg(procmacro2_semver_exempt)]
584 pub fn span_close(&self) -> Span {
585 Span::_new(self.inner.span_close())
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700586 }
587
David Tolnay82ba02d2018-05-20 16:22:43 -0700588 /// Configures the span for this `Group`'s delimiters, but not its internal
589 /// tokens.
590 ///
591 /// This method will **not** set the span of all the internal tokens spanned
592 /// by this group, but rather it will only set the span of the delimiter
593 /// tokens at the level of the `Group`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700594 pub fn set_span(&mut self, span: Span) {
David Tolnayf14813f2018-09-08 17:14:07 -0700595 self.inner.set_span(span.inner)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700596 }
597}
598
David Tolnay82ba02d2018-05-20 16:22:43 -0700599/// Prints the group as a string that should be losslessly convertible back
600/// into the same group (modulo spans), except for possibly `TokenTree::Group`s
601/// with `Delimiter::None` delimiters.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700602impl fmt::Display for Group {
David Tolnayf14813f2018-09-08 17:14:07 -0700603 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
604 fmt::Display::fmt(&self.inner, formatter)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700605 }
606}
607
David Tolnay034205f2018-04-22 16:45:28 -0700608impl fmt::Debug for Group {
David Tolnayf14813f2018-09-08 17:14:07 -0700609 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
610 fmt::Debug::fmt(&self.inner, formatter)
David Tolnay034205f2018-04-22 16:45:28 -0700611 }
612}
613
David Tolnay82ba02d2018-05-20 16:22:43 -0700614/// An `Punct` is an single punctuation character like `+`, `-` or `#`.
615///
616/// Multicharacter operators like `+=` are represented as two instances of
617/// `Punct` with different forms of `Spacing` returned.
Alex Crichtonf3888432018-05-16 09:11:05 -0700618#[derive(Clone)]
619pub struct Punct {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700620 op: char,
621 spacing: Spacing,
622 span: Span,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700623}
624
David Tolnay82ba02d2018-05-20 16:22:43 -0700625/// Whether an `Punct` is followed immediately by another `Punct` or followed by
626/// another token or whitespace.
Lukas Kalbertodteb3f9302017-08-20 18:58:41 +0200627#[derive(Copy, Clone, Debug, Eq, PartialEq)]
Alex Crichton1a7f7622017-07-05 17:47:15 -0700628pub enum Spacing {
David Tolnay82ba02d2018-05-20 16:22:43 -0700629 /// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700630 Alone,
David Tolnay82ba02d2018-05-20 16:22:43 -0700631 /// E.g. `+` is `Joint` in `+=` or `'#`.
632 ///
633 /// Additionally, single quote `'` can join with identifiers to form
634 /// lifetimes `'ident`.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700635 Joint,
636}
637
Alex Crichtonf3888432018-05-16 09:11:05 -0700638impl Punct {
David Tolnay82ba02d2018-05-20 16:22:43 -0700639 /// Creates a new `Punct` from the given character and spacing.
640 ///
641 /// The `ch` argument must be a valid punctuation character permitted by the
642 /// language, otherwise the function will panic.
643 ///
644 /// The returned `Punct` will have the default span of `Span::call_site()`
645 /// which can be further configured with the `set_span` method below.
Alex Crichtonf3888432018-05-16 09:11:05 -0700646 pub fn new(op: char, spacing: Spacing) -> Punct {
647 Punct {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700648 op: op,
649 spacing: spacing,
650 span: Span::call_site(),
651 }
652 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700653
David Tolnay82ba02d2018-05-20 16:22:43 -0700654 /// Returns the value of this punctuation character as `char`.
Alex Crichtonf3888432018-05-16 09:11:05 -0700655 pub fn as_char(&self) -> char {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700656 self.op
657 }
658
David Tolnay82ba02d2018-05-20 16:22:43 -0700659 /// Returns the spacing of this punctuation character, indicating whether
660 /// it's immediately followed by another `Punct` in the token stream, so
661 /// they can potentially be combined into a multicharacter operator
662 /// (`Joint`), or it's followed by some other token or whitespace (`Alone`)
663 /// so the operator has certainly ended.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700664 pub fn spacing(&self) -> Spacing {
665 self.spacing
666 }
667
David Tolnay82ba02d2018-05-20 16:22:43 -0700668 /// Returns the span for this punctuation character.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700669 pub fn span(&self) -> Span {
670 self.span
671 }
672
David Tolnay82ba02d2018-05-20 16:22:43 -0700673 /// Configure the span for this punctuation character.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700674 pub fn set_span(&mut self, span: Span) {
675 self.span = span;
676 }
677}
678
David Tolnay82ba02d2018-05-20 16:22:43 -0700679/// Prints the punctuation character as a string that should be losslessly
680/// convertible back into the same character.
Alex Crichtonf3888432018-05-16 09:11:05 -0700681impl fmt::Display for Punct {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700682 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
683 self.op.fmt(f)
684 }
685}
686
Alex Crichtonf3888432018-05-16 09:11:05 -0700687impl fmt::Debug for Punct {
David Tolnay034205f2018-04-22 16:45:28 -0700688 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonf3888432018-05-16 09:11:05 -0700689 let mut debug = fmt.debug_struct("Punct");
David Tolnay034205f2018-04-22 16:45:28 -0700690 debug.field("op", &self.op);
691 debug.field("spacing", &self.spacing);
692 #[cfg(procmacro2_semver_exempt)]
693 debug.field("span", &self.span);
694 debug.finish()
695 }
696}
697
David Tolnay8b71dac2018-05-20 17:07:47 -0700698/// A word of Rust code, which may be a keyword or legal variable name.
699///
700/// An identifier consists of at least one Unicode code point, the first of
701/// which has the XID_Start property and the rest of which have the XID_Continue
702/// property.
703///
704/// - The empty string is not an identifier. Use `Option<Ident>`.
705/// - A lifetime is not an identifier. Use `syn::Lifetime` instead.
706///
707/// An identifier constructed with `Ident::new` is permitted to be a Rust
David Tolnayc239f032018-11-11 12:57:09 -0800708/// keyword, though parsing one through its [`Parse`] implementation rejects
709/// Rust keywords. Use `input.call(Ident::parse_any)` when parsing to match the
David Tolnay8b71dac2018-05-20 17:07:47 -0700710/// behaviour of `Ident::new`.
711///
David Tolnayc239f032018-11-11 12:57:09 -0800712/// [`Parse`]: https://docs.rs/syn/0.15/syn/parse/trait.Parse.html
David Tolnay8b71dac2018-05-20 17:07:47 -0700713///
714/// # Examples
715///
716/// A new ident can be created from a string using the `Ident::new` function.
717/// A span must be provided explicitly which governs the name resolution
718/// behavior of the resulting identifier.
719///
720/// ```rust
721/// extern crate proc_macro2;
722///
723/// use proc_macro2::{Ident, Span};
724///
725/// fn main() {
726/// let call_ident = Ident::new("calligraphy", Span::call_site());
727///
728/// println!("{}", call_ident);
729/// }
730/// ```
731///
732/// An ident can be interpolated into a token stream using the `quote!` macro.
733///
734/// ```rust
735/// #[macro_use]
736/// extern crate quote;
737///
738/// extern crate proc_macro2;
739///
740/// use proc_macro2::{Ident, Span};
741///
742/// fn main() {
743/// let ident = Ident::new("demo", Span::call_site());
744///
745/// // Create a variable binding whose name is this ident.
746/// let expanded = quote! { let #ident = 10; };
747///
748/// // Create a variable binding with a slightly different name.
749/// let temp_ident = Ident::new(&format!("new_{}", ident), Span::call_site());
750/// let expanded = quote! { let #temp_ident = 10; };
751/// }
752/// ```
753///
754/// A string representation of the ident is available through the `to_string()`
755/// method.
756///
757/// ```rust
758/// # extern crate proc_macro2;
759/// #
760/// # use proc_macro2::{Ident, Span};
761/// #
762/// # let ident = Ident::new("another_identifier", Span::call_site());
763/// #
764/// // Examine the ident as a string.
765/// let ident_string = ident.to_string();
766/// if ident_string.len() > 60 {
767/// println!("Very long identifier: {}", ident_string)
768/// }
769/// ```
Alex Crichtonf3888432018-05-16 09:11:05 -0700770#[derive(Clone)]
771pub struct Ident {
772 inner: imp::Ident,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700773 _marker: marker::PhantomData<Rc<()>>,
774}
775
Alex Crichtonf3888432018-05-16 09:11:05 -0700776impl Ident {
777 fn _new(inner: imp::Ident) -> Ident {
778 Ident {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700779 inner: inner,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700780 _marker: marker::PhantomData,
781 }
782 }
783
David Tolnay82ba02d2018-05-20 16:22:43 -0700784 /// Creates a new `Ident` with the given `string` as well as the specified
785 /// `span`.
786 ///
787 /// The `string` argument must be a valid identifier permitted by the
788 /// language, otherwise the function will panic.
789 ///
790 /// Note that `span`, currently in rustc, configures the hygiene information
791 /// for this identifier.
792 ///
793 /// As of this time `Span::call_site()` explicitly opts-in to "call-site"
794 /// hygiene meaning that identifiers created with this span will be resolved
795 /// as if they were written directly at the location of the macro call, and
796 /// other code at the macro call site will be able to refer to them as well.
797 ///
798 /// Later spans like `Span::def_site()` will allow to opt-in to
799 /// "definition-site" hygiene meaning that identifiers created with this
800 /// span will be resolved at the location of the macro definition and other
801 /// code at the macro call site will not be able to refer to them.
802 ///
803 /// Due to the current importance of hygiene this constructor, unlike other
804 /// tokens, requires a `Span` to be specified at construction.
David Tolnay8b71dac2018-05-20 17:07:47 -0700805 ///
806 /// # Panics
807 ///
808 /// Panics if the input string is neither a keyword nor a legal variable
809 /// name.
Alex Crichtonf3888432018-05-16 09:11:05 -0700810 pub fn new(string: &str, span: Span) -> Ident {
811 Ident::_new(imp::Ident::new(string, span.inner))
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700812 }
813
David Tolnay82ba02d2018-05-20 16:22:43 -0700814 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
David Tolnaya01ca8e2018-06-04 00:55:28 -0700815 ///
816 /// This method is semver exempt and not exposed by default.
Alex Crichtonf3888432018-05-16 09:11:05 -0700817 #[cfg(procmacro2_semver_exempt)]
818 pub fn new_raw(string: &str, span: Span) -> Ident {
819 Ident::_new_raw(string, span)
820 }
821
822 fn _new_raw(string: &str, span: Span) -> Ident {
823 Ident::_new(imp::Ident::new_raw(string, span.inner))
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700824 }
825
David Tolnay82ba02d2018-05-20 16:22:43 -0700826 /// Returns the span of this `Ident`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700827 pub fn span(&self) -> Span {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700828 Span::_new(self.inner.span())
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700829 }
830
David Tolnay82ba02d2018-05-20 16:22:43 -0700831 /// Configures the span of this `Ident`, possibly changing its hygiene
832 /// context.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700833 pub fn set_span(&mut self, span: Span) {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700834 self.inner.set_span(span.inner);
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700835 }
836}
837
Alex Crichtonf3888432018-05-16 09:11:05 -0700838impl PartialEq for Ident {
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700839 fn eq(&self, other: &Ident) -> bool {
David Tolnayc0b0f2e2018-09-02 17:56:08 -0700840 self.inner == other.inner
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700841 }
842}
843
David Tolnayc0bbcc52018-05-18 10:51:04 -0700844impl<T> PartialEq<T> for Ident
845where
846 T: ?Sized + AsRef<str>,
847{
848 fn eq(&self, other: &T) -> bool {
David Tolnayc0b0f2e2018-09-02 17:56:08 -0700849 self.inner == other
David Tolnayc0bbcc52018-05-18 10:51:04 -0700850 }
851}
852
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700853impl Eq for Ident {}
Alex Crichtonf3888432018-05-16 09:11:05 -0700854
855impl PartialOrd for Ident {
856 fn partial_cmp(&self, other: &Ident) -> Option<Ordering> {
857 Some(self.cmp(other))
858 }
859}
860
861impl Ord for Ident {
862 fn cmp(&self, other: &Ident) -> Ordering {
863 self.to_string().cmp(&other.to_string())
864 }
865}
866
867impl Hash for Ident {
868 fn hash<H: Hasher>(&self, hasher: &mut H) {
869 self.to_string().hash(hasher)
870 }
871}
872
David Tolnay82ba02d2018-05-20 16:22:43 -0700873/// Prints the identifier as a string that should be losslessly convertible back
874/// into the same identifier.
Alex Crichtonf3888432018-05-16 09:11:05 -0700875impl fmt::Display for Ident {
876 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
877 self.inner.fmt(f)
878 }
879}
880
881impl fmt::Debug for Ident {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700882 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
883 self.inner.fmt(f)
884 }
885}
886
David Tolnay82ba02d2018-05-20 16:22:43 -0700887/// A literal string (`"hello"`), byte string (`b"hello"`), character (`'a'`),
888/// byte character (`b'a'`), an integer or floating point number with or without
889/// a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
890///
891/// Boolean literals like `true` and `false` do not belong here, they are
892/// `Ident`s.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700893#[derive(Clone)]
894pub struct Literal {
895 inner: imp::Literal,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700896 _marker: marker::PhantomData<Rc<()>>,
897}
898
David Tolnay82ba02d2018-05-20 16:22:43 -0700899macro_rules! suffixed_int_literals {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700900 ($($name:ident => $kind:ident,)*) => ($(
David Tolnay82ba02d2018-05-20 16:22:43 -0700901 /// Creates a new suffixed integer literal with the specified value.
902 ///
903 /// This function will create an integer like `1u32` where the integer
904 /// value specified is the first part of the token and the integral is
905 /// also suffixed at the end. Literals created from negative numbers may
906 /// not survive rountrips through `TokenStream` or strings and may be
907 /// broken into two tokens (`-` and positive literal).
908 ///
909 /// Literals created through this method have the `Span::call_site()`
910 /// span by default, which can be configured with the `set_span` method
911 /// below.
912 pub fn $name(n: $kind) -> Literal {
913 Literal::_new(imp::Literal::$name(n))
914 }
915 )*)
916}
917
918macro_rules! unsuffixed_int_literals {
919 ($($name:ident => $kind:ident,)*) => ($(
920 /// Creates a new unsuffixed integer literal with the specified value.
921 ///
922 /// This function will create an integer like `1` where the integer
923 /// value specified is the first part of the token. No suffix is
924 /// specified on this token, meaning that invocations like
925 /// `Literal::i8_unsuffixed(1)` are equivalent to
926 /// `Literal::u32_unsuffixed(1)`. Literals created from negative numbers
927 /// may not survive rountrips through `TokenStream` or strings and may
928 /// be broken into two tokens (`-` and positive literal).
929 ///
930 /// Literals created through this method have the `Span::call_site()`
931 /// span by default, which can be configured with the `set_span` method
932 /// below.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700933 pub fn $name(n: $kind) -> Literal {
Alex Crichtona914a612018-04-04 07:48:44 -0700934 Literal::_new(imp::Literal::$name(n))
Alex Crichton1a7f7622017-07-05 17:47:15 -0700935 }
936 )*)
937}
938
Alex Crichton852d53d2017-05-19 19:25:08 -0700939impl Literal {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700940 fn _new(inner: imp::Literal) -> Literal {
941 Literal {
942 inner: inner,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700943 _marker: marker::PhantomData,
944 }
Alex Crichton1a7f7622017-07-05 17:47:15 -0700945 }
946
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700947 fn _new_stable(inner: stable::Literal) -> Literal {
948 Literal {
949 inner: inner.into(),
950 _marker: marker::PhantomData,
951 }
952 }
953
David Tolnay82ba02d2018-05-20 16:22:43 -0700954 suffixed_int_literals! {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700955 u8_suffixed => u8,
956 u16_suffixed => u16,
957 u32_suffixed => u32,
958 u64_suffixed => u64,
959 usize_suffixed => usize,
960 i8_suffixed => i8,
961 i16_suffixed => i16,
962 i32_suffixed => i32,
963 i64_suffixed => i64,
964 isize_suffixed => isize,
David Tolnay82ba02d2018-05-20 16:22:43 -0700965 }
Alex Crichton1a7f7622017-07-05 17:47:15 -0700966
Alex Crichton69385662018-11-08 06:30:04 -0800967 #[cfg(u128)]
968 suffixed_int_literals! {
969 u128_suffixed => u128,
970 i128_suffixed => i128,
971 }
972
David Tolnay82ba02d2018-05-20 16:22:43 -0700973 unsuffixed_int_literals! {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700974 u8_unsuffixed => u8,
975 u16_unsuffixed => u16,
976 u32_unsuffixed => u32,
977 u64_unsuffixed => u64,
978 usize_unsuffixed => usize,
979 i8_unsuffixed => i8,
980 i16_unsuffixed => i16,
981 i32_unsuffixed => i32,
982 i64_unsuffixed => i64,
983 isize_unsuffixed => isize,
Alex Crichton1a7f7622017-07-05 17:47:15 -0700984 }
985
Alex Crichton69385662018-11-08 06:30:04 -0800986 #[cfg(u128)]
987 unsuffixed_int_literals! {
988 u128_unsuffixed => u128,
989 i128_unsuffixed => i128,
990 }
991
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700992 pub fn f64_unsuffixed(f: f64) -> Literal {
993 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -0700994 Literal::_new(imp::Literal::f64_unsuffixed(f))
Alex Crichton1a7f7622017-07-05 17:47:15 -0700995 }
996
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700997 pub fn f64_suffixed(f: f64) -> Literal {
998 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -0700999 Literal::_new(imp::Literal::f64_suffixed(f))
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001000 }
1001
David Tolnay82ba02d2018-05-20 16:22:43 -07001002 /// Creates a new unsuffixed floating-point literal.
1003 ///
1004 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1005 /// the float's value is emitted directly into the token but no suffix is
1006 /// used, so it may be inferred to be a `f64` later in the compiler.
1007 /// Literals created from negative numbers may not survive rountrips through
1008 /// `TokenStream` or strings and may be broken into two tokens (`-` and
1009 /// positive literal).
1010 ///
1011 /// # Panics
1012 ///
1013 /// This function requires that the specified float is finite, for example
1014 /// if it is infinity or NaN this function will panic.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001015 pub fn f32_unsuffixed(f: f32) -> Literal {
1016 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -07001017 Literal::_new(imp::Literal::f32_unsuffixed(f))
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001018 }
1019
1020 pub fn f32_suffixed(f: f32) -> Literal {
1021 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -07001022 Literal::_new(imp::Literal::f32_suffixed(f))
Alex Crichton1a7f7622017-07-05 17:47:15 -07001023 }
1024
1025 pub fn string(string: &str) -> Literal {
Alex Crichtona914a612018-04-04 07:48:44 -07001026 Literal::_new(imp::Literal::string(string))
Alex Crichton1a7f7622017-07-05 17:47:15 -07001027 }
1028
1029 pub fn character(ch: char) -> Literal {
Alex Crichtona914a612018-04-04 07:48:44 -07001030 Literal::_new(imp::Literal::character(ch))
Alex Crichton76a5cc82017-05-23 07:01:44 -07001031 }
1032
Alex Crichton9c2fb0a2017-05-26 08:49:31 -07001033 pub fn byte_string(s: &[u8]) -> Literal {
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001034 Literal::_new(imp::Literal::byte_string(s))
Alex Crichton852d53d2017-05-19 19:25:08 -07001035 }
Alex Crichton76a5cc82017-05-23 07:01:44 -07001036
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001037 pub fn span(&self) -> Span {
Alex Crichtonb2c94622018-04-04 07:36:41 -07001038 Span::_new(self.inner.span())
Alex Crichton1a7f7622017-07-05 17:47:15 -07001039 }
1040
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001041 pub fn set_span(&mut self, span: Span) {
Alex Crichtonb2c94622018-04-04 07:36:41 -07001042 self.inner.set_span(span.inner);
Alex Crichton31316622017-05-26 12:54:47 -07001043 }
Alex Crichton852d53d2017-05-19 19:25:08 -07001044}
1045
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001046impl fmt::Debug for Literal {
1047 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1048 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001049 }
1050}
David Tolnaycb1b85f2017-06-03 16:40:35 -07001051
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001052impl fmt::Display for Literal {
1053 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1054 self.inner.fmt(f)
1055 }
1056}
1057
David Tolnay82ba02d2018-05-20 16:22:43 -07001058/// Public implementation details for the `TokenStream` type, such as iterators.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001059pub mod token_stream {
1060 use std::fmt;
1061 use std::marker;
1062 use std::rc::Rc;
1063
David Tolnay48ea5042018-04-23 19:17:35 -07001064 use imp;
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001065 pub use TokenStream;
David Tolnayb28f38a2018-03-31 22:02:29 +02001066 use TokenTree;
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001067
David Tolnay82ba02d2018-05-20 16:22:43 -07001068 /// An iterator over `TokenStream`'s `TokenTree`s.
1069 ///
1070 /// The iteration is "shallow", e.g. the iterator doesn't recurse into
1071 /// delimited groups, and returns whole groups as token trees.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001072 pub struct IntoIter {
1073 inner: imp::TokenTreeIter,
1074 _marker: marker::PhantomData<Rc<()>>,
1075 }
1076
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001077 impl Iterator for IntoIter {
1078 type Item = TokenTree;
1079
1080 fn next(&mut self) -> Option<TokenTree> {
1081 self.inner.next()
1082 }
1083 }
1084
1085 impl fmt::Debug for IntoIter {
1086 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1087 self.inner.fmt(f)
1088 }
1089 }
1090
1091 impl IntoIterator for TokenStream {
1092 type Item = TokenTree;
1093 type IntoIter = IntoIter;
1094
1095 fn into_iter(self) -> IntoIter {
1096 IntoIter {
1097 inner: self.inner.into_iter(),
1098 _marker: marker::PhantomData,
1099 }
1100 }
1101 }
1102}