1 | //! [![github]](https://github.com/dtolnay/proc-macro2) [![crates-io]](https://crates.io/crates/proc-macro2) [![docs-rs]](crate) |
2 | //! |
3 | //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github |
4 | //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust |
5 | //! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs |
6 | //! |
7 | //! <br> |
8 | //! |
9 | //! A wrapper around the procedural macro API of the compiler's [`proc_macro`] |
10 | //! crate. This library serves two purposes: |
11 | //! |
12 | //! - **Bring proc-macro-like functionality to other contexts like build.rs and |
13 | //! main.rs.** Types from `proc_macro` are entirely specific to procedural |
14 | //! macros and cannot ever exist in code outside of a procedural macro. |
15 | //! Meanwhile `proc_macro2` types may exist anywhere including non-macro code. |
16 | //! By developing foundational libraries like [syn] and [quote] against |
17 | //! `proc_macro2` rather than `proc_macro`, the procedural macro ecosystem |
18 | //! becomes easily applicable to many other use cases and we avoid |
19 | //! reimplementing non-macro equivalents of those libraries. |
20 | //! |
21 | //! - **Make procedural macros unit testable.** As a consequence of being |
22 | //! specific to procedural macros, nothing that uses `proc_macro` can be |
23 | //! executed from a unit test. In order for helper libraries or components of |
24 | //! a macro to be testable in isolation, they must be implemented using |
25 | //! `proc_macro2`. |
26 | //! |
27 | //! [syn]: https://github.com/dtolnay/syn |
28 | //! [quote]: https://github.com/dtolnay/quote |
29 | //! |
30 | //! # Usage |
31 | //! |
32 | //! The skeleton of a typical procedural macro typically looks like this: |
33 | //! |
34 | //! ``` |
35 | //! extern crate proc_macro; |
36 | //! |
37 | //! # const IGNORE: &str = stringify! { |
38 | //! #[proc_macro_derive(MyDerive)] |
39 | //! # }; |
40 | //! # #[cfg (wrap_proc_macro)] |
41 | //! pub fn my_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { |
42 | //! let input = proc_macro2::TokenStream::from(input); |
43 | //! |
44 | //! let output: proc_macro2::TokenStream = { |
45 | //! /* transform input */ |
46 | //! # input |
47 | //! }; |
48 | //! |
49 | //! proc_macro::TokenStream::from(output) |
50 | //! } |
51 | //! ``` |
52 | //! |
53 | //! If parsing with [Syn], you'll use [`parse_macro_input!`] instead to |
54 | //! propagate parse errors correctly back to the compiler when parsing fails. |
55 | //! |
56 | //! [`parse_macro_input!`]: https://docs.rs/syn/2.0/syn/macro.parse_macro_input.html |
57 | //! |
58 | //! # Unstable features |
59 | //! |
60 | //! The default feature set of proc-macro2 tracks the most recent stable |
61 | //! compiler API. Functionality in `proc_macro` that is not yet stable is not |
62 | //! exposed by proc-macro2 by default. |
63 | //! |
64 | //! To opt into the additional APIs available in the most recent nightly |
65 | //! compiler, the `procmacro2_semver_exempt` config flag must be passed to |
66 | //! rustc. We will polyfill those nightly-only APIs back to Rust 1.56.0. As |
67 | //! these are unstable APIs that track the nightly compiler, minor versions of |
68 | //! proc-macro2 may make breaking changes to them at any time. |
69 | //! |
70 | //! ```sh |
71 | //! RUSTFLAGS='--cfg procmacro2_semver_exempt' cargo build |
72 | //! ``` |
73 | //! |
74 | //! Note that this must not only be done for your crate, but for any crate that |
75 | //! depends on your crate. This infectious nature is intentional, as it serves |
76 | //! as a reminder that you are outside of the normal semver guarantees. |
77 | //! |
78 | //! Semver exempt methods are marked as such in the proc-macro2 documentation. |
79 | //! |
80 | //! # Thread-Safety |
81 | //! |
82 | //! Most types in this crate are `!Sync` because the underlying compiler |
83 | //! types make use of thread-local memory, meaning they cannot be accessed from |
84 | //! a different thread. |
85 | |
86 | // Proc-macro2 types in rustdoc of other crates get linked to here. |
87 | #![doc (html_root_url = "https://docs.rs/proc-macro2/1.0.95" )] |
88 | #![cfg_attr (any(proc_macro_span, super_unstable), feature(proc_macro_span))] |
89 | #![cfg_attr (super_unstable, feature(proc_macro_def_site))] |
90 | #![cfg_attr (docsrs, feature(doc_cfg))] |
91 | #![deny (unsafe_op_in_unsafe_fn)] |
92 | #![allow ( |
93 | clippy::cast_lossless, |
94 | clippy::cast_possible_truncation, |
95 | clippy::checked_conversions, |
96 | clippy::doc_markdown, |
97 | clippy::elidable_lifetime_names, |
98 | clippy::incompatible_msrv, |
99 | clippy::items_after_statements, |
100 | clippy::iter_without_into_iter, |
101 | clippy::let_underscore_untyped, |
102 | clippy::manual_assert, |
103 | clippy::manual_range_contains, |
104 | clippy::missing_panics_doc, |
105 | clippy::missing_safety_doc, |
106 | clippy::must_use_candidate, |
107 | clippy::needless_doctest_main, |
108 | clippy::needless_lifetimes, |
109 | clippy::new_without_default, |
110 | clippy::return_self_not_must_use, |
111 | clippy::shadow_unrelated, |
112 | clippy::trivially_copy_pass_by_ref, |
113 | clippy::unnecessary_wraps, |
114 | clippy::unused_self, |
115 | clippy::used_underscore_binding, |
116 | clippy::vec_init_then_push |
117 | )] |
118 | |
119 | #[cfg (all(procmacro2_semver_exempt, wrap_proc_macro, not(super_unstable)))] |
120 | compile_error! {"\ |
121 | Something is not right. If you've tried to turn on \ |
122 | procmacro2_semver_exempt, you need to ensure that it \ |
123 | is turned on for the compilation of the proc-macro2 \ |
124 | build script as well. |
125 | " } |
126 | |
127 | #[cfg (all( |
128 | procmacro2_nightly_testing, |
129 | feature = "proc-macro" , |
130 | not(proc_macro_span) |
131 | ))] |
132 | compile_error! {"\ |
133 | Build script probe failed to compile. |
134 | " } |
135 | |
136 | extern crate alloc; |
137 | |
138 | #[cfg (feature = "proc-macro" )] |
139 | extern crate proc_macro; |
140 | |
141 | mod marker; |
142 | mod parse; |
143 | mod rcvec; |
144 | |
145 | #[cfg (wrap_proc_macro)] |
146 | mod detection; |
147 | |
148 | // Public for proc_macro2::fallback::force() and unforce(), but those are quite |
149 | // a niche use case so we omit it from rustdoc. |
150 | #[doc (hidden)] |
151 | pub mod fallback; |
152 | |
153 | pub mod extra; |
154 | |
155 | #[cfg (not(wrap_proc_macro))] |
156 | use crate::fallback as imp; |
157 | #[path = "wrapper.rs" ] |
158 | #[cfg (wrap_proc_macro)] |
159 | mod imp; |
160 | |
161 | #[cfg (span_locations)] |
162 | mod location; |
163 | |
164 | use crate::extra::DelimSpan; |
165 | use crate::marker::{ProcMacroAutoTraits, MARKER}; |
166 | use core::cmp::Ordering; |
167 | use core::fmt::{self, Debug, Display}; |
168 | use core::hash::{Hash, Hasher}; |
169 | #[cfg (span_locations)] |
170 | use core::ops::Range; |
171 | use core::ops::RangeBounds; |
172 | use core::str::FromStr; |
173 | use std::error::Error; |
174 | use std::ffi::CStr; |
175 | #[cfg (procmacro2_semver_exempt)] |
176 | use std::path::PathBuf; |
177 | |
178 | #[cfg (span_locations)] |
179 | #[cfg_attr (docsrs, doc(cfg(feature = "span-locations" )))] |
180 | pub use crate::location::LineColumn; |
181 | |
182 | /// An abstract stream of tokens, or more concretely a sequence of token trees. |
183 | /// |
184 | /// This type provides interfaces for iterating over token trees and for |
185 | /// collecting token trees into one stream. |
186 | /// |
187 | /// Token stream is both the input and output of `#[proc_macro]`, |
188 | /// `#[proc_macro_attribute]` and `#[proc_macro_derive]` definitions. |
189 | #[derive (Clone)] |
190 | pub struct TokenStream { |
191 | inner: imp::TokenStream, |
192 | _marker: ProcMacroAutoTraits, |
193 | } |
194 | |
195 | /// Error returned from `TokenStream::from_str`. |
196 | pub struct LexError { |
197 | inner: imp::LexError, |
198 | _marker: ProcMacroAutoTraits, |
199 | } |
200 | |
201 | impl TokenStream { |
202 | fn _new(inner: imp::TokenStream) -> Self { |
203 | TokenStream { |
204 | inner, |
205 | _marker: MARKER, |
206 | } |
207 | } |
208 | |
209 | fn _new_fallback(inner: fallback::TokenStream) -> Self { |
210 | TokenStream { |
211 | inner: imp::TokenStream::from(inner), |
212 | _marker: MARKER, |
213 | } |
214 | } |
215 | |
216 | /// Returns an empty `TokenStream` containing no token trees. |
217 | pub fn new() -> Self { |
218 | TokenStream::_new(imp::TokenStream::new()) |
219 | } |
220 | |
221 | /// Checks if this `TokenStream` is empty. |
222 | pub fn is_empty(&self) -> bool { |
223 | self.inner.is_empty() |
224 | } |
225 | } |
226 | |
227 | /// `TokenStream::default()` returns an empty stream, |
228 | /// i.e. this is equivalent with `TokenStream::new()`. |
229 | impl Default for TokenStream { |
230 | fn default() -> Self { |
231 | TokenStream::new() |
232 | } |
233 | } |
234 | |
235 | /// Attempts to break the string into tokens and parse those tokens into a token |
236 | /// stream. |
237 | /// |
238 | /// May fail for a number of reasons, for example, if the string contains |
239 | /// unbalanced delimiters or characters not existing in the language. |
240 | /// |
241 | /// NOTE: Some errors may cause panics instead of returning `LexError`. We |
242 | /// reserve the right to change these errors into `LexError`s later. |
243 | impl FromStr for TokenStream { |
244 | type Err = LexError; |
245 | |
246 | fn from_str(src: &str) -> Result<TokenStream, LexError> { |
247 | match imp::TokenStream::from_str_checked(src) { |
248 | Ok(tokens: TokenStream) => Ok(TokenStream::_new(inner:tokens)), |
249 | Err(lex: LexError) => Err(LexError { |
250 | inner: lex, |
251 | _marker: MARKER, |
252 | }), |
253 | } |
254 | } |
255 | } |
256 | |
257 | #[cfg (feature = "proc-macro" )] |
258 | #[cfg_attr (docsrs, doc(cfg(feature = "proc-macro" )))] |
259 | impl From<proc_macro::TokenStream> for TokenStream { |
260 | fn from(inner: proc_macro::TokenStream) -> Self { |
261 | TokenStream::_new(inner:imp::TokenStream::from(inner)) |
262 | } |
263 | } |
264 | |
265 | #[cfg (feature = "proc-macro" )] |
266 | #[cfg_attr (docsrs, doc(cfg(feature = "proc-macro" )))] |
267 | impl From<TokenStream> for proc_macro::TokenStream { |
268 | fn from(inner: TokenStream) -> Self { |
269 | proc_macro::TokenStream::from(inner.inner) |
270 | } |
271 | } |
272 | |
273 | impl From<TokenTree> for TokenStream { |
274 | fn from(token: TokenTree) -> Self { |
275 | TokenStream::_new(inner:imp::TokenStream::from(token)) |
276 | } |
277 | } |
278 | |
279 | impl Extend<TokenTree> for TokenStream { |
280 | fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, streams: I) { |
281 | self.inner.extend(iter:streams); |
282 | } |
283 | } |
284 | |
285 | impl Extend<TokenStream> for TokenStream { |
286 | fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) { |
287 | self.inner |
288 | .extend(iter:streams.into_iter().map(|stream: TokenStream| stream.inner)); |
289 | } |
290 | } |
291 | |
292 | /// Collects a number of token trees into a single stream. |
293 | impl FromIterator<TokenTree> for TokenStream { |
294 | fn from_iter<I: IntoIterator<Item = TokenTree>>(streams: I) -> Self { |
295 | TokenStream::_new(inner:streams.into_iter().collect()) |
296 | } |
297 | } |
298 | impl FromIterator<TokenStream> for TokenStream { |
299 | fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self { |
300 | TokenStream::_new(inner:streams.into_iter().map(|i: TokenStream| i.inner).collect()) |
301 | } |
302 | } |
303 | |
304 | /// Prints the token stream as a string that is supposed to be losslessly |
305 | /// convertible back into the same token stream (modulo spans), except for |
306 | /// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative |
307 | /// numeric literals. |
308 | impl Display for TokenStream { |
309 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
310 | Display::fmt(&self.inner, f) |
311 | } |
312 | } |
313 | |
314 | /// Prints token in a form convenient for debugging. |
315 | impl Debug for TokenStream { |
316 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
317 | Debug::fmt(&self.inner, f) |
318 | } |
319 | } |
320 | |
321 | impl LexError { |
322 | pub fn span(&self) -> Span { |
323 | Span::_new(self.inner.span()) |
324 | } |
325 | } |
326 | |
327 | impl Debug for LexError { |
328 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
329 | Debug::fmt(&self.inner, f) |
330 | } |
331 | } |
332 | |
333 | impl Display for LexError { |
334 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
335 | Display::fmt(&self.inner, f) |
336 | } |
337 | } |
338 | |
339 | impl Error for LexError {} |
340 | |
341 | /// A region of source code, along with macro expansion information. |
342 | #[derive (Copy, Clone)] |
343 | pub struct Span { |
344 | inner: imp::Span, |
345 | _marker: ProcMacroAutoTraits, |
346 | } |
347 | |
348 | impl Span { |
349 | fn _new(inner: imp::Span) -> Self { |
350 | Span { |
351 | inner, |
352 | _marker: MARKER, |
353 | } |
354 | } |
355 | |
356 | fn _new_fallback(inner: fallback::Span) -> Self { |
357 | Span { |
358 | inner: imp::Span::from(inner), |
359 | _marker: MARKER, |
360 | } |
361 | } |
362 | |
363 | /// The span of the invocation of the current procedural macro. |
364 | /// |
365 | /// Identifiers created with this span will be resolved as if they were |
366 | /// written directly at the macro call location (call-site hygiene) and |
367 | /// other code at the macro call site will be able to refer to them as well. |
368 | pub fn call_site() -> Self { |
369 | Span::_new(imp::Span::call_site()) |
370 | } |
371 | |
372 | /// The span located at the invocation of the procedural macro, but with |
373 | /// local variables, labels, and `$crate` resolved at the definition site |
374 | /// of the macro. This is the same hygiene behavior as `macro_rules`. |
375 | pub fn mixed_site() -> Self { |
376 | Span::_new(imp::Span::mixed_site()) |
377 | } |
378 | |
379 | /// A span that resolves at the macro definition site. |
380 | /// |
381 | /// This method is semver exempt and not exposed by default. |
382 | #[cfg (procmacro2_semver_exempt)] |
383 | #[cfg_attr (docsrs, doc(cfg(procmacro2_semver_exempt)))] |
384 | pub fn def_site() -> Self { |
385 | Span::_new(imp::Span::def_site()) |
386 | } |
387 | |
388 | /// Creates a new span with the same line/column information as `self` but |
389 | /// that resolves symbols as though it were at `other`. |
390 | pub fn resolved_at(&self, other: Span) -> Span { |
391 | Span::_new(self.inner.resolved_at(other.inner)) |
392 | } |
393 | |
394 | /// Creates a new span with the same name resolution behavior as `self` but |
395 | /// with the line/column information of `other`. |
396 | pub fn located_at(&self, other: Span) -> Span { |
397 | Span::_new(self.inner.located_at(other.inner)) |
398 | } |
399 | |
400 | /// Convert `proc_macro2::Span` to `proc_macro::Span`. |
401 | /// |
402 | /// This method is available when building with a nightly compiler, or when |
403 | /// building with rustc 1.29+ *without* semver exempt features. |
404 | /// |
405 | /// # Panics |
406 | /// |
407 | /// Panics if called from outside of a procedural macro. Unlike |
408 | /// `proc_macro2::Span`, the `proc_macro::Span` type can only exist within |
409 | /// the context of a procedural macro invocation. |
410 | #[cfg (wrap_proc_macro)] |
411 | pub fn unwrap(self) -> proc_macro::Span { |
412 | self.inner.unwrap() |
413 | } |
414 | |
415 | // Soft deprecated. Please use Span::unwrap. |
416 | #[cfg (wrap_proc_macro)] |
417 | #[doc (hidden)] |
418 | pub fn unstable(self) -> proc_macro::Span { |
419 | self.unwrap() |
420 | } |
421 | |
422 | /// Returns the span's byte position range in the source file. |
423 | /// |
424 | /// This method requires the `"span-locations"` feature to be enabled. |
425 | /// |
426 | /// When executing in a procedural macro context, the returned range is only |
427 | /// accurate if compiled with a nightly toolchain. The stable toolchain does |
428 | /// not have this information available. When executing outside of a |
429 | /// procedural macro, such as main.rs or build.rs, the byte range is always |
430 | /// accurate regardless of toolchain. |
431 | #[cfg (span_locations)] |
432 | #[cfg_attr (docsrs, doc(cfg(feature = "span-locations" )))] |
433 | pub fn byte_range(&self) -> Range<usize> { |
434 | self.inner.byte_range() |
435 | } |
436 | |
437 | /// Get the starting line/column in the source file for this span. |
438 | /// |
439 | /// This method requires the `"span-locations"` feature to be enabled. |
440 | /// |
441 | /// When executing in a procedural macro context, the returned line/column |
442 | /// are only meaningful if compiled with a nightly toolchain. The stable |
443 | /// toolchain does not have this information available. When executing |
444 | /// outside of a procedural macro, such as main.rs or build.rs, the |
445 | /// line/column are always meaningful regardless of toolchain. |
446 | #[cfg (span_locations)] |
447 | #[cfg_attr (docsrs, doc(cfg(feature = "span-locations" )))] |
448 | pub fn start(&self) -> LineColumn { |
449 | self.inner.start() |
450 | } |
451 | |
452 | /// Get the ending line/column in the source file for this span. |
453 | /// |
454 | /// This method requires the `"span-locations"` feature to be enabled. |
455 | /// |
456 | /// When executing in a procedural macro context, the returned line/column |
457 | /// are only meaningful if compiled with a nightly toolchain. The stable |
458 | /// toolchain does not have this information available. When executing |
459 | /// outside of a procedural macro, such as main.rs or build.rs, the |
460 | /// line/column are always meaningful regardless of toolchain. |
461 | #[cfg (span_locations)] |
462 | #[cfg_attr (docsrs, doc(cfg(feature = "span-locations" )))] |
463 | pub fn end(&self) -> LineColumn { |
464 | self.inner.end() |
465 | } |
466 | |
467 | /// The path to the source file in which this span occurs, for display |
468 | /// purposes. |
469 | /// |
470 | /// This might not correspond to a valid file system path. It might be |
471 | /// remapped, or might be an artificial path such as `"<macro expansion>"`. |
472 | /// |
473 | /// This method is semver exempt and not exposed by default. |
474 | #[cfg (all(procmacro2_semver_exempt, any(not(wrap_proc_macro), super_unstable)))] |
475 | #[cfg_attr (docsrs, doc(cfg(procmacro2_semver_exempt)))] |
476 | pub fn file(&self) -> String { |
477 | self.inner.file() |
478 | } |
479 | |
480 | /// The path to the source file in which this span occurs on disk. |
481 | /// |
482 | /// This is the actual path on disk. It is unaffected by path remapping. |
483 | /// |
484 | /// This path should not be embedded in the output of the macro; prefer |
485 | /// `file()` instead. |
486 | /// |
487 | /// This method is semver exempt and not exposed by default. |
488 | #[cfg (all(procmacro2_semver_exempt, any(not(wrap_proc_macro), super_unstable)))] |
489 | #[cfg_attr (docsrs, doc(cfg(procmacro2_semver_exempt)))] |
490 | pub fn local_file(&self) -> Option<PathBuf> { |
491 | self.inner.local_file() |
492 | } |
493 | |
494 | /// Create a new span encompassing `self` and `other`. |
495 | /// |
496 | /// Returns `None` if `self` and `other` are from different files. |
497 | /// |
498 | /// Warning: the underlying [`proc_macro::Span::join`] method is |
499 | /// nightly-only. When called from within a procedural macro not using a |
500 | /// nightly compiler, this method will always return `None`. |
501 | pub fn join(&self, other: Span) -> Option<Span> { |
502 | self.inner.join(other.inner).map(Span::_new) |
503 | } |
504 | |
505 | /// Compares two spans to see if they're equal. |
506 | /// |
507 | /// This method is semver exempt and not exposed by default. |
508 | #[cfg (procmacro2_semver_exempt)] |
509 | #[cfg_attr (docsrs, doc(cfg(procmacro2_semver_exempt)))] |
510 | pub fn eq(&self, other: &Span) -> bool { |
511 | self.inner.eq(&other.inner) |
512 | } |
513 | |
514 | /// Returns the source text behind a span. This preserves the original |
515 | /// source code, including spaces and comments. It only returns a result if |
516 | /// the span corresponds to real source code. |
517 | /// |
518 | /// Note: The observable result of a macro should only rely on the tokens |
519 | /// and not on this source text. The result of this function is a best |
520 | /// effort to be used for diagnostics only. |
521 | pub fn source_text(&self) -> Option<String> { |
522 | self.inner.source_text() |
523 | } |
524 | } |
525 | |
526 | /// Prints a span in a form convenient for debugging. |
527 | impl Debug for Span { |
528 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
529 | Debug::fmt(&self.inner, f) |
530 | } |
531 | } |
532 | |
533 | /// A single token or a delimited sequence of token trees (e.g. `[1, (), ..]`). |
534 | #[derive (Clone)] |
535 | pub enum TokenTree { |
536 | /// A token stream surrounded by bracket delimiters. |
537 | Group(Group), |
538 | /// An identifier. |
539 | Ident(Ident), |
540 | /// A single punctuation character (`+`, `,`, `$`, etc.). |
541 | Punct(Punct), |
542 | /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc. |
543 | Literal(Literal), |
544 | } |
545 | |
546 | impl TokenTree { |
547 | /// Returns the span of this tree, delegating to the `span` method of |
548 | /// the contained token or a delimited stream. |
549 | pub fn span(&self) -> Span { |
550 | match self { |
551 | TokenTree::Group(t) => t.span(), |
552 | TokenTree::Ident(t) => t.span(), |
553 | TokenTree::Punct(t) => t.span(), |
554 | TokenTree::Literal(t) => t.span(), |
555 | } |
556 | } |
557 | |
558 | /// Configures the span for *only this token*. |
559 | /// |
560 | /// Note that if this token is a `Group` then this method will not configure |
561 | /// the span of each of the internal tokens, this will simply delegate to |
562 | /// the `set_span` method of each variant. |
563 | pub fn set_span(&mut self, span: Span) { |
564 | match self { |
565 | TokenTree::Group(t) => t.set_span(span), |
566 | TokenTree::Ident(t) => t.set_span(span), |
567 | TokenTree::Punct(t) => t.set_span(span), |
568 | TokenTree::Literal(t) => t.set_span(span), |
569 | } |
570 | } |
571 | } |
572 | |
573 | impl From<Group> for TokenTree { |
574 | fn from(g: Group) -> Self { |
575 | TokenTree::Group(g) |
576 | } |
577 | } |
578 | |
579 | impl From<Ident> for TokenTree { |
580 | fn from(g: Ident) -> Self { |
581 | TokenTree::Ident(g) |
582 | } |
583 | } |
584 | |
585 | impl From<Punct> for TokenTree { |
586 | fn from(g: Punct) -> Self { |
587 | TokenTree::Punct(g) |
588 | } |
589 | } |
590 | |
591 | impl From<Literal> for TokenTree { |
592 | fn from(g: Literal) -> Self { |
593 | TokenTree::Literal(g) |
594 | } |
595 | } |
596 | |
597 | /// Prints the token tree as a string that is supposed to be losslessly |
598 | /// convertible back into the same token tree (modulo spans), except for |
599 | /// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative |
600 | /// numeric literals. |
601 | impl Display for TokenTree { |
602 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
603 | match self { |
604 | TokenTree::Group(t: &Group) => Display::fmt(self:t, f), |
605 | TokenTree::Ident(t: &Ident) => Display::fmt(self:t, f), |
606 | TokenTree::Punct(t: &Punct) => Display::fmt(self:t, f), |
607 | TokenTree::Literal(t: &Literal) => Display::fmt(self:t, f), |
608 | } |
609 | } |
610 | } |
611 | |
612 | /// Prints token tree in a form convenient for debugging. |
613 | impl Debug for TokenTree { |
614 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
615 | // Each of these has the name in the struct type in the derived debug, |
616 | // so don't bother with an extra layer of indirection |
617 | match self { |
618 | TokenTree::Group(t: &Group) => Debug::fmt(self:t, f), |
619 | TokenTree::Ident(t: &Ident) => { |
620 | let mut debug: DebugStruct<'_, '_> = f.debug_struct(name:"Ident" ); |
621 | debug.field(name:"sym" , &format_args!(" {}" , t)); |
622 | imp::debug_span_field_if_nontrivial(&mut debug, span:t.span().inner); |
623 | debug.finish() |
624 | } |
625 | TokenTree::Punct(t: &Punct) => Debug::fmt(self:t, f), |
626 | TokenTree::Literal(t: &Literal) => Debug::fmt(self:t, f), |
627 | } |
628 | } |
629 | } |
630 | |
631 | /// A delimited token stream. |
632 | /// |
633 | /// A `Group` internally contains a `TokenStream` which is surrounded by |
634 | /// `Delimiter`s. |
635 | #[derive (Clone)] |
636 | pub struct Group { |
637 | inner: imp::Group, |
638 | } |
639 | |
640 | /// Describes how a sequence of token trees is delimited. |
641 | #[derive (Copy, Clone, Debug, Eq, PartialEq)] |
642 | pub enum Delimiter { |
643 | /// `( ... )` |
644 | Parenthesis, |
645 | /// `{ ... }` |
646 | Brace, |
647 | /// `[ ... ]` |
648 | Bracket, |
649 | /// `∅ ... ∅` |
650 | /// |
651 | /// An invisible delimiter, that may, for example, appear around tokens |
652 | /// coming from a "macro variable" `$var`. It is important to preserve |
653 | /// operator priorities in cases like `$var * 3` where `$var` is `1 + 2`. |
654 | /// Invisible delimiters may not survive roundtrip of a token stream through |
655 | /// a string. |
656 | /// |
657 | /// <div class="warning"> |
658 | /// |
659 | /// Note: rustc currently can ignore the grouping of tokens delimited by `None` in the output |
660 | /// of a proc_macro. Only `None`-delimited groups created by a macro_rules macro in the input |
661 | /// of a proc_macro macro are preserved, and only in very specific circumstances. |
662 | /// Any `None`-delimited groups (re)created by a proc_macro will therefore not preserve |
663 | /// operator priorities as indicated above. The other `Delimiter` variants should be used |
664 | /// instead in this context. This is a rustc bug. For details, see |
665 | /// [rust-lang/rust#67062](https://github.com/rust-lang/rust/issues/67062). |
666 | /// |
667 | /// </div> |
668 | None, |
669 | } |
670 | |
671 | impl Group { |
672 | fn _new(inner: imp::Group) -> Self { |
673 | Group { inner } |
674 | } |
675 | |
676 | fn _new_fallback(inner: fallback::Group) -> Self { |
677 | Group { |
678 | inner: imp::Group::from(inner), |
679 | } |
680 | } |
681 | |
682 | /// Creates a new `Group` with the given delimiter and token stream. |
683 | /// |
684 | /// This constructor will set the span for this group to |
685 | /// `Span::call_site()`. To change the span you can use the `set_span` |
686 | /// method below. |
687 | pub fn new(delimiter: Delimiter, stream: TokenStream) -> Self { |
688 | Group { |
689 | inner: imp::Group::new(delimiter, stream.inner), |
690 | } |
691 | } |
692 | |
693 | /// Returns the punctuation used as the delimiter for this group: a set of |
694 | /// parentheses, square brackets, or curly braces. |
695 | pub fn delimiter(&self) -> Delimiter { |
696 | self.inner.delimiter() |
697 | } |
698 | |
699 | /// Returns the `TokenStream` of tokens that are delimited in this `Group`. |
700 | /// |
701 | /// Note that the returned token stream does not include the delimiter |
702 | /// returned above. |
703 | pub fn stream(&self) -> TokenStream { |
704 | TokenStream::_new(self.inner.stream()) |
705 | } |
706 | |
707 | /// Returns the span for the delimiters of this token stream, spanning the |
708 | /// entire `Group`. |
709 | /// |
710 | /// ```text |
711 | /// pub fn span(&self) -> Span { |
712 | /// ^^^^^^^ |
713 | /// ``` |
714 | pub fn span(&self) -> Span { |
715 | Span::_new(self.inner.span()) |
716 | } |
717 | |
718 | /// Returns the span pointing to the opening delimiter of this group. |
719 | /// |
720 | /// ```text |
721 | /// pub fn span_open(&self) -> Span { |
722 | /// ^ |
723 | /// ``` |
724 | pub fn span_open(&self) -> Span { |
725 | Span::_new(self.inner.span_open()) |
726 | } |
727 | |
728 | /// Returns the span pointing to the closing delimiter of this group. |
729 | /// |
730 | /// ```text |
731 | /// pub fn span_close(&self) -> Span { |
732 | /// ^ |
733 | /// ``` |
734 | pub fn span_close(&self) -> Span { |
735 | Span::_new(self.inner.span_close()) |
736 | } |
737 | |
738 | /// Returns an object that holds this group's `span_open()` and |
739 | /// `span_close()` together (in a more compact representation than holding |
740 | /// those 2 spans individually). |
741 | pub fn delim_span(&self) -> DelimSpan { |
742 | DelimSpan::new(&self.inner) |
743 | } |
744 | |
745 | /// Configures the span for this `Group`'s delimiters, but not its internal |
746 | /// tokens. |
747 | /// |
748 | /// This method will **not** set the span of all the internal tokens spanned |
749 | /// by this group, but rather it will only set the span of the delimiter |
750 | /// tokens at the level of the `Group`. |
751 | pub fn set_span(&mut self, span: Span) { |
752 | self.inner.set_span(span.inner); |
753 | } |
754 | } |
755 | |
756 | /// Prints the group as a string that should be losslessly convertible back |
757 | /// into the same group (modulo spans), except for possibly `TokenTree::Group`s |
758 | /// with `Delimiter::None` delimiters. |
759 | impl Display for Group { |
760 | fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { |
761 | Display::fmt(&self.inner, f:formatter) |
762 | } |
763 | } |
764 | |
765 | impl Debug for Group { |
766 | fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { |
767 | Debug::fmt(&self.inner, f:formatter) |
768 | } |
769 | } |
770 | |
771 | /// A `Punct` is a single punctuation character like `+`, `-` or `#`. |
772 | /// |
773 | /// Multicharacter operators like `+=` are represented as two instances of |
774 | /// `Punct` with different forms of `Spacing` returned. |
775 | #[derive (Clone)] |
776 | pub struct Punct { |
777 | ch: char, |
778 | spacing: Spacing, |
779 | span: Span, |
780 | } |
781 | |
782 | /// Whether a `Punct` is followed immediately by another `Punct` or followed by |
783 | /// another token or whitespace. |
784 | #[derive (Copy, Clone, Debug, Eq, PartialEq)] |
785 | pub enum Spacing { |
786 | /// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`. |
787 | Alone, |
788 | /// E.g. `+` is `Joint` in `+=` or `'` is `Joint` in `'#`. |
789 | /// |
790 | /// Additionally, single quote `'` can join with identifiers to form |
791 | /// lifetimes `'ident`. |
792 | Joint, |
793 | } |
794 | |
795 | impl Punct { |
796 | /// Creates a new `Punct` from the given character and spacing. |
797 | /// |
798 | /// The `ch` argument must be a valid punctuation character permitted by the |
799 | /// language, otherwise the function will panic. |
800 | /// |
801 | /// The returned `Punct` will have the default span of `Span::call_site()` |
802 | /// which can be further configured with the `set_span` method below. |
803 | pub fn new(ch: char, spacing: Spacing) -> Self { |
804 | if let '!' | '#' | '$' | '%' | '&' | ' \'' | '*' | '+' | ',' | '-' | '.' | '/' | ':' | ';' |
805 | | '<' | '=' | '>' | '?' | '@' | '^' | '|' | '~' = ch |
806 | { |
807 | Punct { |
808 | ch, |
809 | spacing, |
810 | span: Span::call_site(), |
811 | } |
812 | } else { |
813 | panic!("unsupported proc macro punctuation character {:?}" , ch); |
814 | } |
815 | } |
816 | |
817 | /// Returns the value of this punctuation character as `char`. |
818 | pub fn as_char(&self) -> char { |
819 | self.ch |
820 | } |
821 | |
822 | /// Returns the spacing of this punctuation character, indicating whether |
823 | /// it's immediately followed by another `Punct` in the token stream, so |
824 | /// they can potentially be combined into a multicharacter operator |
825 | /// (`Joint`), or it's followed by some other token or whitespace (`Alone`) |
826 | /// so the operator has certainly ended. |
827 | pub fn spacing(&self) -> Spacing { |
828 | self.spacing |
829 | } |
830 | |
831 | /// Returns the span for this punctuation character. |
832 | pub fn span(&self) -> Span { |
833 | self.span |
834 | } |
835 | |
836 | /// Configure the span for this punctuation character. |
837 | pub fn set_span(&mut self, span: Span) { |
838 | self.span = span; |
839 | } |
840 | } |
841 | |
842 | /// Prints the punctuation character as a string that should be losslessly |
843 | /// convertible back into the same character. |
844 | impl Display for Punct { |
845 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
846 | Display::fmt(&self.ch, f) |
847 | } |
848 | } |
849 | |
850 | impl Debug for Punct { |
851 | fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |
852 | let mut debug: DebugStruct<'_, '_> = fmt.debug_struct(name:"Punct" ); |
853 | debug.field(name:"char" , &self.ch); |
854 | debug.field(name:"spacing" , &self.spacing); |
855 | imp::debug_span_field_if_nontrivial(&mut debug, self.span.inner); |
856 | debug.finish() |
857 | } |
858 | } |
859 | |
860 | /// A word of Rust code, which may be a keyword or legal variable name. |
861 | /// |
862 | /// An identifier consists of at least one Unicode code point, the first of |
863 | /// which has the XID_Start property and the rest of which have the XID_Continue |
864 | /// property. |
865 | /// |
866 | /// - The empty string is not an identifier. Use `Option<Ident>`. |
867 | /// - A lifetime is not an identifier. Use `syn::Lifetime` instead. |
868 | /// |
869 | /// An identifier constructed with `Ident::new` is permitted to be a Rust |
870 | /// keyword, though parsing one through its [`Parse`] implementation rejects |
871 | /// Rust keywords. Use `input.call(Ident::parse_any)` when parsing to match the |
872 | /// behaviour of `Ident::new`. |
873 | /// |
874 | /// [`Parse`]: https://docs.rs/syn/2.0/syn/parse/trait.Parse.html |
875 | /// |
876 | /// # Examples |
877 | /// |
878 | /// A new ident can be created from a string using the `Ident::new` function. |
879 | /// A span must be provided explicitly which governs the name resolution |
880 | /// behavior of the resulting identifier. |
881 | /// |
882 | /// ``` |
883 | /// use proc_macro2::{Ident, Span}; |
884 | /// |
885 | /// fn main() { |
886 | /// let call_ident = Ident::new("calligraphy" , Span::call_site()); |
887 | /// |
888 | /// println!("{}" , call_ident); |
889 | /// } |
890 | /// ``` |
891 | /// |
892 | /// An ident can be interpolated into a token stream using the `quote!` macro. |
893 | /// |
894 | /// ``` |
895 | /// use proc_macro2::{Ident, Span}; |
896 | /// use quote::quote; |
897 | /// |
898 | /// fn main() { |
899 | /// let ident = Ident::new("demo" , Span::call_site()); |
900 | /// |
901 | /// // Create a variable binding whose name is this ident. |
902 | /// let expanded = quote! { let #ident = 10; }; |
903 | /// |
904 | /// // Create a variable binding with a slightly different name. |
905 | /// let temp_ident = Ident::new(&format!("new_{}" , ident), Span::call_site()); |
906 | /// let expanded = quote! { let #temp_ident = 10; }; |
907 | /// } |
908 | /// ``` |
909 | /// |
910 | /// A string representation of the ident is available through the `to_string()` |
911 | /// method. |
912 | /// |
913 | /// ``` |
914 | /// # use proc_macro2::{Ident, Span}; |
915 | /// # |
916 | /// # let ident = Ident::new("another_identifier" , Span::call_site()); |
917 | /// # |
918 | /// // Examine the ident as a string. |
919 | /// let ident_string = ident.to_string(); |
920 | /// if ident_string.len() > 60 { |
921 | /// println!("Very long identifier: {}" , ident_string) |
922 | /// } |
923 | /// ``` |
924 | #[derive (Clone)] |
925 | pub struct Ident { |
926 | inner: imp::Ident, |
927 | _marker: ProcMacroAutoTraits, |
928 | } |
929 | |
930 | impl Ident { |
931 | fn _new(inner: imp::Ident) -> Self { |
932 | Ident { |
933 | inner, |
934 | _marker: MARKER, |
935 | } |
936 | } |
937 | |
938 | fn _new_fallback(inner: fallback::Ident) -> Self { |
939 | Ident { |
940 | inner: imp::Ident::from(inner), |
941 | _marker: MARKER, |
942 | } |
943 | } |
944 | |
945 | /// Creates a new `Ident` with the given `string` as well as the specified |
946 | /// `span`. |
947 | /// |
948 | /// The `string` argument must be a valid identifier permitted by the |
949 | /// language, otherwise the function will panic. |
950 | /// |
951 | /// Note that `span`, currently in rustc, configures the hygiene information |
952 | /// for this identifier. |
953 | /// |
954 | /// As of this time `Span::call_site()` explicitly opts-in to "call-site" |
955 | /// hygiene meaning that identifiers created with this span will be resolved |
956 | /// as if they were written directly at the location of the macro call, and |
957 | /// other code at the macro call site will be able to refer to them as well. |
958 | /// |
959 | /// Later spans like `Span::def_site()` will allow to opt-in to |
960 | /// "definition-site" hygiene meaning that identifiers created with this |
961 | /// span will be resolved at the location of the macro definition and other |
962 | /// code at the macro call site will not be able to refer to them. |
963 | /// |
964 | /// Due to the current importance of hygiene this constructor, unlike other |
965 | /// tokens, requires a `Span` to be specified at construction. |
966 | /// |
967 | /// # Panics |
968 | /// |
969 | /// Panics if the input string is neither a keyword nor a legal variable |
970 | /// name. If you are not sure whether the string contains an identifier and |
971 | /// need to handle an error case, use |
972 | /// <a href="https://docs.rs/syn/2.0/syn/fn.parse_str.html"><code |
973 | /// style="padding-right:0;">syn::parse_str</code></a><code |
974 | /// style="padding-left:0;">::<Ident></code> |
975 | /// rather than `Ident::new`. |
976 | #[track_caller ] |
977 | pub fn new(string: &str, span: Span) -> Self { |
978 | Ident::_new(imp::Ident::new_checked(string, span.inner)) |
979 | } |
980 | |
981 | /// Same as `Ident::new`, but creates a raw identifier (`r#ident`). The |
982 | /// `string` argument must be a valid identifier permitted by the language |
983 | /// (including keywords, e.g. `fn`). Keywords which are usable in path |
984 | /// segments (e.g. `self`, `super`) are not supported, and will cause a |
985 | /// panic. |
986 | #[track_caller ] |
987 | pub fn new_raw(string: &str, span: Span) -> Self { |
988 | Ident::_new(imp::Ident::new_raw_checked(string, span.inner)) |
989 | } |
990 | |
991 | /// Returns the span of this `Ident`. |
992 | pub fn span(&self) -> Span { |
993 | Span::_new(self.inner.span()) |
994 | } |
995 | |
996 | /// Configures the span of this `Ident`, possibly changing its hygiene |
997 | /// context. |
998 | pub fn set_span(&mut self, span: Span) { |
999 | self.inner.set_span(span.inner); |
1000 | } |
1001 | } |
1002 | |
1003 | impl PartialEq for Ident { |
1004 | fn eq(&self, other: &Ident) -> bool { |
1005 | self.inner == other.inner |
1006 | } |
1007 | } |
1008 | |
1009 | impl<T> PartialEq<T> for Ident |
1010 | where |
1011 | T: ?Sized + AsRef<str>, |
1012 | { |
1013 | fn eq(&self, other: &T) -> bool { |
1014 | self.inner == other |
1015 | } |
1016 | } |
1017 | |
1018 | impl Eq for Ident {} |
1019 | |
1020 | impl PartialOrd for Ident { |
1021 | fn partial_cmp(&self, other: &Ident) -> Option<Ordering> { |
1022 | Some(self.cmp(other)) |
1023 | } |
1024 | } |
1025 | |
1026 | impl Ord for Ident { |
1027 | fn cmp(&self, other: &Ident) -> Ordering { |
1028 | self.to_string().cmp(&other.to_string()) |
1029 | } |
1030 | } |
1031 | |
1032 | impl Hash for Ident { |
1033 | fn hash<H: Hasher>(&self, hasher: &mut H) { |
1034 | self.to_string().hash(state:hasher); |
1035 | } |
1036 | } |
1037 | |
1038 | /// Prints the identifier as a string that should be losslessly convertible back |
1039 | /// into the same identifier. |
1040 | impl Display for Ident { |
1041 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
1042 | Display::fmt(&self.inner, f) |
1043 | } |
1044 | } |
1045 | |
1046 | impl Debug for Ident { |
1047 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
1048 | Debug::fmt(&self.inner, f) |
1049 | } |
1050 | } |
1051 | |
1052 | /// A literal string (`"hello"`), byte string (`b"hello"`), character (`'a'`), |
1053 | /// byte character (`b'a'`), an integer or floating point number with or without |
1054 | /// a suffix (`1`, `1u8`, `2.3`, `2.3f32`). |
1055 | /// |
1056 | /// Boolean literals like `true` and `false` do not belong here, they are |
1057 | /// `Ident`s. |
1058 | #[derive (Clone)] |
1059 | pub struct Literal { |
1060 | inner: imp::Literal, |
1061 | _marker: ProcMacroAutoTraits, |
1062 | } |
1063 | |
1064 | macro_rules! suffixed_int_literals { |
1065 | ($($name:ident => $kind:ident,)*) => ($( |
1066 | /// Creates a new suffixed integer literal with the specified value. |
1067 | /// |
1068 | /// This function will create an integer like `1u32` where the integer |
1069 | /// value specified is the first part of the token and the integral is |
1070 | /// also suffixed at the end. Literals created from negative numbers may |
1071 | /// not survive roundtrips through `TokenStream` or strings and may be |
1072 | /// broken into two tokens (`-` and positive literal). |
1073 | /// |
1074 | /// Literals created through this method have the `Span::call_site()` |
1075 | /// span by default, which can be configured with the `set_span` method |
1076 | /// below. |
1077 | pub fn $name(n: $kind) -> Literal { |
1078 | Literal::_new(imp::Literal::$name(n)) |
1079 | } |
1080 | )*) |
1081 | } |
1082 | |
1083 | macro_rules! unsuffixed_int_literals { |
1084 | ($($name:ident => $kind:ident,)*) => ($( |
1085 | /// Creates a new unsuffixed integer literal with the specified value. |
1086 | /// |
1087 | /// This function will create an integer like `1` where the integer |
1088 | /// value specified is the first part of the token. No suffix is |
1089 | /// specified on this token, meaning that invocations like |
1090 | /// `Literal::i8_unsuffixed(1)` are equivalent to |
1091 | /// `Literal::u32_unsuffixed(1)`. Literals created from negative numbers |
1092 | /// may not survive roundtrips through `TokenStream` or strings and may |
1093 | /// be broken into two tokens (`-` and positive literal). |
1094 | /// |
1095 | /// Literals created through this method have the `Span::call_site()` |
1096 | /// span by default, which can be configured with the `set_span` method |
1097 | /// below. |
1098 | pub fn $name(n: $kind) -> Literal { |
1099 | Literal::_new(imp::Literal::$name(n)) |
1100 | } |
1101 | )*) |
1102 | } |
1103 | |
1104 | impl Literal { |
1105 | fn _new(inner: imp::Literal) -> Self { |
1106 | Literal { |
1107 | inner, |
1108 | _marker: MARKER, |
1109 | } |
1110 | } |
1111 | |
1112 | fn _new_fallback(inner: fallback::Literal) -> Self { |
1113 | Literal { |
1114 | inner: imp::Literal::from(inner), |
1115 | _marker: MARKER, |
1116 | } |
1117 | } |
1118 | |
1119 | suffixed_int_literals! { |
1120 | u8_suffixed => u8, |
1121 | u16_suffixed => u16, |
1122 | u32_suffixed => u32, |
1123 | u64_suffixed => u64, |
1124 | u128_suffixed => u128, |
1125 | usize_suffixed => usize, |
1126 | i8_suffixed => i8, |
1127 | i16_suffixed => i16, |
1128 | i32_suffixed => i32, |
1129 | i64_suffixed => i64, |
1130 | i128_suffixed => i128, |
1131 | isize_suffixed => isize, |
1132 | } |
1133 | |
1134 | unsuffixed_int_literals! { |
1135 | u8_unsuffixed => u8, |
1136 | u16_unsuffixed => u16, |
1137 | u32_unsuffixed => u32, |
1138 | u64_unsuffixed => u64, |
1139 | u128_unsuffixed => u128, |
1140 | usize_unsuffixed => usize, |
1141 | i8_unsuffixed => i8, |
1142 | i16_unsuffixed => i16, |
1143 | i32_unsuffixed => i32, |
1144 | i64_unsuffixed => i64, |
1145 | i128_unsuffixed => i128, |
1146 | isize_unsuffixed => isize, |
1147 | } |
1148 | |
1149 | /// Creates a new unsuffixed floating-point literal. |
1150 | /// |
1151 | /// This constructor is similar to those like `Literal::i8_unsuffixed` where |
1152 | /// the float's value is emitted directly into the token but no suffix is |
1153 | /// used, so it may be inferred to be a `f64` later in the compiler. |
1154 | /// Literals created from negative numbers may not survive round-trips |
1155 | /// through `TokenStream` or strings and may be broken into two tokens (`-` |
1156 | /// and positive literal). |
1157 | /// |
1158 | /// # Panics |
1159 | /// |
1160 | /// This function requires that the specified float is finite, for example |
1161 | /// if it is infinity or NaN this function will panic. |
1162 | pub fn f64_unsuffixed(f: f64) -> Literal { |
1163 | assert!(f.is_finite()); |
1164 | Literal::_new(imp::Literal::f64_unsuffixed(f)) |
1165 | } |
1166 | |
1167 | /// Creates a new suffixed floating-point literal. |
1168 | /// |
1169 | /// This constructor will create a literal like `1.0f64` where the value |
1170 | /// specified is the preceding part of the token and `f64` is the suffix of |
1171 | /// the token. This token will always be inferred to be an `f64` in the |
1172 | /// compiler. Literals created from negative numbers may not survive |
1173 | /// round-trips through `TokenStream` or strings and may be broken into two |
1174 | /// tokens (`-` and positive literal). |
1175 | /// |
1176 | /// # Panics |
1177 | /// |
1178 | /// This function requires that the specified float is finite, for example |
1179 | /// if it is infinity or NaN this function will panic. |
1180 | pub fn f64_suffixed(f: f64) -> Literal { |
1181 | assert!(f.is_finite()); |
1182 | Literal::_new(imp::Literal::f64_suffixed(f)) |
1183 | } |
1184 | |
1185 | /// Creates a new unsuffixed floating-point literal. |
1186 | /// |
1187 | /// This constructor is similar to those like `Literal::i8_unsuffixed` where |
1188 | /// the float's value is emitted directly into the token but no suffix is |
1189 | /// used, so it may be inferred to be a `f64` later in the compiler. |
1190 | /// Literals created from negative numbers may not survive round-trips |
1191 | /// through `TokenStream` or strings and may be broken into two tokens (`-` |
1192 | /// and positive literal). |
1193 | /// |
1194 | /// # Panics |
1195 | /// |
1196 | /// This function requires that the specified float is finite, for example |
1197 | /// if it is infinity or NaN this function will panic. |
1198 | pub fn f32_unsuffixed(f: f32) -> Literal { |
1199 | assert!(f.is_finite()); |
1200 | Literal::_new(imp::Literal::f32_unsuffixed(f)) |
1201 | } |
1202 | |
1203 | /// Creates a new suffixed floating-point literal. |
1204 | /// |
1205 | /// This constructor will create a literal like `1.0f32` where the value |
1206 | /// specified is the preceding part of the token and `f32` is the suffix of |
1207 | /// the token. This token will always be inferred to be an `f32` in the |
1208 | /// compiler. Literals created from negative numbers may not survive |
1209 | /// round-trips through `TokenStream` or strings and may be broken into two |
1210 | /// tokens (`-` and positive literal). |
1211 | /// |
1212 | /// # Panics |
1213 | /// |
1214 | /// This function requires that the specified float is finite, for example |
1215 | /// if it is infinity or NaN this function will panic. |
1216 | pub fn f32_suffixed(f: f32) -> Literal { |
1217 | assert!(f.is_finite()); |
1218 | Literal::_new(imp::Literal::f32_suffixed(f)) |
1219 | } |
1220 | |
1221 | /// String literal. |
1222 | pub fn string(string: &str) -> Literal { |
1223 | Literal::_new(imp::Literal::string(string)) |
1224 | } |
1225 | |
1226 | /// Character literal. |
1227 | pub fn character(ch: char) -> Literal { |
1228 | Literal::_new(imp::Literal::character(ch)) |
1229 | } |
1230 | |
1231 | /// Byte character literal. |
1232 | pub fn byte_character(byte: u8) -> Literal { |
1233 | Literal::_new(imp::Literal::byte_character(byte)) |
1234 | } |
1235 | |
1236 | /// Byte string literal. |
1237 | pub fn byte_string(bytes: &[u8]) -> Literal { |
1238 | Literal::_new(imp::Literal::byte_string(bytes)) |
1239 | } |
1240 | |
1241 | /// C string literal. |
1242 | pub fn c_string(string: &CStr) -> Literal { |
1243 | Literal::_new(imp::Literal::c_string(string)) |
1244 | } |
1245 | |
1246 | /// Returns the span encompassing this literal. |
1247 | pub fn span(&self) -> Span { |
1248 | Span::_new(self.inner.span()) |
1249 | } |
1250 | |
1251 | /// Configures the span associated for this literal. |
1252 | pub fn set_span(&mut self, span: Span) { |
1253 | self.inner.set_span(span.inner); |
1254 | } |
1255 | |
1256 | /// Returns a `Span` that is a subset of `self.span()` containing only |
1257 | /// the source bytes in range `range`. Returns `None` if the would-be |
1258 | /// trimmed span is outside the bounds of `self`. |
1259 | /// |
1260 | /// Warning: the underlying [`proc_macro::Literal::subspan`] method is |
1261 | /// nightly-only. When called from within a procedural macro not using a |
1262 | /// nightly compiler, this method will always return `None`. |
1263 | pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> { |
1264 | self.inner.subspan(range).map(Span::_new) |
1265 | } |
1266 | |
1267 | // Intended for the `quote!` macro to use when constructing a proc-macro2 |
1268 | // token out of a macro_rules $:literal token, which is already known to be |
1269 | // a valid literal. This avoids reparsing/validating the literal's string |
1270 | // representation. This is not public API other than for quote. |
1271 | #[doc (hidden)] |
1272 | pub unsafe fn from_str_unchecked(repr: &str) -> Self { |
1273 | Literal::_new(unsafe { imp::Literal::from_str_unchecked(repr) }) |
1274 | } |
1275 | } |
1276 | |
1277 | impl FromStr for Literal { |
1278 | type Err = LexError; |
1279 | |
1280 | fn from_str(repr: &str) -> Result<Self, LexError> { |
1281 | match imp::Literal::from_str_checked(repr) { |
1282 | Ok(lit: Literal) => Ok(Literal::_new(inner:lit)), |
1283 | Err(lex: LexError) => Err(LexError { |
1284 | inner: lex, |
1285 | _marker: MARKER, |
1286 | }), |
1287 | } |
1288 | } |
1289 | } |
1290 | |
1291 | impl Debug for Literal { |
1292 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
1293 | Debug::fmt(&self.inner, f) |
1294 | } |
1295 | } |
1296 | |
1297 | impl Display for Literal { |
1298 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
1299 | Display::fmt(&self.inner, f) |
1300 | } |
1301 | } |
1302 | |
1303 | /// Public implementation details for the `TokenStream` type, such as iterators. |
1304 | pub mod token_stream { |
1305 | use crate::marker::{ProcMacroAutoTraits, MARKER}; |
1306 | use crate::{imp, TokenTree}; |
1307 | use core::fmt::{self, Debug}; |
1308 | |
1309 | pub use crate::TokenStream; |
1310 | |
1311 | /// An iterator over `TokenStream`'s `TokenTree`s. |
1312 | /// |
1313 | /// The iteration is "shallow", e.g. the iterator doesn't recurse into |
1314 | /// delimited groups, and returns whole groups as token trees. |
1315 | #[derive (Clone)] |
1316 | pub struct IntoIter { |
1317 | inner: imp::TokenTreeIter, |
1318 | _marker: ProcMacroAutoTraits, |
1319 | } |
1320 | |
1321 | impl Iterator for IntoIter { |
1322 | type Item = TokenTree; |
1323 | |
1324 | fn next(&mut self) -> Option<TokenTree> { |
1325 | self.inner.next() |
1326 | } |
1327 | |
1328 | fn size_hint(&self) -> (usize, Option<usize>) { |
1329 | self.inner.size_hint() |
1330 | } |
1331 | } |
1332 | |
1333 | impl Debug for IntoIter { |
1334 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
1335 | f.write_str("TokenStream " )?; |
1336 | f.debug_list().entries(self.clone()).finish() |
1337 | } |
1338 | } |
1339 | |
1340 | impl IntoIterator for TokenStream { |
1341 | type Item = TokenTree; |
1342 | type IntoIter = IntoIter; |
1343 | |
1344 | fn into_iter(self) -> IntoIter { |
1345 | IntoIter { |
1346 | inner: self.inner.into_iter(), |
1347 | _marker: MARKER, |
1348 | } |
1349 | } |
1350 | } |
1351 | } |
1352 | |