blob: 44c56c354cda5908e766618e8541632e9d3ab68b [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.
Alex Crichtone9d344f2018-08-28 10:27:17 -070046#![doc(html_root_url = "https://docs.rs/proc-macro2/0.4.14")]
David Tolnay5a556cf2018-08-12 13:49:39 -070047#![cfg_attr(
Alex Crichtonce0904d2018-08-27 17:29:49 -070048 super_unstable,
David Tolnay5a556cf2018-08-12 13:49:39 -070049 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
Alex Crichtonce0904d2018-08-27 17:29:49 -070068#[cfg(not(wrap_proc_macro))]
Alex Crichton30a4e9e2018-04-27 17:02:19 -070069use stable as imp;
Alex Crichtonb15c6352017-05-19 19:36:36 -070070#[path = "unstable.rs"]
Alex Crichtonce0904d2018-08-27 17:29:49 -070071#[cfg(wrap_proc_macro)]
Alex Crichton44bffbc2017-05-19 17:51:59 -070072mod imp;
73
David Tolnay82ba02d2018-05-20 16:22:43 -070074/// An abstract stream of tokens, or more concretely a sequence of token trees.
75///
76/// This type provides interfaces for iterating over token trees and for
77/// collecting token trees into one stream.
78///
79/// Token stream is both the input and output of `#[proc_macro]`,
80/// `#[proc_macro_attribute]` and `#[proc_macro_derive]` definitions.
David Tolnaycb1b85f2017-06-03 16:40:35 -070081#[derive(Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -070082pub struct TokenStream {
83 inner: imp::TokenStream,
84 _marker: marker::PhantomData<Rc<()>>,
85}
Alex Crichton44bffbc2017-05-19 17:51:59 -070086
David Tolnay82ba02d2018-05-20 16:22:43 -070087/// Error returned from `TokenStream::from_str`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -070088pub struct LexError {
89 inner: imp::LexError,
90 _marker: marker::PhantomData<Rc<()>>,
91}
92
93impl TokenStream {
94 fn _new(inner: imp::TokenStream) -> TokenStream {
95 TokenStream {
96 inner: inner,
97 _marker: marker::PhantomData,
98 }
99 }
100
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700101 fn _new_stable(inner: stable::TokenStream) -> TokenStream {
102 TokenStream {
103 inner: inner.into(),
104 _marker: marker::PhantomData,
105 }
106 }
107
David Tolnay82ba02d2018-05-20 16:22:43 -0700108 /// Returns an empty `TokenStream` containing no token trees.
David Tolnayc3bb4592018-05-28 20:09:44 -0700109 pub fn new() -> TokenStream {
110 TokenStream::_new(imp::TokenStream::new())
111 }
112
113 #[deprecated(since = "0.4.4", note = "please use TokenStream::new")]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700114 pub fn empty() -> TokenStream {
David Tolnayc3bb4592018-05-28 20:09:44 -0700115 TokenStream::new()
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700116 }
117
David Tolnay82ba02d2018-05-20 16:22:43 -0700118 /// Checks if this `TokenStream` is empty.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700119 pub fn is_empty(&self) -> bool {
120 self.inner.is_empty()
121 }
122}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700123
Árpád Goretity4f74b682018-07-14 00:47:51 +0200124/// `TokenStream::default()` returns an empty stream,
125/// i.e. this is equivalent with `TokenStream::new()`.
126impl Default for TokenStream {
127 fn default() -> Self {
128 TokenStream::new()
129 }
130}
131
David Tolnay82ba02d2018-05-20 16:22:43 -0700132/// Attempts to break the string into tokens and parse those tokens into a token
133/// stream.
134///
135/// May fail for a number of reasons, for example, if the string contains
136/// unbalanced delimiters or characters not existing in the language.
137///
138/// NOTE: Some errors may cause panics instead of returning `LexError`. We
139/// reserve the right to change these errors into `LexError`s later.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700140impl FromStr for TokenStream {
141 type Err = LexError;
142
143 fn from_str(src: &str) -> Result<TokenStream, LexError> {
David Tolnayb28f38a2018-03-31 22:02:29 +0200144 let e = src.parse().map_err(|e| LexError {
145 inner: e,
146 _marker: marker::PhantomData,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700147 })?;
148 Ok(TokenStream::_new(e))
Alex Crichton44bffbc2017-05-19 17:51:59 -0700149 }
150}
151
Alex Crichton53548482018-08-11 21:54:05 -0700152#[cfg(use_proc_macro)]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700153impl From<proc_macro::TokenStream> for TokenStream {
154 fn from(inner: proc_macro::TokenStream) -> TokenStream {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700155 TokenStream::_new(inner.into())
Alex Crichton44bffbc2017-05-19 17:51:59 -0700156 }
157}
158
Alex Crichton53548482018-08-11 21:54:05 -0700159#[cfg(use_proc_macro)]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700160impl From<TokenStream> for proc_macro::TokenStream {
161 fn from(inner: TokenStream) -> proc_macro::TokenStream {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700162 inner.inner.into()
Alex Crichton44bffbc2017-05-19 17:51:59 -0700163 }
164}
165
Alex Crichtonf3888432018-05-16 09:11:05 -0700166impl Extend<TokenTree> for TokenStream {
167 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, streams: I) {
168 self.inner.extend(streams)
169 }
170}
171
David Tolnay5c58c532018-08-13 11:33:51 -0700172impl Extend<TokenStream> for TokenStream {
173 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
174 self.inner
175 .extend(streams.into_iter().map(|stream| stream.inner))
176 }
177}
178
David Tolnay82ba02d2018-05-20 16:22:43 -0700179/// Collects a number of token trees into a single stream.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700180impl FromIterator<TokenTree> for TokenStream {
181 fn from_iter<I: IntoIterator<Item = TokenTree>>(streams: I) -> Self {
182 TokenStream::_new(streams.into_iter().collect())
Alex Crichton44bffbc2017-05-19 17:51:59 -0700183 }
184}
185
David Tolnay82ba02d2018-05-20 16:22:43 -0700186/// Prints the token stream as a string that is supposed to be losslessly
187/// convertible back into the same token stream (modulo spans), except for
188/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
189/// numeric literals.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700190impl fmt::Display 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
David Tolnay82ba02d2018-05-20 16:22:43 -0700196/// Prints token in a form convenient for debugging.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700197impl fmt::Debug for TokenStream {
198 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
199 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700200 }
201}
202
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700203impl fmt::Debug for LexError {
204 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
205 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700206 }
207}
208
Nika Layzellb35a9a32017-12-30 14:34:35 -0500209// Returned by reference, so we can't easily wrap it.
David Tolnay1ebe3972018-01-02 20:14:20 -0800210#[cfg(procmacro2_semver_exempt)]
Nika Layzellb35a9a32017-12-30 14:34:35 -0500211pub use imp::FileName;
212
David Tolnay82ba02d2018-05-20 16:22:43 -0700213/// The source file of a given `Span`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700214///
215/// This type is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800216#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500217#[derive(Clone, PartialEq, Eq)]
218pub struct SourceFile(imp::SourceFile);
219
David Tolnay1ebe3972018-01-02 20:14:20 -0800220#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500221impl SourceFile {
David Tolnay82ba02d2018-05-20 16:22:43 -0700222 /// Get the path to this source file.
223 ///
224 /// ### Note
225 ///
226 /// If the code span associated with this `SourceFile` was generated by an
227 /// external macro, this may not be an actual path on the filesystem. Use
228 /// [`is_real`] to check.
229 ///
230 /// Also note that even if `is_real` returns `true`, if
231 /// `--remap-path-prefix` was passed on the command line, the path as given
232 /// may not actually be valid.
233 ///
234 /// [`is_real`]: #method.is_real
Nika Layzellb35a9a32017-12-30 14:34:35 -0500235 pub fn path(&self) -> &FileName {
236 self.0.path()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500237 }
238
David Tolnay82ba02d2018-05-20 16:22:43 -0700239 /// Returns `true` if this source file is a real source file, and not
240 /// generated by an external macro's expansion.
Nika Layzellf8d5f212017-12-11 14:07:02 -0500241 pub fn is_real(&self) -> bool {
242 self.0.is_real()
243 }
244}
245
David Tolnay1ebe3972018-01-02 20:14:20 -0800246#[cfg(procmacro2_semver_exempt)]
Nika Layzellb35a9a32017-12-30 14:34:35 -0500247impl AsRef<FileName> for SourceFile {
248 fn as_ref(&self) -> &FileName {
249 self.0.path()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500250 }
251}
252
David Tolnay1ebe3972018-01-02 20:14:20 -0800253#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500254impl fmt::Debug for SourceFile {
255 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
256 self.0.fmt(f)
257 }
258}
259
David Tolnay82ba02d2018-05-20 16:22:43 -0700260/// A line-column pair representing the start or end of a `Span`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700261///
262/// This type is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800263#[cfg(procmacro2_semver_exempt)]
Nika Layzell1ecb6ce2017-12-30 14:34:05 -0500264pub struct LineColumn {
David Tolnay82ba02d2018-05-20 16:22:43 -0700265 /// The 1-indexed line in the source file on which the span starts or ends
266 /// (inclusive).
Nika Layzell1ecb6ce2017-12-30 14:34:05 -0500267 pub line: usize,
David Tolnay82ba02d2018-05-20 16:22:43 -0700268 /// The 0-indexed column (in UTF-8 characters) in the source file on which
269 /// the span starts or ends (inclusive).
Nika Layzell1ecb6ce2017-12-30 14:34:05 -0500270 pub column: usize,
271}
Nika Layzellf8d5f212017-12-11 14:07:02 -0500272
David Tolnay82ba02d2018-05-20 16:22:43 -0700273/// A region of source code, along with macro expansion information.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700274#[derive(Copy, Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700275pub struct Span {
276 inner: imp::Span,
277 _marker: marker::PhantomData<Rc<()>>,
278}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700279
Alex Crichton44bffbc2017-05-19 17:51:59 -0700280impl Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700281 fn _new(inner: imp::Span) -> Span {
282 Span {
283 inner: inner,
284 _marker: marker::PhantomData,
285 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700286 }
Alex Crichtone6085b72017-11-21 07:24:25 -0800287
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700288 fn _new_stable(inner: stable::Span) -> Span {
289 Span {
290 inner: inner.into(),
291 _marker: marker::PhantomData,
292 }
293 }
294
David Tolnay82ba02d2018-05-20 16:22:43 -0700295 /// The span of the invocation of the current procedural macro.
296 ///
297 /// Identifiers created with this span will be resolved as if they were
298 /// written directly at the macro call location (call-site hygiene) and
299 /// other code at the macro call site will be able to refer to them as well.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700300 pub fn call_site() -> Span {
301 Span::_new(imp::Span::call_site())
302 }
303
David Tolnay82ba02d2018-05-20 16:22:43 -0700304 /// A span that resolves at the macro definition site.
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)]
Alex Crichtone6085b72017-11-21 07:24:25 -0800308 pub fn def_site() -> Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700309 Span::_new(imp::Span::def_site())
Alex Crichtone6085b72017-11-21 07:24:25 -0800310 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500311
David Tolnay4e8e3972018-01-05 18:10:22 -0800312 /// Creates a new span with the same line/column information as `self` but
313 /// that resolves symbols as though it were at `other`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700314 ///
315 /// This method is semver exempt and not exposed by default.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700316 #[cfg(procmacro2_semver_exempt)]
David Tolnay4e8e3972018-01-05 18:10:22 -0800317 pub fn resolved_at(&self, other: Span) -> Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700318 Span::_new(self.inner.resolved_at(other.inner))
David Tolnay4e8e3972018-01-05 18:10:22 -0800319 }
320
321 /// Creates a new span with the same name resolution behavior as `self` but
322 /// with the line/column information of `other`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700323 ///
324 /// This method is semver exempt and not exposed by default.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700325 #[cfg(procmacro2_semver_exempt)]
David Tolnay4e8e3972018-01-05 18:10:22 -0800326 pub fn located_at(&self, other: Span) -> Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700327 Span::_new(self.inner.located_at(other.inner))
David Tolnay4e8e3972018-01-05 18:10:22 -0800328 }
329
David Tolnayd66ecf62018-01-02 20:05:42 -0800330 /// This method is only available when the `"nightly"` feature is enabled.
Sergio Benitez4a232822018-08-28 17:06:22 -0700331 #[doc(hidden)]
332 #[cfg(any(feature = "nightly", super_unstable))]
David Tolnay16a17202017-12-31 10:47:24 -0500333 pub fn unstable(self) -> proc_macro::Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700334 self.inner.unstable()
David Tolnay16a17202017-12-31 10:47:24 -0500335 }
336
David Tolnay82ba02d2018-05-20 16:22:43 -0700337 /// The original source file into which this span points.
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 source_file(&self) -> SourceFile {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700342 SourceFile(self.inner.source_file())
Nika Layzellf8d5f212017-12-11 14:07:02 -0500343 }
344
David Tolnay82ba02d2018-05-20 16:22:43 -0700345 /// Get the starting line/column in the source file for this span.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700346 ///
347 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800348 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500349 pub fn start(&self) -> LineColumn {
David Tolnayb28f38a2018-03-31 22:02:29 +0200350 let imp::LineColumn { line, column } = self.inner.start();
351 LineColumn {
352 line: line,
353 column: column,
354 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500355 }
356
David Tolnay82ba02d2018-05-20 16:22:43 -0700357 /// Get the ending line/column in the source file for this span.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700358 ///
359 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800360 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500361 pub fn end(&self) -> LineColumn {
David Tolnayb28f38a2018-03-31 22:02:29 +0200362 let imp::LineColumn { line, column } = self.inner.end();
363 LineColumn {
364 line: line,
365 column: column,
366 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500367 }
368
David Tolnay82ba02d2018-05-20 16:22:43 -0700369 /// Create a new span encompassing `self` and `other`.
370 ///
371 /// Returns `None` if `self` and `other` are from different files.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700372 ///
373 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800374 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500375 pub fn join(&self, other: Span) -> Option<Span> {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700376 self.inner.join(other.inner).map(Span::_new)
377 }
Alex Crichtonb2c94622018-04-04 07:36:41 -0700378
David Tolnay82ba02d2018-05-20 16:22:43 -0700379 /// Compares to spans to see if they're equal.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700380 ///
381 /// This method is semver exempt and not exposed by default.
Alex Crichtonb2c94622018-04-04 07:36:41 -0700382 #[cfg(procmacro2_semver_exempt)]
383 pub fn eq(&self, other: &Span) -> bool {
384 self.inner.eq(&other.inner)
385 }
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700386}
387
David Tolnay82ba02d2018-05-20 16:22:43 -0700388/// Prints a span in a form convenient for debugging.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700389impl fmt::Debug for Span {
390 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
391 self.inner.fmt(f)
Nika Layzellf8d5f212017-12-11 14:07:02 -0500392 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700393}
394
David Tolnay82ba02d2018-05-20 16:22:43 -0700395/// A single token or a delimited sequence of token trees (e.g. `[1, (), ..]`).
David Tolnay034205f2018-04-22 16:45:28 -0700396#[derive(Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700397pub enum TokenTree {
David Tolnay82ba02d2018-05-20 16:22:43 -0700398 /// A token stream surrounded by bracket delimiters.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700399 Group(Group),
David Tolnay82ba02d2018-05-20 16:22:43 -0700400 /// An identifier.
Alex Crichtonf3888432018-05-16 09:11:05 -0700401 Ident(Ident),
David Tolnay82ba02d2018-05-20 16:22:43 -0700402 /// A single punctuation character (`+`, `,`, `$`, etc.).
Alex Crichtonf3888432018-05-16 09:11:05 -0700403 Punct(Punct),
David Tolnay82ba02d2018-05-20 16:22:43 -0700404 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700405 Literal(Literal),
Alex Crichton1a7f7622017-07-05 17:47:15 -0700406}
407
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700408impl TokenTree {
David Tolnay82ba02d2018-05-20 16:22:43 -0700409 /// Returns the span of this tree, delegating to the `span` method of
410 /// the contained token or a delimited stream.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700411 pub fn span(&self) -> Span {
412 match *self {
413 TokenTree::Group(ref t) => t.span(),
Alex Crichtonf3888432018-05-16 09:11:05 -0700414 TokenTree::Ident(ref t) => t.span(),
415 TokenTree::Punct(ref t) => t.span(),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700416 TokenTree::Literal(ref t) => t.span(),
417 }
418 }
419
David Tolnay82ba02d2018-05-20 16:22:43 -0700420 /// Configures the span for *only this token*.
421 ///
422 /// Note that if this token is a `Group` then this method will not configure
423 /// the span of each of the internal tokens, this will simply delegate to
424 /// the `set_span` method of each variant.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700425 pub fn set_span(&mut self, span: Span) {
426 match *self {
427 TokenTree::Group(ref mut t) => t.set_span(span),
Alex Crichtonf3888432018-05-16 09:11:05 -0700428 TokenTree::Ident(ref mut t) => t.set_span(span),
429 TokenTree::Punct(ref mut t) => t.set_span(span),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700430 TokenTree::Literal(ref mut t) => t.set_span(span),
431 }
432 }
433}
434
435impl From<Group> for TokenTree {
436 fn from(g: Group) -> TokenTree {
437 TokenTree::Group(g)
438 }
439}
440
Alex Crichtonf3888432018-05-16 09:11:05 -0700441impl From<Ident> for TokenTree {
442 fn from(g: Ident) -> TokenTree {
443 TokenTree::Ident(g)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700444 }
445}
446
Alex Crichtonf3888432018-05-16 09:11:05 -0700447impl From<Punct> for TokenTree {
448 fn from(g: Punct) -> TokenTree {
449 TokenTree::Punct(g)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700450 }
451}
452
453impl From<Literal> for TokenTree {
454 fn from(g: Literal) -> TokenTree {
455 TokenTree::Literal(g)
Alex Crichton1a7f7622017-07-05 17:47:15 -0700456 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700457}
458
David Tolnay82ba02d2018-05-20 16:22:43 -0700459/// Prints the token tree as a string that is supposed to be losslessly
460/// convertible back into the same token tree (modulo spans), except for
461/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
462/// numeric literals.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700463impl fmt::Display for TokenTree {
464 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700465 match *self {
466 TokenTree::Group(ref t) => t.fmt(f),
Alex Crichtonf3888432018-05-16 09:11:05 -0700467 TokenTree::Ident(ref t) => t.fmt(f),
468 TokenTree::Punct(ref t) => t.fmt(f),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700469 TokenTree::Literal(ref t) => t.fmt(f),
470 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700471 }
472}
473
David Tolnay82ba02d2018-05-20 16:22:43 -0700474/// Prints token tree in a form convenient for debugging.
David Tolnay034205f2018-04-22 16:45:28 -0700475impl fmt::Debug for TokenTree {
476 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
477 // Each of these has the name in the struct type in the derived debug,
478 // so don't bother with an extra layer of indirection
479 match *self {
480 TokenTree::Group(ref t) => t.fmt(f),
David Tolnayd8fcdb82018-06-02 15:43:53 -0700481 TokenTree::Ident(ref t) => {
482 let mut debug = f.debug_struct("Ident");
483 debug.field("sym", &format_args!("{}", t));
484 #[cfg(any(feature = "nightly", procmacro2_semver_exempt))]
485 debug.field("span", &t.span());
486 debug.finish()
487 }
Alex Crichtonf3888432018-05-16 09:11:05 -0700488 TokenTree::Punct(ref t) => t.fmt(f),
David Tolnay034205f2018-04-22 16:45:28 -0700489 TokenTree::Literal(ref t) => t.fmt(f),
490 }
491 }
492}
493
David Tolnay82ba02d2018-05-20 16:22:43 -0700494/// A delimited token stream.
495///
496/// A `Group` internally contains a `TokenStream` which is surrounded by
497/// `Delimiter`s.
David Tolnay034205f2018-04-22 16:45:28 -0700498#[derive(Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700499pub struct Group {
500 delimiter: Delimiter,
501 stream: TokenStream,
502 span: Span,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700503}
504
David Tolnay82ba02d2018-05-20 16:22:43 -0700505/// Describes how a sequence of token trees is delimited.
Michael Layzell5372f4b2017-06-02 10:29:31 -0400506#[derive(Copy, Clone, Debug, Eq, PartialEq)]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700507pub enum Delimiter {
David Tolnay82ba02d2018-05-20 16:22:43 -0700508 /// `( ... )`
Alex Crichton44bffbc2017-05-19 17:51:59 -0700509 Parenthesis,
David Tolnay82ba02d2018-05-20 16:22:43 -0700510 /// `{ ... }`
Alex Crichton44bffbc2017-05-19 17:51:59 -0700511 Brace,
David Tolnay82ba02d2018-05-20 16:22:43 -0700512 /// `[ ... ]`
Alex Crichton44bffbc2017-05-19 17:51:59 -0700513 Bracket,
David Tolnay82ba02d2018-05-20 16:22:43 -0700514 /// `Ø ... Ø`
515 ///
516 /// An implicit delimiter, that may, for example, appear around tokens
517 /// coming from a "macro variable" `$var`. It is important to preserve
518 /// operator priorities in cases like `$var * 3` where `$var` is `1 + 2`.
519 /// Implicit delimiters may not survive roundtrip of a token stream through
520 /// a string.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700521 None,
522}
523
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700524impl Group {
David Tolnay82ba02d2018-05-20 16:22:43 -0700525 /// Creates a new `Group` with the given delimiter and token stream.
526 ///
527 /// This constructor will set the span for this group to
528 /// `Span::call_site()`. To change the span you can use the `set_span`
529 /// method below.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700530 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
531 Group {
532 delimiter: delimiter,
533 stream: stream,
534 span: Span::call_site(),
535 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700536 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700537
David Tolnay82ba02d2018-05-20 16:22:43 -0700538 /// Returns the delimiter of this `Group`
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700539 pub fn delimiter(&self) -> Delimiter {
540 self.delimiter
Alex Crichton44bffbc2017-05-19 17:51:59 -0700541 }
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700542
David Tolnay82ba02d2018-05-20 16:22:43 -0700543 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
544 ///
545 /// Note that the returned token stream does not include the delimiter
546 /// returned above.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700547 pub fn stream(&self) -> TokenStream {
548 self.stream.clone()
549 }
550
David Tolnay82ba02d2018-05-20 16:22:43 -0700551 /// Returns the span for the delimiters of this token stream, spanning the
552 /// entire `Group`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700553 pub fn span(&self) -> Span {
554 self.span
555 }
556
David Tolnay82ba02d2018-05-20 16:22:43 -0700557 /// Configures the span for this `Group`'s delimiters, but not its internal
558 /// tokens.
559 ///
560 /// This method will **not** set the span of all the internal tokens spanned
561 /// by this group, but rather it will only set the span of the delimiter
562 /// tokens at the level of the `Group`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700563 pub fn set_span(&mut self, span: Span) {
564 self.span = span;
565 }
566}
567
David Tolnay82ba02d2018-05-20 16:22:43 -0700568/// Prints the group as a string that should be losslessly convertible back
569/// into the same group (modulo spans), except for possibly `TokenTree::Group`s
570/// with `Delimiter::None` delimiters.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700571impl fmt::Display for Group {
572 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
hcpl1a4d7792018-05-29 21:01:44 +0300573 let (left, right) = match self.delimiter {
574 Delimiter::Parenthesis => ("(", ")"),
David Tolnay03b43da2018-06-02 15:25:57 -0700575 Delimiter::Brace => ("{", "}"),
576 Delimiter::Bracket => ("[", "]"),
577 Delimiter::None => ("", ""),
hcpl1a4d7792018-05-29 21:01:44 +0300578 };
579
580 f.write_str(left)?;
581 self.stream.fmt(f)?;
582 f.write_str(right)?;
583
584 Ok(())
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700585 }
586}
587
David Tolnay034205f2018-04-22 16:45:28 -0700588impl fmt::Debug for Group {
589 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
590 let mut debug = fmt.debug_struct("Group");
591 debug.field("delimiter", &self.delimiter);
592 debug.field("stream", &self.stream);
593 #[cfg(procmacro2_semver_exempt)]
594 debug.field("span", &self.span);
595 debug.finish()
596 }
597}
598
David Tolnay82ba02d2018-05-20 16:22:43 -0700599/// An `Punct` is an single punctuation character like `+`, `-` or `#`.
600///
601/// Multicharacter operators like `+=` are represented as two instances of
602/// `Punct` with different forms of `Spacing` returned.
Alex Crichtonf3888432018-05-16 09:11:05 -0700603#[derive(Clone)]
604pub struct Punct {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700605 op: char,
606 spacing: Spacing,
607 span: Span,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700608}
609
David Tolnay82ba02d2018-05-20 16:22:43 -0700610/// Whether an `Punct` is followed immediately by another `Punct` or followed by
611/// another token or whitespace.
Lukas Kalbertodteb3f9302017-08-20 18:58:41 +0200612#[derive(Copy, Clone, Debug, Eq, PartialEq)]
Alex Crichton1a7f7622017-07-05 17:47:15 -0700613pub enum Spacing {
David Tolnay82ba02d2018-05-20 16:22:43 -0700614 /// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700615 Alone,
David Tolnay82ba02d2018-05-20 16:22:43 -0700616 /// E.g. `+` is `Joint` in `+=` or `'#`.
617 ///
618 /// Additionally, single quote `'` can join with identifiers to form
619 /// lifetimes `'ident`.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700620 Joint,
621}
622
Alex Crichtonf3888432018-05-16 09:11:05 -0700623impl Punct {
David Tolnay82ba02d2018-05-20 16:22:43 -0700624 /// Creates a new `Punct` from the given character and spacing.
625 ///
626 /// The `ch` argument must be a valid punctuation character permitted by the
627 /// language, otherwise the function will panic.
628 ///
629 /// The returned `Punct` will have the default span of `Span::call_site()`
630 /// which can be further configured with the `set_span` method below.
Alex Crichtonf3888432018-05-16 09:11:05 -0700631 pub fn new(op: char, spacing: Spacing) -> Punct {
632 Punct {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700633 op: op,
634 spacing: spacing,
635 span: Span::call_site(),
636 }
637 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700638
David Tolnay82ba02d2018-05-20 16:22:43 -0700639 /// Returns the value of this punctuation character as `char`.
Alex Crichtonf3888432018-05-16 09:11:05 -0700640 pub fn as_char(&self) -> char {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700641 self.op
642 }
643
David Tolnay82ba02d2018-05-20 16:22:43 -0700644 /// Returns the spacing of this punctuation character, indicating whether
645 /// it's immediately followed by another `Punct` in the token stream, so
646 /// they can potentially be combined into a multicharacter operator
647 /// (`Joint`), or it's followed by some other token or whitespace (`Alone`)
648 /// so the operator has certainly ended.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700649 pub fn spacing(&self) -> Spacing {
650 self.spacing
651 }
652
David Tolnay82ba02d2018-05-20 16:22:43 -0700653 /// Returns the span for this punctuation character.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700654 pub fn span(&self) -> Span {
655 self.span
656 }
657
David Tolnay82ba02d2018-05-20 16:22:43 -0700658 /// Configure the span for this punctuation character.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700659 pub fn set_span(&mut self, span: Span) {
660 self.span = span;
661 }
662}
663
David Tolnay82ba02d2018-05-20 16:22:43 -0700664/// Prints the punctuation character as a string that should be losslessly
665/// convertible back into the same character.
Alex Crichtonf3888432018-05-16 09:11:05 -0700666impl fmt::Display for Punct {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700667 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
668 self.op.fmt(f)
669 }
670}
671
Alex Crichtonf3888432018-05-16 09:11:05 -0700672impl fmt::Debug for Punct {
David Tolnay034205f2018-04-22 16:45:28 -0700673 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonf3888432018-05-16 09:11:05 -0700674 let mut debug = fmt.debug_struct("Punct");
David Tolnay034205f2018-04-22 16:45:28 -0700675 debug.field("op", &self.op);
676 debug.field("spacing", &self.spacing);
677 #[cfg(procmacro2_semver_exempt)]
678 debug.field("span", &self.span);
679 debug.finish()
680 }
681}
682
David Tolnay8b71dac2018-05-20 17:07:47 -0700683/// A word of Rust code, which may be a keyword or legal variable name.
684///
685/// An identifier consists of at least one Unicode code point, the first of
686/// which has the XID_Start property and the rest of which have the XID_Continue
687/// property.
688///
689/// - The empty string is not an identifier. Use `Option<Ident>`.
690/// - A lifetime is not an identifier. Use `syn::Lifetime` instead.
691///
692/// An identifier constructed with `Ident::new` is permitted to be a Rust
693/// keyword, though parsing one through its [`Synom`] implementation rejects
694/// Rust keywords. Use `call!(Ident::parse_any)` when parsing to match the
695/// behaviour of `Ident::new`.
696///
697/// [`Synom`]: https://docs.rs/syn/0.14/syn/synom/trait.Synom.html
698///
699/// # Examples
700///
701/// A new ident can be created from a string using the `Ident::new` function.
702/// A span must be provided explicitly which governs the name resolution
703/// behavior of the resulting identifier.
704///
705/// ```rust
706/// extern crate proc_macro2;
707///
708/// use proc_macro2::{Ident, Span};
709///
710/// fn main() {
711/// let call_ident = Ident::new("calligraphy", Span::call_site());
712///
713/// println!("{}", call_ident);
714/// }
715/// ```
716///
717/// An ident can be interpolated into a token stream using the `quote!` macro.
718///
719/// ```rust
720/// #[macro_use]
721/// extern crate quote;
722///
723/// extern crate proc_macro2;
724///
725/// use proc_macro2::{Ident, Span};
726///
727/// fn main() {
728/// let ident = Ident::new("demo", Span::call_site());
729///
730/// // Create a variable binding whose name is this ident.
731/// let expanded = quote! { let #ident = 10; };
732///
733/// // Create a variable binding with a slightly different name.
734/// let temp_ident = Ident::new(&format!("new_{}", ident), Span::call_site());
735/// let expanded = quote! { let #temp_ident = 10; };
736/// }
737/// ```
738///
739/// A string representation of the ident is available through the `to_string()`
740/// method.
741///
742/// ```rust
743/// # extern crate proc_macro2;
744/// #
745/// # use proc_macro2::{Ident, Span};
746/// #
747/// # let ident = Ident::new("another_identifier", Span::call_site());
748/// #
749/// // Examine the ident as a string.
750/// let ident_string = ident.to_string();
751/// if ident_string.len() > 60 {
752/// println!("Very long identifier: {}", ident_string)
753/// }
754/// ```
Alex Crichtonf3888432018-05-16 09:11:05 -0700755#[derive(Clone)]
756pub struct Ident {
757 inner: imp::Ident,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700758 _marker: marker::PhantomData<Rc<()>>,
759}
760
Alex Crichtonf3888432018-05-16 09:11:05 -0700761impl Ident {
762 fn _new(inner: imp::Ident) -> Ident {
763 Ident {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700764 inner: inner,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700765 _marker: marker::PhantomData,
766 }
767 }
768
David Tolnay82ba02d2018-05-20 16:22:43 -0700769 /// Creates a new `Ident` with the given `string` as well as the specified
770 /// `span`.
771 ///
772 /// The `string` argument must be a valid identifier permitted by the
773 /// language, otherwise the function will panic.
774 ///
775 /// Note that `span`, currently in rustc, configures the hygiene information
776 /// for this identifier.
777 ///
778 /// As of this time `Span::call_site()` explicitly opts-in to "call-site"
779 /// hygiene meaning that identifiers created with this span will be resolved
780 /// as if they were written directly at the location of the macro call, and
781 /// other code at the macro call site will be able to refer to them as well.
782 ///
783 /// Later spans like `Span::def_site()` will allow to opt-in to
784 /// "definition-site" hygiene meaning that identifiers created with this
785 /// span will be resolved at the location of the macro definition and other
786 /// code at the macro call site will not be able to refer to them.
787 ///
788 /// Due to the current importance of hygiene this constructor, unlike other
789 /// tokens, requires a `Span` to be specified at construction.
David Tolnay8b71dac2018-05-20 17:07:47 -0700790 ///
791 /// # Panics
792 ///
793 /// Panics if the input string is neither a keyword nor a legal variable
794 /// name.
Alex Crichtonf3888432018-05-16 09:11:05 -0700795 pub fn new(string: &str, span: Span) -> Ident {
796 Ident::_new(imp::Ident::new(string, span.inner))
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700797 }
798
David Tolnay82ba02d2018-05-20 16:22:43 -0700799 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
David Tolnaya01ca8e2018-06-04 00:55:28 -0700800 ///
801 /// This method is semver exempt and not exposed by default.
Alex Crichtonf3888432018-05-16 09:11:05 -0700802 #[cfg(procmacro2_semver_exempt)]
803 pub fn new_raw(string: &str, span: Span) -> Ident {
804 Ident::_new_raw(string, span)
805 }
806
807 fn _new_raw(string: &str, span: Span) -> Ident {
808 Ident::_new(imp::Ident::new_raw(string, span.inner))
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700809 }
810
David Tolnay82ba02d2018-05-20 16:22:43 -0700811 /// Returns the span of this `Ident`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700812 pub fn span(&self) -> Span {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700813 Span::_new(self.inner.span())
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700814 }
815
David Tolnay82ba02d2018-05-20 16:22:43 -0700816 /// Configures the span of this `Ident`, possibly changing its hygiene
817 /// context.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700818 pub fn set_span(&mut self, span: Span) {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700819 self.inner.set_span(span.inner);
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700820 }
821}
822
Alex Crichtonf3888432018-05-16 09:11:05 -0700823impl PartialEq for Ident {
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700824 fn eq(&self, other: &Ident) -> bool {
Alex Crichtonf3888432018-05-16 09:11:05 -0700825 self.to_string() == other.to_string()
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700826 }
827}
828
David Tolnayc0bbcc52018-05-18 10:51:04 -0700829impl<T> PartialEq<T> for Ident
830where
831 T: ?Sized + AsRef<str>,
832{
833 fn eq(&self, other: &T) -> bool {
834 self.to_string() == other.as_ref()
835 }
836}
837
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700838impl Eq for Ident {}
Alex Crichtonf3888432018-05-16 09:11:05 -0700839
840impl PartialOrd for Ident {
841 fn partial_cmp(&self, other: &Ident) -> Option<Ordering> {
842 Some(self.cmp(other))
843 }
844}
845
846impl Ord for Ident {
847 fn cmp(&self, other: &Ident) -> Ordering {
848 self.to_string().cmp(&other.to_string())
849 }
850}
851
852impl Hash for Ident {
853 fn hash<H: Hasher>(&self, hasher: &mut H) {
854 self.to_string().hash(hasher)
855 }
856}
857
David Tolnay82ba02d2018-05-20 16:22:43 -0700858/// Prints the identifier as a string that should be losslessly convertible back
859/// into the same identifier.
Alex Crichtonf3888432018-05-16 09:11:05 -0700860impl fmt::Display for Ident {
861 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
862 self.inner.fmt(f)
863 }
864}
865
866impl fmt::Debug for Ident {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700867 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
868 self.inner.fmt(f)
869 }
870}
871
David Tolnay82ba02d2018-05-20 16:22:43 -0700872/// A literal string (`"hello"`), byte string (`b"hello"`), character (`'a'`),
873/// byte character (`b'a'`), an integer or floating point number with or without
874/// a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
875///
876/// Boolean literals like `true` and `false` do not belong here, they are
877/// `Ident`s.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700878#[derive(Clone)]
879pub struct Literal {
880 inner: imp::Literal,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700881 _marker: marker::PhantomData<Rc<()>>,
882}
883
David Tolnay82ba02d2018-05-20 16:22:43 -0700884macro_rules! suffixed_int_literals {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700885 ($($name:ident => $kind:ident,)*) => ($(
David Tolnay82ba02d2018-05-20 16:22:43 -0700886 /// Creates a new suffixed integer literal with the specified value.
887 ///
888 /// This function will create an integer like `1u32` where the integer
889 /// value specified is the first part of the token and the integral is
890 /// also suffixed at the end. Literals created from negative numbers may
891 /// not survive rountrips through `TokenStream` or strings and may be
892 /// broken into two tokens (`-` and positive literal).
893 ///
894 /// Literals created through this method have the `Span::call_site()`
895 /// span by default, which can be configured with the `set_span` method
896 /// below.
897 pub fn $name(n: $kind) -> Literal {
898 Literal::_new(imp::Literal::$name(n))
899 }
900 )*)
901}
902
903macro_rules! unsuffixed_int_literals {
904 ($($name:ident => $kind:ident,)*) => ($(
905 /// Creates a new unsuffixed integer literal with the specified value.
906 ///
907 /// This function will create an integer like `1` where the integer
908 /// value specified is the first part of the token. No suffix is
909 /// specified on this token, meaning that invocations like
910 /// `Literal::i8_unsuffixed(1)` are equivalent to
911 /// `Literal::u32_unsuffixed(1)`. Literals created from negative numbers
912 /// may not survive rountrips through `TokenStream` or strings and may
913 /// be broken into two tokens (`-` and positive literal).
914 ///
915 /// Literals created through this method have the `Span::call_site()`
916 /// span by default, which can be configured with the `set_span` method
917 /// below.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700918 pub fn $name(n: $kind) -> Literal {
Alex Crichtona914a612018-04-04 07:48:44 -0700919 Literal::_new(imp::Literal::$name(n))
Alex Crichton1a7f7622017-07-05 17:47:15 -0700920 }
921 )*)
922}
923
Alex Crichton852d53d2017-05-19 19:25:08 -0700924impl Literal {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700925 fn _new(inner: imp::Literal) -> Literal {
926 Literal {
927 inner: inner,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700928 _marker: marker::PhantomData,
929 }
Alex Crichton1a7f7622017-07-05 17:47:15 -0700930 }
931
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700932 fn _new_stable(inner: stable::Literal) -> Literal {
933 Literal {
934 inner: inner.into(),
935 _marker: marker::PhantomData,
936 }
937 }
938
David Tolnay82ba02d2018-05-20 16:22:43 -0700939 suffixed_int_literals! {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700940 u8_suffixed => u8,
941 u16_suffixed => u16,
942 u32_suffixed => u32,
943 u64_suffixed => u64,
944 usize_suffixed => usize,
945 i8_suffixed => i8,
946 i16_suffixed => i16,
947 i32_suffixed => i32,
948 i64_suffixed => i64,
949 isize_suffixed => isize,
David Tolnay82ba02d2018-05-20 16:22:43 -0700950 }
Alex Crichton1a7f7622017-07-05 17:47:15 -0700951
David Tolnay82ba02d2018-05-20 16:22:43 -0700952 unsuffixed_int_literals! {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700953 u8_unsuffixed => u8,
954 u16_unsuffixed => u16,
955 u32_unsuffixed => u32,
956 u64_unsuffixed => u64,
957 usize_unsuffixed => usize,
958 i8_unsuffixed => i8,
959 i16_unsuffixed => i16,
960 i32_unsuffixed => i32,
961 i64_unsuffixed => i64,
962 isize_unsuffixed => isize,
Alex Crichton1a7f7622017-07-05 17:47:15 -0700963 }
964
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700965 pub fn f64_unsuffixed(f: f64) -> Literal {
966 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -0700967 Literal::_new(imp::Literal::f64_unsuffixed(f))
Alex Crichton1a7f7622017-07-05 17:47:15 -0700968 }
969
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700970 pub fn f64_suffixed(f: f64) -> Literal {
971 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -0700972 Literal::_new(imp::Literal::f64_suffixed(f))
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700973 }
974
David Tolnay82ba02d2018-05-20 16:22:43 -0700975 /// Creates a new unsuffixed floating-point literal.
976 ///
977 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
978 /// the float's value is emitted directly into the token but no suffix is
979 /// used, so it may be inferred to be a `f64` later in the compiler.
980 /// Literals created from negative numbers may not survive rountrips through
981 /// `TokenStream` or strings and may be broken into two tokens (`-` and
982 /// positive literal).
983 ///
984 /// # Panics
985 ///
986 /// This function requires that the specified float is finite, for example
987 /// if it is infinity or NaN this function will panic.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700988 pub fn f32_unsuffixed(f: f32) -> Literal {
989 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -0700990 Literal::_new(imp::Literal::f32_unsuffixed(f))
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700991 }
992
993 pub fn f32_suffixed(f: f32) -> Literal {
994 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -0700995 Literal::_new(imp::Literal::f32_suffixed(f))
Alex Crichton1a7f7622017-07-05 17:47:15 -0700996 }
997
998 pub fn string(string: &str) -> Literal {
Alex Crichtona914a612018-04-04 07:48:44 -0700999 Literal::_new(imp::Literal::string(string))
Alex Crichton1a7f7622017-07-05 17:47:15 -07001000 }
1001
1002 pub fn character(ch: char) -> Literal {
Alex Crichtona914a612018-04-04 07:48:44 -07001003 Literal::_new(imp::Literal::character(ch))
Alex Crichton76a5cc82017-05-23 07:01:44 -07001004 }
1005
Alex Crichton9c2fb0a2017-05-26 08:49:31 -07001006 pub fn byte_string(s: &[u8]) -> Literal {
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001007 Literal::_new(imp::Literal::byte_string(s))
Alex Crichton852d53d2017-05-19 19:25:08 -07001008 }
Alex Crichton76a5cc82017-05-23 07:01:44 -07001009
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001010 pub fn span(&self) -> Span {
Alex Crichtonb2c94622018-04-04 07:36:41 -07001011 Span::_new(self.inner.span())
Alex Crichton1a7f7622017-07-05 17:47:15 -07001012 }
1013
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001014 pub fn set_span(&mut self, span: Span) {
Alex Crichtonb2c94622018-04-04 07:36:41 -07001015 self.inner.set_span(span.inner);
Alex Crichton31316622017-05-26 12:54:47 -07001016 }
Alex Crichton852d53d2017-05-19 19:25:08 -07001017}
1018
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001019impl fmt::Debug for Literal {
1020 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1021 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001022 }
1023}
David Tolnaycb1b85f2017-06-03 16:40:35 -07001024
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001025impl fmt::Display for Literal {
1026 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1027 self.inner.fmt(f)
1028 }
1029}
1030
David Tolnay82ba02d2018-05-20 16:22:43 -07001031/// Public implementation details for the `TokenStream` type, such as iterators.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001032pub mod token_stream {
1033 use std::fmt;
1034 use std::marker;
1035 use std::rc::Rc;
1036
David Tolnay48ea5042018-04-23 19:17:35 -07001037 use imp;
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001038 pub use TokenStream;
David Tolnayb28f38a2018-03-31 22:02:29 +02001039 use TokenTree;
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001040
David Tolnay82ba02d2018-05-20 16:22:43 -07001041 /// An iterator over `TokenStream`'s `TokenTree`s.
1042 ///
1043 /// The iteration is "shallow", e.g. the iterator doesn't recurse into
1044 /// delimited groups, and returns whole groups as token trees.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001045 pub struct IntoIter {
1046 inner: imp::TokenTreeIter,
1047 _marker: marker::PhantomData<Rc<()>>,
1048 }
1049
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001050 impl Iterator for IntoIter {
1051 type Item = TokenTree;
1052
1053 fn next(&mut self) -> Option<TokenTree> {
1054 self.inner.next()
1055 }
1056 }
1057
1058 impl fmt::Debug for IntoIter {
1059 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1060 self.inner.fmt(f)
1061 }
1062 }
1063
1064 impl IntoIterator for TokenStream {
1065 type Item = TokenTree;
1066 type IntoIter = IntoIter;
1067
1068 fn into_iter(self) -> IntoIter {
1069 IntoIter {
1070 inner: self.inner.into_iter(),
1071 _marker: marker::PhantomData,
1072 }
1073 }
1074 }
1075}