1 //! A support library for macro authors when defining new macros.
3 //! This library, provided by the standard distribution, provides the types
4 //! consumed in the interfaces of procedurally defined macro definitions such as
5 //! function-like macros `#[proc_macro]`, macro attributes `#[proc_macro_attribute]` and
6 //! custom derive attributes`#[proc_macro_derive]`.
8 //! See [the book] for more.
10 //! [the book]: ../book/ch19-06-macros.html#procedural-macros-for-generating-code-from-attributes
12 #![stable(feature = "proc_macro_lib", since = "1.15.0")]
13 #![deny(missing_docs)]
15 html_playground_url
= "https://play.rust-lang.org/",
16 issue_tracker_base_url
= "https://github.com/rust-lang/rust/issues/",
17 test(no_crate_inject
, attr(deny(warnings
))),
18 test(attr(allow(dead_code
, deprecated
, unused_variables
, unused_mut
)))
20 #![feature(rustc_allow_const_fn_unstable)]
22 #![feature(staged_api)]
23 #![feature(const_fn_trait_bound)]
24 #![feature(const_fn_fn_ptr_basics)]
25 #![feature(allow_internal_unstable)]
26 #![feature(decl_macro)]
27 #![feature(extern_types)]
28 #![feature(in_band_lifetimes)]
29 #![feature(negative_impls)]
30 #![feature(auto_traits)]
31 #![feature(restricted_std)]
32 #![feature(rustc_attrs)]
33 #![feature(min_specialization)]
34 #![recursion_limit = "256"]
36 #[unstable(feature = "proc_macro_internals", issue = "27812")]
42 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
43 pub use diagnostic
::{Diagnostic, Level, MultiSpan}
;
45 use std
::cmp
::Ordering
;
46 use std
::ops
::RangeBounds
;
47 use std
::path
::PathBuf
;
48 use std
::str::FromStr
;
49 use std
::{error, fmt, iter, mem}
;
51 /// Determines whether proc_macro has been made accessible to the currently
54 /// The proc_macro crate is only intended for use inside the implementation of
55 /// procedural macros. All the functions in this crate panic if invoked from
56 /// outside of a procedural macro, such as from a build script or unit test or
57 /// ordinary Rust binary.
59 /// With consideration for Rust libraries that are designed to support both
60 /// macro and non-macro use cases, `proc_macro::is_available()` provides a
61 /// non-panicking way to detect whether the infrastructure required to use the
62 /// API of proc_macro is presently available. Returns true if invoked from
63 /// inside of a procedural macro, false if invoked from any other binary.
64 #[unstable(feature = "proc_macro_is_available", issue = "71436")]
65 pub fn is_available() -> bool
{
66 bridge
::Bridge
::is_available()
69 /// The main type provided by this crate, representing an abstract stream of
70 /// tokens, or, more specifically, a sequence of token trees.
71 /// The type provide interfaces for iterating over those token trees and, conversely,
72 /// collecting a number of token trees into one stream.
74 /// This is both the input and output of `#[proc_macro]`, `#[proc_macro_attribute]`
75 /// and `#[proc_macro_derive]` definitions.
76 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
78 pub struct TokenStream(bridge
::client
::TokenStream
);
80 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
81 impl !Send
for TokenStream {}
82 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
83 impl !Sync
for TokenStream {}
85 /// Error returned from `TokenStream::from_str`.
86 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
97 #[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
98 impl fmt
::Display
for LexError
{
99 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
100 f
.write_str("cannot parse string into token stream")
104 #[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
105 impl error
::Error
for LexError {}
107 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
108 impl !Send
for LexError {}
109 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
110 impl !Sync
for LexError {}
113 /// Returns an empty `TokenStream` containing no token trees.
114 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
115 pub fn new() -> TokenStream
{
116 TokenStream(bridge
::client
::TokenStream
::new())
119 /// Checks if this `TokenStream` is empty.
120 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
121 pub fn is_empty(&self) -> bool
{
126 /// Attempts to break the string into tokens and parse those tokens into a token stream.
127 /// May fail for a number of reasons, for example, if the string contains unbalanced delimiters
128 /// or characters not existing in the language.
129 /// All tokens in the parsed stream get `Span::call_site()` spans.
131 /// NOTE: some errors may cause panics instead of returning `LexError`. We reserve the right to
132 /// change these errors into `LexError`s later.
133 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
134 impl FromStr
for TokenStream
{
137 fn from_str(src
: &str) -> Result
<TokenStream
, LexError
> {
138 Ok(TokenStream(bridge
::client
::TokenStream
::from_str(src
)))
142 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
143 // based on it (the reverse of the usual relationship between the two).
144 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
145 impl ToString
for TokenStream
{
146 fn to_string(&self) -> String
{
151 /// Prints the token stream as a string that is supposed to be losslessly convertible back
152 /// into the same token stream (modulo spans), except for possibly `TokenTree::Group`s
153 /// with `Delimiter::None` delimiters and negative numeric literals.
154 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
155 impl fmt
::Display
for TokenStream
{
156 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
157 f
.write_str(&self.to_string())
161 /// Prints token in a form convenient for debugging.
162 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
163 impl fmt
::Debug
for TokenStream
{
164 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
165 f
.write_str("TokenStream ")?
;
166 f
.debug_list().entries(self.clone()).finish()
170 #[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
171 impl Default
for TokenStream
{
172 fn default() -> Self {
177 #[unstable(feature = "proc_macro_quote", issue = "54722")]
178 pub use quote
::{quote, quote_span}
;
180 /// Creates a token stream containing a single token tree.
181 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
182 impl From
<TokenTree
> for TokenStream
{
183 fn from(tree
: TokenTree
) -> TokenStream
{
184 TokenStream(bridge
::client
::TokenStream
::from_token_tree(match tree
{
185 TokenTree
::Group(tt
) => bridge
::TokenTree
::Group(tt
.0),
186 TokenTree
::Punct(tt
) => bridge
::TokenTree
::Punct(tt
.0),
187 TokenTree
::Ident(tt
) => bridge
::TokenTree
::Ident(tt
.0),
188 TokenTree
::Literal(tt
) => bridge
::TokenTree
::Literal(tt
.0),
193 /// Collects a number of token trees into a single stream.
194 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
195 impl iter
::FromIterator
<TokenTree
> for TokenStream
{
196 fn from_iter
<I
: IntoIterator
<Item
= TokenTree
>>(trees
: I
) -> Self {
197 trees
.into_iter().map(TokenStream
::from
).collect()
201 /// A "flattening" operation on token streams, collects token trees
202 /// from multiple token streams into a single stream.
203 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
204 impl iter
::FromIterator
<TokenStream
> for TokenStream
{
205 fn from_iter
<I
: IntoIterator
<Item
= TokenStream
>>(streams
: I
) -> Self {
206 let mut builder
= bridge
::client
::TokenStreamBuilder
::new();
207 streams
.into_iter().for_each(|stream
| builder
.push(stream
.0));
208 TokenStream(builder
.build())
212 #[stable(feature = "token_stream_extend", since = "1.30.0")]
213 impl Extend
<TokenTree
> for TokenStream
{
214 fn extend
<I
: IntoIterator
<Item
= TokenTree
>>(&mut self, trees
: I
) {
215 self.extend(trees
.into_iter().map(TokenStream
::from
));
219 #[stable(feature = "token_stream_extend", since = "1.30.0")]
220 impl Extend
<TokenStream
> for TokenStream
{
221 fn extend
<I
: IntoIterator
<Item
= TokenStream
>>(&mut self, streams
: I
) {
222 // FIXME(eddyb) Use an optimized implementation if/when possible.
223 *self = iter
::once(mem
::replace(self, Self::new())).chain(streams
).collect();
227 /// Public implementation details for the `TokenStream` type, such as iterators.
228 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
229 pub mod token_stream
{
230 use crate::{bridge, Group, Ident, Literal, Punct, TokenStream, TokenTree}
;
232 /// An iterator over `TokenStream`'s `TokenTree`s.
233 /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups,
234 /// and returns whole groups as token trees.
236 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
237 pub struct IntoIter(bridge
::client
::TokenStreamIter
);
239 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
240 impl Iterator
for IntoIter
{
241 type Item
= TokenTree
;
243 fn next(&mut self) -> Option
<TokenTree
> {
244 self.0.next().map(|tree
| match tree
{
245 bridge
::TokenTree
::Group(tt
) => TokenTree
::Group(Group(tt
)),
246 bridge
::TokenTree
::Punct(tt
) => TokenTree
::Punct(Punct(tt
)),
247 bridge
::TokenTree
::Ident(tt
) => TokenTree
::Ident(Ident(tt
)),
248 bridge
::TokenTree
::Literal(tt
) => TokenTree
::Literal(Literal(tt
)),
253 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
254 impl IntoIterator
for TokenStream
{
255 type Item
= TokenTree
;
256 type IntoIter
= IntoIter
;
258 fn into_iter(self) -> IntoIter
{
259 IntoIter(self.0.into_iter
())
264 /// `quote!(..)` accepts arbitrary tokens and expands into a `TokenStream` describing the input.
265 /// For example, `quote!(a + b)` will produce an expression, that, when evaluated, constructs
266 /// the `TokenStream` `[Ident("a"), Punct('+', Alone), Ident("b")]`.
268 /// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
269 /// To quote `$` itself, use `$$`.
270 #[unstable(feature = "proc_macro_quote", issue = "54722")]
271 #[allow_internal_unstable(proc_macro_def_site, proc_macro_internals)]
272 #[rustc_builtin_macro]
273 pub macro quote($
($t
:tt
)*) {
274 /* compiler built-in */
277 #[unstable(feature = "proc_macro_internals", issue = "27812")]
281 /// A region of source code, along with macro expansion information.
282 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
283 #[derive(Copy, Clone)]
284 pub struct Span(bridge
::client
::Span
);
286 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
287 impl !Send
for Span {}
288 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
289 impl !Sync
for Span {}
291 macro_rules
! diagnostic_method
{
292 ($name
:ident
, $level
:expr
) => {
293 /// Creates a new `Diagnostic` with the given `message` at the span
295 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
296 pub fn $name
<T
: Into
<String
>>(self, message
: T
) -> Diagnostic
{
297 Diagnostic
::spanned(self, $level
, message
)
303 /// A span that resolves at the macro definition site.
304 #[unstable(feature = "proc_macro_def_site", issue = "54724")]
305 pub fn def_site() -> Span
{
306 Span(bridge
::client
::Span
::def_site())
309 /// The span of the invocation of the current procedural macro.
310 /// Identifiers created with this span will be resolved as if they were written
311 /// directly at the macro call location (call-site hygiene) and other code
312 /// at the macro call site will be able to refer to them as well.
313 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
314 pub fn call_site() -> Span
{
315 Span(bridge
::client
::Span
::call_site())
318 /// A span that represents `macro_rules` hygiene, and sometimes resolves at the macro
319 /// definition site (local variables, labels, `$crate`) and sometimes at the macro
320 /// call site (everything else).
321 /// The span location is taken from the call-site.
322 #[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
323 pub fn mixed_site() -> Span
{
324 Span(bridge
::client
::Span
::mixed_site())
327 /// The original source file into which this span points.
328 #[unstable(feature = "proc_macro_span", issue = "54725")]
329 pub fn source_file(&self) -> SourceFile
{
330 SourceFile(self.0.source_file())
333 /// The `Span` for the tokens in the previous macro expansion from which
334 /// `self` was generated from, if any.
335 #[unstable(feature = "proc_macro_span", issue = "54725")]
336 pub fn parent(&self) -> Option
<Span
> {
337 self.0.parent().map(Span
)
340 /// The span for the origin source code that `self` was generated from. If
341 /// this `Span` wasn't generated from other macro expansions then the return
342 /// value is the same as `*self`.
343 #[unstable(feature = "proc_macro_span", issue = "54725")]
344 pub fn source(&self) -> Span
{
345 Span(self.0.source())
348 /// Gets the starting line/column in the source file for this span.
349 #[unstable(feature = "proc_macro_span", issue = "54725")]
350 pub fn start(&self) -> LineColumn
{
351 self.0.start().add_1_to_column()
354 /// Gets the ending line/column in the source file for this span.
355 #[unstable(feature = "proc_macro_span", issue = "54725")]
356 pub fn end(&self) -> LineColumn
{
357 self.0.end().add_1_to_column()
360 /// Creates a new span encompassing `self` and `other`.
362 /// Returns `None` if `self` and `other` are from different files.
363 #[unstable(feature = "proc_macro_span", issue = "54725")]
364 pub fn join(&self, other
: Span
) -> Option
<Span
> {
365 self.0.join(other
.0).map(Span
)
368 /// Creates a new span with the same line/column information as `self` but
369 /// that resolves symbols as though it were at `other`.
370 #[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
371 pub fn resolved_at(&self, other
: Span
) -> Span
{
372 Span(self.0.resolved_at(other
.0))
375 /// Creates a new span with the same name resolution behavior as `self` but
376 /// with the line/column information of `other`.
377 #[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
378 pub fn located_at(&self, other
: Span
) -> Span
{
379 other
.resolved_at(*self)
382 /// Compares to spans to see if they're equal.
383 #[unstable(feature = "proc_macro_span", issue = "54725")]
384 pub fn eq(&self, other
: &Span
) -> bool
{
388 /// Returns the source text behind a span. This preserves the original source
389 /// code, including spaces and comments. It only returns a result if the span
390 /// corresponds to real source code.
392 /// Note: The observable result of a macro should only rely on the tokens and
393 /// not on this source text. The result of this function is a best effort to
394 /// be used for diagnostics only.
395 #[unstable(feature = "proc_macro_span", issue = "54725")]
396 pub fn source_text(&self) -> Option
<String
> {
400 // Used by the implementation of `Span::quote`
402 #[unstable(feature = "proc_macro_internals", issue = "27812")]
403 pub fn save_span(&self) -> usize {
407 // Used by the implementation of `Span::quote`
409 #[unstable(feature = "proc_macro_internals", issue = "27812")]
410 pub fn recover_proc_macro_span(id
: usize) -> Span
{
411 Span(bridge
::client
::Span
::recover_proc_macro_span(id
))
414 diagnostic_method
!(error
, Level
::Error
);
415 diagnostic_method
!(warning
, Level
::Warning
);
416 diagnostic_method
!(note
, Level
::Note
);
417 diagnostic_method
!(help
, Level
::Help
);
420 /// Prints a span in a form convenient for debugging.
421 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
422 impl fmt
::Debug
for Span
{
423 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
428 /// A line-column pair representing the start or end of a `Span`.
429 #[unstable(feature = "proc_macro_span", issue = "54725")]
430 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
431 pub struct LineColumn
{
432 /// The 1-indexed line in the source file on which the span starts or ends (inclusive).
433 #[unstable(feature = "proc_macro_span", issue = "54725")]
435 /// The 1-indexed column (number of bytes in UTF-8 encoding) in the source
436 /// file on which the span starts or ends (inclusive).
437 #[unstable(feature = "proc_macro_span", issue = "54725")]
442 fn add_1_to_column(self) -> Self {
443 LineColumn { line: self.line, column: self.column + 1 }
447 #[unstable(feature = "proc_macro_span", issue = "54725")]
448 impl !Send
for LineColumn {}
449 #[unstable(feature = "proc_macro_span", issue = "54725")]
450 impl !Sync
for LineColumn {}
452 #[unstable(feature = "proc_macro_span", issue = "54725")]
453 impl Ord
for LineColumn
{
454 fn cmp(&self, other
: &Self) -> Ordering
{
455 self.line
.cmp(&other
.line
).then(self.column
.cmp(&other
.column
))
459 #[unstable(feature = "proc_macro_span", issue = "54725")]
460 impl PartialOrd
for LineColumn
{
461 fn partial_cmp(&self, other
: &Self) -> Option
<Ordering
> {
462 Some(self.cmp(other
))
466 /// The source file of a given `Span`.
467 #[unstable(feature = "proc_macro_span", issue = "54725")]
469 pub struct SourceFile(bridge
::client
::SourceFile
);
472 /// Gets the path to this source file.
475 /// If the code span associated with this `SourceFile` was generated by an external macro, this
476 /// macro, this might not be an actual path on the filesystem. Use [`is_real`] to check.
478 /// Also note that even if `is_real` returns `true`, if `--remap-path-prefix` was passed on
479 /// the command line, the path as given might not actually be valid.
481 /// [`is_real`]: Self::is_real
482 #[unstable(feature = "proc_macro_span", issue = "54725")]
483 pub fn path(&self) -> PathBuf
{
484 PathBuf
::from(self.0.path())
487 /// Returns `true` if this source file is a real source file, and not generated by an external
488 /// macro's expansion.
489 #[unstable(feature = "proc_macro_span", issue = "54725")]
490 pub fn is_real(&self) -> bool
{
491 // This is a hack until intercrate spans are implemented and we can have real source files
492 // for spans generated in external macros.
493 // https://github.com/rust-lang/rust/pull/43604#issuecomment-333334368
498 #[unstable(feature = "proc_macro_span", issue = "54725")]
499 impl fmt
::Debug
for SourceFile
{
500 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
501 f
.debug_struct("SourceFile")
502 .field("path", &self.path())
503 .field("is_real", &self.is_real())
508 #[unstable(feature = "proc_macro_span", issue = "54725")]
509 impl PartialEq
for SourceFile
{
510 fn eq(&self, other
: &Self) -> bool
{
515 #[unstable(feature = "proc_macro_span", issue = "54725")]
516 impl Eq
for SourceFile {}
518 /// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
519 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
522 /// A token stream surrounded by bracket delimiters.
523 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
524 Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
526 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
527 Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
528 /// A single punctuation character (`+`, `,`, `$`, etc.).
529 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
530 Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
531 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
532 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
533 Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
536 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
537 impl !Send
for TokenTree {}
538 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
539 impl !Sync
for TokenTree {}
542 /// Returns the span of this tree, delegating to the `span` method of
543 /// the contained token or a delimited stream.
544 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
545 pub fn span(&self) -> Span
{
547 TokenTree
::Group(ref t
) => t
.span(),
548 TokenTree
::Ident(ref t
) => t
.span(),
549 TokenTree
::Punct(ref t
) => t
.span(),
550 TokenTree
::Literal(ref t
) => t
.span(),
554 /// Configures the span for *only this token*.
556 /// Note that if this token is a `Group` then this method will not configure
557 /// the span of each of the internal tokens, this will simply delegate to
558 /// the `set_span` method of each variant.
559 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
560 pub fn set_span(&mut self, span
: Span
) {
562 TokenTree
::Group(ref mut t
) => t
.set_span(span
),
563 TokenTree
::Ident(ref mut t
) => t
.set_span(span
),
564 TokenTree
::Punct(ref mut t
) => t
.set_span(span
),
565 TokenTree
::Literal(ref mut t
) => t
.set_span(span
),
570 /// Prints token tree in a form convenient for debugging.
571 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
572 impl fmt
::Debug
for TokenTree
{
573 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
574 // Each of these has the name in the struct type in the derived debug,
575 // so don't bother with an extra layer of indirection
577 TokenTree
::Group(ref tt
) => tt
.fmt(f
),
578 TokenTree
::Ident(ref tt
) => tt
.fmt(f
),
579 TokenTree
::Punct(ref tt
) => tt
.fmt(f
),
580 TokenTree
::Literal(ref tt
) => tt
.fmt(f
),
585 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
586 impl From
<Group
> for TokenTree
{
587 fn from(g
: Group
) -> TokenTree
{
592 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
593 impl From
<Ident
> for TokenTree
{
594 fn from(g
: Ident
) -> TokenTree
{
599 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
600 impl From
<Punct
> for TokenTree
{
601 fn from(g
: Punct
) -> TokenTree
{
606 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
607 impl From
<Literal
> for TokenTree
{
608 fn from(g
: Literal
) -> TokenTree
{
609 TokenTree
::Literal(g
)
613 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
614 // based on it (the reverse of the usual relationship between the two).
615 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
616 impl ToString
for TokenTree
{
617 fn to_string(&self) -> String
{
619 TokenTree
::Group(ref t
) => t
.to_string(),
620 TokenTree
::Ident(ref t
) => t
.to_string(),
621 TokenTree
::Punct(ref t
) => t
.to_string(),
622 TokenTree
::Literal(ref t
) => t
.to_string(),
627 /// Prints the token tree as a string that is supposed to be losslessly convertible back
628 /// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
629 /// with `Delimiter::None` delimiters and negative numeric literals.
630 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
631 impl fmt
::Display
for TokenTree
{
632 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
633 f
.write_str(&self.to_string())
637 /// A delimited token stream.
639 /// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
641 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
642 pub struct Group(bridge
::client
::Group
);
644 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
645 impl !Send
for Group {}
646 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
647 impl !Sync
for Group {}
649 /// Describes how a sequence of token trees is delimited.
650 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
651 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
654 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
657 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
660 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
663 /// An implicit delimiter, that may, for example, appear around tokens coming from a
664 /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
665 /// `$var * 3` where `$var` is `1 + 2`.
666 /// Implicit delimiters might not survive roundtrip of a token stream through a string.
667 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
672 /// Creates a new `Group` with the given delimiter and token stream.
674 /// This constructor will set the span for this group to
675 /// `Span::call_site()`. To change the span you can use the `set_span`
677 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
678 pub fn new(delimiter
: Delimiter
, stream
: TokenStream
) -> Group
{
679 Group(bridge
::client
::Group
::new(delimiter
, stream
.0))
682 /// Returns the delimiter of this `Group`
683 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
684 pub fn delimiter(&self) -> Delimiter
{
688 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
690 /// Note that the returned token stream does not include the delimiter
692 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
693 pub fn stream(&self) -> TokenStream
{
694 TokenStream(self.0.stream())
697 /// Returns the span for the delimiters of this token stream, spanning the
701 /// pub fn span(&self) -> Span {
704 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
705 pub fn span(&self) -> Span
{
709 /// Returns the span pointing to the opening delimiter of this group.
712 /// pub fn span_open(&self) -> Span {
715 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
716 pub fn span_open(&self) -> Span
{
717 Span(self.0.span_open())
720 /// Returns the span pointing to the closing delimiter of this group.
723 /// pub fn span_close(&self) -> Span {
726 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
727 pub fn span_close(&self) -> Span
{
728 Span(self.0.span_close())
731 /// Configures the span for this `Group`'s delimiters, but not its internal
734 /// This method will **not** set the span of all the internal tokens spanned
735 /// by this group, but rather it will only set the span of the delimiter
736 /// tokens at the level of the `Group`.
737 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
738 pub fn set_span(&mut self, span
: Span
) {
739 self.0.set_span(span
.0);
743 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
744 // based on it (the reverse of the usual relationship between the two).
745 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
746 impl ToString
for Group
{
747 fn to_string(&self) -> String
{
748 TokenStream
::from(TokenTree
::from(self.clone())).to_string()
752 /// Prints the group as a string that should be losslessly convertible back
753 /// into the same group (modulo spans), except for possibly `TokenTree::Group`s
754 /// with `Delimiter::None` delimiters.
755 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
756 impl fmt
::Display
for Group
{
757 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
758 f
.write_str(&self.to_string())
762 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
763 impl fmt
::Debug
for Group
{
764 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
765 f
.debug_struct("Group")
766 .field("delimiter", &self.delimiter())
767 .field("stream", &self.stream())
768 .field("span", &self.span())
773 /// A `Punct` is a single punctuation character such as `+`, `-` or `#`.
775 /// Multi-character operators like `+=` are represented as two instances of `Punct` with different
776 /// forms of `Spacing` returned.
777 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
779 pub struct Punct(bridge
::client
::Punct
);
781 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
782 impl !Send
for Punct {}
783 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
784 impl !Sync
for Punct {}
786 /// Describes whether a `Punct` is followed immediately by another `Punct` ([`Spacing::Joint`]) or
787 /// by a different token or whitespace ([`Spacing::Alone`]).
788 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
789 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
791 /// A `Punct` is not immediately followed by another `Punct`.
792 /// E.g. `+` is `Alone` in `+ =`, `+ident` and `+()`.
793 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
795 /// A `Punct` is immediately followed by another `Punct`.
796 /// E.g. `+` is `Joint` in `+=` and `++`.
798 /// Additionally, single quote `'` can join with identifiers to form lifetimes: `'ident`.
799 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
804 /// Creates a new `Punct` from the given character and spacing.
805 /// The `ch` argument must be a valid punctuation character permitted by the language,
806 /// otherwise the function will panic.
808 /// The returned `Punct` will have the default span of `Span::call_site()`
809 /// which can be further configured with the `set_span` method below.
810 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
811 pub fn new(ch
: char, spacing
: Spacing
) -> Punct
{
812 Punct(bridge
::client
::Punct
::new(ch
, spacing
))
815 /// Returns the value of this punctuation character as `char`.
816 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
817 pub fn as_char(&self) -> char {
821 /// Returns the spacing of this punctuation character, indicating whether it's immediately
822 /// followed by another `Punct` in the token stream, so they can potentially be combined into
823 /// a multi-character operator (`Joint`), or it's followed by some other token or whitespace
824 /// (`Alone`) so the operator has certainly ended.
825 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
826 pub fn spacing(&self) -> Spacing
{
830 /// Returns the span for this punctuation character.
831 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
832 pub fn span(&self) -> Span
{
836 /// Configure the span for this punctuation character.
837 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
838 pub fn set_span(&mut self, span
: Span
) {
839 self.0 = self.0.with_span(span
.0);
843 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
844 // based on it (the reverse of the usual relationship between the two).
845 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
846 impl ToString
for Punct
{
847 fn to_string(&self) -> String
{
848 TokenStream
::from(TokenTree
::from(self.clone())).to_string()
852 /// Prints the punctuation character as a string that should be losslessly convertible
853 /// back into the same character.
854 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
855 impl fmt
::Display
for Punct
{
856 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
857 f
.write_str(&self.to_string())
861 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
862 impl fmt
::Debug
for Punct
{
863 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
864 f
.debug_struct("Punct")
865 .field("ch", &self.as_char())
866 .field("spacing", &self.spacing())
867 .field("span", &self.span())
872 #[stable(feature = "proc_macro_punct_eq", since = "1.50.0")]
873 impl PartialEq
<char> for Punct
{
874 fn eq(&self, rhs
: &char) -> bool
{
875 self.as_char() == *rhs
879 #[stable(feature = "proc_macro_punct_eq_flipped", since = "1.52.0")]
880 impl PartialEq
<Punct
> for char {
881 fn eq(&self, rhs
: &Punct
) -> bool
{
882 *self == rhs
.as_char()
886 /// An identifier (`ident`).
888 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
889 pub struct Ident(bridge
::client
::Ident
);
892 /// Creates a new `Ident` with the given `string` as well as the specified
894 /// The `string` argument must be a valid identifier permitted by the
895 /// language (including keywords, e.g. `self` or `fn`). Otherwise, the function will panic.
897 /// Note that `span`, currently in rustc, configures the hygiene information
898 /// for this identifier.
900 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
901 /// meaning that identifiers created with this span will be resolved as if they were written
902 /// directly at the location of the macro call, and other code at the macro call site will be
903 /// able to refer to them as well.
905 /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
906 /// meaning that identifiers created with this span will be resolved at the location of the
907 /// macro definition and other code at the macro call site will not be able to refer to them.
909 /// Due to the current importance of hygiene this constructor, unlike other
910 /// tokens, requires a `Span` to be specified at construction.
911 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
912 pub fn new(string
: &str, span
: Span
) -> Ident
{
913 Ident(bridge
::client
::Ident
::new(string
, span
.0, false))
916 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
917 /// The `string` argument be a valid identifier permitted by the language
918 /// (including keywords, e.g. `fn`). Keywords which are usable in path segments
919 /// (e.g. `self`, `super`) are not supported, and will cause a panic.
920 #[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
921 pub fn new_raw(string
: &str, span
: Span
) -> Ident
{
922 Ident(bridge
::client
::Ident
::new(string
, span
.0, true))
925 /// Returns the span of this `Ident`, encompassing the entire string returned
926 /// by [`to_string`](Self::to_string).
927 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
928 pub fn span(&self) -> Span
{
932 /// Configures the span of this `Ident`, possibly changing its hygiene context.
933 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
934 pub fn set_span(&mut self, span
: Span
) {
935 self.0 = self.0.with_span(span
.0);
939 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
940 // based on it (the reverse of the usual relationship between the two).
941 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
942 impl ToString
for Ident
{
943 fn to_string(&self) -> String
{
944 TokenStream
::from(TokenTree
::from(self.clone())).to_string()
948 /// Prints the identifier as a string that should be losslessly convertible
949 /// back into the same identifier.
950 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
951 impl fmt
::Display
for Ident
{
952 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
953 f
.write_str(&self.to_string())
957 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
958 impl fmt
::Debug
for Ident
{
959 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
960 f
.debug_struct("Ident")
961 .field("ident", &self.to_string())
962 .field("span", &self.span())
967 /// A literal string (`"hello"`), byte string (`b"hello"`),
968 /// character (`'a'`), byte character (`b'a'`), an integer or floating point number
969 /// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
970 /// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
972 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
973 pub struct Literal(bridge
::client
::Literal
);
975 macro_rules
! suffixed_int_literals
{
976 ($
($name
:ident
=> $kind
:ident
,)*) => ($
(
977 /// Creates a new suffixed integer literal with the specified value.
979 /// This function will create an integer like `1u32` where the integer
980 /// value specified is the first part of the token and the integral is
981 /// also suffixed at the end.
982 /// Literals created from negative numbers might not survive round-trips through
983 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
985 /// Literals created through this method have the `Span::call_site()`
986 /// span by default, which can be configured with the `set_span` method
988 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
989 pub fn $
name(n
: $kind
) -> Literal
{
990 Literal(bridge
::client
::Literal
::typed_integer(&n
.to_string(), stringify
!($kind
)))
995 macro_rules
! unsuffixed_int_literals
{
996 ($
($name
:ident
=> $kind
:ident
,)*) => ($
(
997 /// Creates a new unsuffixed integer literal with the specified value.
999 /// This function will create an integer like `1` where the integer
1000 /// value specified is the first part of the token. No suffix is
1001 /// specified on this token, meaning that invocations like
1002 /// `Literal::i8_unsuffixed(1)` are equivalent to
1003 /// `Literal::u32_unsuffixed(1)`.
1004 /// Literals created from negative numbers might not survive rountrips through
1005 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1007 /// Literals created through this method have the `Span::call_site()`
1008 /// span by default, which can be configured with the `set_span` method
1010 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1011 pub fn $
name(n
: $kind
) -> Literal
{
1012 Literal(bridge
::client
::Literal
::integer(&n
.to_string()))
1018 suffixed_int_literals
! {
1020 u16_suffixed
=> u16,
1021 u32_suffixed
=> u32,
1022 u64_suffixed
=> u64,
1023 u128_suffixed
=> u128
,
1024 usize_suffixed
=> usize,
1026 i16_suffixed
=> i16,
1027 i32_suffixed
=> i32,
1028 i64_suffixed
=> i64,
1029 i128_suffixed
=> i128
,
1030 isize_suffixed
=> isize,
1033 unsuffixed_int_literals
! {
1034 u8_unsuffixed
=> u8,
1035 u16_unsuffixed
=> u16,
1036 u32_unsuffixed
=> u32,
1037 u64_unsuffixed
=> u64,
1038 u128_unsuffixed
=> u128
,
1039 usize_unsuffixed
=> usize,
1040 i8_unsuffixed
=> i8,
1041 i16_unsuffixed
=> i16,
1042 i32_unsuffixed
=> i32,
1043 i64_unsuffixed
=> i64,
1044 i128_unsuffixed
=> i128
,
1045 isize_unsuffixed
=> isize,
1048 /// Creates a new unsuffixed floating-point literal.
1050 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1051 /// the float's value is emitted directly into the token but no suffix is
1052 /// used, so it may be inferred to be a `f64` later in the compiler.
1053 /// Literals created from negative numbers might not survive rountrips through
1054 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1058 /// This function requires that the specified float is finite, for
1059 /// example if it is infinity or NaN this function will panic.
1060 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1061 pub fn f32_unsuffixed(n
: f32) -> Literal
{
1063 panic
!("Invalid float literal {}", n
);
1065 Literal(bridge
::client
::Literal
::float(&n
.to_string()))
1068 /// Creates a new suffixed floating-point literal.
1070 /// This constructor will create a literal like `1.0f32` where the value
1071 /// specified is the preceding part of the token and `f32` is the suffix of
1072 /// the token. This token will always be inferred to be an `f32` in the
1074 /// Literals created from negative numbers might not survive rountrips through
1075 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1079 /// This function requires that the specified float is finite, for
1080 /// example if it is infinity or NaN this function will panic.
1081 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1082 pub fn f32_suffixed(n
: f32) -> Literal
{
1084 panic
!("Invalid float literal {}", n
);
1086 Literal(bridge
::client
::Literal
::f32(&n
.to_string()))
1089 /// Creates a new unsuffixed floating-point literal.
1091 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1092 /// the float's value is emitted directly into the token but no suffix is
1093 /// used, so it may be inferred to be a `f64` later in the compiler.
1094 /// Literals created from negative numbers might not survive rountrips through
1095 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1099 /// This function requires that the specified float is finite, for
1100 /// example if it is infinity or NaN this function will panic.
1101 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1102 pub fn f64_unsuffixed(n
: f64) -> Literal
{
1104 panic
!("Invalid float literal {}", n
);
1106 Literal(bridge
::client
::Literal
::float(&n
.to_string()))
1109 /// Creates a new suffixed floating-point literal.
1111 /// This constructor will create a literal like `1.0f64` where the value
1112 /// specified is the preceding part of the token and `f64` is the suffix of
1113 /// the token. This token will always be inferred to be an `f64` in the
1115 /// Literals created from negative numbers might not survive rountrips through
1116 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1120 /// This function requires that the specified float is finite, for
1121 /// example if it is infinity or NaN this function will panic.
1122 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1123 pub fn f64_suffixed(n
: f64) -> Literal
{
1125 panic
!("Invalid float literal {}", n
);
1127 Literal(bridge
::client
::Literal
::f64(&n
.to_string()))
1131 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1132 pub fn string(string
: &str) -> Literal
{
1133 Literal(bridge
::client
::Literal
::string(string
))
1136 /// Character literal.
1137 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1138 pub fn character(ch
: char) -> Literal
{
1139 Literal(bridge
::client
::Literal
::character(ch
))
1142 /// Byte string literal.
1143 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1144 pub fn byte_string(bytes
: &[u8]) -> Literal
{
1145 Literal(bridge
::client
::Literal
::byte_string(bytes
))
1148 /// Returns the span encompassing this literal.
1149 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1150 pub fn span(&self) -> Span
{
1154 /// Configures the span associated for this literal.
1155 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1156 pub fn set_span(&mut self, span
: Span
) {
1157 self.0.set_span(span
.0);
1160 /// Returns a `Span` that is a subset of `self.span()` containing only the
1161 /// source bytes in range `range`. Returns `None` if the would-be trimmed
1162 /// span is outside the bounds of `self`.
1163 // FIXME(SergioBenitez): check that the byte range starts and ends at a
1164 // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1165 // occur elsewhere when the source text is printed.
1166 // FIXME(SergioBenitez): there is no way for the user to know what
1167 // `self.span()` actually maps to, so this method can currently only be
1168 // called blindly. For example, `to_string()` for the character 'c' returns
1169 // "'\u{63}'"; there is no way for the user to know whether the source text
1170 // was 'c' or whether it was '\u{63}'.
1171 #[unstable(feature = "proc_macro_span", issue = "54725")]
1172 pub fn subspan
<R
: RangeBounds
<usize>>(&self, range
: R
) -> Option
<Span
> {
1173 self.0.subspan(range
.start_bound().cloned(), range
.end_bound().cloned()).map(Span
)
1177 /// Parse a single literal from its stringified representation.
1179 /// In order to parse successfully, the input string must not contain anything
1180 /// but the literal token. Specifically, it must not contain whitespace or
1181 /// comments in addition to the literal.
1183 /// The resulting literal token will have a `Span::call_site()` span.
1185 /// NOTE: some errors may cause panics instead of returning `LexError`. We
1186 /// reserve the right to change these errors into `LexError`s later.
1187 #[stable(feature = "proc_macro_literal_parse", since = "1.54.0")]
1188 impl FromStr
for Literal
{
1189 type Err
= LexError
;
1191 fn from_str(src
: &str) -> Result
<Self, LexError
> {
1192 match bridge
::client
::Literal
::from_str(src
) {
1193 Ok(literal
) => Ok(Literal(literal
)),
1194 Err(()) => Err(LexError
::new()),
1199 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
1200 // based on it (the reverse of the usual relationship between the two).
1201 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
1202 impl ToString
for Literal
{
1203 fn to_string(&self) -> String
{
1208 /// Prints the literal as a string that should be losslessly convertible
1209 /// back into the same literal (except for possible rounding for floating point literals).
1210 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1211 impl fmt
::Display
for Literal
{
1212 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1213 f
.write_str(&self.to_string())
1217 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1218 impl fmt
::Debug
for Literal
{
1219 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1224 /// Tracked access to environment variables.
1225 #[unstable(feature = "proc_macro_tracked_env", issue = "74690")]
1226 pub mod tracked_env
{
1227 use std
::env
::{self, VarError}
;
1228 use std
::ffi
::OsStr
;
1230 /// Retrieve an environment variable and add it to build dependency info.
1231 /// Build system executing the compiler will know that the variable was accessed during
1232 /// compilation, and will be able to rerun the build when the value of that variable changes.
1233 /// Besides the dependency tracking this function should be equivalent to `env::var` from the
1234 /// standard library, except that the argument must be UTF-8.
1235 #[unstable(feature = "proc_macro_tracked_env", issue = "74690")]
1236 pub fn var
<K
: AsRef
<OsStr
> + AsRef
<str>>(key
: K
) -> Result
<String
, VarError
> {
1237 let key
: &str = key
.as_ref();
1238 let value
= env
::var(key
);
1239 crate::bridge
::client
::FreeFunctions
::track_env_var(key
, value
.as_deref().ok());
1244 /// Tracked access to additional files.
1245 #[unstable(feature = "track_path", issue = "73921")]
1246 pub mod tracked_path
{
1248 /// Track a file explicitly.
1250 /// Commonly used for tracking asset preprocessing.
1251 #[unstable(feature = "track_path", issue = "73921")]
1252 pub fn path
<P
: AsRef
<str>>(path
: P
) {
1253 let path
: &str = path
.as_ref();
1254 crate::bridge
::client
::FreeFunctions
::track_path(path
);