blob: a72be230ecc7c752e747899064a189b1cc9cd158 [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 Tolnay35856292018-06-02 15:52:45 -070046#![doc(html_root_url = "https://docs.rs/proc-macro2/0.4.5")]
David Tolnayd66ecf62018-01-02 20:05:42 -080047#![cfg_attr(feature = "nightly", feature(proc_macro))]
Alex Crichtoncbec8ec2017-06-02 13:19:33 -070048
Alex Crichton0e8e7f42018-02-22 06:15:13 -080049#[cfg(feature = "proc-macro")]
Alex Crichton44bffbc2017-05-19 17:51:59 -070050extern crate proc_macro;
David Tolnayb1032662017-05-31 15:52:28 -070051extern crate unicode_xid;
Alex Crichton44bffbc2017-05-19 17:51:59 -070052
Alex Crichtonf3888432018-05-16 09:11:05 -070053use std::cmp::Ordering;
Alex Crichton44bffbc2017-05-19 17:51:59 -070054use std::fmt;
Alex Crichtonf3888432018-05-16 09:11:05 -070055use std::hash::{Hash, Hasher};
Alex Crichton44bffbc2017-05-19 17:51:59 -070056use std::iter::FromIterator;
Alex Crichtonaf5bad42018-03-27 14:45:10 -070057use std::marker;
58use std::rc::Rc;
59use std::str::FromStr;
Alex Crichton44bffbc2017-05-19 17:51:59 -070060
David Tolnayb1032662017-05-31 15:52:28 -070061#[macro_use]
David Tolnayb1032662017-05-31 15:52:28 -070062mod strnom;
Alex Crichton30a4e9e2018-04-27 17:02:19 -070063mod stable;
David Tolnayb1032662017-05-31 15:52:28 -070064
David Tolnayd66ecf62018-01-02 20:05:42 -080065#[cfg(not(feature = "nightly"))]
Alex Crichton30a4e9e2018-04-27 17:02:19 -070066use stable as imp;
Alex Crichtonb15c6352017-05-19 19:36:36 -070067#[path = "unstable.rs"]
David Tolnayd66ecf62018-01-02 20:05:42 -080068#[cfg(feature = "nightly")]
Alex Crichton44bffbc2017-05-19 17:51:59 -070069mod imp;
70
David Tolnay82ba02d2018-05-20 16:22:43 -070071/// An abstract stream of tokens, or more concretely a sequence of token trees.
72///
73/// This type provides interfaces for iterating over token trees and for
74/// collecting token trees into one stream.
75///
76/// Token stream is both the input and output of `#[proc_macro]`,
77/// `#[proc_macro_attribute]` and `#[proc_macro_derive]` definitions.
David Tolnaycb1b85f2017-06-03 16:40:35 -070078#[derive(Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -070079pub struct TokenStream {
80 inner: imp::TokenStream,
81 _marker: marker::PhantomData<Rc<()>>,
82}
Alex Crichton44bffbc2017-05-19 17:51:59 -070083
David Tolnay82ba02d2018-05-20 16:22:43 -070084/// Error returned from `TokenStream::from_str`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -070085pub struct LexError {
86 inner: imp::LexError,
87 _marker: marker::PhantomData<Rc<()>>,
88}
89
90impl TokenStream {
91 fn _new(inner: imp::TokenStream) -> TokenStream {
92 TokenStream {
93 inner: inner,
94 _marker: marker::PhantomData,
95 }
96 }
97
Alex Crichton30a4e9e2018-04-27 17:02:19 -070098 fn _new_stable(inner: stable::TokenStream) -> TokenStream {
99 TokenStream {
100 inner: inner.into(),
101 _marker: marker::PhantomData,
102 }
103 }
104
David Tolnay82ba02d2018-05-20 16:22:43 -0700105 /// Returns an empty `TokenStream` containing no token trees.
David Tolnayc3bb4592018-05-28 20:09:44 -0700106 pub fn new() -> TokenStream {
107 TokenStream::_new(imp::TokenStream::new())
108 }
109
110 #[deprecated(since = "0.4.4", note = "please use TokenStream::new")]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700111 pub fn empty() -> TokenStream {
David Tolnayc3bb4592018-05-28 20:09:44 -0700112 TokenStream::new()
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700113 }
114
David Tolnay82ba02d2018-05-20 16:22:43 -0700115 /// Checks if this `TokenStream` is empty.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700116 pub fn is_empty(&self) -> bool {
117 self.inner.is_empty()
118 }
119}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700120
David Tolnay82ba02d2018-05-20 16:22:43 -0700121/// Attempts to break the string into tokens and parse those tokens into a token
122/// stream.
123///
124/// May fail for a number of reasons, for example, if the string contains
125/// unbalanced delimiters or characters not existing in the language.
126///
127/// NOTE: Some errors may cause panics instead of returning `LexError`. We
128/// reserve the right to change these errors into `LexError`s later.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700129impl FromStr for TokenStream {
130 type Err = LexError;
131
132 fn from_str(src: &str) -> Result<TokenStream, LexError> {
David Tolnayb28f38a2018-03-31 22:02:29 +0200133 let e = src.parse().map_err(|e| LexError {
134 inner: e,
135 _marker: marker::PhantomData,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700136 })?;
137 Ok(TokenStream::_new(e))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700138 }
139}
140
Alex Crichton0e8e7f42018-02-22 06:15:13 -0800141#[cfg(feature = "proc-macro")]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700142impl From<proc_macro::TokenStream> for TokenStream {
143 fn from(inner: proc_macro::TokenStream) -> TokenStream {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700144 TokenStream::_new(inner.into())
Alex Crichton44bffbc2017-05-19 17:51:59 -0700145 }
146}
147
Alex Crichton0e8e7f42018-02-22 06:15:13 -0800148#[cfg(feature = "proc-macro")]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700149impl From<TokenStream> for proc_macro::TokenStream {
150 fn from(inner: TokenStream) -> proc_macro::TokenStream {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700151 inner.inner.into()
Alex Crichton44bffbc2017-05-19 17:51:59 -0700152 }
153}
154
Alex Crichtonf3888432018-05-16 09:11:05 -0700155impl Extend<TokenTree> for TokenStream {
156 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, streams: I) {
157 self.inner.extend(streams)
158 }
159}
160
David Tolnay82ba02d2018-05-20 16:22:43 -0700161/// Collects a number of token trees into a single stream.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700162impl FromIterator<TokenTree> for TokenStream {
163 fn from_iter<I: IntoIterator<Item = TokenTree>>(streams: I) -> Self {
164 TokenStream::_new(streams.into_iter().collect())
Alex Crichton44bffbc2017-05-19 17:51:59 -0700165 }
166}
167
David Tolnay82ba02d2018-05-20 16:22:43 -0700168/// Prints the token stream as a string that is supposed to be losslessly
169/// convertible back into the same token stream (modulo spans), except for
170/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
171/// numeric literals.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700172impl fmt::Display for TokenStream {
173 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
174 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700175 }
176}
177
David Tolnay82ba02d2018-05-20 16:22:43 -0700178/// Prints token in a form convenient for debugging.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700179impl fmt::Debug for TokenStream {
180 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
181 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700182 }
183}
184
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700185impl fmt::Debug for LexError {
186 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
187 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700188 }
189}
190
Nika Layzellb35a9a32017-12-30 14:34:35 -0500191// Returned by reference, so we can't easily wrap it.
David Tolnay1ebe3972018-01-02 20:14:20 -0800192#[cfg(procmacro2_semver_exempt)]
Nika Layzellb35a9a32017-12-30 14:34:35 -0500193pub use imp::FileName;
194
David Tolnay82ba02d2018-05-20 16:22:43 -0700195/// The source file of a given `Span`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700196///
197/// This type is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800198#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500199#[derive(Clone, PartialEq, Eq)]
200pub struct SourceFile(imp::SourceFile);
201
David Tolnay1ebe3972018-01-02 20:14:20 -0800202#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500203impl SourceFile {
David Tolnay82ba02d2018-05-20 16:22:43 -0700204 /// Get the path to this source file.
205 ///
206 /// ### Note
207 ///
208 /// If the code span associated with this `SourceFile` was generated by an
209 /// external macro, this may not be an actual path on the filesystem. Use
210 /// [`is_real`] to check.
211 ///
212 /// Also note that even if `is_real` returns `true`, if
213 /// `--remap-path-prefix` was passed on the command line, the path as given
214 /// may not actually be valid.
215 ///
216 /// [`is_real`]: #method.is_real
Nika Layzellb35a9a32017-12-30 14:34:35 -0500217 pub fn path(&self) -> &FileName {
218 self.0.path()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500219 }
220
David Tolnay82ba02d2018-05-20 16:22:43 -0700221 /// Returns `true` if this source file is a real source file, and not
222 /// generated by an external macro's expansion.
Nika Layzellf8d5f212017-12-11 14:07:02 -0500223 pub fn is_real(&self) -> bool {
224 self.0.is_real()
225 }
226}
227
David Tolnay1ebe3972018-01-02 20:14:20 -0800228#[cfg(procmacro2_semver_exempt)]
Nika Layzellb35a9a32017-12-30 14:34:35 -0500229impl AsRef<FileName> for SourceFile {
230 fn as_ref(&self) -> &FileName {
231 self.0.path()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500232 }
233}
234
David Tolnay1ebe3972018-01-02 20:14:20 -0800235#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500236impl fmt::Debug for SourceFile {
237 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
238 self.0.fmt(f)
239 }
240}
241
David Tolnay82ba02d2018-05-20 16:22:43 -0700242/// A line-column pair representing the start or end of a `Span`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700243///
244/// This type is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800245#[cfg(procmacro2_semver_exempt)]
Nika Layzell1ecb6ce2017-12-30 14:34:05 -0500246pub struct LineColumn {
David Tolnay82ba02d2018-05-20 16:22:43 -0700247 /// The 1-indexed line in the source file on which the span starts or ends
248 /// (inclusive).
Nika Layzell1ecb6ce2017-12-30 14:34:05 -0500249 pub line: usize,
David Tolnay82ba02d2018-05-20 16:22:43 -0700250 /// The 0-indexed column (in UTF-8 characters) in the source file on which
251 /// the span starts or ends (inclusive).
Nika Layzell1ecb6ce2017-12-30 14:34:05 -0500252 pub column: usize,
253}
Nika Layzellf8d5f212017-12-11 14:07:02 -0500254
David Tolnay82ba02d2018-05-20 16:22:43 -0700255/// A region of source code, along with macro expansion information.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700256#[derive(Copy, Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700257pub struct Span {
258 inner: imp::Span,
259 _marker: marker::PhantomData<Rc<()>>,
260}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700261
Alex Crichton44bffbc2017-05-19 17:51:59 -0700262impl Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700263 fn _new(inner: imp::Span) -> Span {
264 Span {
265 inner: inner,
266 _marker: marker::PhantomData,
267 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700268 }
Alex Crichtone6085b72017-11-21 07:24:25 -0800269
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700270 fn _new_stable(inner: stable::Span) -> Span {
271 Span {
272 inner: inner.into(),
273 _marker: marker::PhantomData,
274 }
275 }
276
David Tolnay82ba02d2018-05-20 16:22:43 -0700277 /// The span of the invocation of the current procedural macro.
278 ///
279 /// Identifiers created with this span will be resolved as if they were
280 /// written directly at the macro call location (call-site hygiene) and
281 /// other code at the macro call site will be able to refer to them as well.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700282 pub fn call_site() -> Span {
283 Span::_new(imp::Span::call_site())
284 }
285
David Tolnay82ba02d2018-05-20 16:22:43 -0700286 /// A span that resolves at the macro definition site.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700287 ///
288 /// This method is semver exempt and not exposed by default.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700289 #[cfg(procmacro2_semver_exempt)]
Alex Crichtone6085b72017-11-21 07:24:25 -0800290 pub fn def_site() -> Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700291 Span::_new(imp::Span::def_site())
Alex Crichtone6085b72017-11-21 07:24:25 -0800292 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500293
David Tolnay4e8e3972018-01-05 18:10:22 -0800294 /// Creates a new span with the same line/column information as `self` but
295 /// that resolves symbols as though it were at `other`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700296 ///
297 /// This method is semver exempt and not exposed by default.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700298 #[cfg(procmacro2_semver_exempt)]
David Tolnay4e8e3972018-01-05 18:10:22 -0800299 pub fn resolved_at(&self, other: Span) -> Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700300 Span::_new(self.inner.resolved_at(other.inner))
David Tolnay4e8e3972018-01-05 18:10:22 -0800301 }
302
303 /// Creates a new span with the same name resolution behavior as `self` but
304 /// with the line/column information of `other`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700305 ///
306 /// This method is semver exempt and not exposed by default.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700307 #[cfg(procmacro2_semver_exempt)]
David Tolnay4e8e3972018-01-05 18:10:22 -0800308 pub fn located_at(&self, other: Span) -> Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700309 Span::_new(self.inner.located_at(other.inner))
David Tolnay4e8e3972018-01-05 18:10:22 -0800310 }
311
David Tolnayd66ecf62018-01-02 20:05:42 -0800312 /// This method is only available when the `"nightly"` feature is enabled.
Alex Crichton0e8e7f42018-02-22 06:15:13 -0800313 #[cfg(all(feature = "nightly", feature = "proc-macro"))]
David Tolnay16a17202017-12-31 10:47:24 -0500314 pub fn unstable(self) -> proc_macro::Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700315 self.inner.unstable()
David Tolnay16a17202017-12-31 10:47:24 -0500316 }
317
David Tolnay82ba02d2018-05-20 16:22:43 -0700318 /// The original source file into which this span points.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700319 ///
320 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800321 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500322 pub fn source_file(&self) -> SourceFile {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700323 SourceFile(self.inner.source_file())
Nika Layzellf8d5f212017-12-11 14:07:02 -0500324 }
325
David Tolnay82ba02d2018-05-20 16:22:43 -0700326 /// Get the starting line/column in the source file for this span.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700327 ///
328 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800329 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500330 pub fn start(&self) -> LineColumn {
David Tolnayb28f38a2018-03-31 22:02:29 +0200331 let imp::LineColumn { line, column } = self.inner.start();
332 LineColumn {
333 line: line,
334 column: column,
335 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500336 }
337
David Tolnay82ba02d2018-05-20 16:22:43 -0700338 /// Get the ending line/column in the source file for this span.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700339 ///
340 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800341 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500342 pub fn end(&self) -> LineColumn {
David Tolnayb28f38a2018-03-31 22:02:29 +0200343 let imp::LineColumn { line, column } = self.inner.end();
344 LineColumn {
345 line: line,
346 column: column,
347 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500348 }
349
David Tolnay82ba02d2018-05-20 16:22:43 -0700350 /// Create a new span encompassing `self` and `other`.
351 ///
352 /// Returns `None` if `self` and `other` are from different files.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700353 ///
354 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800355 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500356 pub fn join(&self, other: Span) -> Option<Span> {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700357 self.inner.join(other.inner).map(Span::_new)
358 }
Alex Crichtonb2c94622018-04-04 07:36:41 -0700359
David Tolnay82ba02d2018-05-20 16:22:43 -0700360 /// Compares to spans to see if they're equal.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700361 ///
362 /// This method is semver exempt and not exposed by default.
Alex Crichtonb2c94622018-04-04 07:36:41 -0700363 #[cfg(procmacro2_semver_exempt)]
364 pub fn eq(&self, other: &Span) -> bool {
365 self.inner.eq(&other.inner)
366 }
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700367}
368
David Tolnay82ba02d2018-05-20 16:22:43 -0700369/// Prints a span in a form convenient for debugging.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700370impl fmt::Debug for Span {
371 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
372 self.inner.fmt(f)
Nika Layzellf8d5f212017-12-11 14:07:02 -0500373 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700374}
375
David Tolnay82ba02d2018-05-20 16:22:43 -0700376/// A single token or a delimited sequence of token trees (e.g. `[1, (), ..]`).
David Tolnay034205f2018-04-22 16:45:28 -0700377#[derive(Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700378pub enum TokenTree {
David Tolnay82ba02d2018-05-20 16:22:43 -0700379 /// A token stream surrounded by bracket delimiters.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700380 Group(Group),
David Tolnay82ba02d2018-05-20 16:22:43 -0700381 /// An identifier.
Alex Crichtonf3888432018-05-16 09:11:05 -0700382 Ident(Ident),
David Tolnay82ba02d2018-05-20 16:22:43 -0700383 /// A single punctuation character (`+`, `,`, `$`, etc.).
Alex Crichtonf3888432018-05-16 09:11:05 -0700384 Punct(Punct),
David Tolnay82ba02d2018-05-20 16:22:43 -0700385 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700386 Literal(Literal),
Alex Crichton1a7f7622017-07-05 17:47:15 -0700387}
388
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700389impl TokenTree {
David Tolnay82ba02d2018-05-20 16:22:43 -0700390 /// Returns the span of this tree, delegating to the `span` method of
391 /// the contained token or a delimited stream.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700392 pub fn span(&self) -> Span {
393 match *self {
394 TokenTree::Group(ref t) => t.span(),
Alex Crichtonf3888432018-05-16 09:11:05 -0700395 TokenTree::Ident(ref t) => t.span(),
396 TokenTree::Punct(ref t) => t.span(),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700397 TokenTree::Literal(ref t) => t.span(),
398 }
399 }
400
David Tolnay82ba02d2018-05-20 16:22:43 -0700401 /// Configures the span for *only this token*.
402 ///
403 /// Note that if this token is a `Group` then this method will not configure
404 /// the span of each of the internal tokens, this will simply delegate to
405 /// the `set_span` method of each variant.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700406 pub fn set_span(&mut self, span: Span) {
407 match *self {
408 TokenTree::Group(ref mut t) => t.set_span(span),
Alex Crichtonf3888432018-05-16 09:11:05 -0700409 TokenTree::Ident(ref mut t) => t.set_span(span),
410 TokenTree::Punct(ref mut t) => t.set_span(span),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700411 TokenTree::Literal(ref mut t) => t.set_span(span),
412 }
413 }
414}
415
416impl From<Group> for TokenTree {
417 fn from(g: Group) -> TokenTree {
418 TokenTree::Group(g)
419 }
420}
421
Alex Crichtonf3888432018-05-16 09:11:05 -0700422impl From<Ident> for TokenTree {
423 fn from(g: Ident) -> TokenTree {
424 TokenTree::Ident(g)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700425 }
426}
427
Alex Crichtonf3888432018-05-16 09:11:05 -0700428impl From<Punct> for TokenTree {
429 fn from(g: Punct) -> TokenTree {
430 TokenTree::Punct(g)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700431 }
432}
433
434impl From<Literal> for TokenTree {
435 fn from(g: Literal) -> TokenTree {
436 TokenTree::Literal(g)
Alex Crichton1a7f7622017-07-05 17:47:15 -0700437 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700438}
439
David Tolnay82ba02d2018-05-20 16:22:43 -0700440/// Prints the token tree as a string that is supposed to be losslessly
441/// convertible back into the same token tree (modulo spans), except for
442/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
443/// numeric literals.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700444impl fmt::Display for TokenTree {
445 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700446 match *self {
447 TokenTree::Group(ref t) => t.fmt(f),
Alex Crichtonf3888432018-05-16 09:11:05 -0700448 TokenTree::Ident(ref t) => t.fmt(f),
449 TokenTree::Punct(ref t) => t.fmt(f),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700450 TokenTree::Literal(ref t) => t.fmt(f),
451 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700452 }
453}
454
David Tolnay82ba02d2018-05-20 16:22:43 -0700455/// Prints token tree in a form convenient for debugging.
David Tolnay034205f2018-04-22 16:45:28 -0700456impl fmt::Debug for TokenTree {
457 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
458 // Each of these has the name in the struct type in the derived debug,
459 // so don't bother with an extra layer of indirection
460 match *self {
461 TokenTree::Group(ref t) => t.fmt(f),
David Tolnayd8fcdb82018-06-02 15:43:53 -0700462 TokenTree::Ident(ref t) => {
463 let mut debug = f.debug_struct("Ident");
464 debug.field("sym", &format_args!("{}", t));
465 #[cfg(any(feature = "nightly", procmacro2_semver_exempt))]
466 debug.field("span", &t.span());
467 debug.finish()
468 }
Alex Crichtonf3888432018-05-16 09:11:05 -0700469 TokenTree::Punct(ref t) => t.fmt(f),
David Tolnay034205f2018-04-22 16:45:28 -0700470 TokenTree::Literal(ref t) => t.fmt(f),
471 }
472 }
473}
474
David Tolnay82ba02d2018-05-20 16:22:43 -0700475/// A delimited token stream.
476///
477/// A `Group` internally contains a `TokenStream` which is surrounded by
478/// `Delimiter`s.
David Tolnay034205f2018-04-22 16:45:28 -0700479#[derive(Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700480pub struct Group {
481 delimiter: Delimiter,
482 stream: TokenStream,
483 span: Span,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700484}
485
David Tolnay82ba02d2018-05-20 16:22:43 -0700486/// Describes how a sequence of token trees is delimited.
Michael Layzell5372f4b2017-06-02 10:29:31 -0400487#[derive(Copy, Clone, Debug, Eq, PartialEq)]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700488pub enum Delimiter {
David Tolnay82ba02d2018-05-20 16:22:43 -0700489 /// `( ... )`
Alex Crichton44bffbc2017-05-19 17:51:59 -0700490 Parenthesis,
David Tolnay82ba02d2018-05-20 16:22:43 -0700491 /// `{ ... }`
Alex Crichton44bffbc2017-05-19 17:51:59 -0700492 Brace,
David Tolnay82ba02d2018-05-20 16:22:43 -0700493 /// `[ ... ]`
Alex Crichton44bffbc2017-05-19 17:51:59 -0700494 Bracket,
David Tolnay82ba02d2018-05-20 16:22:43 -0700495 /// `Ø ... Ø`
496 ///
497 /// An implicit delimiter, that may, for example, appear around tokens
498 /// coming from a "macro variable" `$var`. It is important to preserve
499 /// operator priorities in cases like `$var * 3` where `$var` is `1 + 2`.
500 /// Implicit delimiters may not survive roundtrip of a token stream through
501 /// a string.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700502 None,
503}
504
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700505impl Group {
David Tolnay82ba02d2018-05-20 16:22:43 -0700506 /// Creates a new `Group` with the given delimiter and token stream.
507 ///
508 /// This constructor will set the span for this group to
509 /// `Span::call_site()`. To change the span you can use the `set_span`
510 /// method below.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700511 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
512 Group {
513 delimiter: delimiter,
514 stream: stream,
515 span: Span::call_site(),
516 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700517 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700518
David Tolnay82ba02d2018-05-20 16:22:43 -0700519 /// Returns the delimiter of this `Group`
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700520 pub fn delimiter(&self) -> Delimiter {
521 self.delimiter
Alex Crichton44bffbc2017-05-19 17:51:59 -0700522 }
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700523
David Tolnay82ba02d2018-05-20 16:22:43 -0700524 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
525 ///
526 /// Note that the returned token stream does not include the delimiter
527 /// returned above.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700528 pub fn stream(&self) -> TokenStream {
529 self.stream.clone()
530 }
531
David Tolnay82ba02d2018-05-20 16:22:43 -0700532 /// Returns the span for the delimiters of this token stream, spanning the
533 /// entire `Group`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700534 pub fn span(&self) -> Span {
535 self.span
536 }
537
David Tolnay82ba02d2018-05-20 16:22:43 -0700538 /// Configures the span for this `Group`'s delimiters, but not its internal
539 /// tokens.
540 ///
541 /// This method will **not** set the span of all the internal tokens spanned
542 /// by this group, but rather it will only set the span of the delimiter
543 /// tokens at the level of the `Group`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700544 pub fn set_span(&mut self, span: Span) {
545 self.span = span;
546 }
547}
548
David Tolnay82ba02d2018-05-20 16:22:43 -0700549/// Prints the group as a string that should be losslessly convertible back
550/// into the same group (modulo spans), except for possibly `TokenTree::Group`s
551/// with `Delimiter::None` delimiters.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700552impl fmt::Display for Group {
553 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
hcpl1a4d7792018-05-29 21:01:44 +0300554 let (left, right) = match self.delimiter {
555 Delimiter::Parenthesis => ("(", ")"),
David Tolnay03b43da2018-06-02 15:25:57 -0700556 Delimiter::Brace => ("{", "}"),
557 Delimiter::Bracket => ("[", "]"),
558 Delimiter::None => ("", ""),
hcpl1a4d7792018-05-29 21:01:44 +0300559 };
560
561 f.write_str(left)?;
562 self.stream.fmt(f)?;
563 f.write_str(right)?;
564
565 Ok(())
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700566 }
567}
568
David Tolnay034205f2018-04-22 16:45:28 -0700569impl fmt::Debug for Group {
570 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
571 let mut debug = fmt.debug_struct("Group");
572 debug.field("delimiter", &self.delimiter);
573 debug.field("stream", &self.stream);
574 #[cfg(procmacro2_semver_exempt)]
575 debug.field("span", &self.span);
576 debug.finish()
577 }
578}
579
David Tolnay82ba02d2018-05-20 16:22:43 -0700580/// An `Punct` is an single punctuation character like `+`, `-` or `#`.
581///
582/// Multicharacter operators like `+=` are represented as two instances of
583/// `Punct` with different forms of `Spacing` returned.
Alex Crichtonf3888432018-05-16 09:11:05 -0700584#[derive(Clone)]
585pub struct Punct {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700586 op: char,
587 spacing: Spacing,
588 span: Span,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700589}
590
David Tolnay82ba02d2018-05-20 16:22:43 -0700591/// Whether an `Punct` is followed immediately by another `Punct` or followed by
592/// another token or whitespace.
Lukas Kalbertodteb3f9302017-08-20 18:58:41 +0200593#[derive(Copy, Clone, Debug, Eq, PartialEq)]
Alex Crichton1a7f7622017-07-05 17:47:15 -0700594pub enum Spacing {
David Tolnay82ba02d2018-05-20 16:22:43 -0700595 /// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700596 Alone,
David Tolnay82ba02d2018-05-20 16:22:43 -0700597 /// E.g. `+` is `Joint` in `+=` or `'#`.
598 ///
599 /// Additionally, single quote `'` can join with identifiers to form
600 /// lifetimes `'ident`.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700601 Joint,
602}
603
Alex Crichtonf3888432018-05-16 09:11:05 -0700604impl Punct {
David Tolnay82ba02d2018-05-20 16:22:43 -0700605 /// Creates a new `Punct` from the given character and spacing.
606 ///
607 /// The `ch` argument must be a valid punctuation character permitted by the
608 /// language, otherwise the function will panic.
609 ///
610 /// The returned `Punct` will have the default span of `Span::call_site()`
611 /// which can be further configured with the `set_span` method below.
Alex Crichtonf3888432018-05-16 09:11:05 -0700612 pub fn new(op: char, spacing: Spacing) -> Punct {
613 Punct {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700614 op: op,
615 spacing: spacing,
616 span: Span::call_site(),
617 }
618 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700619
David Tolnay82ba02d2018-05-20 16:22:43 -0700620 /// Returns the value of this punctuation character as `char`.
Alex Crichtonf3888432018-05-16 09:11:05 -0700621 pub fn as_char(&self) -> char {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700622 self.op
623 }
624
David Tolnay82ba02d2018-05-20 16:22:43 -0700625 /// Returns the spacing of this punctuation character, indicating whether
626 /// it's immediately followed by another `Punct` in the token stream, so
627 /// they can potentially be combined into a multicharacter operator
628 /// (`Joint`), or it's followed by some other token or whitespace (`Alone`)
629 /// so the operator has certainly ended.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700630 pub fn spacing(&self) -> Spacing {
631 self.spacing
632 }
633
David Tolnay82ba02d2018-05-20 16:22:43 -0700634 /// Returns the span for this punctuation character.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700635 pub fn span(&self) -> Span {
636 self.span
637 }
638
David Tolnay82ba02d2018-05-20 16:22:43 -0700639 /// Configure the span for this punctuation character.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700640 pub fn set_span(&mut self, span: Span) {
641 self.span = span;
642 }
643}
644
David Tolnay82ba02d2018-05-20 16:22:43 -0700645/// Prints the punctuation character as a string that should be losslessly
646/// convertible back into the same character.
Alex Crichtonf3888432018-05-16 09:11:05 -0700647impl fmt::Display for Punct {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700648 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
649 self.op.fmt(f)
650 }
651}
652
Alex Crichtonf3888432018-05-16 09:11:05 -0700653impl fmt::Debug for Punct {
David Tolnay034205f2018-04-22 16:45:28 -0700654 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonf3888432018-05-16 09:11:05 -0700655 let mut debug = fmt.debug_struct("Punct");
David Tolnay034205f2018-04-22 16:45:28 -0700656 debug.field("op", &self.op);
657 debug.field("spacing", &self.spacing);
658 #[cfg(procmacro2_semver_exempt)]
659 debug.field("span", &self.span);
660 debug.finish()
661 }
662}
663
David Tolnay8b71dac2018-05-20 17:07:47 -0700664/// A word of Rust code, which may be a keyword or legal variable name.
665///
666/// An identifier consists of at least one Unicode code point, the first of
667/// which has the XID_Start property and the rest of which have the XID_Continue
668/// property.
669///
670/// - The empty string is not an identifier. Use `Option<Ident>`.
671/// - A lifetime is not an identifier. Use `syn::Lifetime` instead.
672///
673/// An identifier constructed with `Ident::new` is permitted to be a Rust
674/// keyword, though parsing one through its [`Synom`] implementation rejects
675/// Rust keywords. Use `call!(Ident::parse_any)` when parsing to match the
676/// behaviour of `Ident::new`.
677///
678/// [`Synom`]: https://docs.rs/syn/0.14/syn/synom/trait.Synom.html
679///
680/// # Examples
681///
682/// A new ident can be created from a string using the `Ident::new` function.
683/// A span must be provided explicitly which governs the name resolution
684/// behavior of the resulting identifier.
685///
686/// ```rust
687/// extern crate proc_macro2;
688///
689/// use proc_macro2::{Ident, Span};
690///
691/// fn main() {
692/// let call_ident = Ident::new("calligraphy", Span::call_site());
693///
694/// println!("{}", call_ident);
695/// }
696/// ```
697///
698/// An ident can be interpolated into a token stream using the `quote!` macro.
699///
700/// ```rust
701/// #[macro_use]
702/// extern crate quote;
703///
704/// extern crate proc_macro2;
705///
706/// use proc_macro2::{Ident, Span};
707///
708/// fn main() {
709/// let ident = Ident::new("demo", Span::call_site());
710///
711/// // Create a variable binding whose name is this ident.
712/// let expanded = quote! { let #ident = 10; };
713///
714/// // Create a variable binding with a slightly different name.
715/// let temp_ident = Ident::new(&format!("new_{}", ident), Span::call_site());
716/// let expanded = quote! { let #temp_ident = 10; };
717/// }
718/// ```
719///
720/// A string representation of the ident is available through the `to_string()`
721/// method.
722///
723/// ```rust
724/// # extern crate proc_macro2;
725/// #
726/// # use proc_macro2::{Ident, Span};
727/// #
728/// # let ident = Ident::new("another_identifier", Span::call_site());
729/// #
730/// // Examine the ident as a string.
731/// let ident_string = ident.to_string();
732/// if ident_string.len() > 60 {
733/// println!("Very long identifier: {}", ident_string)
734/// }
735/// ```
Alex Crichtonf3888432018-05-16 09:11:05 -0700736#[derive(Clone)]
737pub struct Ident {
738 inner: imp::Ident,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700739 _marker: marker::PhantomData<Rc<()>>,
740}
741
Alex Crichtonf3888432018-05-16 09:11:05 -0700742impl Ident {
743 fn _new(inner: imp::Ident) -> Ident {
744 Ident {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700745 inner: inner,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700746 _marker: marker::PhantomData,
747 }
748 }
749
David Tolnay82ba02d2018-05-20 16:22:43 -0700750 /// Creates a new `Ident` with the given `string` as well as the specified
751 /// `span`.
752 ///
753 /// The `string` argument must be a valid identifier permitted by the
754 /// language, otherwise the function will panic.
755 ///
756 /// Note that `span`, currently in rustc, configures the hygiene information
757 /// for this identifier.
758 ///
759 /// As of this time `Span::call_site()` explicitly opts-in to "call-site"
760 /// hygiene meaning that identifiers created with this span will be resolved
761 /// as if they were written directly at the location of the macro call, and
762 /// other code at the macro call site will be able to refer to them as well.
763 ///
764 /// Later spans like `Span::def_site()` will allow to opt-in to
765 /// "definition-site" hygiene meaning that identifiers created with this
766 /// span will be resolved at the location of the macro definition and other
767 /// code at the macro call site will not be able to refer to them.
768 ///
769 /// Due to the current importance of hygiene this constructor, unlike other
770 /// tokens, requires a `Span` to be specified at construction.
David Tolnay8b71dac2018-05-20 17:07:47 -0700771 ///
772 /// # Panics
773 ///
774 /// Panics if the input string is neither a keyword nor a legal variable
775 /// name.
Alex Crichtonf3888432018-05-16 09:11:05 -0700776 pub fn new(string: &str, span: Span) -> Ident {
777 Ident::_new(imp::Ident::new(string, span.inner))
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700778 }
779
David Tolnay82ba02d2018-05-20 16:22:43 -0700780 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
David Tolnaya01ca8e2018-06-04 00:55:28 -0700781 ///
782 /// This method is semver exempt and not exposed by default.
Alex Crichtonf3888432018-05-16 09:11:05 -0700783 #[cfg(procmacro2_semver_exempt)]
784 pub fn new_raw(string: &str, span: Span) -> Ident {
785 Ident::_new_raw(string, span)
786 }
787
788 fn _new_raw(string: &str, span: Span) -> Ident {
789 Ident::_new(imp::Ident::new_raw(string, span.inner))
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700790 }
791
David Tolnay82ba02d2018-05-20 16:22:43 -0700792 /// Returns the span of this `Ident`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700793 pub fn span(&self) -> Span {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700794 Span::_new(self.inner.span())
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700795 }
796
David Tolnay82ba02d2018-05-20 16:22:43 -0700797 /// Configures the span of this `Ident`, possibly changing its hygiene
798 /// context.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700799 pub fn set_span(&mut self, span: Span) {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700800 self.inner.set_span(span.inner);
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700801 }
802}
803
Alex Crichtonf3888432018-05-16 09:11:05 -0700804impl PartialEq for Ident {
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700805 fn eq(&self, other: &Ident) -> bool {
Alex Crichtonf3888432018-05-16 09:11:05 -0700806 self.to_string() == other.to_string()
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700807 }
808}
809
David Tolnayc0bbcc52018-05-18 10:51:04 -0700810impl<T> PartialEq<T> for Ident
811where
812 T: ?Sized + AsRef<str>,
813{
814 fn eq(&self, other: &T) -> bool {
815 self.to_string() == other.as_ref()
816 }
817}
818
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700819impl Eq for Ident {}
Alex Crichtonf3888432018-05-16 09:11:05 -0700820
821impl PartialOrd for Ident {
822 fn partial_cmp(&self, other: &Ident) -> Option<Ordering> {
823 Some(self.cmp(other))
824 }
825}
826
827impl Ord for Ident {
828 fn cmp(&self, other: &Ident) -> Ordering {
829 self.to_string().cmp(&other.to_string())
830 }
831}
832
833impl Hash for Ident {
834 fn hash<H: Hasher>(&self, hasher: &mut H) {
835 self.to_string().hash(hasher)
836 }
837}
838
David Tolnay82ba02d2018-05-20 16:22:43 -0700839/// Prints the identifier as a string that should be losslessly convertible back
840/// into the same identifier.
Alex Crichtonf3888432018-05-16 09:11:05 -0700841impl fmt::Display for Ident {
842 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
843 self.inner.fmt(f)
844 }
845}
846
847impl fmt::Debug for Ident {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700848 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
849 self.inner.fmt(f)
850 }
851}
852
David Tolnay82ba02d2018-05-20 16:22:43 -0700853/// A literal string (`"hello"`), byte string (`b"hello"`), character (`'a'`),
854/// byte character (`b'a'`), an integer or floating point number with or without
855/// a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
856///
857/// Boolean literals like `true` and `false` do not belong here, they are
858/// `Ident`s.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700859#[derive(Clone)]
860pub struct Literal {
861 inner: imp::Literal,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700862 _marker: marker::PhantomData<Rc<()>>,
863}
864
David Tolnay82ba02d2018-05-20 16:22:43 -0700865macro_rules! suffixed_int_literals {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700866 ($($name:ident => $kind:ident,)*) => ($(
David Tolnay82ba02d2018-05-20 16:22:43 -0700867 /// Creates a new suffixed integer literal with the specified value.
868 ///
869 /// This function will create an integer like `1u32` where the integer
870 /// value specified is the first part of the token and the integral is
871 /// also suffixed at the end. Literals created from negative numbers may
872 /// not survive rountrips through `TokenStream` or strings and may be
873 /// broken into two tokens (`-` and positive literal).
874 ///
875 /// Literals created through this method have the `Span::call_site()`
876 /// span by default, which can be configured with the `set_span` method
877 /// below.
878 pub fn $name(n: $kind) -> Literal {
879 Literal::_new(imp::Literal::$name(n))
880 }
881 )*)
882}
883
884macro_rules! unsuffixed_int_literals {
885 ($($name:ident => $kind:ident,)*) => ($(
886 /// Creates a new unsuffixed integer literal with the specified value.
887 ///
888 /// This function will create an integer like `1` where the integer
889 /// value specified is the first part of the token. No suffix is
890 /// specified on this token, meaning that invocations like
891 /// `Literal::i8_unsuffixed(1)` are equivalent to
892 /// `Literal::u32_unsuffixed(1)`. Literals created from negative numbers
893 /// may not survive rountrips through `TokenStream` or strings and may
894 /// be broken into two tokens (`-` and positive literal).
895 ///
896 /// Literals created through this method have the `Span::call_site()`
897 /// span by default, which can be configured with the `set_span` method
898 /// below.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700899 pub fn $name(n: $kind) -> Literal {
Alex Crichtona914a612018-04-04 07:48:44 -0700900 Literal::_new(imp::Literal::$name(n))
Alex Crichton1a7f7622017-07-05 17:47:15 -0700901 }
902 )*)
903}
904
Alex Crichton852d53d2017-05-19 19:25:08 -0700905impl Literal {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700906 fn _new(inner: imp::Literal) -> Literal {
907 Literal {
908 inner: inner,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700909 _marker: marker::PhantomData,
910 }
Alex Crichton1a7f7622017-07-05 17:47:15 -0700911 }
912
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700913 fn _new_stable(inner: stable::Literal) -> Literal {
914 Literal {
915 inner: inner.into(),
916 _marker: marker::PhantomData,
917 }
918 }
919
David Tolnay82ba02d2018-05-20 16:22:43 -0700920 suffixed_int_literals! {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700921 u8_suffixed => u8,
922 u16_suffixed => u16,
923 u32_suffixed => u32,
924 u64_suffixed => u64,
925 usize_suffixed => usize,
926 i8_suffixed => i8,
927 i16_suffixed => i16,
928 i32_suffixed => i32,
929 i64_suffixed => i64,
930 isize_suffixed => isize,
David Tolnay82ba02d2018-05-20 16:22:43 -0700931 }
Alex Crichton1a7f7622017-07-05 17:47:15 -0700932
David Tolnay82ba02d2018-05-20 16:22:43 -0700933 unsuffixed_int_literals! {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700934 u8_unsuffixed => u8,
935 u16_unsuffixed => u16,
936 u32_unsuffixed => u32,
937 u64_unsuffixed => u64,
938 usize_unsuffixed => usize,
939 i8_unsuffixed => i8,
940 i16_unsuffixed => i16,
941 i32_unsuffixed => i32,
942 i64_unsuffixed => i64,
943 isize_unsuffixed => isize,
Alex Crichton1a7f7622017-07-05 17:47:15 -0700944 }
945
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700946 pub fn f64_unsuffixed(f: f64) -> Literal {
947 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -0700948 Literal::_new(imp::Literal::f64_unsuffixed(f))
Alex Crichton1a7f7622017-07-05 17:47:15 -0700949 }
950
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700951 pub fn f64_suffixed(f: f64) -> Literal {
952 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -0700953 Literal::_new(imp::Literal::f64_suffixed(f))
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700954 }
955
David Tolnay82ba02d2018-05-20 16:22:43 -0700956 /// Creates a new unsuffixed floating-point literal.
957 ///
958 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
959 /// the float's value is emitted directly into the token but no suffix is
960 /// used, so it may be inferred to be a `f64` later in the compiler.
961 /// Literals created from negative numbers may not survive rountrips through
962 /// `TokenStream` or strings and may be broken into two tokens (`-` and
963 /// positive literal).
964 ///
965 /// # Panics
966 ///
967 /// This function requires that the specified float is finite, for example
968 /// if it is infinity or NaN this function will panic.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700969 pub fn f32_unsuffixed(f: f32) -> Literal {
970 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -0700971 Literal::_new(imp::Literal::f32_unsuffixed(f))
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700972 }
973
974 pub fn f32_suffixed(f: f32) -> Literal {
975 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -0700976 Literal::_new(imp::Literal::f32_suffixed(f))
Alex Crichton1a7f7622017-07-05 17:47:15 -0700977 }
978
979 pub fn string(string: &str) -> Literal {
Alex Crichtona914a612018-04-04 07:48:44 -0700980 Literal::_new(imp::Literal::string(string))
Alex Crichton1a7f7622017-07-05 17:47:15 -0700981 }
982
983 pub fn character(ch: char) -> Literal {
Alex Crichtona914a612018-04-04 07:48:44 -0700984 Literal::_new(imp::Literal::character(ch))
Alex Crichton76a5cc82017-05-23 07:01:44 -0700985 }
986
Alex Crichton9c2fb0a2017-05-26 08:49:31 -0700987 pub fn byte_string(s: &[u8]) -> Literal {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700988 Literal::_new(imp::Literal::byte_string(s))
Alex Crichton852d53d2017-05-19 19:25:08 -0700989 }
Alex Crichton76a5cc82017-05-23 07:01:44 -0700990
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700991 pub fn span(&self) -> Span {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700992 Span::_new(self.inner.span())
Alex Crichton1a7f7622017-07-05 17:47:15 -0700993 }
994
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700995 pub fn set_span(&mut self, span: Span) {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700996 self.inner.set_span(span.inner);
Alex Crichton31316622017-05-26 12:54:47 -0700997 }
Alex Crichton852d53d2017-05-19 19:25:08 -0700998}
999
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001000impl fmt::Debug for Literal {
1001 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1002 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001003 }
1004}
David Tolnaycb1b85f2017-06-03 16:40:35 -07001005
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001006impl fmt::Display for Literal {
1007 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1008 self.inner.fmt(f)
1009 }
1010}
1011
David Tolnay82ba02d2018-05-20 16:22:43 -07001012/// Public implementation details for the `TokenStream` type, such as iterators.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001013pub mod token_stream {
1014 use std::fmt;
1015 use std::marker;
1016 use std::rc::Rc;
1017
David Tolnay48ea5042018-04-23 19:17:35 -07001018 use imp;
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001019 pub use TokenStream;
David Tolnayb28f38a2018-03-31 22:02:29 +02001020 use TokenTree;
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001021
David Tolnay82ba02d2018-05-20 16:22:43 -07001022 /// An iterator over `TokenStream`'s `TokenTree`s.
1023 ///
1024 /// The iteration is "shallow", e.g. the iterator doesn't recurse into
1025 /// delimited groups, and returns whole groups as token trees.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001026 pub struct IntoIter {
1027 inner: imp::TokenTreeIter,
1028 _marker: marker::PhantomData<Rc<()>>,
1029 }
1030
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001031 impl Iterator for IntoIter {
1032 type Item = TokenTree;
1033
1034 fn next(&mut self) -> Option<TokenTree> {
1035 self.inner.next()
1036 }
1037 }
1038
1039 impl fmt::Debug for IntoIter {
1040 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1041 self.inner.fmt(f)
1042 }
1043 }
1044
1045 impl IntoIterator for TokenStream {
1046 type Item = TokenTree;
1047 type IntoIter = IntoIter;
1048
1049 fn into_iter(self) -> IntoIter {
1050 IntoIter {
1051 inner: self.inner.into_iter(),
1052 _marker: marker::PhantomData,
1053 }
1054 }
1055 }
1056}