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_root_url
= "https://doc.rust-lang.org/nightly/",
16 html_playground_url
= "https://play.rust-lang.org/",
17 issue_tracker_base_url
= "https://github.com/rust-lang/rust/issues/",
18 test(no_crate_inject
, attr(deny(warnings
))),
19 test(attr(allow(dead_code
, deprecated
, unused_variables
, unused_mut
)))
21 #![feature(rustc_allow_const_fn_unstable)]
23 #![feature(staged_api)]
25 #![feature(const_fn_fn_ptr_basics)]
26 #![feature(allow_internal_unstable)]
27 #![feature(decl_macro)]
28 #![feature(extern_types)]
29 #![feature(in_band_lifetimes)]
30 #![feature(negative_impls)]
31 #![cfg_attr(bootstrap, feature(optin_builtin_traits))]
32 #![cfg_attr(not(bootstrap), feature(auto_traits))]
33 #![feature(restricted_std)]
34 #![feature(rustc_attrs)]
35 #![feature(min_specialization)]
36 #![recursion_limit = "256"]
38 #[unstable(feature = "proc_macro_internals", issue = "27812")]
44 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
45 pub use diagnostic
::{Diagnostic, Level, MultiSpan}
;
47 use std
::cmp
::Ordering
;
48 use std
::ops
::{Bound, RangeBounds}
;
49 use std
::path
::PathBuf
;
50 use std
::str::FromStr
;
51 use std
::{error, fmt, iter, mem}
;
53 /// Determines whether proc_macro has been made accessible to the currently
56 /// The proc_macro crate is only intended for use inside the implementation of
57 /// procedural macros. All the functions in this crate panic if invoked from
58 /// outside of a procedural macro, such as from a build script or unit test or
59 /// ordinary Rust binary.
61 /// With consideration for Rust libraries that are designed to support both
62 /// macro and non-macro use cases, `proc_macro::is_available()` provides a
63 /// non-panicking way to detect whether the infrastructure required to use the
64 /// API of proc_macro is presently available. Returns true if invoked from
65 /// inside of a procedural macro, false if invoked from any other binary.
66 #[unstable(feature = "proc_macro_is_available", issue = "71436")]
67 pub fn is_available() -> bool
{
68 bridge
::Bridge
::is_available()
71 /// The main type provided by this crate, representing an abstract stream of
72 /// tokens, or, more specifically, a sequence of token trees.
73 /// The type provide interfaces for iterating over those token trees and, conversely,
74 /// collecting a number of token trees into one stream.
76 /// This is both the input and output of `#[proc_macro]`, `#[proc_macro_attribute]`
77 /// and `#[proc_macro_derive]` definitions.
78 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
80 pub struct TokenStream(bridge
::client
::TokenStream
);
82 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
83 impl !Send
for TokenStream {}
84 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
85 impl !Sync
for TokenStream {}
87 /// Error returned from `TokenStream::from_str`.
88 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
94 #[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
95 impl fmt
::Display
for LexError
{
96 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
97 f
.write_str("cannot parse string into token stream")
101 #[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
102 impl error
::Error
for LexError {}
104 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
105 impl !Send
for LexError {}
106 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
107 impl !Sync
for LexError {}
110 /// Returns an empty `TokenStream` containing no token trees.
111 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
112 pub fn new() -> TokenStream
{
113 TokenStream(bridge
::client
::TokenStream
::new())
116 /// Checks if this `TokenStream` is empty.
117 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
118 pub fn is_empty(&self) -> bool
{
123 /// Attempts to break the string into tokens and parse those tokens into a token stream.
124 /// May fail for a number of reasons, for example, if the string contains unbalanced delimiters
125 /// or characters not existing in the language.
126 /// All tokens in the parsed stream get `Span::call_site()` spans.
128 /// NOTE: some errors may cause panics instead of returning `LexError`. We reserve the right to
129 /// change these errors into `LexError`s later.
130 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
131 impl FromStr
for TokenStream
{
134 fn from_str(src
: &str) -> Result
<TokenStream
, LexError
> {
135 Ok(TokenStream(bridge
::client
::TokenStream
::from_str(src
)))
139 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
140 // based on it (the reverse of the usual relationship between the two).
141 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
142 impl ToString
for TokenStream
{
143 fn to_string(&self) -> String
{
148 /// Prints the token stream as a string that is supposed to be losslessly convertible back
149 /// into the same token stream (modulo spans), except for possibly `TokenTree::Group`s
150 /// with `Delimiter::None` delimiters and negative numeric literals.
151 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
152 impl fmt
::Display
for TokenStream
{
153 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
154 f
.write_str(&self.to_string())
158 /// Prints token in a form convenient for debugging.
159 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
160 impl fmt
::Debug
for TokenStream
{
161 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
162 f
.write_str("TokenStream ")?
;
163 f
.debug_list().entries(self.clone()).finish()
167 #[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
168 impl Default
for TokenStream
{
169 fn default() -> Self {
174 #[unstable(feature = "proc_macro_quote", issue = "54722")]
175 pub use quote
::{quote, quote_span}
;
177 /// Creates a token stream containing a single token tree.
178 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
179 impl From
<TokenTree
> for TokenStream
{
180 fn from(tree
: TokenTree
) -> TokenStream
{
181 TokenStream(bridge
::client
::TokenStream
::from_token_tree(match tree
{
182 TokenTree
::Group(tt
) => bridge
::TokenTree
::Group(tt
.0),
183 TokenTree
::Punct(tt
) => bridge
::TokenTree
::Punct(tt
.0),
184 TokenTree
::Ident(tt
) => bridge
::TokenTree
::Ident(tt
.0),
185 TokenTree
::Literal(tt
) => bridge
::TokenTree
::Literal(tt
.0),
190 /// Collects a number of token trees into a single stream.
191 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
192 impl iter
::FromIterator
<TokenTree
> for TokenStream
{
193 fn from_iter
<I
: IntoIterator
<Item
= TokenTree
>>(trees
: I
) -> Self {
194 trees
.into_iter().map(TokenStream
::from
).collect()
198 /// A "flattening" operation on token streams, collects token trees
199 /// from multiple token streams into a single stream.
200 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
201 impl iter
::FromIterator
<TokenStream
> for TokenStream
{
202 fn from_iter
<I
: IntoIterator
<Item
= TokenStream
>>(streams
: I
) -> Self {
203 let mut builder
= bridge
::client
::TokenStreamBuilder
::new();
204 streams
.into_iter().for_each(|stream
| builder
.push(stream
.0));
205 TokenStream(builder
.build())
209 #[stable(feature = "token_stream_extend", since = "1.30.0")]
210 impl Extend
<TokenTree
> for TokenStream
{
211 fn extend
<I
: IntoIterator
<Item
= TokenTree
>>(&mut self, trees
: I
) {
212 self.extend(trees
.into_iter().map(TokenStream
::from
));
216 #[stable(feature = "token_stream_extend", since = "1.30.0")]
217 impl Extend
<TokenStream
> for TokenStream
{
218 fn extend
<I
: IntoIterator
<Item
= TokenStream
>>(&mut self, streams
: I
) {
219 // FIXME(eddyb) Use an optimized implementation if/when possible.
220 *self = iter
::once(mem
::replace(self, Self::new())).chain(streams
).collect();
224 /// Public implementation details for the `TokenStream` type, such as iterators.
225 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
226 pub mod token_stream
{
227 use crate::{bridge, Group, Ident, Literal, Punct, TokenStream, TokenTree}
;
229 /// An iterator over `TokenStream`'s `TokenTree`s.
230 /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups,
231 /// and returns whole groups as token trees.
233 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
234 pub struct IntoIter(bridge
::client
::TokenStreamIter
);
236 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
237 impl Iterator
for IntoIter
{
238 type Item
= TokenTree
;
240 fn next(&mut self) -> Option
<TokenTree
> {
241 self.0.next().map(|tree
| match tree
{
242 bridge
::TokenTree
::Group(tt
) => TokenTree
::Group(Group(tt
)),
243 bridge
::TokenTree
::Punct(tt
) => TokenTree
::Punct(Punct(tt
)),
244 bridge
::TokenTree
::Ident(tt
) => TokenTree
::Ident(Ident(tt
)),
245 bridge
::TokenTree
::Literal(tt
) => TokenTree
::Literal(Literal(tt
)),
250 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
251 impl IntoIterator
for TokenStream
{
252 type Item
= TokenTree
;
253 type IntoIter
= IntoIter
;
255 fn into_iter(self) -> IntoIter
{
256 IntoIter(self.0.into_iter
())
261 /// `quote!(..)` accepts arbitrary tokens and expands into a `TokenStream` describing the input.
262 /// For example, `quote!(a + b)` will produce a expression, that, when evaluated, constructs
263 /// the `TokenStream` `[Ident("a"), Punct('+', Alone), Ident("b")]`.
265 /// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
266 /// To quote `$` itself, use `$$`.
267 #[unstable(feature = "proc_macro_quote", issue = "54722")]
268 #[allow_internal_unstable(proc_macro_def_site)]
269 #[rustc_builtin_macro]
270 pub macro quote($
($t
:tt
)*) {
271 /* compiler built-in */
274 #[unstable(feature = "proc_macro_internals", issue = "27812")]
278 /// A region of source code, along with macro expansion information.
279 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
280 #[derive(Copy, Clone)]
281 pub struct Span(bridge
::client
::Span
);
283 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
284 impl !Send
for Span {}
285 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
286 impl !Sync
for Span {}
288 macro_rules
! diagnostic_method
{
289 ($name
:ident
, $level
:expr
) => {
290 /// Creates a new `Diagnostic` with the given `message` at the span
292 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
293 pub fn $name
<T
: Into
<String
>>(self, message
: T
) -> Diagnostic
{
294 Diagnostic
::spanned(self, $level
, message
)
300 /// A span that resolves at the macro definition site.
301 #[unstable(feature = "proc_macro_def_site", issue = "54724")]
302 pub fn def_site() -> Span
{
303 Span(bridge
::client
::Span
::def_site())
306 /// The span of the invocation of the current procedural macro.
307 /// Identifiers created with this span will be resolved as if they were written
308 /// directly at the macro call location (call-site hygiene) and other code
309 /// at the macro call site will be able to refer to them as well.
310 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
311 pub fn call_site() -> Span
{
312 Span(bridge
::client
::Span
::call_site())
315 /// A span that represents `macro_rules` hygiene, and sometimes resolves at the macro
316 /// definition site (local variables, labels, `$crate`) and sometimes at the macro
317 /// call site (everything else).
318 /// The span location is taken from the call-site.
319 #[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
320 pub fn mixed_site() -> Span
{
321 Span(bridge
::client
::Span
::mixed_site())
324 /// The original source file into which this span points.
325 #[unstable(feature = "proc_macro_span", issue = "54725")]
326 pub fn source_file(&self) -> SourceFile
{
327 SourceFile(self.0.source_file())
330 /// The `Span` for the tokens in the previous macro expansion from which
331 /// `self` was generated from, if any.
332 #[unstable(feature = "proc_macro_span", issue = "54725")]
333 pub fn parent(&self) -> Option
<Span
> {
334 self.0.parent().map(Span
)
337 /// The span for the origin source code that `self` was generated from. If
338 /// this `Span` wasn't generated from other macro expansions then the return
339 /// value is the same as `*self`.
340 #[unstable(feature = "proc_macro_span", issue = "54725")]
341 pub fn source(&self) -> Span
{
342 Span(self.0.source())
345 /// Gets the starting line/column in the source file for this span.
346 #[unstable(feature = "proc_macro_span", issue = "54725")]
347 pub fn start(&self) -> LineColumn
{
351 /// Gets the ending line/column in the source file for this span.
352 #[unstable(feature = "proc_macro_span", issue = "54725")]
353 pub fn end(&self) -> LineColumn
{
357 /// Creates a new span encompassing `self` and `other`.
359 /// Returns `None` if `self` and `other` are from different files.
360 #[unstable(feature = "proc_macro_span", issue = "54725")]
361 pub fn join(&self, other
: Span
) -> Option
<Span
> {
362 self.0.join(other
.0).map(Span
)
365 /// Creates a new span with the same line/column information as `self` but
366 /// that resolves symbols as though it were at `other`.
367 #[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
368 pub fn resolved_at(&self, other
: Span
) -> Span
{
369 Span(self.0.resolved_at(other
.0))
372 /// Creates a new span with the same name resolution behavior as `self` but
373 /// with the line/column information of `other`.
374 #[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
375 pub fn located_at(&self, other
: Span
) -> Span
{
376 other
.resolved_at(*self)
379 /// Compares to spans to see if they're equal.
380 #[unstable(feature = "proc_macro_span", issue = "54725")]
381 pub fn eq(&self, other
: &Span
) -> bool
{
385 /// Returns the source text behind a span. This preserves the original source
386 /// code, including spaces and comments. It only returns a result if the span
387 /// corresponds to real source code.
389 /// Note: The observable result of a macro should only rely on the tokens and
390 /// not on this source text. The result of this function is a best effort to
391 /// be used for diagnostics only.
392 #[unstable(feature = "proc_macro_span", issue = "54725")]
393 pub fn source_text(&self) -> Option
<String
> {
397 diagnostic_method
!(error
, Level
::Error
);
398 diagnostic_method
!(warning
, Level
::Warning
);
399 diagnostic_method
!(note
, Level
::Note
);
400 diagnostic_method
!(help
, Level
::Help
);
403 /// Prints a span in a form convenient for debugging.
404 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
405 impl fmt
::Debug
for Span
{
406 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
411 /// A line-column pair representing the start or end of a `Span`.
412 #[unstable(feature = "proc_macro_span", issue = "54725")]
413 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
414 pub struct LineColumn
{
415 /// The 1-indexed line in the source file on which the span starts or ends (inclusive).
416 #[unstable(feature = "proc_macro_span", issue = "54725")]
418 /// The 0-indexed column (in UTF-8 characters) in the source file on which
419 /// the span starts or ends (inclusive).
420 #[unstable(feature = "proc_macro_span", issue = "54725")]
424 #[unstable(feature = "proc_macro_span", issue = "54725")]
425 impl !Send
for LineColumn {}
426 #[unstable(feature = "proc_macro_span", issue = "54725")]
427 impl !Sync
for LineColumn {}
429 #[unstable(feature = "proc_macro_span", issue = "54725")]
430 impl Ord
for LineColumn
{
431 fn cmp(&self, other
: &Self) -> Ordering
{
432 self.line
.cmp(&other
.line
).then(self.column
.cmp(&other
.column
))
436 #[unstable(feature = "proc_macro_span", issue = "54725")]
437 impl PartialOrd
for LineColumn
{
438 fn partial_cmp(&self, other
: &Self) -> Option
<Ordering
> {
439 Some(self.cmp(other
))
443 /// The source file of a given `Span`.
444 #[unstable(feature = "proc_macro_span", issue = "54725")]
446 pub struct SourceFile(bridge
::client
::SourceFile
);
449 /// Gets the path to this source file.
452 /// If the code span associated with this `SourceFile` was generated by an external macro, this
453 /// macro, this may not be an actual path on the filesystem. Use [`is_real`] to check.
455 /// Also note that even if `is_real` returns `true`, if `--remap-path-prefix` was passed on
456 /// the command line, the path as given may not actually be valid.
458 /// [`is_real`]: Self::is_real
459 #[unstable(feature = "proc_macro_span", issue = "54725")]
460 pub fn path(&self) -> PathBuf
{
461 PathBuf
::from(self.0.path())
464 /// Returns `true` if this source file is a real source file, and not generated by an external
465 /// macro's expansion.
466 #[unstable(feature = "proc_macro_span", issue = "54725")]
467 pub fn is_real(&self) -> bool
{
468 // This is a hack until intercrate spans are implemented and we can have real source files
469 // for spans generated in external macros.
470 // https://github.com/rust-lang/rust/pull/43604#issuecomment-333334368
475 #[unstable(feature = "proc_macro_span", issue = "54725")]
476 impl fmt
::Debug
for SourceFile
{
477 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
478 f
.debug_struct("SourceFile")
479 .field("path", &self.path())
480 .field("is_real", &self.is_real())
485 #[unstable(feature = "proc_macro_span", issue = "54725")]
486 impl PartialEq
for SourceFile
{
487 fn eq(&self, other
: &Self) -> bool
{
492 #[unstable(feature = "proc_macro_span", issue = "54725")]
493 impl Eq
for SourceFile {}
495 /// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
496 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
499 /// A token stream surrounded by bracket delimiters.
500 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
501 Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
503 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
504 Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
505 /// A single punctuation character (`+`, `,`, `$`, etc.).
506 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
507 Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
508 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
509 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
510 Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
513 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
514 impl !Send
for TokenTree {}
515 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
516 impl !Sync
for TokenTree {}
519 /// Returns the span of this tree, delegating to the `span` method of
520 /// the contained token or a delimited stream.
521 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
522 pub fn span(&self) -> Span
{
524 TokenTree
::Group(ref t
) => t
.span(),
525 TokenTree
::Ident(ref t
) => t
.span(),
526 TokenTree
::Punct(ref t
) => t
.span(),
527 TokenTree
::Literal(ref t
) => t
.span(),
531 /// Configures the span for *only this token*.
533 /// Note that if this token is a `Group` then this method will not configure
534 /// the span of each of the internal tokens, this will simply delegate to
535 /// the `set_span` method of each variant.
536 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
537 pub fn set_span(&mut self, span
: Span
) {
539 TokenTree
::Group(ref mut t
) => t
.set_span(span
),
540 TokenTree
::Ident(ref mut t
) => t
.set_span(span
),
541 TokenTree
::Punct(ref mut t
) => t
.set_span(span
),
542 TokenTree
::Literal(ref mut t
) => t
.set_span(span
),
547 /// Prints token tree in a form convenient for debugging.
548 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
549 impl fmt
::Debug
for TokenTree
{
550 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
551 // Each of these has the name in the struct type in the derived debug,
552 // so don't bother with an extra layer of indirection
554 TokenTree
::Group(ref tt
) => tt
.fmt(f
),
555 TokenTree
::Ident(ref tt
) => tt
.fmt(f
),
556 TokenTree
::Punct(ref tt
) => tt
.fmt(f
),
557 TokenTree
::Literal(ref tt
) => tt
.fmt(f
),
562 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
563 impl From
<Group
> for TokenTree
{
564 fn from(g
: Group
) -> TokenTree
{
569 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
570 impl From
<Ident
> for TokenTree
{
571 fn from(g
: Ident
) -> TokenTree
{
576 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
577 impl From
<Punct
> for TokenTree
{
578 fn from(g
: Punct
) -> TokenTree
{
583 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
584 impl From
<Literal
> for TokenTree
{
585 fn from(g
: Literal
) -> TokenTree
{
586 TokenTree
::Literal(g
)
590 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
591 // based on it (the reverse of the usual relationship between the two).
592 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
593 impl ToString
for TokenTree
{
594 fn to_string(&self) -> String
{
596 TokenTree
::Group(ref t
) => t
.to_string(),
597 TokenTree
::Ident(ref t
) => t
.to_string(),
598 TokenTree
::Punct(ref t
) => t
.to_string(),
599 TokenTree
::Literal(ref t
) => t
.to_string(),
604 /// Prints the token tree as a string that is supposed to be losslessly convertible back
605 /// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
606 /// with `Delimiter::None` delimiters and negative numeric literals.
607 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
608 impl fmt
::Display
for TokenTree
{
609 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
610 f
.write_str(&self.to_string())
614 /// A delimited token stream.
616 /// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
618 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
619 pub struct Group(bridge
::client
::Group
);
621 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
622 impl !Send
for Group {}
623 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
624 impl !Sync
for Group {}
626 /// Describes how a sequence of token trees is delimited.
627 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
628 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
631 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
634 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
637 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
640 /// An implicit delimiter, that may, for example, appear around tokens coming from a
641 /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
642 /// `$var * 3` where `$var` is `1 + 2`.
643 /// Implicit delimiters may not survive roundtrip of a token stream through a string.
644 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
649 /// Creates a new `Group` with the given delimiter and token stream.
651 /// This constructor will set the span for this group to
652 /// `Span::call_site()`. To change the span you can use the `set_span`
654 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
655 pub fn new(delimiter
: Delimiter
, stream
: TokenStream
) -> Group
{
656 Group(bridge
::client
::Group
::new(delimiter
, stream
.0))
659 /// Returns the delimiter of this `Group`
660 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
661 pub fn delimiter(&self) -> Delimiter
{
665 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
667 /// Note that the returned token stream does not include the delimiter
669 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
670 pub fn stream(&self) -> TokenStream
{
671 TokenStream(self.0.stream())
674 /// Returns the span for the delimiters of this token stream, spanning the
678 /// pub fn span(&self) -> Span {
681 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
682 pub fn span(&self) -> Span
{
686 /// Returns the span pointing to the opening delimiter of this group.
689 /// pub fn span_open(&self) -> Span {
692 #[unstable(feature = "proc_macro_span", issue = "54725")]
693 pub fn span_open(&self) -> Span
{
694 Span(self.0.span_open())
697 /// Returns the span pointing to the closing delimiter of this group.
700 /// pub fn span_close(&self) -> Span {
703 #[unstable(feature = "proc_macro_span", issue = "54725")]
704 pub fn span_close(&self) -> Span
{
705 Span(self.0.span_close())
708 /// Configures the span for this `Group`'s delimiters, but not its internal
711 /// This method will **not** set the span of all the internal tokens spanned
712 /// by this group, but rather it will only set the span of the delimiter
713 /// tokens at the level of the `Group`.
714 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
715 pub fn set_span(&mut self, span
: Span
) {
716 self.0.set_span(span
.0);
720 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
721 // based on it (the reverse of the usual relationship between the two).
722 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
723 impl ToString
for Group
{
724 fn to_string(&self) -> String
{
725 TokenStream
::from(TokenTree
::from(self.clone())).to_string()
729 /// Prints the group as a string that should be losslessly convertible back
730 /// into the same group (modulo spans), except for possibly `TokenTree::Group`s
731 /// with `Delimiter::None` delimiters.
732 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
733 impl fmt
::Display
for Group
{
734 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
735 f
.write_str(&self.to_string())
739 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
740 impl fmt
::Debug
for Group
{
741 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
742 f
.debug_struct("Group")
743 .field("delimiter", &self.delimiter())
744 .field("stream", &self.stream())
745 .field("span", &self.span())
750 /// An `Punct` is an single punctuation character like `+`, `-` or `#`.
752 /// Multi-character operators like `+=` are represented as two instances of `Punct` with different
753 /// forms of `Spacing` returned.
754 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
756 pub struct Punct(bridge
::client
::Punct
);
758 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
759 impl !Send
for Punct {}
760 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
761 impl !Sync
for Punct {}
763 /// Whether an `Punct` is followed immediately by another `Punct` or
764 /// followed by another token or whitespace.
765 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
766 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
768 /// e.g., `+` is `Alone` in `+ =`, `+ident` or `+()`.
769 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
771 /// e.g., `+` is `Joint` in `+=` or `'#`.
772 /// Additionally, single quote `'` can join with identifiers to form lifetimes `'ident`.
773 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
778 /// Creates a new `Punct` from the given character and spacing.
779 /// The `ch` argument must be a valid punctuation character permitted by the language,
780 /// otherwise the function will panic.
782 /// The returned `Punct` will have the default span of `Span::call_site()`
783 /// which can be further configured with the `set_span` method below.
784 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
785 pub fn new(ch
: char, spacing
: Spacing
) -> Punct
{
786 Punct(bridge
::client
::Punct
::new(ch
, spacing
))
789 /// Returns the value of this punctuation character as `char`.
790 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
791 pub fn as_char(&self) -> char {
795 /// Returns the spacing of this punctuation character, indicating whether it's immediately
796 /// followed by another `Punct` in the token stream, so they can potentially be combined into
797 /// a multi-character operator (`Joint`), or it's followed by some other token or whitespace
798 /// (`Alone`) so the operator has certainly ended.
799 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
800 pub fn spacing(&self) -> Spacing
{
804 /// Returns the span for this punctuation character.
805 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
806 pub fn span(&self) -> Span
{
810 /// Configure the span for this punctuation character.
811 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
812 pub fn set_span(&mut self, span
: Span
) {
813 self.0 = self.0.with_span(span
.0);
817 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
818 // based on it (the reverse of the usual relationship between the two).
819 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
820 impl ToString
for Punct
{
821 fn to_string(&self) -> String
{
822 TokenStream
::from(TokenTree
::from(self.clone())).to_string()
826 /// Prints the punctuation character as a string that should be losslessly convertible
827 /// back into the same character.
828 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
829 impl fmt
::Display
for Punct
{
830 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
831 f
.write_str(&self.to_string())
835 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
836 impl fmt
::Debug
for Punct
{
837 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
838 f
.debug_struct("Punct")
839 .field("ch", &self.as_char())
840 .field("spacing", &self.spacing())
841 .field("span", &self.span())
846 #[stable(feature = "proc_macro_punct_eq", since = "1.49.0")]
847 impl PartialEq
<char> for Punct
{
848 fn eq(&self, rhs
: &char) -> bool
{
849 self.as_char() == *rhs
853 /// An identifier (`ident`).
855 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
856 pub struct Ident(bridge
::client
::Ident
);
859 /// Creates a new `Ident` with the given `string` as well as the specified
861 /// The `string` argument must be a valid identifier permitted by the
862 /// language (including keywords, e.g. `self` or `fn`). Otherwise, the function will panic.
864 /// Note that `span`, currently in rustc, configures the hygiene information
865 /// for this identifier.
867 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
868 /// meaning that identifiers created with this span will be resolved as if they were written
869 /// directly at the location of the macro call, and other code at the macro call site will be
870 /// able to refer to them as well.
872 /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
873 /// meaning that identifiers created with this span will be resolved at the location of the
874 /// macro definition and other code at the macro call site will not be able to refer to them.
876 /// Due to the current importance of hygiene this constructor, unlike other
877 /// tokens, requires a `Span` to be specified at construction.
878 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
879 pub fn new(string
: &str, span
: Span
) -> Ident
{
880 Ident(bridge
::client
::Ident
::new(string
, span
.0, false))
883 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
884 /// The `string` argument be a valid identifier permitted by the language
885 /// (including keywords, e.g. `fn`). Keywords which are usable in path segments
886 /// (e.g. `self`, `super`) are not supported, and will cause a panic.
887 #[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
888 pub fn new_raw(string
: &str, span
: Span
) -> Ident
{
889 Ident(bridge
::client
::Ident
::new(string
, span
.0, true))
892 /// Returns the span of this `Ident`, encompassing the entire string returned
893 /// by [`to_string`](Self::to_string).
894 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
895 pub fn span(&self) -> Span
{
899 /// Configures the span of this `Ident`, possibly changing its hygiene context.
900 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
901 pub fn set_span(&mut self, span
: Span
) {
902 self.0 = self.0.with_span(span
.0);
906 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
907 // based on it (the reverse of the usual relationship between the two).
908 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
909 impl ToString
for Ident
{
910 fn to_string(&self) -> String
{
911 TokenStream
::from(TokenTree
::from(self.clone())).to_string()
915 /// Prints the identifier as a string that should be losslessly convertible
916 /// back into the same identifier.
917 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
918 impl fmt
::Display
for Ident
{
919 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
920 f
.write_str(&self.to_string())
924 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
925 impl fmt
::Debug
for Ident
{
926 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
927 f
.debug_struct("Ident")
928 .field("ident", &self.to_string())
929 .field("span", &self.span())
934 /// A literal string (`"hello"`), byte string (`b"hello"`),
935 /// character (`'a'`), byte character (`b'a'`), an integer or floating point number
936 /// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
937 /// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
939 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
940 pub struct Literal(bridge
::client
::Literal
);
942 macro_rules
! suffixed_int_literals
{
943 ($
($name
:ident
=> $kind
:ident
,)*) => ($
(
944 /// Creates a new suffixed integer literal with the specified value.
946 /// This function will create an integer like `1u32` where the integer
947 /// value specified is the first part of the token and the integral is
948 /// also suffixed at the end.
949 /// Literals created from negative numbers may not survive round-trips through
950 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
952 /// Literals created through this method have the `Span::call_site()`
953 /// span by default, which can be configured with the `set_span` method
955 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
956 pub fn $
name(n
: $kind
) -> Literal
{
957 Literal(bridge
::client
::Literal
::typed_integer(&n
.to_string(), stringify
!($kind
)))
962 macro_rules
! unsuffixed_int_literals
{
963 ($
($name
:ident
=> $kind
:ident
,)*) => ($
(
964 /// Creates a new unsuffixed integer literal with the specified value.
966 /// This function will create an integer like `1` where the integer
967 /// value specified is the first part of the token. No suffix is
968 /// specified on this token, meaning that invocations like
969 /// `Literal::i8_unsuffixed(1)` are equivalent to
970 /// `Literal::u32_unsuffixed(1)`.
971 /// Literals created from negative numbers may not survive rountrips through
972 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
974 /// Literals created through this method have the `Span::call_site()`
975 /// span by default, which can be configured with the `set_span` method
977 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
978 pub fn $
name(n
: $kind
) -> Literal
{
979 Literal(bridge
::client
::Literal
::integer(&n
.to_string()))
985 suffixed_int_literals
! {
990 u128_suffixed
=> u128
,
991 usize_suffixed
=> usize,
996 i128_suffixed
=> i128
,
997 isize_suffixed
=> isize,
1000 unsuffixed_int_literals
! {
1001 u8_unsuffixed
=> u8,
1002 u16_unsuffixed
=> u16,
1003 u32_unsuffixed
=> u32,
1004 u64_unsuffixed
=> u64,
1005 u128_unsuffixed
=> u128
,
1006 usize_unsuffixed
=> usize,
1007 i8_unsuffixed
=> i8,
1008 i16_unsuffixed
=> i16,
1009 i32_unsuffixed
=> i32,
1010 i64_unsuffixed
=> i64,
1011 i128_unsuffixed
=> i128
,
1012 isize_unsuffixed
=> isize,
1015 /// Creates a new unsuffixed floating-point literal.
1017 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1018 /// the float's value is emitted directly into the token but no suffix is
1019 /// used, so it may be inferred to be a `f64` later in the compiler.
1020 /// Literals created from negative numbers may not survive rountrips through
1021 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1025 /// This function requires that the specified float is finite, for
1026 /// example if it is infinity or NaN this function will panic.
1027 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1028 pub fn f32_unsuffixed(n
: f32) -> Literal
{
1030 panic
!("Invalid float literal {}", n
);
1032 Literal(bridge
::client
::Literal
::float(&n
.to_string()))
1035 /// Creates a new suffixed floating-point literal.
1037 /// This constructor will create a literal like `1.0f32` where the value
1038 /// specified is the preceding part of the token and `f32` is the suffix of
1039 /// the token. This token will always be inferred to be an `f32` in the
1041 /// Literals created from negative numbers may not survive rountrips through
1042 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1046 /// This function requires that the specified float is finite, for
1047 /// example if it is infinity or NaN this function will panic.
1048 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1049 pub fn f32_suffixed(n
: f32) -> Literal
{
1051 panic
!("Invalid float literal {}", n
);
1053 Literal(bridge
::client
::Literal
::f32(&n
.to_string()))
1056 /// Creates a new unsuffixed floating-point literal.
1058 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1059 /// the float's value is emitted directly into the token but no suffix is
1060 /// used, so it may be inferred to be a `f64` later in the compiler.
1061 /// Literals created from negative numbers may not survive rountrips through
1062 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1066 /// This function requires that the specified float is finite, for
1067 /// example if it is infinity or NaN this function will panic.
1068 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1069 pub fn f64_unsuffixed(n
: f64) -> Literal
{
1071 panic
!("Invalid float literal {}", n
);
1073 Literal(bridge
::client
::Literal
::float(&n
.to_string()))
1076 /// Creates a new suffixed floating-point literal.
1078 /// This constructor will create a literal like `1.0f64` where the value
1079 /// specified is the preceding part of the token and `f64` is the suffix of
1080 /// the token. This token will always be inferred to be an `f64` in the
1082 /// Literals created from negative numbers may not survive rountrips through
1083 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1087 /// This function requires that the specified float is finite, for
1088 /// example if it is infinity or NaN this function will panic.
1089 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1090 pub fn f64_suffixed(n
: f64) -> Literal
{
1092 panic
!("Invalid float literal {}", n
);
1094 Literal(bridge
::client
::Literal
::f64(&n
.to_string()))
1098 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1099 pub fn string(string
: &str) -> Literal
{
1100 Literal(bridge
::client
::Literal
::string(string
))
1103 /// Character literal.
1104 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1105 pub fn character(ch
: char) -> Literal
{
1106 Literal(bridge
::client
::Literal
::character(ch
))
1109 /// Byte string literal.
1110 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1111 pub fn byte_string(bytes
: &[u8]) -> Literal
{
1112 Literal(bridge
::client
::Literal
::byte_string(bytes
))
1115 /// Returns the span encompassing this literal.
1116 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1117 pub fn span(&self) -> Span
{
1121 /// Configures the span associated for this literal.
1122 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1123 pub fn set_span(&mut self, span
: Span
) {
1124 self.0.set_span(span
.0);
1127 /// Returns a `Span` that is a subset of `self.span()` containing only the
1128 /// source bytes in range `range`. Returns `None` if the would-be trimmed
1129 /// span is outside the bounds of `self`.
1130 // FIXME(SergioBenitez): check that the byte range starts and ends at a
1131 // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1132 // occur elsewhere when the source text is printed.
1133 // FIXME(SergioBenitez): there is no way for the user to know what
1134 // `self.span()` actually maps to, so this method can currently only be
1135 // called blindly. For example, `to_string()` for the character 'c' returns
1136 // "'\u{63}'"; there is no way for the user to know whether the source text
1137 // was 'c' or whether it was '\u{63}'.
1138 #[unstable(feature = "proc_macro_span", issue = "54725")]
1139 pub fn subspan
<R
: RangeBounds
<usize>>(&self, range
: R
) -> Option
<Span
> {
1140 // HACK(eddyb) something akin to `Option::cloned`, but for `Bound<&T>`.
1141 fn cloned_bound
<T
: Clone
>(bound
: Bound
<&T
>) -> Bound
<T
> {
1143 Bound
::Included(x
) => Bound
::Included(x
.clone()),
1144 Bound
::Excluded(x
) => Bound
::Excluded(x
.clone()),
1145 Bound
::Unbounded
=> Bound
::Unbounded
,
1149 self.0.subspan(cloned_bound(range
.start_bound()), cloned_bound(range
.end_bound())).map(Span
)
1153 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
1154 // based on it (the reverse of the usual relationship between the two).
1155 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
1156 impl ToString
for Literal
{
1157 fn to_string(&self) -> String
{
1158 TokenStream
::from(TokenTree
::from(self.clone())).to_string()
1162 /// Prints the literal as a string that should be losslessly convertible
1163 /// back into the same literal (except for possible rounding for floating point literals).
1164 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1165 impl fmt
::Display
for Literal
{
1166 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1167 f
.write_str(&self.to_string())
1171 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1172 impl fmt
::Debug
for Literal
{
1173 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1178 /// Tracked access to environment variables.
1179 #[unstable(feature = "proc_macro_tracked_env", issue = "74690")]
1180 pub mod tracked_env
{
1181 use std
::env
::{self, VarError}
;
1182 use std
::ffi
::OsStr
;
1184 /// Retrieve an environment variable and add it to build dependency info.
1185 /// Build system executing the compiler will know that the variable was accessed during
1186 /// compilation, and will be able to rerun the build when the value of that variable changes.
1187 /// Besides the dependency tracking this function should be equivalent to `env::var` from the
1188 /// standard library, except that the argument must be UTF-8.
1189 #[unstable(feature = "proc_macro_tracked_env", issue = "74690")]
1190 pub fn var
<K
: AsRef
<OsStr
> + AsRef
<str>>(key
: K
) -> Result
<String
, VarError
> {
1191 let key
: &str = key
.as_ref();
1192 let value
= env
::var(key
);
1193 crate::bridge
::client
::FreeFunctions
::track_env_var(key
, value
.as_deref().ok());