blob: fd49f0118344f31dd3065f1864058a4120a3325b [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 Tolnaydd1af432019-01-16 12:08:47 -080046#![doc(html_root_url = "https://docs.rs/proc-macro2/0.4.25")]
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;
David Tolnayaef075b2019-01-16 16:29:18 -080068mod fallback;
David Tolnayb1032662017-05-31 15:52:28 -070069
Alex Crichtonce0904d2018-08-27 17:29:49 -070070#[cfg(not(wrap_proc_macro))]
David Tolnayaef075b2019-01-16 16:29:18 -080071use fallback as imp;
72#[path = "wrapper.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
David Tolnayaef075b2019-01-16 16:29:18 -0800103 fn _new_stable(inner: fallback::TokenStream) -> TokenStream {
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700104 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)]
David Tolnay7e654a82018-11-11 13:33:18 -0800221pub struct SourceFile {
222 inner: imp::SourceFile,
223 _marker: marker::PhantomData<Rc<()>>,
224}
Nika Layzellf8d5f212017-12-11 14:07:02 -0500225
David Tolnay1ebe3972018-01-02 20:14:20 -0800226#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500227impl SourceFile {
David Tolnay7e654a82018-11-11 13:33:18 -0800228 fn _new(inner: imp::SourceFile) -> Self {
229 SourceFile {
230 inner: inner,
231 _marker: marker::PhantomData,
232 }
233 }
234
David Tolnay82ba02d2018-05-20 16:22:43 -0700235 /// Get the path to this source file.
236 ///
237 /// ### Note
238 ///
239 /// If the code span associated with this `SourceFile` was generated by an
240 /// external macro, this may not be an actual path on the filesystem. Use
241 /// [`is_real`] to check.
242 ///
243 /// Also note that even if `is_real` returns `true`, if
244 /// `--remap-path-prefix` was passed on the command line, the path as given
245 /// may not actually be valid.
246 ///
247 /// [`is_real`]: #method.is_real
David Tolnay9cd3b4c2018-11-11 16:47:32 -0800248 pub fn path(&self) -> PathBuf {
David Tolnay7e654a82018-11-11 13:33:18 -0800249 self.inner.path()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500250 }
251
David Tolnay82ba02d2018-05-20 16:22:43 -0700252 /// Returns `true` if this source file is a real source file, and not
253 /// generated by an external macro's expansion.
Nika Layzellf8d5f212017-12-11 14:07:02 -0500254 pub fn is_real(&self) -> bool {
David Tolnay7e654a82018-11-11 13:33:18 -0800255 self.inner.is_real()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500256 }
257}
258
David Tolnay1ebe3972018-01-02 20:14:20 -0800259#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500260impl fmt::Debug for SourceFile {
261 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
David Tolnay7e654a82018-11-11 13:33:18 -0800262 self.inner.fmt(f)
Nika Layzellf8d5f212017-12-11 14:07:02 -0500263 }
264}
265
David Tolnay82ba02d2018-05-20 16:22:43 -0700266/// A line-column pair representing the start or end of a `Span`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700267///
268/// This type is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800269#[cfg(procmacro2_semver_exempt)]
Nika Layzell1ecb6ce2017-12-30 14:34:05 -0500270pub struct LineColumn {
David Tolnay82ba02d2018-05-20 16:22:43 -0700271 /// The 1-indexed line in the source file on which the span starts or ends
272 /// (inclusive).
Nika Layzell1ecb6ce2017-12-30 14:34:05 -0500273 pub line: usize,
David Tolnay82ba02d2018-05-20 16:22:43 -0700274 /// The 0-indexed column (in UTF-8 characters) in the source file on which
275 /// the span starts or ends (inclusive).
Nika Layzell1ecb6ce2017-12-30 14:34:05 -0500276 pub column: usize,
277}
Nika Layzellf8d5f212017-12-11 14:07:02 -0500278
David Tolnay82ba02d2018-05-20 16:22:43 -0700279/// A region of source code, along with macro expansion information.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700280#[derive(Copy, Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700281pub struct Span {
282 inner: imp::Span,
283 _marker: marker::PhantomData<Rc<()>>,
284}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700285
Alex Crichton44bffbc2017-05-19 17:51:59 -0700286impl Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700287 fn _new(inner: imp::Span) -> Span {
288 Span {
289 inner: inner,
290 _marker: marker::PhantomData,
291 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700292 }
Alex Crichtone6085b72017-11-21 07:24:25 -0800293
David Tolnayaef075b2019-01-16 16:29:18 -0800294 fn _new_stable(inner: fallback::Span) -> Span {
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700295 Span {
296 inner: inner.into(),
297 _marker: marker::PhantomData,
298 }
299 }
300
David Tolnay82ba02d2018-05-20 16:22:43 -0700301 /// The span of the invocation of the current procedural macro.
302 ///
303 /// Identifiers created with this span will be resolved as if they were
304 /// written directly at the macro call location (call-site hygiene) and
305 /// other code at the macro call site will be able to refer to them as well.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700306 pub fn call_site() -> Span {
307 Span::_new(imp::Span::call_site())
308 }
309
David Tolnay82ba02d2018-05-20 16:22:43 -0700310 /// A span that resolves at the macro definition site.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700311 ///
312 /// This method is semver exempt and not exposed by default.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700313 #[cfg(procmacro2_semver_exempt)]
Alex Crichtone6085b72017-11-21 07:24:25 -0800314 pub fn def_site() -> Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700315 Span::_new(imp::Span::def_site())
Alex Crichtone6085b72017-11-21 07:24:25 -0800316 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500317
David Tolnay4e8e3972018-01-05 18:10:22 -0800318 /// Creates a new span with the same line/column information as `self` but
319 /// that resolves symbols as though it were at `other`.
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)]
David Tolnay4e8e3972018-01-05 18:10:22 -0800323 pub fn resolved_at(&self, other: Span) -> Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700324 Span::_new(self.inner.resolved_at(other.inner))
David Tolnay4e8e3972018-01-05 18:10:22 -0800325 }
326
327 /// Creates a new span with the same name resolution behavior as `self` but
328 /// with the line/column information of `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 located_at(&self, other: Span) -> Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700333 Span::_new(self.inner.located_at(other.inner))
David Tolnay4e8e3972018-01-05 18:10:22 -0800334 }
335
David Tolnay17eb0702019-01-05 12:23:17 -0800336 /// Convert `proc_macro2::Span` to `proc_macro::Span`.
337 ///
338 /// This method is available when building with a nightly compiler, or when
339 /// building with rustc 1.29+ *without* semver exempt features.
David Tolnayc0425cd2019-01-16 12:13:15 -0800340 ///
341 /// # Panics
342 ///
343 /// Panics if called from outside of a procedural macro. Unlike
344 /// `proc_macro2::Span`, the `proc_macro::Span` type can only exist within
345 /// the context of a procedural macro invocation.
David Tolnay17eb0702019-01-05 12:23:17 -0800346 #[cfg(wrap_proc_macro)]
David Tolnay16a17202017-12-31 10:47:24 -0500347 pub fn unstable(self) -> proc_macro::Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700348 self.inner.unstable()
David Tolnay16a17202017-12-31 10:47:24 -0500349 }
350
David Tolnay82ba02d2018-05-20 16:22:43 -0700351 /// The original source file into which this span points.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700352 ///
353 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800354 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500355 pub fn source_file(&self) -> SourceFile {
David Tolnay7e654a82018-11-11 13:33:18 -0800356 SourceFile::_new(self.inner.source_file())
Nika Layzellf8d5f212017-12-11 14:07:02 -0500357 }
358
David Tolnay82ba02d2018-05-20 16:22:43 -0700359 /// Get the starting line/column in the source file for this span.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700360 ///
361 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800362 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500363 pub fn start(&self) -> LineColumn {
David Tolnayb28f38a2018-03-31 22:02:29 +0200364 let imp::LineColumn { line, column } = self.inner.start();
365 LineColumn {
366 line: line,
367 column: column,
368 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500369 }
370
David Tolnay82ba02d2018-05-20 16:22:43 -0700371 /// Get the ending line/column in the source file for this span.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700372 ///
373 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800374 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500375 pub fn end(&self) -> LineColumn {
David Tolnayb28f38a2018-03-31 22:02:29 +0200376 let imp::LineColumn { line, column } = self.inner.end();
377 LineColumn {
378 line: line,
379 column: column,
380 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500381 }
382
David Tolnay82ba02d2018-05-20 16:22:43 -0700383 /// Create a new span encompassing `self` and `other`.
384 ///
385 /// Returns `None` if `self` and `other` are from different files.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700386 ///
387 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800388 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500389 pub fn join(&self, other: Span) -> Option<Span> {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700390 self.inner.join(other.inner).map(Span::_new)
391 }
Alex Crichtonb2c94622018-04-04 07:36:41 -0700392
David Tolnay82ba02d2018-05-20 16:22:43 -0700393 /// Compares to spans to see if they're equal.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700394 ///
395 /// This method is semver exempt and not exposed by default.
Alex Crichtonb2c94622018-04-04 07:36:41 -0700396 #[cfg(procmacro2_semver_exempt)]
397 pub fn eq(&self, other: &Span) -> bool {
398 self.inner.eq(&other.inner)
399 }
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700400}
401
David Tolnay82ba02d2018-05-20 16:22:43 -0700402/// Prints a span in a form convenient for debugging.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700403impl fmt::Debug for Span {
404 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
405 self.inner.fmt(f)
Nika Layzellf8d5f212017-12-11 14:07:02 -0500406 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700407}
408
David Tolnay82ba02d2018-05-20 16:22:43 -0700409/// A single token or a delimited sequence of token trees (e.g. `[1, (), ..]`).
David Tolnay034205f2018-04-22 16:45:28 -0700410#[derive(Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700411pub enum TokenTree {
David Tolnay82ba02d2018-05-20 16:22:43 -0700412 /// A token stream surrounded by bracket delimiters.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700413 Group(Group),
David Tolnay82ba02d2018-05-20 16:22:43 -0700414 /// An identifier.
Alex Crichtonf3888432018-05-16 09:11:05 -0700415 Ident(Ident),
David Tolnay82ba02d2018-05-20 16:22:43 -0700416 /// A single punctuation character (`+`, `,`, `$`, etc.).
Alex Crichtonf3888432018-05-16 09:11:05 -0700417 Punct(Punct),
David Tolnay82ba02d2018-05-20 16:22:43 -0700418 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700419 Literal(Literal),
Alex Crichton1a7f7622017-07-05 17:47:15 -0700420}
421
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700422impl TokenTree {
David Tolnay82ba02d2018-05-20 16:22:43 -0700423 /// Returns the span of this tree, delegating to the `span` method of
424 /// the contained token or a delimited stream.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700425 pub fn span(&self) -> Span {
426 match *self {
427 TokenTree::Group(ref t) => t.span(),
Alex Crichtonf3888432018-05-16 09:11:05 -0700428 TokenTree::Ident(ref t) => t.span(),
429 TokenTree::Punct(ref t) => t.span(),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700430 TokenTree::Literal(ref t) => t.span(),
431 }
432 }
433
David Tolnay82ba02d2018-05-20 16:22:43 -0700434 /// Configures the span for *only this token*.
435 ///
436 /// Note that if this token is a `Group` then this method will not configure
437 /// the span of each of the internal tokens, this will simply delegate to
438 /// the `set_span` method of each variant.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700439 pub fn set_span(&mut self, span: Span) {
440 match *self {
441 TokenTree::Group(ref mut t) => t.set_span(span),
Alex Crichtonf3888432018-05-16 09:11:05 -0700442 TokenTree::Ident(ref mut t) => t.set_span(span),
443 TokenTree::Punct(ref mut t) => t.set_span(span),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700444 TokenTree::Literal(ref mut t) => t.set_span(span),
445 }
446 }
447}
448
449impl From<Group> for TokenTree {
450 fn from(g: Group) -> TokenTree {
451 TokenTree::Group(g)
452 }
453}
454
Alex Crichtonf3888432018-05-16 09:11:05 -0700455impl From<Ident> for TokenTree {
456 fn from(g: Ident) -> TokenTree {
457 TokenTree::Ident(g)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700458 }
459}
460
Alex Crichtonf3888432018-05-16 09:11:05 -0700461impl From<Punct> for TokenTree {
462 fn from(g: Punct) -> TokenTree {
463 TokenTree::Punct(g)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700464 }
465}
466
467impl From<Literal> for TokenTree {
468 fn from(g: Literal) -> TokenTree {
469 TokenTree::Literal(g)
Alex Crichton1a7f7622017-07-05 17:47:15 -0700470 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700471}
472
David Tolnay82ba02d2018-05-20 16:22:43 -0700473/// Prints the token tree as a string that is supposed to be losslessly
474/// convertible back into the same token tree (modulo spans), except for
475/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
476/// numeric literals.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700477impl fmt::Display for TokenTree {
478 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700479 match *self {
480 TokenTree::Group(ref t) => t.fmt(f),
Alex Crichtonf3888432018-05-16 09:11:05 -0700481 TokenTree::Ident(ref t) => t.fmt(f),
482 TokenTree::Punct(ref t) => t.fmt(f),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700483 TokenTree::Literal(ref t) => t.fmt(f),
484 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700485 }
486}
487
David Tolnay82ba02d2018-05-20 16:22:43 -0700488/// Prints token tree in a form convenient for debugging.
David Tolnay034205f2018-04-22 16:45:28 -0700489impl fmt::Debug for TokenTree {
490 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
491 // Each of these has the name in the struct type in the derived debug,
492 // so don't bother with an extra layer of indirection
493 match *self {
494 TokenTree::Group(ref t) => t.fmt(f),
David Tolnayd8fcdb82018-06-02 15:43:53 -0700495 TokenTree::Ident(ref t) => {
496 let mut debug = f.debug_struct("Ident");
497 debug.field("sym", &format_args!("{}", t));
David Tolnayfd8cdc82019-01-19 19:23:59 -0800498 imp::debug_span_field_if_nontrivial(&mut debug, t.span().inner);
David Tolnayd8fcdb82018-06-02 15:43:53 -0700499 debug.finish()
500 }
Alex Crichtonf3888432018-05-16 09:11:05 -0700501 TokenTree::Punct(ref t) => t.fmt(f),
David Tolnay034205f2018-04-22 16:45:28 -0700502 TokenTree::Literal(ref t) => t.fmt(f),
503 }
504 }
505}
506
David Tolnay82ba02d2018-05-20 16:22:43 -0700507/// A delimited token stream.
508///
509/// A `Group` internally contains a `TokenStream` which is surrounded by
510/// `Delimiter`s.
David Tolnay034205f2018-04-22 16:45:28 -0700511#[derive(Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700512pub struct Group {
David Tolnayf14813f2018-09-08 17:14:07 -0700513 inner: imp::Group,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700514}
515
David Tolnay82ba02d2018-05-20 16:22:43 -0700516/// Describes how a sequence of token trees is delimited.
Michael Layzell5372f4b2017-06-02 10:29:31 -0400517#[derive(Copy, Clone, Debug, Eq, PartialEq)]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700518pub enum Delimiter {
David Tolnay82ba02d2018-05-20 16:22:43 -0700519 /// `( ... )`
Alex Crichton44bffbc2017-05-19 17:51:59 -0700520 Parenthesis,
David Tolnay82ba02d2018-05-20 16:22:43 -0700521 /// `{ ... }`
Alex Crichton44bffbc2017-05-19 17:51:59 -0700522 Brace,
David Tolnay82ba02d2018-05-20 16:22:43 -0700523 /// `[ ... ]`
Alex Crichton44bffbc2017-05-19 17:51:59 -0700524 Bracket,
David Tolnay82ba02d2018-05-20 16:22:43 -0700525 /// `Ø ... Ø`
526 ///
527 /// An implicit delimiter, that may, for example, appear around tokens
528 /// coming from a "macro variable" `$var`. It is important to preserve
529 /// operator priorities in cases like `$var * 3` where `$var` is `1 + 2`.
530 /// Implicit delimiters may not survive roundtrip of a token stream through
531 /// a string.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700532 None,
533}
534
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700535impl Group {
David Tolnayf14813f2018-09-08 17:14:07 -0700536 fn _new(inner: imp::Group) -> Self {
David Tolnay4453fcc2019-01-16 12:15:01 -0800537 Group { inner: inner }
David Tolnayf14813f2018-09-08 17:14:07 -0700538 }
539
David Tolnayaef075b2019-01-16 16:29:18 -0800540 fn _new_stable(inner: fallback::Group) -> Self {
David Tolnayf14813f2018-09-08 17:14:07 -0700541 Group {
542 inner: inner.into(),
543 }
544 }
545
David Tolnay82ba02d2018-05-20 16:22:43 -0700546 /// Creates a new `Group` with the given delimiter and token stream.
547 ///
548 /// This constructor will set the span for this group to
549 /// `Span::call_site()`. To change the span you can use the `set_span`
550 /// method below.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700551 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
552 Group {
David Tolnayf14813f2018-09-08 17:14:07 -0700553 inner: imp::Group::new(delimiter, stream.inner),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700554 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700555 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700556
David Tolnay82ba02d2018-05-20 16:22:43 -0700557 /// Returns the delimiter of this `Group`
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700558 pub fn delimiter(&self) -> Delimiter {
David Tolnayf14813f2018-09-08 17:14:07 -0700559 self.inner.delimiter()
Alex Crichton44bffbc2017-05-19 17:51:59 -0700560 }
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700561
David Tolnay82ba02d2018-05-20 16:22:43 -0700562 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
563 ///
564 /// Note that the returned token stream does not include the delimiter
565 /// returned above.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700566 pub fn stream(&self) -> TokenStream {
David Tolnayf14813f2018-09-08 17:14:07 -0700567 TokenStream::_new(self.inner.stream())
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700568 }
569
David Tolnay82ba02d2018-05-20 16:22:43 -0700570 /// Returns the span for the delimiters of this token stream, spanning the
571 /// entire `Group`.
David Tolnayf14813f2018-09-08 17:14:07 -0700572 ///
573 /// ```text
574 /// pub fn span(&self) -> Span {
575 /// ^^^^^^^
576 /// ```
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700577 pub fn span(&self) -> Span {
David Tolnayf14813f2018-09-08 17:14:07 -0700578 Span::_new(self.inner.span())
579 }
580
581 /// Returns the span pointing to the opening delimiter of this group.
582 ///
583 /// ```text
584 /// pub fn span_open(&self) -> Span {
585 /// ^
586 /// ```
587 #[cfg(procmacro2_semver_exempt)]
588 pub fn span_open(&self) -> Span {
589 Span::_new(self.inner.span_open())
590 }
591
592 /// Returns the span pointing to the closing delimiter of this group.
593 ///
594 /// ```text
595 /// pub fn span_close(&self) -> Span {
596 /// ^
597 /// ```
598 #[cfg(procmacro2_semver_exempt)]
599 pub fn span_close(&self) -> Span {
600 Span::_new(self.inner.span_close())
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700601 }
602
David Tolnay82ba02d2018-05-20 16:22:43 -0700603 /// Configures the span for this `Group`'s delimiters, but not its internal
604 /// tokens.
605 ///
606 /// This method will **not** set the span of all the internal tokens spanned
607 /// by this group, but rather it will only set the span of the delimiter
608 /// tokens at the level of the `Group`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700609 pub fn set_span(&mut self, span: Span) {
David Tolnayf14813f2018-09-08 17:14:07 -0700610 self.inner.set_span(span.inner)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700611 }
612}
613
David Tolnay82ba02d2018-05-20 16:22:43 -0700614/// Prints the group as a string that should be losslessly convertible back
615/// into the same group (modulo spans), except for possibly `TokenTree::Group`s
616/// with `Delimiter::None` delimiters.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700617impl fmt::Display for Group {
David Tolnayf14813f2018-09-08 17:14:07 -0700618 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
619 fmt::Display::fmt(&self.inner, formatter)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700620 }
621}
622
David Tolnay034205f2018-04-22 16:45:28 -0700623impl fmt::Debug for Group {
David Tolnayf14813f2018-09-08 17:14:07 -0700624 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
625 fmt::Debug::fmt(&self.inner, formatter)
David Tolnay034205f2018-04-22 16:45:28 -0700626 }
627}
628
David Tolnay82ba02d2018-05-20 16:22:43 -0700629/// An `Punct` is an single punctuation character like `+`, `-` or `#`.
630///
631/// Multicharacter operators like `+=` are represented as two instances of
632/// `Punct` with different forms of `Spacing` returned.
Alex Crichtonf3888432018-05-16 09:11:05 -0700633#[derive(Clone)]
634pub struct Punct {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700635 op: char,
636 spacing: Spacing,
637 span: Span,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700638}
639
David Tolnay82ba02d2018-05-20 16:22:43 -0700640/// Whether an `Punct` is followed immediately by another `Punct` or followed by
641/// another token or whitespace.
Lukas Kalbertodteb3f9302017-08-20 18:58:41 +0200642#[derive(Copy, Clone, Debug, Eq, PartialEq)]
Alex Crichton1a7f7622017-07-05 17:47:15 -0700643pub enum Spacing {
David Tolnay82ba02d2018-05-20 16:22:43 -0700644 /// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700645 Alone,
David Tolnay82ba02d2018-05-20 16:22:43 -0700646 /// E.g. `+` is `Joint` in `+=` or `'#`.
647 ///
648 /// Additionally, single quote `'` can join with identifiers to form
649 /// lifetimes `'ident`.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700650 Joint,
651}
652
Alex Crichtonf3888432018-05-16 09:11:05 -0700653impl Punct {
David Tolnay82ba02d2018-05-20 16:22:43 -0700654 /// Creates a new `Punct` from the given character and spacing.
655 ///
656 /// The `ch` argument must be a valid punctuation character permitted by the
657 /// language, otherwise the function will panic.
658 ///
659 /// The returned `Punct` will have the default span of `Span::call_site()`
660 /// which can be further configured with the `set_span` method below.
Alex Crichtonf3888432018-05-16 09:11:05 -0700661 pub fn new(op: char, spacing: Spacing) -> Punct {
662 Punct {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700663 op: op,
664 spacing: spacing,
665 span: Span::call_site(),
666 }
667 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700668
David Tolnay82ba02d2018-05-20 16:22:43 -0700669 /// Returns the value of this punctuation character as `char`.
Alex Crichtonf3888432018-05-16 09:11:05 -0700670 pub fn as_char(&self) -> char {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700671 self.op
672 }
673
David Tolnay82ba02d2018-05-20 16:22:43 -0700674 /// Returns the spacing of this punctuation character, indicating whether
675 /// it's immediately followed by another `Punct` in the token stream, so
676 /// they can potentially be combined into a multicharacter operator
677 /// (`Joint`), or it's followed by some other token or whitespace (`Alone`)
678 /// so the operator has certainly ended.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700679 pub fn spacing(&self) -> Spacing {
680 self.spacing
681 }
682
David Tolnay82ba02d2018-05-20 16:22:43 -0700683 /// Returns the span for this punctuation character.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700684 pub fn span(&self) -> Span {
685 self.span
686 }
687
David Tolnay82ba02d2018-05-20 16:22:43 -0700688 /// Configure the span for this punctuation character.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700689 pub fn set_span(&mut self, span: Span) {
690 self.span = span;
691 }
692}
693
David Tolnay82ba02d2018-05-20 16:22:43 -0700694/// Prints the punctuation character as a string that should be losslessly
695/// convertible back into the same character.
Alex Crichtonf3888432018-05-16 09:11:05 -0700696impl fmt::Display for Punct {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700697 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
698 self.op.fmt(f)
699 }
700}
701
Alex Crichtonf3888432018-05-16 09:11:05 -0700702impl fmt::Debug for Punct {
David Tolnay034205f2018-04-22 16:45:28 -0700703 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonf3888432018-05-16 09:11:05 -0700704 let mut debug = fmt.debug_struct("Punct");
David Tolnay034205f2018-04-22 16:45:28 -0700705 debug.field("op", &self.op);
706 debug.field("spacing", &self.spacing);
David Tolnayfd8cdc82019-01-19 19:23:59 -0800707 imp::debug_span_field_if_nontrivial(&mut debug, self.span.inner);
David Tolnay034205f2018-04-22 16:45:28 -0700708 debug.finish()
709 }
710}
711
David Tolnay8b71dac2018-05-20 17:07:47 -0700712/// A word of Rust code, which may be a keyword or legal variable name.
713///
714/// An identifier consists of at least one Unicode code point, the first of
715/// which has the XID_Start property and the rest of which have the XID_Continue
716/// property.
717///
718/// - The empty string is not an identifier. Use `Option<Ident>`.
719/// - A lifetime is not an identifier. Use `syn::Lifetime` instead.
720///
721/// An identifier constructed with `Ident::new` is permitted to be a Rust
David Tolnayc239f032018-11-11 12:57:09 -0800722/// keyword, though parsing one through its [`Parse`] implementation rejects
723/// Rust keywords. Use `input.call(Ident::parse_any)` when parsing to match the
David Tolnay8b71dac2018-05-20 17:07:47 -0700724/// behaviour of `Ident::new`.
725///
David Tolnayc239f032018-11-11 12:57:09 -0800726/// [`Parse`]: https://docs.rs/syn/0.15/syn/parse/trait.Parse.html
David Tolnay8b71dac2018-05-20 17:07:47 -0700727///
728/// # Examples
729///
730/// A new ident can be created from a string using the `Ident::new` function.
731/// A span must be provided explicitly which governs the name resolution
732/// behavior of the resulting identifier.
733///
David Tolnay7a964732019-01-19 19:03:20 -0800734/// ```edition2018
David Tolnay8b71dac2018-05-20 17:07:47 -0700735/// use proc_macro2::{Ident, Span};
736///
737/// fn main() {
738/// let call_ident = Ident::new("calligraphy", Span::call_site());
739///
740/// println!("{}", call_ident);
741/// }
742/// ```
743///
744/// An ident can be interpolated into a token stream using the `quote!` macro.
745///
David Tolnay7a964732019-01-19 19:03:20 -0800746/// ```edition2018
David Tolnay8b71dac2018-05-20 17:07:47 -0700747/// use proc_macro2::{Ident, Span};
David Tolnay7a964732019-01-19 19:03:20 -0800748/// use quote::quote;
David Tolnay8b71dac2018-05-20 17:07:47 -0700749///
750/// fn main() {
751/// let ident = Ident::new("demo", Span::call_site());
752///
753/// // Create a variable binding whose name is this ident.
754/// let expanded = quote! { let #ident = 10; };
755///
756/// // Create a variable binding with a slightly different name.
757/// let temp_ident = Ident::new(&format!("new_{}", ident), Span::call_site());
758/// let expanded = quote! { let #temp_ident = 10; };
759/// }
760/// ```
761///
762/// A string representation of the ident is available through the `to_string()`
763/// method.
764///
David Tolnay7a964732019-01-19 19:03:20 -0800765/// ```edition2018
David Tolnay8b71dac2018-05-20 17:07:47 -0700766/// # use proc_macro2::{Ident, Span};
767/// #
768/// # let ident = Ident::new("another_identifier", Span::call_site());
769/// #
770/// // Examine the ident as a string.
771/// let ident_string = ident.to_string();
772/// if ident_string.len() > 60 {
773/// println!("Very long identifier: {}", ident_string)
774/// }
775/// ```
Alex Crichtonf3888432018-05-16 09:11:05 -0700776#[derive(Clone)]
777pub struct Ident {
778 inner: imp::Ident,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700779 _marker: marker::PhantomData<Rc<()>>,
780}
781
Alex Crichtonf3888432018-05-16 09:11:05 -0700782impl Ident {
783 fn _new(inner: imp::Ident) -> Ident {
784 Ident {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700785 inner: inner,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700786 _marker: marker::PhantomData,
787 }
788 }
789
David Tolnay82ba02d2018-05-20 16:22:43 -0700790 /// Creates a new `Ident` with the given `string` as well as the specified
791 /// `span`.
792 ///
793 /// The `string` argument must be a valid identifier permitted by the
794 /// language, otherwise the function will panic.
795 ///
796 /// Note that `span`, currently in rustc, configures the hygiene information
797 /// for this identifier.
798 ///
799 /// As of this time `Span::call_site()` explicitly opts-in to "call-site"
800 /// hygiene meaning that identifiers created with this span will be resolved
801 /// as if they were written directly at the location of the macro call, and
802 /// other code at the macro call site will be able to refer to them as well.
803 ///
804 /// Later spans like `Span::def_site()` will allow to opt-in to
805 /// "definition-site" hygiene meaning that identifiers created with this
806 /// span will be resolved at the location of the macro definition and other
807 /// code at the macro call site will not be able to refer to them.
808 ///
809 /// Due to the current importance of hygiene this constructor, unlike other
810 /// tokens, requires a `Span` to be specified at construction.
David Tolnay8b71dac2018-05-20 17:07:47 -0700811 ///
812 /// # Panics
813 ///
814 /// Panics if the input string is neither a keyword nor a legal variable
815 /// name.
Alex Crichtonf3888432018-05-16 09:11:05 -0700816 pub fn new(string: &str, span: Span) -> Ident {
817 Ident::_new(imp::Ident::new(string, span.inner))
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700818 }
819
David Tolnay82ba02d2018-05-20 16:22:43 -0700820 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
David Tolnaya01ca8e2018-06-04 00:55:28 -0700821 ///
822 /// This method is semver exempt and not exposed by default.
Alex Crichtonf3888432018-05-16 09:11:05 -0700823 #[cfg(procmacro2_semver_exempt)]
824 pub fn new_raw(string: &str, span: Span) -> Ident {
825 Ident::_new_raw(string, span)
826 }
827
828 fn _new_raw(string: &str, span: Span) -> Ident {
829 Ident::_new(imp::Ident::new_raw(string, span.inner))
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700830 }
831
David Tolnay82ba02d2018-05-20 16:22:43 -0700832 /// Returns the span of this `Ident`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700833 pub fn span(&self) -> Span {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700834 Span::_new(self.inner.span())
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700835 }
836
David Tolnay82ba02d2018-05-20 16:22:43 -0700837 /// Configures the span of this `Ident`, possibly changing its hygiene
838 /// context.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700839 pub fn set_span(&mut self, span: Span) {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700840 self.inner.set_span(span.inner);
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700841 }
842}
843
Alex Crichtonf3888432018-05-16 09:11:05 -0700844impl PartialEq for Ident {
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700845 fn eq(&self, other: &Ident) -> bool {
David Tolnayc0b0f2e2018-09-02 17:56:08 -0700846 self.inner == other.inner
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700847 }
848}
849
David Tolnayc0bbcc52018-05-18 10:51:04 -0700850impl<T> PartialEq<T> for Ident
851where
852 T: ?Sized + AsRef<str>,
853{
854 fn eq(&self, other: &T) -> bool {
David Tolnayc0b0f2e2018-09-02 17:56:08 -0700855 self.inner == other
David Tolnayc0bbcc52018-05-18 10:51:04 -0700856 }
857}
858
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700859impl Eq for Ident {}
Alex Crichtonf3888432018-05-16 09:11:05 -0700860
861impl PartialOrd for Ident {
862 fn partial_cmp(&self, other: &Ident) -> Option<Ordering> {
863 Some(self.cmp(other))
864 }
865}
866
867impl Ord for Ident {
868 fn cmp(&self, other: &Ident) -> Ordering {
869 self.to_string().cmp(&other.to_string())
870 }
871}
872
873impl Hash for Ident {
874 fn hash<H: Hasher>(&self, hasher: &mut H) {
875 self.to_string().hash(hasher)
876 }
877}
878
David Tolnay82ba02d2018-05-20 16:22:43 -0700879/// Prints the identifier as a string that should be losslessly convertible back
880/// into the same identifier.
Alex Crichtonf3888432018-05-16 09:11:05 -0700881impl fmt::Display for Ident {
882 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
883 self.inner.fmt(f)
884 }
885}
886
887impl fmt::Debug for Ident {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700888 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
889 self.inner.fmt(f)
890 }
891}
892
David Tolnay82ba02d2018-05-20 16:22:43 -0700893/// A literal string (`"hello"`), byte string (`b"hello"`), character (`'a'`),
894/// byte character (`b'a'`), an integer or floating point number with or without
895/// a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
896///
897/// Boolean literals like `true` and `false` do not belong here, they are
898/// `Ident`s.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700899#[derive(Clone)]
900pub struct Literal {
901 inner: imp::Literal,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700902 _marker: marker::PhantomData<Rc<()>>,
903}
904
David Tolnay82ba02d2018-05-20 16:22:43 -0700905macro_rules! suffixed_int_literals {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700906 ($($name:ident => $kind:ident,)*) => ($(
David Tolnay82ba02d2018-05-20 16:22:43 -0700907 /// Creates a new suffixed integer literal with the specified value.
908 ///
909 /// This function will create an integer like `1u32` where the integer
910 /// value specified is the first part of the token and the integral is
911 /// also suffixed at the end. Literals created from negative numbers may
912 /// not survive rountrips through `TokenStream` or strings and may be
913 /// broken into two tokens (`-` and positive literal).
914 ///
915 /// Literals created through this method have the `Span::call_site()`
916 /// span by default, which can be configured with the `set_span` method
917 /// below.
918 pub fn $name(n: $kind) -> Literal {
919 Literal::_new(imp::Literal::$name(n))
920 }
921 )*)
922}
923
924macro_rules! unsuffixed_int_literals {
925 ($($name:ident => $kind:ident,)*) => ($(
926 /// Creates a new unsuffixed integer literal with the specified value.
927 ///
928 /// This function will create an integer like `1` where the integer
929 /// value specified is the first part of the token. No suffix is
930 /// specified on this token, meaning that invocations like
931 /// `Literal::i8_unsuffixed(1)` are equivalent to
932 /// `Literal::u32_unsuffixed(1)`. Literals created from negative numbers
933 /// may not survive rountrips through `TokenStream` or strings and may
934 /// be broken into two tokens (`-` and positive literal).
935 ///
936 /// Literals created through this method have the `Span::call_site()`
937 /// span by default, which can be configured with the `set_span` method
938 /// below.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700939 pub fn $name(n: $kind) -> Literal {
Alex Crichtona914a612018-04-04 07:48:44 -0700940 Literal::_new(imp::Literal::$name(n))
Alex Crichton1a7f7622017-07-05 17:47:15 -0700941 }
942 )*)
943}
944
Alex Crichton852d53d2017-05-19 19:25:08 -0700945impl Literal {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700946 fn _new(inner: imp::Literal) -> Literal {
947 Literal {
948 inner: inner,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700949 _marker: marker::PhantomData,
950 }
Alex Crichton1a7f7622017-07-05 17:47:15 -0700951 }
952
David Tolnayaef075b2019-01-16 16:29:18 -0800953 fn _new_stable(inner: fallback::Literal) -> Literal {
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700954 Literal {
955 inner: inner.into(),
956 _marker: marker::PhantomData,
957 }
958 }
959
David Tolnay82ba02d2018-05-20 16:22:43 -0700960 suffixed_int_literals! {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700961 u8_suffixed => u8,
962 u16_suffixed => u16,
963 u32_suffixed => u32,
964 u64_suffixed => u64,
965 usize_suffixed => usize,
966 i8_suffixed => i8,
967 i16_suffixed => i16,
968 i32_suffixed => i32,
969 i64_suffixed => i64,
970 isize_suffixed => isize,
David Tolnay82ba02d2018-05-20 16:22:43 -0700971 }
Alex Crichton1a7f7622017-07-05 17:47:15 -0700972
Alex Crichton69385662018-11-08 06:30:04 -0800973 #[cfg(u128)]
974 suffixed_int_literals! {
975 u128_suffixed => u128,
976 i128_suffixed => i128,
977 }
978
David Tolnay82ba02d2018-05-20 16:22:43 -0700979 unsuffixed_int_literals! {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700980 u8_unsuffixed => u8,
981 u16_unsuffixed => u16,
982 u32_unsuffixed => u32,
983 u64_unsuffixed => u64,
984 usize_unsuffixed => usize,
985 i8_unsuffixed => i8,
986 i16_unsuffixed => i16,
987 i32_unsuffixed => i32,
988 i64_unsuffixed => i64,
989 isize_unsuffixed => isize,
Alex Crichton1a7f7622017-07-05 17:47:15 -0700990 }
991
Alex Crichton69385662018-11-08 06:30:04 -0800992 #[cfg(u128)]
993 unsuffixed_int_literals! {
994 u128_unsuffixed => u128,
995 i128_unsuffixed => i128,
996 }
997
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700998 pub fn f64_unsuffixed(f: f64) -> Literal {
999 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -07001000 Literal::_new(imp::Literal::f64_unsuffixed(f))
Alex Crichton1a7f7622017-07-05 17:47:15 -07001001 }
1002
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001003 pub fn f64_suffixed(f: f64) -> Literal {
1004 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -07001005 Literal::_new(imp::Literal::f64_suffixed(f))
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001006 }
1007
David Tolnay82ba02d2018-05-20 16:22:43 -07001008 /// Creates a new unsuffixed floating-point literal.
1009 ///
1010 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1011 /// the float's value is emitted directly into the token but no suffix is
1012 /// used, so it may be inferred to be a `f64` later in the compiler.
1013 /// Literals created from negative numbers may not survive rountrips through
1014 /// `TokenStream` or strings and may be broken into two tokens (`-` and
1015 /// positive literal).
1016 ///
1017 /// # Panics
1018 ///
1019 /// This function requires that the specified float is finite, for example
1020 /// if it is infinity or NaN this function will panic.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001021 pub fn f32_unsuffixed(f: f32) -> Literal {
1022 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -07001023 Literal::_new(imp::Literal::f32_unsuffixed(f))
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001024 }
1025
1026 pub fn f32_suffixed(f: f32) -> Literal {
1027 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -07001028 Literal::_new(imp::Literal::f32_suffixed(f))
Alex Crichton1a7f7622017-07-05 17:47:15 -07001029 }
1030
1031 pub fn string(string: &str) -> Literal {
Alex Crichtona914a612018-04-04 07:48:44 -07001032 Literal::_new(imp::Literal::string(string))
Alex Crichton1a7f7622017-07-05 17:47:15 -07001033 }
1034
1035 pub fn character(ch: char) -> Literal {
Alex Crichtona914a612018-04-04 07:48:44 -07001036 Literal::_new(imp::Literal::character(ch))
Alex Crichton76a5cc82017-05-23 07:01:44 -07001037 }
1038
Alex Crichton9c2fb0a2017-05-26 08:49:31 -07001039 pub fn byte_string(s: &[u8]) -> Literal {
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001040 Literal::_new(imp::Literal::byte_string(s))
Alex Crichton852d53d2017-05-19 19:25:08 -07001041 }
Alex Crichton76a5cc82017-05-23 07:01:44 -07001042
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001043 pub fn span(&self) -> Span {
Alex Crichtonb2c94622018-04-04 07:36:41 -07001044 Span::_new(self.inner.span())
Alex Crichton1a7f7622017-07-05 17:47:15 -07001045 }
1046
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001047 pub fn set_span(&mut self, span: Span) {
Alex Crichtonb2c94622018-04-04 07:36:41 -07001048 self.inner.set_span(span.inner);
Alex Crichton31316622017-05-26 12:54:47 -07001049 }
Alex Crichton852d53d2017-05-19 19:25:08 -07001050}
1051
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001052impl fmt::Debug for Literal {
1053 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1054 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001055 }
1056}
David Tolnaycb1b85f2017-06-03 16:40:35 -07001057
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001058impl fmt::Display for Literal {
1059 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1060 self.inner.fmt(f)
1061 }
1062}
1063
David Tolnay82ba02d2018-05-20 16:22:43 -07001064/// Public implementation details for the `TokenStream` type, such as iterators.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001065pub mod token_stream {
1066 use std::fmt;
1067 use std::marker;
1068 use std::rc::Rc;
1069
David Tolnay48ea5042018-04-23 19:17:35 -07001070 use imp;
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001071 pub use TokenStream;
David Tolnayb28f38a2018-03-31 22:02:29 +02001072 use TokenTree;
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001073
David Tolnay82ba02d2018-05-20 16:22:43 -07001074 /// An iterator over `TokenStream`'s `TokenTree`s.
1075 ///
1076 /// The iteration is "shallow", e.g. the iterator doesn't recurse into
1077 /// delimited groups, and returns whole groups as token trees.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001078 pub struct IntoIter {
1079 inner: imp::TokenTreeIter,
1080 _marker: marker::PhantomData<Rc<()>>,
1081 }
1082
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001083 impl Iterator for IntoIter {
1084 type Item = TokenTree;
1085
1086 fn next(&mut self) -> Option<TokenTree> {
1087 self.inner.next()
1088 }
1089 }
1090
1091 impl fmt::Debug for IntoIter {
1092 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1093 self.inner.fmt(f)
1094 }
1095 }
1096
1097 impl IntoIterator for TokenStream {
1098 type Item = TokenTree;
1099 type IntoIter = IntoIter;
1100
1101 fn into_iter(self) -> IntoIter {
1102 IntoIter {
1103 inner: self.inner.into_iter(),
1104 _marker: marker::PhantomData,
1105 }
1106 }
1107 }
1108}