blob: 9a033c07da1b996a70c716352c1493b6c0f1e86b [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 Tolnay1ded3502018-09-06 09:52:54 -070046#![doc(html_root_url = "https://docs.rs/proc-macro2/0.4.18")]
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}
Alex Crichton53b00672018-09-06 17:16:10 -0700185impl FromIterator<TokenStream> for TokenStream {
186 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
187 TokenStream::_new(streams.into_iter().map(|i| i.inner).collect())
188 }
189}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700190
David Tolnay82ba02d2018-05-20 16:22:43 -0700191/// Prints the token stream as a string that is supposed to be losslessly
192/// convertible back into the same token stream (modulo spans), except for
193/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
194/// numeric literals.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700195impl fmt::Display for TokenStream {
196 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
197 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700198 }
199}
200
David Tolnay82ba02d2018-05-20 16:22:43 -0700201/// Prints token in a form convenient for debugging.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700202impl fmt::Debug for TokenStream {
203 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
204 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700205 }
206}
207
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700208impl fmt::Debug for LexError {
209 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
210 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -0700211 }
212}
213
Nika Layzellb35a9a32017-12-30 14:34:35 -0500214// Returned by reference, so we can't easily wrap it.
David Tolnay1ebe3972018-01-02 20:14:20 -0800215#[cfg(procmacro2_semver_exempt)]
Nika Layzellb35a9a32017-12-30 14:34:35 -0500216pub use imp::FileName;
217
David Tolnay82ba02d2018-05-20 16:22:43 -0700218/// The source file of a given `Span`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700219///
220/// This type is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800221#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500222#[derive(Clone, PartialEq, Eq)]
223pub struct SourceFile(imp::SourceFile);
224
David Tolnay1ebe3972018-01-02 20:14:20 -0800225#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500226impl SourceFile {
David Tolnay82ba02d2018-05-20 16:22:43 -0700227 /// Get the path to this source file.
228 ///
229 /// ### Note
230 ///
231 /// If the code span associated with this `SourceFile` was generated by an
232 /// external macro, this may not be an actual path on the filesystem. Use
233 /// [`is_real`] to check.
234 ///
235 /// Also note that even if `is_real` returns `true`, if
236 /// `--remap-path-prefix` was passed on the command line, the path as given
237 /// may not actually be valid.
238 ///
239 /// [`is_real`]: #method.is_real
Nika Layzellb35a9a32017-12-30 14:34:35 -0500240 pub fn path(&self) -> &FileName {
241 self.0.path()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500242 }
243
David Tolnay82ba02d2018-05-20 16:22:43 -0700244 /// Returns `true` if this source file is a real source file, and not
245 /// generated by an external macro's expansion.
Nika Layzellf8d5f212017-12-11 14:07:02 -0500246 pub fn is_real(&self) -> bool {
247 self.0.is_real()
248 }
249}
250
David Tolnay1ebe3972018-01-02 20:14:20 -0800251#[cfg(procmacro2_semver_exempt)]
Nika Layzellb35a9a32017-12-30 14:34:35 -0500252impl AsRef<FileName> for SourceFile {
253 fn as_ref(&self) -> &FileName {
254 self.0.path()
Nika Layzellf8d5f212017-12-11 14:07:02 -0500255 }
256}
257
David Tolnay1ebe3972018-01-02 20:14:20 -0800258#[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500259impl fmt::Debug for SourceFile {
260 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
261 self.0.fmt(f)
262 }
263}
264
David Tolnay82ba02d2018-05-20 16:22:43 -0700265/// A line-column pair representing the start or end of a `Span`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700266///
267/// This type is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800268#[cfg(procmacro2_semver_exempt)]
Nika Layzell1ecb6ce2017-12-30 14:34:05 -0500269pub struct LineColumn {
David Tolnay82ba02d2018-05-20 16:22:43 -0700270 /// The 1-indexed line in the source file on which the span starts or ends
271 /// (inclusive).
Nika Layzell1ecb6ce2017-12-30 14:34:05 -0500272 pub line: usize,
David Tolnay82ba02d2018-05-20 16:22:43 -0700273 /// The 0-indexed column (in UTF-8 characters) in the source file on which
274 /// the span starts or ends (inclusive).
Nika Layzell1ecb6ce2017-12-30 14:34:05 -0500275 pub column: usize,
276}
Nika Layzellf8d5f212017-12-11 14:07:02 -0500277
David Tolnay82ba02d2018-05-20 16:22:43 -0700278/// A region of source code, along with macro expansion information.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700279#[derive(Copy, Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700280pub struct Span {
281 inner: imp::Span,
282 _marker: marker::PhantomData<Rc<()>>,
283}
Alex Crichton44bffbc2017-05-19 17:51:59 -0700284
Alex Crichton44bffbc2017-05-19 17:51:59 -0700285impl Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700286 fn _new(inner: imp::Span) -> Span {
287 Span {
288 inner: inner,
289 _marker: marker::PhantomData,
290 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700291 }
Alex Crichtone6085b72017-11-21 07:24:25 -0800292
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700293 fn _new_stable(inner: stable::Span) -> Span {
294 Span {
295 inner: inner.into(),
296 _marker: marker::PhantomData,
297 }
298 }
299
David Tolnay82ba02d2018-05-20 16:22:43 -0700300 /// The span of the invocation of the current procedural macro.
301 ///
302 /// Identifiers created with this span will be resolved as if they were
303 /// written directly at the macro call location (call-site hygiene) and
304 /// other code at the macro call site will be able to refer to them as well.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700305 pub fn call_site() -> Span {
306 Span::_new(imp::Span::call_site())
307 }
308
David Tolnay82ba02d2018-05-20 16:22:43 -0700309 /// A span that resolves at the macro definition site.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700310 ///
311 /// This method is semver exempt and not exposed by default.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700312 #[cfg(procmacro2_semver_exempt)]
Alex Crichtone6085b72017-11-21 07:24:25 -0800313 pub fn def_site() -> Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700314 Span::_new(imp::Span::def_site())
Alex Crichtone6085b72017-11-21 07:24:25 -0800315 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500316
David Tolnay4e8e3972018-01-05 18:10:22 -0800317 /// Creates a new span with the same line/column information as `self` but
318 /// that resolves symbols as though it were at `other`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700319 ///
320 /// This method is semver exempt and not exposed by default.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700321 #[cfg(procmacro2_semver_exempt)]
David Tolnay4e8e3972018-01-05 18:10:22 -0800322 pub fn resolved_at(&self, other: Span) -> Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700323 Span::_new(self.inner.resolved_at(other.inner))
David Tolnay4e8e3972018-01-05 18:10:22 -0800324 }
325
326 /// Creates a new span with the same name resolution behavior as `self` but
327 /// with the line/column information of `other`.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700328 ///
329 /// This method is semver exempt and not exposed by default.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700330 #[cfg(procmacro2_semver_exempt)]
David Tolnay4e8e3972018-01-05 18:10:22 -0800331 pub fn located_at(&self, other: Span) -> Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700332 Span::_new(self.inner.located_at(other.inner))
David Tolnay4e8e3972018-01-05 18:10:22 -0800333 }
334
David Tolnayd66ecf62018-01-02 20:05:42 -0800335 /// This method is only available when the `"nightly"` feature is enabled.
Sergio Benitez4a232822018-08-28 17:06:22 -0700336 #[doc(hidden)]
337 #[cfg(any(feature = "nightly", super_unstable))]
David Tolnay16a17202017-12-31 10:47:24 -0500338 pub fn unstable(self) -> proc_macro::Span {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700339 self.inner.unstable()
David Tolnay16a17202017-12-31 10:47:24 -0500340 }
341
David Tolnay82ba02d2018-05-20 16:22:43 -0700342 /// The original source file into which this span points.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700343 ///
344 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800345 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500346 pub fn source_file(&self) -> SourceFile {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700347 SourceFile(self.inner.source_file())
Nika Layzellf8d5f212017-12-11 14:07:02 -0500348 }
349
David Tolnay82ba02d2018-05-20 16:22:43 -0700350 /// Get the starting line/column in the source file for this span.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700351 ///
352 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800353 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500354 pub fn start(&self) -> LineColumn {
David Tolnayb28f38a2018-03-31 22:02:29 +0200355 let imp::LineColumn { line, column } = self.inner.start();
356 LineColumn {
357 line: line,
358 column: column,
359 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500360 }
361
David Tolnay82ba02d2018-05-20 16:22:43 -0700362 /// Get the ending line/column in the source file for this span.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700363 ///
364 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800365 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500366 pub fn end(&self) -> LineColumn {
David Tolnayb28f38a2018-03-31 22:02:29 +0200367 let imp::LineColumn { line, column } = self.inner.end();
368 LineColumn {
369 line: line,
370 column: column,
371 }
Nika Layzellf8d5f212017-12-11 14:07:02 -0500372 }
373
David Tolnay82ba02d2018-05-20 16:22:43 -0700374 /// Create a new span encompassing `self` and `other`.
375 ///
376 /// Returns `None` if `self` and `other` are from different files.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700377 ///
378 /// This method is semver exempt and not exposed by default.
David Tolnay1ebe3972018-01-02 20:14:20 -0800379 #[cfg(procmacro2_semver_exempt)]
Nika Layzellf8d5f212017-12-11 14:07:02 -0500380 pub fn join(&self, other: Span) -> Option<Span> {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700381 self.inner.join(other.inner).map(Span::_new)
382 }
Alex Crichtonb2c94622018-04-04 07:36:41 -0700383
David Tolnay82ba02d2018-05-20 16:22:43 -0700384 /// Compares to spans to see if they're equal.
David Tolnaya01ca8e2018-06-04 00:55:28 -0700385 ///
386 /// This method is semver exempt and not exposed by default.
Alex Crichtonb2c94622018-04-04 07:36:41 -0700387 #[cfg(procmacro2_semver_exempt)]
388 pub fn eq(&self, other: &Span) -> bool {
389 self.inner.eq(&other.inner)
390 }
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700391}
392
David Tolnay82ba02d2018-05-20 16:22:43 -0700393/// Prints a span in a form convenient for debugging.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700394impl fmt::Debug for Span {
395 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
396 self.inner.fmt(f)
Nika Layzellf8d5f212017-12-11 14:07:02 -0500397 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700398}
399
David Tolnay82ba02d2018-05-20 16:22:43 -0700400/// A single token or a delimited sequence of token trees (e.g. `[1, (), ..]`).
David Tolnay034205f2018-04-22 16:45:28 -0700401#[derive(Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700402pub enum TokenTree {
David Tolnay82ba02d2018-05-20 16:22:43 -0700403 /// A token stream surrounded by bracket delimiters.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700404 Group(Group),
David Tolnay82ba02d2018-05-20 16:22:43 -0700405 /// An identifier.
Alex Crichtonf3888432018-05-16 09:11:05 -0700406 Ident(Ident),
David Tolnay82ba02d2018-05-20 16:22:43 -0700407 /// A single punctuation character (`+`, `,`, `$`, etc.).
Alex Crichtonf3888432018-05-16 09:11:05 -0700408 Punct(Punct),
David Tolnay82ba02d2018-05-20 16:22:43 -0700409 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700410 Literal(Literal),
Alex Crichton1a7f7622017-07-05 17:47:15 -0700411}
412
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700413impl TokenTree {
David Tolnay82ba02d2018-05-20 16:22:43 -0700414 /// Returns the span of this tree, delegating to the `span` method of
415 /// the contained token or a delimited stream.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700416 pub fn span(&self) -> Span {
417 match *self {
418 TokenTree::Group(ref t) => t.span(),
Alex Crichtonf3888432018-05-16 09:11:05 -0700419 TokenTree::Ident(ref t) => t.span(),
420 TokenTree::Punct(ref t) => t.span(),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700421 TokenTree::Literal(ref t) => t.span(),
422 }
423 }
424
David Tolnay82ba02d2018-05-20 16:22:43 -0700425 /// Configures the span for *only this token*.
426 ///
427 /// Note that if this token is a `Group` then this method will not configure
428 /// the span of each of the internal tokens, this will simply delegate to
429 /// the `set_span` method of each variant.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700430 pub fn set_span(&mut self, span: Span) {
431 match *self {
432 TokenTree::Group(ref mut t) => t.set_span(span),
Alex Crichtonf3888432018-05-16 09:11:05 -0700433 TokenTree::Ident(ref mut t) => t.set_span(span),
434 TokenTree::Punct(ref mut t) => t.set_span(span),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700435 TokenTree::Literal(ref mut t) => t.set_span(span),
436 }
437 }
438}
439
440impl From<Group> for TokenTree {
441 fn from(g: Group) -> TokenTree {
442 TokenTree::Group(g)
443 }
444}
445
Alex Crichtonf3888432018-05-16 09:11:05 -0700446impl From<Ident> for TokenTree {
447 fn from(g: Ident) -> TokenTree {
448 TokenTree::Ident(g)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700449 }
450}
451
Alex Crichtonf3888432018-05-16 09:11:05 -0700452impl From<Punct> for TokenTree {
453 fn from(g: Punct) -> TokenTree {
454 TokenTree::Punct(g)
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700455 }
456}
457
458impl From<Literal> for TokenTree {
459 fn from(g: Literal) -> TokenTree {
460 TokenTree::Literal(g)
Alex Crichton1a7f7622017-07-05 17:47:15 -0700461 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700462}
463
David Tolnay82ba02d2018-05-20 16:22:43 -0700464/// Prints the token tree as a string that is supposed to be losslessly
465/// convertible back into the same token tree (modulo spans), except for
466/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
467/// numeric literals.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700468impl fmt::Display for TokenTree {
469 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700470 match *self {
471 TokenTree::Group(ref t) => t.fmt(f),
Alex Crichtonf3888432018-05-16 09:11:05 -0700472 TokenTree::Ident(ref t) => t.fmt(f),
473 TokenTree::Punct(ref t) => t.fmt(f),
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700474 TokenTree::Literal(ref t) => t.fmt(f),
475 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700476 }
477}
478
David Tolnay82ba02d2018-05-20 16:22:43 -0700479/// Prints token tree in a form convenient for debugging.
David Tolnay034205f2018-04-22 16:45:28 -0700480impl fmt::Debug for TokenTree {
481 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
482 // Each of these has the name in the struct type in the derived debug,
483 // so don't bother with an extra layer of indirection
484 match *self {
485 TokenTree::Group(ref t) => t.fmt(f),
David Tolnayd8fcdb82018-06-02 15:43:53 -0700486 TokenTree::Ident(ref t) => {
487 let mut debug = f.debug_struct("Ident");
488 debug.field("sym", &format_args!("{}", t));
489 #[cfg(any(feature = "nightly", procmacro2_semver_exempt))]
490 debug.field("span", &t.span());
491 debug.finish()
492 }
Alex Crichtonf3888432018-05-16 09:11:05 -0700493 TokenTree::Punct(ref t) => t.fmt(f),
David Tolnay034205f2018-04-22 16:45:28 -0700494 TokenTree::Literal(ref t) => t.fmt(f),
495 }
496 }
497}
498
David Tolnay82ba02d2018-05-20 16:22:43 -0700499/// A delimited token stream.
500///
501/// A `Group` internally contains a `TokenStream` which is surrounded by
502/// `Delimiter`s.
David Tolnay034205f2018-04-22 16:45:28 -0700503#[derive(Clone)]
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700504pub struct Group {
505 delimiter: Delimiter,
506 stream: TokenStream,
507 span: Span,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700508}
509
David Tolnay82ba02d2018-05-20 16:22:43 -0700510/// Describes how a sequence of token trees is delimited.
Michael Layzell5372f4b2017-06-02 10:29:31 -0400511#[derive(Copy, Clone, Debug, Eq, PartialEq)]
Alex Crichton44bffbc2017-05-19 17:51:59 -0700512pub enum Delimiter {
David Tolnay82ba02d2018-05-20 16:22:43 -0700513 /// `( ... )`
Alex Crichton44bffbc2017-05-19 17:51:59 -0700514 Parenthesis,
David Tolnay82ba02d2018-05-20 16:22:43 -0700515 /// `{ ... }`
Alex Crichton44bffbc2017-05-19 17:51:59 -0700516 Brace,
David Tolnay82ba02d2018-05-20 16:22:43 -0700517 /// `[ ... ]`
Alex Crichton44bffbc2017-05-19 17:51:59 -0700518 Bracket,
David Tolnay82ba02d2018-05-20 16:22:43 -0700519 /// `Ø ... Ø`
520 ///
521 /// An implicit delimiter, that may, for example, appear around tokens
522 /// coming from a "macro variable" `$var`. It is important to preserve
523 /// operator priorities in cases like `$var * 3` where `$var` is `1 + 2`.
524 /// Implicit delimiters may not survive roundtrip of a token stream through
525 /// a string.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700526 None,
527}
528
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700529impl Group {
David Tolnay82ba02d2018-05-20 16:22:43 -0700530 /// Creates a new `Group` with the given delimiter and token stream.
531 ///
532 /// This constructor will set the span for this group to
533 /// `Span::call_site()`. To change the span you can use the `set_span`
534 /// method below.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700535 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
536 Group {
537 delimiter: delimiter,
538 stream: stream,
539 span: Span::call_site(),
540 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700541 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700542
David Tolnay82ba02d2018-05-20 16:22:43 -0700543 /// Returns the delimiter of this `Group`
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700544 pub fn delimiter(&self) -> Delimiter {
545 self.delimiter
Alex Crichton44bffbc2017-05-19 17:51:59 -0700546 }
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700547
David Tolnay82ba02d2018-05-20 16:22:43 -0700548 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
549 ///
550 /// Note that the returned token stream does not include the delimiter
551 /// returned above.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700552 pub fn stream(&self) -> TokenStream {
553 self.stream.clone()
554 }
555
David Tolnay82ba02d2018-05-20 16:22:43 -0700556 /// Returns the span for the delimiters of this token stream, spanning the
557 /// entire `Group`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700558 pub fn span(&self) -> Span {
559 self.span
560 }
561
David Tolnay82ba02d2018-05-20 16:22:43 -0700562 /// Configures the span for this `Group`'s delimiters, but not its internal
563 /// tokens.
564 ///
565 /// This method will **not** set the span of all the internal tokens spanned
566 /// by this group, but rather it will only set the span of the delimiter
567 /// tokens at the level of the `Group`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700568 pub fn set_span(&mut self, span: Span) {
569 self.span = span;
570 }
571}
572
David Tolnay82ba02d2018-05-20 16:22:43 -0700573/// Prints the group as a string that should be losslessly convertible back
574/// into the same group (modulo spans), except for possibly `TokenTree::Group`s
575/// with `Delimiter::None` delimiters.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700576impl fmt::Display for Group {
577 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
hcpl1a4d7792018-05-29 21:01:44 +0300578 let (left, right) = match self.delimiter {
579 Delimiter::Parenthesis => ("(", ")"),
David Tolnay03b43da2018-06-02 15:25:57 -0700580 Delimiter::Brace => ("{", "}"),
581 Delimiter::Bracket => ("[", "]"),
582 Delimiter::None => ("", ""),
hcpl1a4d7792018-05-29 21:01:44 +0300583 };
584
585 f.write_str(left)?;
586 self.stream.fmt(f)?;
587 f.write_str(right)?;
588
589 Ok(())
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700590 }
591}
592
David Tolnay034205f2018-04-22 16:45:28 -0700593impl fmt::Debug for Group {
594 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
595 let mut debug = fmt.debug_struct("Group");
596 debug.field("delimiter", &self.delimiter);
597 debug.field("stream", &self.stream);
598 #[cfg(procmacro2_semver_exempt)]
599 debug.field("span", &self.span);
600 debug.finish()
601 }
602}
603
David Tolnay82ba02d2018-05-20 16:22:43 -0700604/// An `Punct` is an single punctuation character like `+`, `-` or `#`.
605///
606/// Multicharacter operators like `+=` are represented as two instances of
607/// `Punct` with different forms of `Spacing` returned.
Alex Crichtonf3888432018-05-16 09:11:05 -0700608#[derive(Clone)]
609pub struct Punct {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700610 op: char,
611 spacing: Spacing,
612 span: Span,
Alex Crichton44bffbc2017-05-19 17:51:59 -0700613}
614
David Tolnay82ba02d2018-05-20 16:22:43 -0700615/// Whether an `Punct` is followed immediately by another `Punct` or followed by
616/// another token or whitespace.
Lukas Kalbertodteb3f9302017-08-20 18:58:41 +0200617#[derive(Copy, Clone, Debug, Eq, PartialEq)]
Alex Crichton1a7f7622017-07-05 17:47:15 -0700618pub enum Spacing {
David Tolnay82ba02d2018-05-20 16:22:43 -0700619 /// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700620 Alone,
David Tolnay82ba02d2018-05-20 16:22:43 -0700621 /// E.g. `+` is `Joint` in `+=` or `'#`.
622 ///
623 /// Additionally, single quote `'` can join with identifiers to form
624 /// lifetimes `'ident`.
Alex Crichton44bffbc2017-05-19 17:51:59 -0700625 Joint,
626}
627
Alex Crichtonf3888432018-05-16 09:11:05 -0700628impl Punct {
David Tolnay82ba02d2018-05-20 16:22:43 -0700629 /// Creates a new `Punct` from the given character and spacing.
630 ///
631 /// The `ch` argument must be a valid punctuation character permitted by the
632 /// language, otherwise the function will panic.
633 ///
634 /// The returned `Punct` will have the default span of `Span::call_site()`
635 /// which can be further configured with the `set_span` method below.
Alex Crichtonf3888432018-05-16 09:11:05 -0700636 pub fn new(op: char, spacing: Spacing) -> Punct {
637 Punct {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700638 op: op,
639 spacing: spacing,
640 span: Span::call_site(),
641 }
642 }
Alex Crichton44bffbc2017-05-19 17:51:59 -0700643
David Tolnay82ba02d2018-05-20 16:22:43 -0700644 /// Returns the value of this punctuation character as `char`.
Alex Crichtonf3888432018-05-16 09:11:05 -0700645 pub fn as_char(&self) -> char {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700646 self.op
647 }
648
David Tolnay82ba02d2018-05-20 16:22:43 -0700649 /// Returns the spacing of this punctuation character, indicating whether
650 /// it's immediately followed by another `Punct` in the token stream, so
651 /// they can potentially be combined into a multicharacter operator
652 /// (`Joint`), or it's followed by some other token or whitespace (`Alone`)
653 /// so the operator has certainly ended.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700654 pub fn spacing(&self) -> Spacing {
655 self.spacing
656 }
657
David Tolnay82ba02d2018-05-20 16:22:43 -0700658 /// Returns the span for this punctuation character.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700659 pub fn span(&self) -> Span {
660 self.span
661 }
662
David Tolnay82ba02d2018-05-20 16:22:43 -0700663 /// Configure the span for this punctuation character.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700664 pub fn set_span(&mut self, span: Span) {
665 self.span = span;
666 }
667}
668
David Tolnay82ba02d2018-05-20 16:22:43 -0700669/// Prints the punctuation character as a string that should be losslessly
670/// convertible back into the same character.
Alex Crichtonf3888432018-05-16 09:11:05 -0700671impl fmt::Display for Punct {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700672 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
673 self.op.fmt(f)
674 }
675}
676
Alex Crichtonf3888432018-05-16 09:11:05 -0700677impl fmt::Debug for Punct {
David Tolnay034205f2018-04-22 16:45:28 -0700678 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
Alex Crichtonf3888432018-05-16 09:11:05 -0700679 let mut debug = fmt.debug_struct("Punct");
David Tolnay034205f2018-04-22 16:45:28 -0700680 debug.field("op", &self.op);
681 debug.field("spacing", &self.spacing);
682 #[cfg(procmacro2_semver_exempt)]
683 debug.field("span", &self.span);
684 debug.finish()
685 }
686}
687
David Tolnay8b71dac2018-05-20 17:07:47 -0700688/// A word of Rust code, which may be a keyword or legal variable name.
689///
690/// An identifier consists of at least one Unicode code point, the first of
691/// which has the XID_Start property and the rest of which have the XID_Continue
692/// property.
693///
694/// - The empty string is not an identifier. Use `Option<Ident>`.
695/// - A lifetime is not an identifier. Use `syn::Lifetime` instead.
696///
697/// An identifier constructed with `Ident::new` is permitted to be a Rust
698/// keyword, though parsing one through its [`Synom`] implementation rejects
699/// Rust keywords. Use `call!(Ident::parse_any)` when parsing to match the
700/// behaviour of `Ident::new`.
701///
702/// [`Synom`]: https://docs.rs/syn/0.14/syn/synom/trait.Synom.html
703///
704/// # Examples
705///
706/// A new ident can be created from a string using the `Ident::new` function.
707/// A span must be provided explicitly which governs the name resolution
708/// behavior of the resulting identifier.
709///
710/// ```rust
711/// extern crate proc_macro2;
712///
713/// use proc_macro2::{Ident, Span};
714///
715/// fn main() {
716/// let call_ident = Ident::new("calligraphy", Span::call_site());
717///
718/// println!("{}", call_ident);
719/// }
720/// ```
721///
722/// An ident can be interpolated into a token stream using the `quote!` macro.
723///
724/// ```rust
725/// #[macro_use]
726/// extern crate quote;
727///
728/// extern crate proc_macro2;
729///
730/// use proc_macro2::{Ident, Span};
731///
732/// fn main() {
733/// let ident = Ident::new("demo", Span::call_site());
734///
735/// // Create a variable binding whose name is this ident.
736/// let expanded = quote! { let #ident = 10; };
737///
738/// // Create a variable binding with a slightly different name.
739/// let temp_ident = Ident::new(&format!("new_{}", ident), Span::call_site());
740/// let expanded = quote! { let #temp_ident = 10; };
741/// }
742/// ```
743///
744/// A string representation of the ident is available through the `to_string()`
745/// method.
746///
747/// ```rust
748/// # extern crate proc_macro2;
749/// #
750/// # use proc_macro2::{Ident, Span};
751/// #
752/// # let ident = Ident::new("another_identifier", Span::call_site());
753/// #
754/// // Examine the ident as a string.
755/// let ident_string = ident.to_string();
756/// if ident_string.len() > 60 {
757/// println!("Very long identifier: {}", ident_string)
758/// }
759/// ```
Alex Crichtonf3888432018-05-16 09:11:05 -0700760#[derive(Clone)]
761pub struct Ident {
762 inner: imp::Ident,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700763 _marker: marker::PhantomData<Rc<()>>,
764}
765
Alex Crichtonf3888432018-05-16 09:11:05 -0700766impl Ident {
767 fn _new(inner: imp::Ident) -> Ident {
768 Ident {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700769 inner: inner,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700770 _marker: marker::PhantomData,
771 }
772 }
773
David Tolnay82ba02d2018-05-20 16:22:43 -0700774 /// Creates a new `Ident` with the given `string` as well as the specified
775 /// `span`.
776 ///
777 /// The `string` argument must be a valid identifier permitted by the
778 /// language, otherwise the function will panic.
779 ///
780 /// Note that `span`, currently in rustc, configures the hygiene information
781 /// for this identifier.
782 ///
783 /// As of this time `Span::call_site()` explicitly opts-in to "call-site"
784 /// hygiene meaning that identifiers created with this span will be resolved
785 /// as if they were written directly at the location of the macro call, and
786 /// other code at the macro call site will be able to refer to them as well.
787 ///
788 /// Later spans like `Span::def_site()` will allow to opt-in to
789 /// "definition-site" hygiene meaning that identifiers created with this
790 /// span will be resolved at the location of the macro definition and other
791 /// code at the macro call site will not be able to refer to them.
792 ///
793 /// Due to the current importance of hygiene this constructor, unlike other
794 /// tokens, requires a `Span` to be specified at construction.
David Tolnay8b71dac2018-05-20 17:07:47 -0700795 ///
796 /// # Panics
797 ///
798 /// Panics if the input string is neither a keyword nor a legal variable
799 /// name.
Alex Crichtonf3888432018-05-16 09:11:05 -0700800 pub fn new(string: &str, span: Span) -> Ident {
801 Ident::_new(imp::Ident::new(string, span.inner))
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700802 }
803
David Tolnay82ba02d2018-05-20 16:22:43 -0700804 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
David Tolnaya01ca8e2018-06-04 00:55:28 -0700805 ///
806 /// This method is semver exempt and not exposed by default.
Alex Crichtonf3888432018-05-16 09:11:05 -0700807 #[cfg(procmacro2_semver_exempt)]
808 pub fn new_raw(string: &str, span: Span) -> Ident {
809 Ident::_new_raw(string, span)
810 }
811
812 fn _new_raw(string: &str, span: Span) -> Ident {
813 Ident::_new(imp::Ident::new_raw(string, span.inner))
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700814 }
815
David Tolnay82ba02d2018-05-20 16:22:43 -0700816 /// Returns the span of this `Ident`.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700817 pub fn span(&self) -> Span {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700818 Span::_new(self.inner.span())
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700819 }
820
David Tolnay82ba02d2018-05-20 16:22:43 -0700821 /// Configures the span of this `Ident`, possibly changing its hygiene
822 /// context.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700823 pub fn set_span(&mut self, span: Span) {
Alex Crichtonb2c94622018-04-04 07:36:41 -0700824 self.inner.set_span(span.inner);
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700825 }
826}
827
Alex Crichtonf3888432018-05-16 09:11:05 -0700828impl PartialEq for Ident {
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700829 fn eq(&self, other: &Ident) -> bool {
David Tolnayc0b0f2e2018-09-02 17:56:08 -0700830 self.inner == other.inner
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700831 }
832}
833
David Tolnayc0bbcc52018-05-18 10:51:04 -0700834impl<T> PartialEq<T> for Ident
835where
836 T: ?Sized + AsRef<str>,
837{
838 fn eq(&self, other: &T) -> bool {
David Tolnayc0b0f2e2018-09-02 17:56:08 -0700839 self.inner == other
David Tolnayc0bbcc52018-05-18 10:51:04 -0700840 }
841}
842
David Tolnay3d9d6ad2018-05-18 10:51:55 -0700843impl Eq for Ident {}
Alex Crichtonf3888432018-05-16 09:11:05 -0700844
845impl PartialOrd for Ident {
846 fn partial_cmp(&self, other: &Ident) -> Option<Ordering> {
847 Some(self.cmp(other))
848 }
849}
850
851impl Ord for Ident {
852 fn cmp(&self, other: &Ident) -> Ordering {
853 self.to_string().cmp(&other.to_string())
854 }
855}
856
857impl Hash for Ident {
858 fn hash<H: Hasher>(&self, hasher: &mut H) {
859 self.to_string().hash(hasher)
860 }
861}
862
David Tolnay82ba02d2018-05-20 16:22:43 -0700863/// Prints the identifier as a string that should be losslessly convertible back
864/// into the same identifier.
Alex Crichtonf3888432018-05-16 09:11:05 -0700865impl fmt::Display for Ident {
866 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
867 self.inner.fmt(f)
868 }
869}
870
871impl fmt::Debug for Ident {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700872 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
873 self.inner.fmt(f)
874 }
875}
876
David Tolnay82ba02d2018-05-20 16:22:43 -0700877/// A literal string (`"hello"`), byte string (`b"hello"`), character (`'a'`),
878/// byte character (`b'a'`), an integer or floating point number with or without
879/// a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
880///
881/// Boolean literals like `true` and `false` do not belong here, they are
882/// `Ident`s.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700883#[derive(Clone)]
884pub struct Literal {
885 inner: imp::Literal,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700886 _marker: marker::PhantomData<Rc<()>>,
887}
888
David Tolnay82ba02d2018-05-20 16:22:43 -0700889macro_rules! suffixed_int_literals {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700890 ($($name:ident => $kind:ident,)*) => ($(
David Tolnay82ba02d2018-05-20 16:22:43 -0700891 /// Creates a new suffixed integer literal with the specified value.
892 ///
893 /// This function will create an integer like `1u32` where the integer
894 /// value specified is the first part of the token and the integral is
895 /// also suffixed at the end. Literals created from negative numbers may
896 /// not survive rountrips through `TokenStream` or strings and may be
897 /// broken into two tokens (`-` and positive literal).
898 ///
899 /// Literals created through this method have the `Span::call_site()`
900 /// span by default, which can be configured with the `set_span` method
901 /// below.
902 pub fn $name(n: $kind) -> Literal {
903 Literal::_new(imp::Literal::$name(n))
904 }
905 )*)
906}
907
908macro_rules! unsuffixed_int_literals {
909 ($($name:ident => $kind:ident,)*) => ($(
910 /// Creates a new unsuffixed integer literal with the specified value.
911 ///
912 /// This function will create an integer like `1` where the integer
913 /// value specified is the first part of the token. No suffix is
914 /// specified on this token, meaning that invocations like
915 /// `Literal::i8_unsuffixed(1)` are equivalent to
916 /// `Literal::u32_unsuffixed(1)`. Literals created from negative numbers
917 /// may not survive rountrips through `TokenStream` or strings and may
918 /// be broken into two tokens (`-` and positive literal).
919 ///
920 /// Literals created through this method have the `Span::call_site()`
921 /// span by default, which can be configured with the `set_span` method
922 /// below.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700923 pub fn $name(n: $kind) -> Literal {
Alex Crichtona914a612018-04-04 07:48:44 -0700924 Literal::_new(imp::Literal::$name(n))
Alex Crichton1a7f7622017-07-05 17:47:15 -0700925 }
926 )*)
927}
928
Alex Crichton852d53d2017-05-19 19:25:08 -0700929impl Literal {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700930 fn _new(inner: imp::Literal) -> Literal {
931 Literal {
932 inner: inner,
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700933 _marker: marker::PhantomData,
934 }
Alex Crichton1a7f7622017-07-05 17:47:15 -0700935 }
936
Alex Crichton30a4e9e2018-04-27 17:02:19 -0700937 fn _new_stable(inner: stable::Literal) -> Literal {
938 Literal {
939 inner: inner.into(),
940 _marker: marker::PhantomData,
941 }
942 }
943
David Tolnay82ba02d2018-05-20 16:22:43 -0700944 suffixed_int_literals! {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700945 u8_suffixed => u8,
946 u16_suffixed => u16,
947 u32_suffixed => u32,
948 u64_suffixed => u64,
949 usize_suffixed => usize,
950 i8_suffixed => i8,
951 i16_suffixed => i16,
952 i32_suffixed => i32,
953 i64_suffixed => i64,
954 isize_suffixed => isize,
David Tolnay82ba02d2018-05-20 16:22:43 -0700955 }
Alex Crichton1a7f7622017-07-05 17:47:15 -0700956
David Tolnay82ba02d2018-05-20 16:22:43 -0700957 unsuffixed_int_literals! {
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700958 u8_unsuffixed => u8,
959 u16_unsuffixed => u16,
960 u32_unsuffixed => u32,
961 u64_unsuffixed => u64,
962 usize_unsuffixed => usize,
963 i8_unsuffixed => i8,
964 i16_unsuffixed => i16,
965 i32_unsuffixed => i32,
966 i64_unsuffixed => i64,
967 isize_unsuffixed => isize,
Alex Crichton1a7f7622017-07-05 17:47:15 -0700968 }
969
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700970 pub fn f64_unsuffixed(f: f64) -> Literal {
971 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -0700972 Literal::_new(imp::Literal::f64_unsuffixed(f))
Alex Crichton1a7f7622017-07-05 17:47:15 -0700973 }
974
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700975 pub fn f64_suffixed(f: f64) -> Literal {
976 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -0700977 Literal::_new(imp::Literal::f64_suffixed(f))
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700978 }
979
David Tolnay82ba02d2018-05-20 16:22:43 -0700980 /// Creates a new unsuffixed floating-point literal.
981 ///
982 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
983 /// the float's value is emitted directly into the token but no suffix is
984 /// used, so it may be inferred to be a `f64` later in the compiler.
985 /// Literals created from negative numbers may not survive rountrips through
986 /// `TokenStream` or strings and may be broken into two tokens (`-` and
987 /// positive literal).
988 ///
989 /// # Panics
990 ///
991 /// This function requires that the specified float is finite, for example
992 /// if it is infinity or NaN this function will panic.
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700993 pub fn f32_unsuffixed(f: f32) -> Literal {
994 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -0700995 Literal::_new(imp::Literal::f32_unsuffixed(f))
Alex Crichtonaf5bad42018-03-27 14:45:10 -0700996 }
997
998 pub fn f32_suffixed(f: f32) -> Literal {
999 assert!(f.is_finite());
Alex Crichtona914a612018-04-04 07:48:44 -07001000 Literal::_new(imp::Literal::f32_suffixed(f))
Alex Crichton1a7f7622017-07-05 17:47:15 -07001001 }
1002
1003 pub fn string(string: &str) -> Literal {
Alex Crichtona914a612018-04-04 07:48:44 -07001004 Literal::_new(imp::Literal::string(string))
Alex Crichton1a7f7622017-07-05 17:47:15 -07001005 }
1006
1007 pub fn character(ch: char) -> Literal {
Alex Crichtona914a612018-04-04 07:48:44 -07001008 Literal::_new(imp::Literal::character(ch))
Alex Crichton76a5cc82017-05-23 07:01:44 -07001009 }
1010
Alex Crichton9c2fb0a2017-05-26 08:49:31 -07001011 pub fn byte_string(s: &[u8]) -> Literal {
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001012 Literal::_new(imp::Literal::byte_string(s))
Alex Crichton852d53d2017-05-19 19:25:08 -07001013 }
Alex Crichton76a5cc82017-05-23 07:01:44 -07001014
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001015 pub fn span(&self) -> Span {
Alex Crichtonb2c94622018-04-04 07:36:41 -07001016 Span::_new(self.inner.span())
Alex Crichton1a7f7622017-07-05 17:47:15 -07001017 }
1018
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001019 pub fn set_span(&mut self, span: Span) {
Alex Crichtonb2c94622018-04-04 07:36:41 -07001020 self.inner.set_span(span.inner);
Alex Crichton31316622017-05-26 12:54:47 -07001021 }
Alex Crichton852d53d2017-05-19 19:25:08 -07001022}
1023
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001024impl fmt::Debug for Literal {
1025 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1026 self.inner.fmt(f)
Alex Crichton44bffbc2017-05-19 17:51:59 -07001027 }
1028}
David Tolnaycb1b85f2017-06-03 16:40:35 -07001029
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001030impl fmt::Display for Literal {
1031 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1032 self.inner.fmt(f)
1033 }
1034}
1035
David Tolnay82ba02d2018-05-20 16:22:43 -07001036/// Public implementation details for the `TokenStream` type, such as iterators.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001037pub mod token_stream {
1038 use std::fmt;
1039 use std::marker;
1040 use std::rc::Rc;
1041
David Tolnay48ea5042018-04-23 19:17:35 -07001042 use imp;
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001043 pub use TokenStream;
David Tolnayb28f38a2018-03-31 22:02:29 +02001044 use TokenTree;
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001045
David Tolnay82ba02d2018-05-20 16:22:43 -07001046 /// An iterator over `TokenStream`'s `TokenTree`s.
1047 ///
1048 /// The iteration is "shallow", e.g. the iterator doesn't recurse into
1049 /// delimited groups, and returns whole groups as token trees.
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001050 pub struct IntoIter {
1051 inner: imp::TokenTreeIter,
1052 _marker: marker::PhantomData<Rc<()>>,
1053 }
1054
Alex Crichtonaf5bad42018-03-27 14:45:10 -07001055 impl Iterator for IntoIter {
1056 type Item = TokenTree;
1057
1058 fn next(&mut self) -> Option<TokenTree> {
1059 self.inner.next()
1060 }
1061 }
1062
1063 impl fmt::Debug for IntoIter {
1064 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1065 self.inner.fmt(f)
1066 }
1067 }
1068
1069 impl IntoIterator for TokenStream {
1070 type Item = TokenTree;
1071 type IntoIter = IntoIter;
1072
1073 fn into_iter(self) -> IntoIter {
1074 IntoIter {
1075 inner: self.inner.into_iter(),
1076 _marker: marker::PhantomData,
1077 }
1078 }
1079 }
1080}