blob: 299f9b8c5080a78f73d70f64e965ef34f5d82f19 [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 Tolnay60b48bd2018-08-13 11:00:42 -070046#![doc(html_root_url = "https://docs.rs/proc-macro2/0.4.12")]
David Tolnay5a556cf2018-08-12 13:49:39 -070047#![cfg_attr(
48 feature = "nightly",
49 feature(proc_macro_raw_ident, proc_macro_span)
50)]
Alex Crichtoncbec8ec2017-06-02 13:19:33 -070051
Alex Crichton53548482018-08-11 21:54:05 -070052#[cfg(use_proc_macro)]
Alex Crichton44bffbc2017-05-19 17:51:59 -070053extern crate proc_macro;
David Tolnayb1032662017-05-31 15:52:28 -070054extern crate unicode_xid;
Alex Crichton44bffbc2017-05-19 17:51:59 -070055
Alex Crichtonf3888432018-05-16 09:11:05 -070056use std::cmp::Ordering;
Alex Crichton44bffbc2017-05-19 17:51:59 -070057use std::fmt;
Alex Crichtonf3888432018-05-16 09:11:05 -070058use std::hash::{Hash, Hasher};
Alex Crichton44bffbc2017-05-19 17:51:59 -070059use std::iter::FromIterator;
Alex Crichtonaf5bad42018-03-27 14:45:10 -070060use std::marker;
61use std::rc::Rc;
62use std::str::FromStr;
Alex Crichton44bffbc2017-05-19 17:51:59 -070063
David Tolnayb1032662017-05-31 15:52:28 -070064#[macro_use]
David Tolnayb1032662017-05-31 15:52:28 -070065mod strnom;
Alex Crichton30a4e9e2018-04-27 17:02:19 -070066mod stable;
David Tolnayb1032662017-05-31 15:52:28 -070067
David Tolnayd66ecf62018-01-02 20:05:42 -080068#[cfg(not(feature = "nightly"))]
Alex Crichton30a4e9e2018-04-27 17:02:19 -070069use stable as imp;
Alex Crichtonb15c6352017-05-19 19:36:36 -070070#[path = "unstable.rs"]
David Tolnayd66ecf62018-01-02 20:05:42 -080071#[cfg(feature = "nightly")]
Alex Crichton44bffbc2017-05-19 17:51:59 -070072mod imp;
73
David Tolnay82ba02d2018-05-20 16:22:43 -070074/// An abstract stream of tokens, or more concretely a sequence of token trees.
75///
76/// This type provides interfaces for iterating over token trees and for
77/// collecting token trees into one stream.
78///
79/// Token stream is both the input and output of `#[proc_macro]`,
80/// `#[proc_macro_attribute]` and `#[proc_macro_derive]` definitions.
David Tolnaycb1b85f2017-06-03 16:40:35 -070081#[derive(Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -070082pub struct TokenStream {
83 inner: imp::TokenStream,
84 _marker: marker::PhantomData<Rc<()>>,
85}
Alex Crichton44bffbc2017-05-19 17:51:59 -070086
David Tolnay82ba02d2018-05-20 16:22:43 -070087/// Error returned from `TokenStream::from_str`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -070088pub struct LexError {
89 inner: imp::LexError,
90 _marker: marker::PhantomData<Rc<()>>,
91}
92
93impl TokenStream {
94 fn _new(inner: imp::TokenStream) -> TokenStream {
95 TokenStream {
96 inner: inner,
97 _marker: marker::PhantomData,
98 }
99 }
100
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700101 fn _new_stable(inner: stable::TokenStream) -> TokenStream {
102 TokenStream {
103 inner: inner.into(),
104 _marker: marker::PhantomData,
105 }
106 }
107
David Tolnay82ba02d2018-05-20 16:22:43 -0700108 /// Returns an empty `TokenStream` containing no token trees.
David Tolnayc3bb4592018-05-28 20:09:44 -0700109 pub fn new() -> TokenStream {
110 TokenStream::_new(imp::TokenStream::new())
111 }
112
113 #[deprecated(since = "0.4.4", note = "please use TokenStream::new")]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700114 pub fn empty() -> TokenStream {
David Tolnayc3bb4592018-05-28 20:09:44 -0700115 TokenStream::new()
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700116 }
117
David Tolnay82ba02d2018-05-20 16:22:43 -0700118 /// Checks if this `TokenStream` is empty.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700119 pub fn is_empty(&self) -> bool {
120 self.inner.is_empty()
121 }
122}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700123
Árpád Goretity4f74b682018-07-14 00:47:51 +0200124/// `TokenStream::default()` returns an empty stream,
125/// i.e. this is equivalent with `TokenStream::new()`.
126impl Default for TokenStream {
127 fn default() -> Self {
128 TokenStream::new()
129 }
130}
131
David Tolnay82ba02d2018-05-20 16:22:43 -0700132/// Attempts to break the string into tokens and parse those tokens into a token
133/// stream.
134///
135/// May fail for a number of reasons, for example, if the string contains
136/// unbalanced delimiters or characters not existing in the language.
137///
138/// NOTE: Some errors may cause panics instead of returning `LexError`. We
139/// reserve the right to change these errors into `LexError`s later.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700140impl FromStr for TokenStream {
141 type Err = LexError;
142
143 fn from_str(src: &str) -> Result<TokenStream, LexError> {
David Tolnayb28f38a2018-03-31 22:02:29 +0200144 let e = src.parse().map_err(|e| LexError {
145 inner: e,
146 _marker: marker::PhantomData,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700147 })?;
148 Ok(TokenStream::_new(e))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700149 }
150}
151
Alex Crichton53548482018-08-11 21:54:05 -0700152#[cfg(use_proc_macro)]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700153impl From<proc_macro::TokenStream> for TokenStream {
154 fn from(inner: proc_macro::TokenStream) -> TokenStream {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700155 TokenStream::_new(inner.into())
Alex Crichton44bffbc2017-05-19 17:51:59 -0700156 }
157}
158
Alex Crichton53548482018-08-11 21:54:05 -0700159#[cfg(use_proc_macro)]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700160impl From<TokenStream> for proc_macro::TokenStream {
161 fn from(inner: TokenStream) -> proc_macro::TokenStream {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700162 inner.inner.into()
Alex Crichton44bffbc2017-05-19 17:51:59 -0700163 }
164}
165
Alex Crichtonf3888432018-05-16 09:11:05 -0700166impl Extend<TokenTree> for TokenStream {
167 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, streams: I) {
168 self.inner.extend(streams)
169 }
170}
171
David Tolnay82ba02d2018-05-20 16:22:43 -0700172/// Collects a number of token trees into a single stream.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700173impl FromIterator<TokenTree> for TokenStream {
174 fn from_iter<I: IntoIterator<Item = TokenTree>>(streams: I) -> Self {
175 TokenStream::_new(streams.into_iter().collect())
Alex Crichton44bffbc2017-05-19 17:51:59 -0700176 }
177}
178
David Tolnay82ba02d2018-05-20 16:22:43 -0700179/// Prints the token stream as a string that is supposed to be losslessly
180/// convertible back into the same token stream (modulo spans), except for
181/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
182/// numeric literals.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700183impl fmt::Display for TokenStream {
184 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
185 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700186 }
187}
188
David Tolnay82ba02d2018-05-20 16:22:43 -0700189/// Prints token in a form convenient for debugging.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700190impl fmt::Debug for TokenStream {
191 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
192 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700193 }
194}
195
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700196impl fmt::Debug for LexError {
197 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
198 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700199 }
200}
201
Nika Layzellb35a9a32017-12-30 14:34:35 -0500202// Returned by reference, so we can't easily wrap it.
David Tolnay1ebe3972018-01-02 20:14:20 -0800203#[cfg(procmacro2_semver_exempt)]
Nika Layzellb35a9a32017-12-30 14:34:35 -0500204pub use imp::FileName;
205
David Tolnay82ba02d2018-05-20 16:22:43 -0700206/// The source file of a given `Span`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700207///
208/// This type is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800209#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500210#[derive(Clone, PartialEq, Eq)]
211pub struct SourceFile(imp::SourceFile);
212
David Tolnay1ebe3972018-01-02 20:14:20 -0800213#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500214impl SourceFile {
David Tolnay82ba02d2018-05-20 16:22:43 -0700215 /// Get the path to this source file.
216 ///
217 /// ### Note
218 ///
219 /// If the code span associated with this `SourceFile` was generated by an
220 /// external macro, this may not be an actual path on the filesystem. Use
221 /// [`is_real`] to check.
222 ///
223 /// Also note that even if `is_real` returns `true`, if
224 /// `--remap-path-prefix` was passed on the command line, the path as given
225 /// may not actually be valid.
226 ///
227 /// [`is_real`]: #method.is_real
Nika Layzellb35a9a32017-12-30 14:34:35 -0500228 pub fn path(&self) -> &FileName {
229 self.0.path()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500230 }
231
David Tolnay82ba02d2018-05-20 16:22:43 -0700232 /// Returns `true` if this source file is a real source file, and not
233 /// generated by an external macro's expansion.
Nika Layzellf8d5f212017-12-11 14:07:02 -0500234 pub fn is_real(&self) -> bool {
235 self.0.is_real()
236 }
237}
238
David Tolnay1ebe3972018-01-02 20:14:20 -0800239#[cfg(procmacro2_semver_exempt)]
Nika Layzellb35a9a32017-12-30 14:34:35 -0500240impl AsRef<FileName> for SourceFile {
241 fn as_ref(&self) -> &FileName {
242 self.0.path()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500243 }
244}
245
David Tolnay1ebe3972018-01-02 20:14:20 -0800246#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500247impl fmt::Debug for SourceFile {
248 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
249 self.0.fmt(f)
250 }
251}
252
David Tolnay82ba02d2018-05-20 16:22:43 -0700253/// A line-column pair representing the start or end of a `Span`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700254///
255/// This type is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800256#[cfg(procmacro2_semver_exempt)]
Nika Layzell1ecb6ce2017-12-30 14:34:05 -0500257pub struct LineColumn {
David Tolnay82ba02d2018-05-20 16:22:43 -0700258 /// The 1-indexed line in the source file on which the span starts or ends
259 /// (inclusive).
Nika Layzell1ecb6ce2017-12-30 14:34:05 -0500260 pub line: usize,
David Tolnay82ba02d2018-05-20 16:22:43 -0700261 /// The 0-indexed column (in UTF-8 characters) in the source file on which
262 /// the span starts or ends (inclusive).
Nika Layzell1ecb6ce2017-12-30 14:34:05 -0500263 pub column: usize,
264}
Nika Layzellf8d5f212017-12-11 14:07:02 -0500265
David Tolnay82ba02d2018-05-20 16:22:43 -0700266/// A region of source code, along with macro expansion information.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700267#[derive(Copy, Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700268pub struct Span {
269 inner: imp::Span,
270 _marker: marker::PhantomData<Rc<()>>,
271}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700272
Alex Crichton44bffbc2017-05-19 17:51:59 -0700273impl Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700274 fn _new(inner: imp::Span) -> Span {
275 Span {
276 inner: inner,
277 _marker: marker::PhantomData,
278 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700279 }
Alex Crichtone6085b72017-11-21 07:24:25 -0800280
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700281 fn _new_stable(inner: stable::Span) -> Span {
282 Span {
283 inner: inner.into(),
284 _marker: marker::PhantomData,
285 }
286 }
287
David Tolnay82ba02d2018-05-20 16:22:43 -0700288 /// The span of the invocation of the current procedural macro.
289 ///
290 /// Identifiers created with this span will be resolved as if they were
291 /// written directly at the macro call location (call-site hygiene) and
292 /// other code at the macro call site will be able to refer to them as well.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700293 pub fn call_site() -> Span {
294 Span::_new(imp::Span::call_site())
295 }
296
David Tolnay82ba02d2018-05-20 16:22:43 -0700297 /// A span that resolves at the macro definition site.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700298 ///
299 /// This method is semver exempt and not exposed by default.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700300 #[cfg(procmacro2_semver_exempt)]
Alex Crichtone6085b72017-11-21 07:24:25 -0800301 pub fn def_site() -> Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700302 Span::_new(imp::Span::def_site())
Alex Crichtone6085b72017-11-21 07:24:25 -0800303 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500304
David Tolnay4e8e3972018-01-05 18:10:22 -0800305 /// Creates a new span with the same line/column information as `self` but
306 /// that resolves symbols as though it were at `other`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700307 ///
308 /// This method is semver exempt and not exposed by default.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700309 #[cfg(procmacro2_semver_exempt)]
David Tolnay4e8e3972018-01-05 18:10:22 -0800310 pub fn resolved_at(&self, other: Span) -> Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700311 Span::_new(self.inner.resolved_at(other.inner))
David Tolnay4e8e3972018-01-05 18:10:22 -0800312 }
313
314 /// Creates a new span with the same name resolution behavior as `self` but
315 /// with the line/column information of `other`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700316 ///
317 /// This method is semver exempt and not exposed by default.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700318 #[cfg(procmacro2_semver_exempt)]
David Tolnay4e8e3972018-01-05 18:10:22 -0800319 pub fn located_at(&self, other: Span) -> Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700320 Span::_new(self.inner.located_at(other.inner))
David Tolnay4e8e3972018-01-05 18:10:22 -0800321 }
322
David Tolnayd66ecf62018-01-02 20:05:42 -0800323 /// This method is only available when the `"nightly"` feature is enabled.
Alex Crichton53548482018-08-11 21:54:05 -0700324 #[cfg(all(feature = "nightly", use_proc_macro))]
David Tolnay16a17202017-12-31 10:47:24 -0500325 pub fn unstable(self) -> proc_macro::Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700326 self.inner.unstable()
David Tolnay16a17202017-12-31 10:47:24 -0500327 }
328
David Tolnay82ba02d2018-05-20 16:22:43 -0700329 /// The original source file into which this span points.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700330 ///
331 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800332 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500333 pub fn source_file(&self) -> SourceFile {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700334 SourceFile(self.inner.source_file())
Nika Layzellf8d5f212017-12-11 14:07:02 -0500335 }
336
David Tolnay82ba02d2018-05-20 16:22:43 -0700337 /// Get the starting line/column in the source file for this span.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700338 ///
339 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800340 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500341 pub fn start(&self) -> LineColumn {
David Tolnayb28f38a2018-03-31 22:02:29 +0200342 let imp::LineColumn { line, column } = self.inner.start();
343 LineColumn {
344 line: line,
345 column: column,
346 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500347 }
348
David Tolnay82ba02d2018-05-20 16:22:43 -0700349 /// Get the ending line/column in the source file for this span.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700350 ///
351 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800352 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500353 pub fn end(&self) -> LineColumn {
David Tolnayb28f38a2018-03-31 22:02:29 +0200354 let imp::LineColumn { line, column } = self.inner.end();
355 LineColumn {
356 line: line,
357 column: column,
358 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500359 }
360
David Tolnay82ba02d2018-05-20 16:22:43 -0700361 /// Create a new span encompassing `self` and `other`.
362 ///
363 /// Returns `None` if `self` and `other` are from different files.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700364 ///
365 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800366 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500367 pub fn join(&self, other: Span) -> Option<Span> {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700368 self.inner.join(other.inner).map(Span::_new)
369 }
Alex Crichtonb2c94622018-04-04 07:36:41 -0700370
David Tolnay82ba02d2018-05-20 16:22:43 -0700371 /// Compares to spans to see if they're equal.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700372 ///
373 /// This method is semver exempt and not exposed by default.
Alex Crichtonb2c94622018-04-04 07:36:41 -0700374 #[cfg(procmacro2_semver_exempt)]
375 pub fn eq(&self, other: &Span) -> bool {
376 self.inner.eq(&other.inner)
377 }
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700378}
379
David Tolnay82ba02d2018-05-20 16:22:43 -0700380/// Prints a span in a form convenient for debugging.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700381impl fmt::Debug for Span {
382 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
383 self.inner.fmt(f)
Nika Layzellf8d5f212017-12-11 14:07:02 -0500384 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700385}
386
David Tolnay82ba02d2018-05-20 16:22:43 -0700387/// A single token or a delimited sequence of token trees (e.g. `[1, (), ..]`).
David Tolnay034205f2018-04-22 16:45:28 -0700388#[derive(Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700389pub enum TokenTree {
David Tolnay82ba02d2018-05-20 16:22:43 -0700390 /// A token stream surrounded by bracket delimiters.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700391 Group(Group),
David Tolnay82ba02d2018-05-20 16:22:43 -0700392 /// An identifier.
Alex Crichtonf3888432018-05-16 09:11:05 -0700393 Ident(Ident),
David Tolnay82ba02d2018-05-20 16:22:43 -0700394 /// A single punctuation character (`+`, `,`, `$`, etc.).
Alex Crichtonf3888432018-05-16 09:11:05 -0700395 Punct(Punct),
David Tolnay82ba02d2018-05-20 16:22:43 -0700396 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700397 Literal(Literal),
Alex Crichton1a7f7622017-07-05 17:47:15 -0700398}
399
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700400impl TokenTree {
David Tolnay82ba02d2018-05-20 16:22:43 -0700401 /// Returns the span of this tree, delegating to the `span` method of
402 /// the contained token or a delimited stream.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700403 pub fn span(&self) -> Span {
404 match *self {
405 TokenTree::Group(ref t) => t.span(),
Alex Crichtonf3888432018-05-16 09:11:05 -0700406 TokenTree::Ident(ref t) => t.span(),
407 TokenTree::Punct(ref t) => t.span(),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700408 TokenTree::Literal(ref t) => t.span(),
409 }
410 }
411
David Tolnay82ba02d2018-05-20 16:22:43 -0700412 /// Configures the span for *only this token*.
413 ///
414 /// Note that if this token is a `Group` then this method will not configure
415 /// the span of each of the internal tokens, this will simply delegate to
416 /// the `set_span` method of each variant.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700417 pub fn set_span(&mut self, span: Span) {
418 match *self {
419 TokenTree::Group(ref mut t) => t.set_span(span),
Alex Crichtonf3888432018-05-16 09:11:05 -0700420 TokenTree::Ident(ref mut t) => t.set_span(span),
421 TokenTree::Punct(ref mut t) => t.set_span(span),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700422 TokenTree::Literal(ref mut t) => t.set_span(span),
423 }
424 }
425}
426
427impl From<Group> for TokenTree {
428 fn from(g: Group) -> TokenTree {
429 TokenTree::Group(g)
430 }
431}
432
Alex Crichtonf3888432018-05-16 09:11:05 -0700433impl From<Ident> for TokenTree {
434 fn from(g: Ident) -> TokenTree {
435 TokenTree::Ident(g)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700436 }
437}
438
Alex Crichtonf3888432018-05-16 09:11:05 -0700439impl From<Punct> for TokenTree {
440 fn from(g: Punct) -> TokenTree {
441 TokenTree::Punct(g)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700442 }
443}
444
445impl From<Literal> for TokenTree {
446 fn from(g: Literal) -> TokenTree {
447 TokenTree::Literal(g)
Alex Crichton1a7f7622017-07-05 17:47:15 -0700448 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700449}
450
David Tolnay82ba02d2018-05-20 16:22:43 -0700451/// Prints the token tree as a string that is supposed to be losslessly
452/// convertible back into the same token tree (modulo spans), except for
453/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
454/// numeric literals.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700455impl fmt::Display for TokenTree {
456 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700457 match *self {
458 TokenTree::Group(ref t) => t.fmt(f),
Alex Crichtonf3888432018-05-16 09:11:05 -0700459 TokenTree::Ident(ref t) => t.fmt(f),
460 TokenTree::Punct(ref t) => t.fmt(f),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700461 TokenTree::Literal(ref t) => t.fmt(f),
462 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700463 }
464}
465
David Tolnay82ba02d2018-05-20 16:22:43 -0700466/// Prints token tree in a form convenient for debugging.
David Tolnay034205f2018-04-22 16:45:28 -0700467impl fmt::Debug for TokenTree {
468 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
469 // Each of these has the name in the struct type in the derived debug,
470 // so don't bother with an extra layer of indirection
471 match *self {
472 TokenTree::Group(ref t) => t.fmt(f),
David Tolnayd8fcdb82018-06-02 15:43:53 -0700473 TokenTree::Ident(ref t) => {
474 let mut debug = f.debug_struct("Ident");
475 debug.field("sym", &format_args!("{}", t));
476 #[cfg(any(feature = "nightly", procmacro2_semver_exempt))]
477 debug.field("span", &t.span());
478 debug.finish()
479 }
Alex Crichtonf3888432018-05-16 09:11:05 -0700480 TokenTree::Punct(ref t) => t.fmt(f),
David Tolnay034205f2018-04-22 16:45:28 -0700481 TokenTree::Literal(ref t) => t.fmt(f),
482 }
483 }
484}
485
David Tolnay82ba02d2018-05-20 16:22:43 -0700486/// A delimited token stream.
487///
488/// A `Group` internally contains a `TokenStream` which is surrounded by
489/// `Delimiter`s.
David Tolnay034205f2018-04-22 16:45:28 -0700490#[derive(Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700491pub struct Group {
492 delimiter: Delimiter,
493 stream: TokenStream,
494 span: Span,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700495}
496
David Tolnay82ba02d2018-05-20 16:22:43 -0700497/// Describes how a sequence of token trees is delimited.
Michael Layzell5372f4b2017-06-02 10:29:31 -0400498#[derive(Copy, Clone, Debug, Eq, PartialEq)]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700499pub enum Delimiter {
David Tolnay82ba02d2018-05-20 16:22:43 -0700500 /// `( ... )`
Alex Crichton44bffbc2017-05-19 17:51:59 -0700501 Parenthesis,
David Tolnay82ba02d2018-05-20 16:22:43 -0700502 /// `{ ... }`
Alex Crichton44bffbc2017-05-19 17:51:59 -0700503 Brace,
David Tolnay82ba02d2018-05-20 16:22:43 -0700504 /// `[ ... ]`
Alex Crichton44bffbc2017-05-19 17:51:59 -0700505 Bracket,
David Tolnay82ba02d2018-05-20 16:22:43 -0700506 /// `Ø ... Ø`
507 ///
508 /// An implicit delimiter, that may, for example, appear around tokens
509 /// coming from a "macro variable" `$var`. It is important to preserve
510 /// operator priorities in cases like `$var * 3` where `$var` is `1 + 2`.
511 /// Implicit delimiters may not survive roundtrip of a token stream through
512 /// a string.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700513 None,
514}
515
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700516impl Group {
David Tolnay82ba02d2018-05-20 16:22:43 -0700517 /// Creates a new `Group` with the given delimiter and token stream.
518 ///
519 /// This constructor will set the span for this group to
520 /// `Span::call_site()`. To change the span you can use the `set_span`
521 /// method below.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700522 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
523 Group {
524 delimiter: delimiter,
525 stream: stream,
526 span: Span::call_site(),
527 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700528 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700529
David Tolnay82ba02d2018-05-20 16:22:43 -0700530 /// Returns the delimiter of this `Group`
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700531 pub fn delimiter(&self) -> Delimiter {
532 self.delimiter
Alex Crichton44bffbc2017-05-19 17:51:59 -0700533 }
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700534
David Tolnay82ba02d2018-05-20 16:22:43 -0700535 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
536 ///
537 /// Note that the returned token stream does not include the delimiter
538 /// returned above.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700539 pub fn stream(&self) -> TokenStream {
540 self.stream.clone()
541 }
542
David Tolnay82ba02d2018-05-20 16:22:43 -0700543 /// Returns the span for the delimiters of this token stream, spanning the
544 /// entire `Group`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700545 pub fn span(&self) -> Span {
546 self.span
547 }
548
David Tolnay82ba02d2018-05-20 16:22:43 -0700549 /// Configures the span for this `Group`'s delimiters, but not its internal
550 /// tokens.
551 ///
552 /// This method will **not** set the span of all the internal tokens spanned
553 /// by this group, but rather it will only set the span of the delimiter
554 /// tokens at the level of the `Group`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700555 pub fn set_span(&mut self, span: Span) {
556 self.span = span;
557 }
558}
559
David Tolnay82ba02d2018-05-20 16:22:43 -0700560/// Prints the group as a string that should be losslessly convertible back
561/// into the same group (modulo spans), except for possibly `TokenTree::Group`s
562/// with `Delimiter::None` delimiters.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700563impl fmt::Display for Group {
564 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
hcpl1a4d7792018-05-29 21:01:44 +0300565 let (left, right) = match self.delimiter {
566 Delimiter::Parenthesis => ("(", ")"),
David Tolnay03b43da2018-06-02 15:25:57 -0700567 Delimiter::Brace => ("{", "}"),
568 Delimiter::Bracket => ("[", "]"),
569 Delimiter::None => ("", ""),
hcpl1a4d7792018-05-29 21:01:44 +0300570 };
571
572 f.write_str(left)?;
573 self.stream.fmt(f)?;
574 f.write_str(right)?;
575
576 Ok(())
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700577 }
578}
579
David Tolnay034205f2018-04-22 16:45:28 -0700580impl fmt::Debug for Group {
581 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
582 let mut debug = fmt.debug_struct("Group");
583 debug.field("delimiter", &self.delimiter);
584 debug.field("stream", &self.stream);
585 #[cfg(procmacro2_semver_exempt)]
586 debug.field("span", &self.span);
587 debug.finish()
588 }
589}
590
David Tolnay82ba02d2018-05-20 16:22:43 -0700591/// An `Punct` is an single punctuation character like `+`, `-` or `#`.
592///
593/// Multicharacter operators like `+=` are represented as two instances of
594/// `Punct` with different forms of `Spacing` returned.
Alex Crichtonf3888432018-05-16 09:11:05 -0700595#[derive(Clone)]
596pub struct Punct {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700597 op: char,
598 spacing: Spacing,
599 span: Span,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700600}
601
David Tolnay82ba02d2018-05-20 16:22:43 -0700602/// Whether an `Punct` is followed immediately by another `Punct` or followed by
603/// another token or whitespace.
Lukas Kalbertodteb3f9302017-08-20 18:58:41 +0200604#[derive(Copy, Clone, Debug, Eq, PartialEq)]
Alex Crichton1a7f7622017-07-05 17:47:15 -0700605pub enum Spacing {
David Tolnay82ba02d2018-05-20 16:22:43 -0700606 /// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700607 Alone,
David Tolnay82ba02d2018-05-20 16:22:43 -0700608 /// E.g. `+` is `Joint` in `+=` or `'#`.
609 ///
610 /// Additionally, single quote `'` can join with identifiers to form
611 /// lifetimes `'ident`.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700612 Joint,
613}
614
Alex Crichtonf3888432018-05-16 09:11:05 -0700615impl Punct {
David Tolnay82ba02d2018-05-20 16:22:43 -0700616 /// Creates a new `Punct` from the given character and spacing.
617 ///
618 /// The `ch` argument must be a valid punctuation character permitted by the
619 /// language, otherwise the function will panic.
620 ///
621 /// The returned `Punct` will have the default span of `Span::call_site()`
622 /// which can be further configured with the `set_span` method below.
Alex Crichtonf3888432018-05-16 09:11:05 -0700623 pub fn new(op: char, spacing: Spacing) -> Punct {
624 Punct {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700625 op: op,
626 spacing: spacing,
627 span: Span::call_site(),
628 }
629 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700630
David Tolnay82ba02d2018-05-20 16:22:43 -0700631 /// Returns the value of this punctuation character as `char`.
Alex Crichtonf3888432018-05-16 09:11:05 -0700632 pub fn as_char(&self) -> char {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700633 self.op
634 }
635
David Tolnay82ba02d2018-05-20 16:22:43 -0700636 /// Returns the spacing of this punctuation character, indicating whether
637 /// it's immediately followed by another `Punct` in the token stream, so
638 /// they can potentially be combined into a multicharacter operator
639 /// (`Joint`), or it's followed by some other token or whitespace (`Alone`)
640 /// so the operator has certainly ended.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700641 pub fn spacing(&self) -> Spacing {
642 self.spacing
643 }
644
David Tolnay82ba02d2018-05-20 16:22:43 -0700645 /// Returns the span for this punctuation character.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700646 pub fn span(&self) -> Span {
647 self.span
648 }
649
David Tolnay82ba02d2018-05-20 16:22:43 -0700650 /// Configure the span for this punctuation character.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700651 pub fn set_span(&mut self, span: Span) {
652 self.span = span;
653 }
654}
655
David Tolnay82ba02d2018-05-20 16:22:43 -0700656/// Prints the punctuation character as a string that should be losslessly
657/// convertible back into the same character.
Alex Crichtonf3888432018-05-16 09:11:05 -0700658impl fmt::Display for Punct {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700659 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
660 self.op.fmt(f)
661 }
662}
663
Alex Crichtonf3888432018-05-16 09:11:05 -0700664impl fmt::Debug for Punct {
David Tolnay034205f2018-04-22 16:45:28 -0700665 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonf3888432018-05-16 09:11:05 -0700666 let mut debug = fmt.debug_struct("Punct");
David Tolnay034205f2018-04-22 16:45:28 -0700667 debug.field("op", &self.op);
668 debug.field("spacing", &self.spacing);
669 #[cfg(procmacro2_semver_exempt)]
670 debug.field("span", &self.span);
671 debug.finish()
672 }
673}
674
David Tolnay8b71dac2018-05-20 17:07:47 -0700675/// A word of Rust code, which may be a keyword or legal variable name.
676///
677/// An identifier consists of at least one Unicode code point, the first of
678/// which has the XID_Start property and the rest of which have the XID_Continue
679/// property.
680///
681/// - The empty string is not an identifier. Use `Option<Ident>`.
682/// - A lifetime is not an identifier. Use `syn::Lifetime` instead.
683///
684/// An identifier constructed with `Ident::new` is permitted to be a Rust
685/// keyword, though parsing one through its [`Synom`] implementation rejects
686/// Rust keywords. Use `call!(Ident::parse_any)` when parsing to match the
687/// behaviour of `Ident::new`.
688///
689/// [`Synom`]: https://docs.rs/syn/0.14/syn/synom/trait.Synom.html
690///
691/// # Examples
692///
693/// A new ident can be created from a string using the `Ident::new` function.
694/// A span must be provided explicitly which governs the name resolution
695/// behavior of the resulting identifier.
696///
697/// ```rust
698/// extern crate proc_macro2;
699///
700/// use proc_macro2::{Ident, Span};
701///
702/// fn main() {
703/// let call_ident = Ident::new("calligraphy", Span::call_site());
704///
705/// println!("{}", call_ident);
706/// }
707/// ```
708///
709/// An ident can be interpolated into a token stream using the `quote!` macro.
710///
711/// ```rust
712/// #[macro_use]
713/// extern crate quote;
714///
715/// extern crate proc_macro2;
716///
717/// use proc_macro2::{Ident, Span};
718///
719/// fn main() {
720/// let ident = Ident::new("demo", Span::call_site());
721///
722/// // Create a variable binding whose name is this ident.
723/// let expanded = quote! { let #ident = 10; };
724///
725/// // Create a variable binding with a slightly different name.
726/// let temp_ident = Ident::new(&format!("new_{}", ident), Span::call_site());
727/// let expanded = quote! { let #temp_ident = 10; };
728/// }
729/// ```
730///
731/// A string representation of the ident is available through the `to_string()`
732/// method.
733///
734/// ```rust
735/// # extern crate proc_macro2;
736/// #
737/// # use proc_macro2::{Ident, Span};
738/// #
739/// # let ident = Ident::new("another_identifier", Span::call_site());
740/// #
741/// // Examine the ident as a string.
742/// let ident_string = ident.to_string();
743/// if ident_string.len() > 60 {
744/// println!("Very long identifier: {}", ident_string)
745/// }
746/// ```
Alex Crichtonf3888432018-05-16 09:11:05 -0700747#[derive(Clone)]
748pub struct Ident {
749 inner: imp::Ident,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700750 _marker: marker::PhantomData<Rc<()>>,
751}
752
Alex Crichtonf3888432018-05-16 09:11:05 -0700753impl Ident {
754 fn _new(inner: imp::Ident) -> Ident {
755 Ident {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700756 inner: inner,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700757 _marker: marker::PhantomData,
758 }
759 }
760
David Tolnay82ba02d2018-05-20 16:22:43 -0700761 /// Creates a new `Ident` with the given `string` as well as the specified
762 /// `span`.
763 ///
764 /// The `string` argument must be a valid identifier permitted by the
765 /// language, otherwise the function will panic.
766 ///
767 /// Note that `span`, currently in rustc, configures the hygiene information
768 /// for this identifier.
769 ///
770 /// As of this time `Span::call_site()` explicitly opts-in to "call-site"
771 /// hygiene meaning that identifiers created with this span will be resolved
772 /// as if they were written directly at the location of the macro call, and
773 /// other code at the macro call site will be able to refer to them as well.
774 ///
775 /// Later spans like `Span::def_site()` will allow to opt-in to
776 /// "definition-site" hygiene meaning that identifiers created with this
777 /// span will be resolved at the location of the macro definition and other
778 /// code at the macro call site will not be able to refer to them.
779 ///
780 /// Due to the current importance of hygiene this constructor, unlike other
781 /// tokens, requires a `Span` to be specified at construction.
David Tolnay8b71dac2018-05-20 17:07:47 -0700782 ///
783 /// # Panics
784 ///
785 /// Panics if the input string is neither a keyword nor a legal variable
786 /// name.
Alex Crichtonf3888432018-05-16 09:11:05 -0700787 pub fn new(string: &str, span: Span) -> Ident {
788 Ident::_new(imp::Ident::new(string, span.inner))
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700789 }
790
David Tolnay82ba02d2018-05-20 16:22:43 -0700791 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
David Tolnaya01ca8e2018-06-04 00:55:28 -0700792 ///
793 /// This method is semver exempt and not exposed by default.
Alex Crichtonf3888432018-05-16 09:11:05 -0700794 #[cfg(procmacro2_semver_exempt)]
795 pub fn new_raw(string: &str, span: Span) -> Ident {
796 Ident::_new_raw(string, span)
797 }
798
799 fn _new_raw(string: &str, span: Span) -> Ident {
800 Ident::_new(imp::Ident::new_raw(string, span.inner))
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700801 }
802
David Tolnay82ba02d2018-05-20 16:22:43 -0700803 /// Returns the span of this `Ident`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700804 pub fn span(&self) -> Span {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700805 Span::_new(self.inner.span())
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700806 }
807
David Tolnay82ba02d2018-05-20 16:22:43 -0700808 /// Configures the span of this `Ident`, possibly changing its hygiene
809 /// context.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700810 pub fn set_span(&mut self, span: Span) {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700811 self.inner.set_span(span.inner);
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700812 }
813}
814
Alex Crichtonf3888432018-05-16 09:11:05 -0700815impl PartialEq for Ident {
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700816 fn eq(&self, other: &Ident) -> bool {
Alex Crichtonf3888432018-05-16 09:11:05 -0700817 self.to_string() == other.to_string()
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700818 }
819}
820
David Tolnayc0bbcc52018-05-18 10:51:04 -0700821impl<T> PartialEq<T> for Ident
822where
823 T: ?Sized + AsRef<str>,
824{
825 fn eq(&self, other: &T) -> bool {
826 self.to_string() == other.as_ref()
827 }
828}
829
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700830impl Eq for Ident {}
Alex Crichtonf3888432018-05-16 09:11:05 -0700831
832impl PartialOrd for Ident {
833 fn partial_cmp(&self, other: &Ident) -> Option<Ordering> {
834 Some(self.cmp(other))
835 }
836}
837
838impl Ord for Ident {
839 fn cmp(&self, other: &Ident) -> Ordering {
840 self.to_string().cmp(&other.to_string())
841 }
842}
843
844impl Hash for Ident {
845 fn hash<H: Hasher>(&self, hasher: &mut H) {
846 self.to_string().hash(hasher)
847 }
848}
849
David Tolnay82ba02d2018-05-20 16:22:43 -0700850/// Prints the identifier as a string that should be losslessly convertible back
851/// into the same identifier.
Alex Crichtonf3888432018-05-16 09:11:05 -0700852impl fmt::Display for Ident {
853 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
854 self.inner.fmt(f)
855 }
856}
857
858impl fmt::Debug for Ident {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700859 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
860 self.inner.fmt(f)
861 }
862}
863
David Tolnay82ba02d2018-05-20 16:22:43 -0700864/// A literal string (`"hello"`), byte string (`b"hello"`), character (`'a'`),
865/// byte character (`b'a'`), an integer or floating point number with or without
866/// a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
867///
868/// Boolean literals like `true` and `false` do not belong here, they are
869/// `Ident`s.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700870#[derive(Clone)]
871pub struct Literal {
872 inner: imp::Literal,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700873 _marker: marker::PhantomData<Rc<()>>,
874}
875
David Tolnay82ba02d2018-05-20 16:22:43 -0700876macro_rules! suffixed_int_literals {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700877 ($($name:ident => $kind:ident,)*) => ($(
David Tolnay82ba02d2018-05-20 16:22:43 -0700878 /// Creates a new suffixed integer literal with the specified value.
879 ///
880 /// This function will create an integer like `1u32` where the integer
881 /// value specified is the first part of the token and the integral is
882 /// also suffixed at the end. Literals created from negative numbers may
883 /// not survive rountrips through `TokenStream` or strings and may be
884 /// broken into two tokens (`-` and positive literal).
885 ///
886 /// Literals created through this method have the `Span::call_site()`
887 /// span by default, which can be configured with the `set_span` method
888 /// below.
889 pub fn $name(n: $kind) -> Literal {
890 Literal::_new(imp::Literal::$name(n))
891 }
892 )*)
893}
894
895macro_rules! unsuffixed_int_literals {
896 ($($name:ident => $kind:ident,)*) => ($(
897 /// Creates a new unsuffixed integer literal with the specified value.
898 ///
899 /// This function will create an integer like `1` where the integer
900 /// value specified is the first part of the token. No suffix is
901 /// specified on this token, meaning that invocations like
902 /// `Literal::i8_unsuffixed(1)` are equivalent to
903 /// `Literal::u32_unsuffixed(1)`. Literals created from negative numbers
904 /// may not survive rountrips through `TokenStream` or strings and may
905 /// be broken into two tokens (`-` and positive literal).
906 ///
907 /// Literals created through this method have the `Span::call_site()`
908 /// span by default, which can be configured with the `set_span` method
909 /// below.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700910 pub fn $name(n: $kind) -> Literal {
Alex Crichtona914a612018-04-04 07:48:44 -0700911 Literal::_new(imp::Literal::$name(n))
Alex Crichton1a7f7622017-07-05 17:47:15 -0700912 }
913 )*)
914}
915
Alex Crichton852d53d2017-05-19 19:25:08 -0700916impl Literal {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700917 fn _new(inner: imp::Literal) -> Literal {
918 Literal {
919 inner: inner,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700920 _marker: marker::PhantomData,
921 }
Alex Crichton1a7f7622017-07-05 17:47:15 -0700922 }
923
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700924 fn _new_stable(inner: stable::Literal) -> Literal {
925 Literal {
926 inner: inner.into(),
927 _marker: marker::PhantomData,
928 }
929 }
930
David Tolnay82ba02d2018-05-20 16:22:43 -0700931 suffixed_int_literals! {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700932 u8_suffixed => u8,
933 u16_suffixed => u16,
934 u32_suffixed => u32,
935 u64_suffixed => u64,
936 usize_suffixed => usize,
937 i8_suffixed => i8,
938 i16_suffixed => i16,
939 i32_suffixed => i32,
940 i64_suffixed => i64,
941 isize_suffixed => isize,
David Tolnay82ba02d2018-05-20 16:22:43 -0700942 }
Alex Crichton1a7f7622017-07-05 17:47:15 -0700943
David Tolnay82ba02d2018-05-20 16:22:43 -0700944 unsuffixed_int_literals! {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700945 u8_unsuffixed => u8,
946 u16_unsuffixed => u16,
947 u32_unsuffixed => u32,
948 u64_unsuffixed => u64,
949 usize_unsuffixed => usize,
950 i8_unsuffixed => i8,
951 i16_unsuffixed => i16,
952 i32_unsuffixed => i32,
953 i64_unsuffixed => i64,
954 isize_unsuffixed => isize,
Alex Crichton1a7f7622017-07-05 17:47:15 -0700955 }
956
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700957 pub fn f64_unsuffixed(f: f64) -> Literal {
958 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -0700959 Literal::_new(imp::Literal::f64_unsuffixed(f))
Alex Crichton1a7f7622017-07-05 17:47:15 -0700960 }
961
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700962 pub fn f64_suffixed(f: f64) -> Literal {
963 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -0700964 Literal::_new(imp::Literal::f64_suffixed(f))
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700965 }
966
David Tolnay82ba02d2018-05-20 16:22:43 -0700967 /// Creates a new unsuffixed floating-point literal.
968 ///
969 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
970 /// the float's value is emitted directly into the token but no suffix is
971 /// used, so it may be inferred to be a `f64` later in the compiler.
972 /// Literals created from negative numbers may not survive rountrips through
973 /// `TokenStream` or strings and may be broken into two tokens (`-` and
974 /// positive literal).
975 ///
976 /// # Panics
977 ///
978 /// This function requires that the specified float is finite, for example
979 /// if it is infinity or NaN this function will panic.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700980 pub fn f32_unsuffixed(f: f32) -> Literal {
981 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -0700982 Literal::_new(imp::Literal::f32_unsuffixed(f))
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700983 }
984
985 pub fn f32_suffixed(f: f32) -> Literal {
986 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -0700987 Literal::_new(imp::Literal::f32_suffixed(f))
Alex Crichton1a7f7622017-07-05 17:47:15 -0700988 }
989
990 pub fn string(string: &str) -> Literal {
Alex Crichtona914a612018-04-04 07:48:44 -0700991 Literal::_new(imp::Literal::string(string))
Alex Crichton1a7f7622017-07-05 17:47:15 -0700992 }
993
994 pub fn character(ch: char) -> Literal {
Alex Crichtona914a612018-04-04 07:48:44 -0700995 Literal::_new(imp::Literal::character(ch))
Alex Crichton76a5cc82017-05-23 07:01:44 -0700996 }
997
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700998 pub fn byte_string(s: &[u8]) -> Literal {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700999 Literal::_new(imp::Literal::byte_string(s))
Alex Crichton852d53d2017-05-19 19:25:08 -07001000 }
Alex Crichton76a5cc82017-05-23 07:01:44 -07001001
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001002 pub fn span(&self) -> Span {
Alex Crichtonb2c94622018-04-04 07:36:41 -07001003 Span::_new(self.inner.span())
Alex Crichton1a7f7622017-07-05 17:47:15 -07001004 }
1005
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001006 pub fn set_span(&mut self, span: Span) {
Alex Crichtonb2c94622018-04-04 07:36:41 -07001007 self.inner.set_span(span.inner);
Alex Crichton31316622017-05-26 12:54:47 -07001008 }
Alex Crichton852d53d2017-05-19 19:25:08 -07001009}
1010
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001011impl fmt::Debug for Literal {
1012 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1013 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001014 }
1015}
David Tolnaycb1b85f2017-06-03 16:40:35 -07001016
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001017impl fmt::Display for Literal {
1018 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1019 self.inner.fmt(f)
1020 }
1021}
1022
David Tolnay82ba02d2018-05-20 16:22:43 -07001023/// Public implementation details for the `TokenStream` type, such as iterators.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001024pub mod token_stream {
1025 use std::fmt;
1026 use std::marker;
1027 use std::rc::Rc;
1028
David Tolnay48ea5042018-04-23 19:17:35 -07001029 use imp;
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001030 pub use TokenStream;
David Tolnayb28f38a2018-03-31 22:02:29 +02001031 use TokenTree;
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001032
David Tolnay82ba02d2018-05-20 16:22:43 -07001033 /// An iterator over `TokenStream`'s `TokenTree`s.
1034 ///
1035 /// The iteration is "shallow", e.g. the iterator doesn't recurse into
1036 /// delimited groups, and returns whole groups as token trees.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001037 pub struct IntoIter {
1038 inner: imp::TokenTreeIter,
1039 _marker: marker::PhantomData<Rc<()>>,
1040 }
1041
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001042 impl Iterator for IntoIter {
1043 type Item = TokenTree;
1044
1045 fn next(&mut self) -> Option<TokenTree> {
1046 self.inner.next()
1047 }
1048 }
1049
1050 impl fmt::Debug for IntoIter {
1051 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1052 self.inner.fmt(f)
1053 }
1054 }
1055
1056 impl IntoIterator for TokenStream {
1057 type Item = TokenTree;
1058 type IntoIter = IntoIter;
1059
1060 fn into_iter(self) -> IntoIter {
1061 IntoIter {
1062 inner: self.inner.into_iter(),
1063 _marker: marker::PhantomData,
1064 }
1065 }
1066 }
1067}