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)))
22 #![feature(staged_api)]
23 #![feature(allow_internal_unstable)]
24 #![feature(decl_macro)]
25 #![feature(extern_types)]
26 #![feature(in_band_lifetimes)]
27 #![feature(negative_impls)]
28 #![feature(optin_builtin_traits)]
29 #![feature(restricted_std)]
30 #![feature(rustc_attrs)]
31 #![feature(min_specialization)]
32 #![recursion_limit = "256"]
34 #[unstable(feature = "proc_macro_internals", issue = "27812")]
40 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
41 pub use diagnostic::{Diagnostic, Level, MultiSpan};
43 use std::cmp::Ordering;
44 use std::ops::{Bound, RangeBounds};
45 use std::path::PathBuf;
46 use std::str::FromStr;
47 use std::{error, fmt, iter, mem};
49 /// Determines whether proc_macro has been made accessible to the currently
52 /// The proc_macro crate is only intended for use inside the implementation of
53 /// procedural macros. All the functions in this crate panic if invoked from
54 /// outside of a procedural macro, such as from a build script or unit test or
55 /// ordinary Rust binary.
57 /// With consideration for Rust libraries that are designed to support both
58 /// macro and non-macro use cases, `proc_macro::is_available()` provides a
59 /// non-panicking way to detect whether the infrastructure required to use the
60 /// API of proc_macro is presently available. Returns true if invoked from
61 /// inside of a procedural macro, false if invoked from any other binary.
62 #[unstable(feature = "proc_macro_is_available", issue = "71436")]
63 pub fn is_available() -> bool {
64 bridge::Bridge::is_available()
67 /// The main type provided by this crate, representing an abstract stream of
68 /// tokens, or, more specifically, a sequence of token trees.
69 /// The type provide interfaces for iterating over those token trees and, conversely,
70 /// collecting a number of token trees into one stream.
72 /// This is both the input and output of `#[proc_macro]`, `#[proc_macro_attribute]`
73 /// and `#[proc_macro_derive]` definitions.
74 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
76 pub struct TokenStream(bridge::client::TokenStream);
78 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
79 impl !Send for TokenStream {}
80 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
81 impl !Sync for TokenStream {}
83 /// Error returned from `TokenStream::from_str`.
84 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
90 #[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
91 impl fmt::Display for LexError {
92 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93 f.write_str("cannot parse string into token stream")
97 #[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
98 impl error::Error for LexError {}
100 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
101 impl !Send for LexError {}
102 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
103 impl !Sync for LexError {}
106 /// Returns an empty `TokenStream` containing no token trees.
107 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
108 pub fn new() -> TokenStream {
109 TokenStream(bridge::client::TokenStream::new())
112 /// Checks if this `TokenStream` is empty.
113 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
114 pub fn is_empty(&self) -> bool {
119 /// Attempts to break the string into tokens and parse those tokens into a token stream.
120 /// May fail for a number of reasons, for example, if the string contains unbalanced delimiters
121 /// or characters not existing in the language.
122 /// All tokens in the parsed stream get `Span::call_site()` spans.
124 /// NOTE: some errors may cause panics instead of returning `LexError`. We reserve the right to
125 /// change these errors into `LexError`s later.
126 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
127 impl FromStr for TokenStream {
130 fn from_str(src: &str) -> Result<TokenStream, LexError> {
131 Ok(TokenStream(bridge::client::TokenStream::from_str(src)))
135 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
136 // based on it (the reverse of the usual relationship between the two).
137 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
138 impl ToString for TokenStream {
139 fn to_string(&self) -> String {
144 /// Prints the token stream as a string that is supposed to be losslessly convertible back
145 /// into the same token stream (modulo spans), except for possibly `TokenTree::Group`s
146 /// with `Delimiter::None` delimiters and negative numeric literals.
147 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
148 impl fmt::Display for TokenStream {
149 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150 f.write_str(&self.to_string())
154 /// Prints token in a form convenient for debugging.
155 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
156 impl fmt::Debug for TokenStream {
157 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158 f.write_str("TokenStream ")?;
159 f.debug_list().entries(self.clone()).finish()
163 #[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
164 impl Default for TokenStream {
165 fn default() -> Self {
170 #[unstable(feature = "proc_macro_quote", issue = "54722")]
171 pub use quote::{quote, quote_span};
173 /// Creates a token stream containing a single token tree.
174 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
175 impl From<TokenTree> for TokenStream {
176 fn from(tree: TokenTree) -> TokenStream {
177 TokenStream(bridge::client::TokenStream::from_token_tree(match tree {
178 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
179 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
180 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
181 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
186 /// Collects a number of token trees into a single stream.
187 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
188 impl iter::FromIterator<TokenTree> for TokenStream {
189 fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
190 trees.into_iter().map(TokenStream::from).collect()
194 /// A "flattening" operation on token streams, collects token trees
195 /// from multiple token streams into a single stream.
196 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
197 impl iter::FromIterator<TokenStream> for TokenStream {
198 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
199 let mut builder = bridge::client::TokenStreamBuilder::new();
200 streams.into_iter().for_each(|stream| builder.push(stream.0));
201 TokenStream(builder.build())
205 #[stable(feature = "token_stream_extend", since = "1.30.0")]
206 impl Extend<TokenTree> for TokenStream {
207 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
208 self.extend(trees.into_iter().map(TokenStream::from));
212 #[stable(feature = "token_stream_extend", since = "1.30.0")]
213 impl Extend<TokenStream> for TokenStream {
214 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
215 // FIXME(eddyb) Use an optimized implementation if/when possible.
216 *self = iter::once(mem::replace(self, Self::new())).chain(streams).collect();
220 /// Public implementation details for the `TokenStream` type, such as iterators.
221 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
222 pub mod token_stream {
223 use crate::{bridge, Group, Ident, Literal, Punct, TokenStream, TokenTree};
225 /// An iterator over `TokenStream`'s `TokenTree`s.
226 /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups,
227 /// and returns whole groups as token trees.
229 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
230 pub struct IntoIter(bridge::client::TokenStreamIter);
232 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
233 impl Iterator for IntoIter {
234 type Item = TokenTree;
236 fn next(&mut self) -> Option<TokenTree> {
237 self.0.next().map(|tree| match tree {
238 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
239 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
240 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
241 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
246 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
247 impl IntoIterator for TokenStream {
248 type Item = TokenTree;
249 type IntoIter = IntoIter;
251 fn into_iter(self) -> IntoIter {
252 IntoIter(self.0.into_iter())
257 /// `quote!(..)` accepts arbitrary tokens and expands into a `TokenStream` describing the input.
258 /// For example, `quote!(a + b)` will produce a expression, that, when evaluated, constructs
259 /// the `TokenStream` `[Ident("a"), Punct('+', Alone), Ident("b")]`.
261 /// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
262 /// To quote `$` itself, use `$$`.
263 #[unstable(feature = "proc_macro_quote", issue = "54722")]
264 #[allow_internal_unstable(proc_macro_def_site)]
265 #[rustc_builtin_macro]
266 pub macro quote($($t:tt)*) {
267 /* compiler built-in */
270 #[unstable(feature = "proc_macro_internals", issue = "27812")]
274 /// A region of source code, along with macro expansion information.
275 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
276 #[derive(Copy, Clone)]
277 pub struct Span(bridge::client::Span);
279 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
280 impl !Send for Span {}
281 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
282 impl !Sync for Span {}
284 macro_rules! diagnostic_method {
285 ($name:ident, $level:expr) => {
286 /// Creates a new `Diagnostic` with the given `message` at the span
288 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
289 pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
290 Diagnostic::spanned(self, $level, message)
296 /// A span that resolves at the macro definition site.
297 #[unstable(feature = "proc_macro_def_site", issue = "54724")]
298 pub fn def_site() -> Span {
299 Span(bridge::client::Span::def_site())
302 /// The span of the invocation of the current procedural macro.
303 /// Identifiers created with this span will be resolved as if they were written
304 /// directly at the macro call location (call-site hygiene) and other code
305 /// at the macro call site will be able to refer to them as well.
306 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
307 pub fn call_site() -> Span {
308 Span(bridge::client::Span::call_site())
311 /// A span that represents `macro_rules` hygiene, and sometimes resolves at the macro
312 /// definition site (local variables, labels, `$crate`) and sometimes at the macro
313 /// call site (everything else).
314 /// The span location is taken from the call-site.
315 #[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
316 pub fn mixed_site() -> Span {
317 Span(bridge::client::Span::mixed_site())
320 /// The original source file into which this span points.
321 #[unstable(feature = "proc_macro_span", issue = "54725")]
322 pub fn source_file(&self) -> SourceFile {
323 SourceFile(self.0.source_file())
326 /// The `Span` for the tokens in the previous macro expansion from which
327 /// `self` was generated from, if any.
328 #[unstable(feature = "proc_macro_span", issue = "54725")]
329 pub fn parent(&self) -> Option<Span> {
330 self.0.parent().map(Span)
333 /// The span for the origin source code that `self` was generated from. If
334 /// this `Span` wasn't generated from other macro expansions then the return
335 /// value is the same as `*self`.
336 #[unstable(feature = "proc_macro_span", issue = "54725")]
337 pub fn source(&self) -> Span {
338 Span(self.0.source())
341 /// Gets the starting line/column in the source file for this span.
342 #[unstable(feature = "proc_macro_span", issue = "54725")]
343 pub fn start(&self) -> LineColumn {
347 /// Gets the ending line/column in the source file for this span.
348 #[unstable(feature = "proc_macro_span", issue = "54725")]
349 pub fn end(&self) -> LineColumn {
353 /// Creates a new span encompassing `self` and `other`.
355 /// Returns `None` if `self` and `other` are from different files.
356 #[unstable(feature = "proc_macro_span", issue = "54725")]
357 pub fn join(&self, other: Span) -> Option<Span> {
358 self.0.join(other.0).map(Span)
361 /// Creates a new span with the same line/column information as `self` but
362 /// that resolves symbols as though it were at `other`.
363 #[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
364 pub fn resolved_at(&self, other: Span) -> Span {
365 Span(self.0.resolved_at(other.0))
368 /// Creates a new span with the same name resolution behavior as `self` but
369 /// with the line/column information of `other`.
370 #[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
371 pub fn located_at(&self, other: Span) -> Span {
372 other.resolved_at(*self)
375 /// Compares to spans to see if they're equal.
376 #[unstable(feature = "proc_macro_span", issue = "54725")]
377 pub fn eq(&self, other: &Span) -> bool {
381 /// Returns the source text behind a span. This preserves the original source
382 /// code, including spaces and comments. It only returns a result if the span
383 /// corresponds to real source code.
385 /// Note: The observable result of a macro should only rely on the tokens and
386 /// not on this source text. The result of this function is a best effort to
387 /// be used for diagnostics only.
388 #[unstable(feature = "proc_macro_span", issue = "54725")]
389 pub fn source_text(&self) -> Option<String> {
393 diagnostic_method!(error, Level::Error);
394 diagnostic_method!(warning, Level::Warning);
395 diagnostic_method!(note, Level::Note);
396 diagnostic_method!(help, Level::Help);
399 /// Prints a span in a form convenient for debugging.
400 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
401 impl fmt::Debug for Span {
402 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
407 /// A line-column pair representing the start or end of a `Span`.
408 #[unstable(feature = "proc_macro_span", issue = "54725")]
409 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
410 pub struct LineColumn {
411 /// The 1-indexed line in the source file on which the span starts or ends (inclusive).
412 #[unstable(feature = "proc_macro_span", issue = "54725")]
414 /// The 0-indexed column (in UTF-8 characters) in the source file on which
415 /// the span starts or ends (inclusive).
416 #[unstable(feature = "proc_macro_span", issue = "54725")]
420 #[unstable(feature = "proc_macro_span", issue = "54725")]
421 impl !Send for LineColumn {}
422 #[unstable(feature = "proc_macro_span", issue = "54725")]
423 impl !Sync for LineColumn {}
425 #[unstable(feature = "proc_macro_span", issue = "54725")]
426 impl Ord for LineColumn {
427 fn cmp(&self, other: &Self) -> Ordering {
428 self.line.cmp(&other.line).then(self.column.cmp(&other.column))
432 #[unstable(feature = "proc_macro_span", issue = "54725")]
433 impl PartialOrd for LineColumn {
434 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
435 Some(self.cmp(other))
439 /// The source file of a given `Span`.
440 #[unstable(feature = "proc_macro_span", issue = "54725")]
442 pub struct SourceFile(bridge::client::SourceFile);
445 /// Gets the path to this source file.
448 /// If the code span associated with this `SourceFile` was generated by an external macro, this
449 /// macro, this may not be an actual path on the filesystem. Use [`is_real`] to check.
451 /// Also note that even if `is_real` returns `true`, if `--remap-path-prefix` was passed on
452 /// the command line, the path as given may not actually be valid.
454 /// [`is_real`]: Self::is_real
455 #[unstable(feature = "proc_macro_span", issue = "54725")]
456 pub fn path(&self) -> PathBuf {
457 PathBuf::from(self.0.path())
460 /// Returns `true` if this source file is a real source file, and not generated by an external
461 /// macro's expansion.
462 #[unstable(feature = "proc_macro_span", issue = "54725")]
463 pub fn is_real(&self) -> bool {
464 // This is a hack until intercrate spans are implemented and we can have real source files
465 // for spans generated in external macros.
466 // https://github.com/rust-lang/rust/pull/43604#issuecomment-333334368
471 #[unstable(feature = "proc_macro_span", issue = "54725")]
472 impl fmt::Debug for SourceFile {
473 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
474 f.debug_struct("SourceFile")
475 .field("path", &self.path())
476 .field("is_real", &self.is_real())
481 #[unstable(feature = "proc_macro_span", issue = "54725")]
482 impl PartialEq for SourceFile {
483 fn eq(&self, other: &Self) -> bool {
488 #[unstable(feature = "proc_macro_span", issue = "54725")]
489 impl Eq for SourceFile {}
491 /// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
492 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
495 /// A token stream surrounded by bracket delimiters.
496 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
497 Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
499 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
500 Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
501 /// A single punctuation character (`+`, `,`, `$`, etc.).
502 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
503 Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
504 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
505 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
506 Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
509 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
510 impl !Send for TokenTree {}
511 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
512 impl !Sync for TokenTree {}
515 /// Returns the span of this tree, delegating to the `span` method of
516 /// the contained token or a delimited stream.
517 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
518 pub fn span(&self) -> Span {
520 TokenTree::Group(ref t) => t.span(),
521 TokenTree::Ident(ref t) => t.span(),
522 TokenTree::Punct(ref t) => t.span(),
523 TokenTree::Literal(ref t) => t.span(),
527 /// Configures the span for *only this token*.
529 /// Note that if this token is a `Group` then this method will not configure
530 /// the span of each of the internal tokens, this will simply delegate to
531 /// the `set_span` method of each variant.
532 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
533 pub fn set_span(&mut self, span: Span) {
535 TokenTree::Group(ref mut t) => t.set_span(span),
536 TokenTree::Ident(ref mut t) => t.set_span(span),
537 TokenTree::Punct(ref mut t) => t.set_span(span),
538 TokenTree::Literal(ref mut t) => t.set_span(span),
543 /// Prints token tree in a form convenient for debugging.
544 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
545 impl fmt::Debug for TokenTree {
546 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
547 // Each of these has the name in the struct type in the derived debug,
548 // so don't bother with an extra layer of indirection
550 TokenTree::Group(ref tt) => tt.fmt(f),
551 TokenTree::Ident(ref tt) => tt.fmt(f),
552 TokenTree::Punct(ref tt) => tt.fmt(f),
553 TokenTree::Literal(ref tt) => tt.fmt(f),
558 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
559 impl From<Group> for TokenTree {
560 fn from(g: Group) -> TokenTree {
565 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
566 impl From<Ident> for TokenTree {
567 fn from(g: Ident) -> TokenTree {
572 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
573 impl From<Punct> for TokenTree {
574 fn from(g: Punct) -> TokenTree {
579 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
580 impl From<Literal> for TokenTree {
581 fn from(g: Literal) -> TokenTree {
582 TokenTree::Literal(g)
586 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
587 // based on it (the reverse of the usual relationship between the two).
588 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
589 impl ToString for TokenTree {
590 fn to_string(&self) -> String {
592 TokenTree::Group(ref t) => t.to_string(),
593 TokenTree::Ident(ref t) => t.to_string(),
594 TokenTree::Punct(ref t) => t.to_string(),
595 TokenTree::Literal(ref t) => t.to_string(),
600 /// Prints the token tree as a string that is supposed to be losslessly convertible back
601 /// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
602 /// with `Delimiter::None` delimiters and negative numeric literals.
603 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
604 impl fmt::Display for TokenTree {
605 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
606 f.write_str(&self.to_string())
610 /// A delimited token stream.
612 /// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
614 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
615 pub struct Group(bridge::client::Group);
617 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
618 impl !Send for Group {}
619 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
620 impl !Sync for Group {}
622 /// Describes how a sequence of token trees is delimited.
623 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
624 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
627 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
630 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
633 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
636 /// An implicit delimiter, that may, for example, appear around tokens coming from a
637 /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
638 /// `$var * 3` where `$var` is `1 + 2`.
639 /// Implicit delimiters may not survive roundtrip of a token stream through a string.
640 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
645 /// Creates a new `Group` with the given delimiter and token stream.
647 /// This constructor will set the span for this group to
648 /// `Span::call_site()`. To change the span you can use the `set_span`
650 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
651 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
652 Group(bridge::client::Group::new(delimiter, stream.0))
655 /// Returns the delimiter of this `Group`
656 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
657 pub fn delimiter(&self) -> Delimiter {
661 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
663 /// Note that the returned token stream does not include the delimiter
665 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
666 pub fn stream(&self) -> TokenStream {
667 TokenStream(self.0.stream())
670 /// Returns the span for the delimiters of this token stream, spanning the
674 /// pub fn span(&self) -> Span {
677 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
678 pub fn span(&self) -> Span {
682 /// Returns the span pointing to the opening delimiter of this group.
685 /// pub fn span_open(&self) -> Span {
688 #[unstable(feature = "proc_macro_span", issue = "54725")]
689 pub fn span_open(&self) -> Span {
690 Span(self.0.span_open())
693 /// Returns the span pointing to the closing delimiter of this group.
696 /// pub fn span_close(&self) -> Span {
699 #[unstable(feature = "proc_macro_span", issue = "54725")]
700 pub fn span_close(&self) -> Span {
701 Span(self.0.span_close())
704 /// Configures the span for this `Group`'s delimiters, but not its internal
707 /// This method will **not** set the span of all the internal tokens spanned
708 /// by this group, but rather it will only set the span of the delimiter
709 /// tokens at the level of the `Group`.
710 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
711 pub fn set_span(&mut self, span: Span) {
712 self.0.set_span(span.0);
716 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
717 // based on it (the reverse of the usual relationship between the two).
718 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
719 impl ToString for Group {
720 fn to_string(&self) -> String {
721 TokenStream::from(TokenTree::from(self.clone())).to_string()
725 /// Prints the group as a string that should be losslessly convertible back
726 /// into the same group (modulo spans), except for possibly `TokenTree::Group`s
727 /// with `Delimiter::None` delimiters.
728 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
729 impl fmt::Display for Group {
730 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
731 f.write_str(&self.to_string())
735 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
736 impl fmt::Debug for Group {
737 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
738 f.debug_struct("Group")
739 .field("delimiter", &self.delimiter())
740 .field("stream", &self.stream())
741 .field("span", &self.span())
746 /// An `Punct` is an single punctuation character like `+`, `-` or `#`.
748 /// Multi-character operators like `+=` are represented as two instances of `Punct` with different
749 /// forms of `Spacing` returned.
750 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
752 pub struct Punct(bridge::client::Punct);
754 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
755 impl !Send for Punct {}
756 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
757 impl !Sync for Punct {}
759 /// Whether an `Punct` is followed immediately by another `Punct` or
760 /// followed by another token or whitespace.
761 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
762 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
764 /// e.g., `+` is `Alone` in `+ =`, `+ident` or `+()`.
765 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
767 /// e.g., `+` is `Joint` in `+=` or `'#`.
768 /// Additionally, single quote `'` can join with identifiers to form lifetimes `'ident`.
769 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
774 /// Creates a new `Punct` from the given character and spacing.
775 /// The `ch` argument must be a valid punctuation character permitted by the language,
776 /// otherwise the function will panic.
778 /// The returned `Punct` will have the default span of `Span::call_site()`
779 /// which can be further configured with the `set_span` method below.
780 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
781 pub fn new(ch: char, spacing: Spacing) -> Punct {
782 Punct(bridge::client::Punct::new(ch, spacing))
785 /// Returns the value of this punctuation character as `char`.
786 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
787 pub fn as_char(&self) -> char {
791 /// Returns the spacing of this punctuation character, indicating whether it's immediately
792 /// followed by another `Punct` in the token stream, so they can potentially be combined into
793 /// a multi-character operator (`Joint`), or it's followed by some other token or whitespace
794 /// (`Alone`) so the operator has certainly ended.
795 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
796 pub fn spacing(&self) -> Spacing {
800 /// Returns the span for this punctuation character.
801 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
802 pub fn span(&self) -> Span {
806 /// Configure the span for this punctuation character.
807 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
808 pub fn set_span(&mut self, span: Span) {
809 self.0 = self.0.with_span(span.0);
813 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
814 // based on it (the reverse of the usual relationship between the two).
815 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
816 impl ToString for Punct {
817 fn to_string(&self) -> String {
818 TokenStream::from(TokenTree::from(self.clone())).to_string()
822 /// Prints the punctuation character as a string that should be losslessly convertible
823 /// back into the same character.
824 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
825 impl fmt::Display for Punct {
826 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
827 f.write_str(&self.to_string())
831 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
832 impl fmt::Debug for Punct {
833 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
834 f.debug_struct("Punct")
835 .field("ch", &self.as_char())
836 .field("spacing", &self.spacing())
837 .field("span", &self.span())
842 /// An identifier (`ident`).
844 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
845 pub struct Ident(bridge::client::Ident);
848 /// Creates a new `Ident` with the given `string` as well as the specified
850 /// The `string` argument must be a valid identifier permitted by the
851 /// language (including keywords, e.g. `self` or `fn`). Otherwise, the function will panic.
853 /// Note that `span`, currently in rustc, configures the hygiene information
854 /// for this identifier.
856 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
857 /// meaning that identifiers created with this span will be resolved as if they were written
858 /// directly at the location of the macro call, and other code at the macro call site will be
859 /// able to refer to them as well.
861 /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
862 /// meaning that identifiers created with this span will be resolved at the location of the
863 /// macro definition and other code at the macro call site will not be able to refer to them.
865 /// Due to the current importance of hygiene this constructor, unlike other
866 /// tokens, requires a `Span` to be specified at construction.
867 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
868 pub fn new(string: &str, span: Span) -> Ident {
869 Ident(bridge::client::Ident::new(string, span.0, false))
872 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
873 /// The `string` argument be a valid identifier permitted by the language
874 /// (including keywords, e.g. `fn`). Keywords which are usable in path segments
875 /// (e.g. `self`, `super`) are not supported, and will cause a panic.
876 #[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
877 pub fn new_raw(string: &str, span: Span) -> Ident {
878 Ident(bridge::client::Ident::new(string, span.0, true))
881 /// Returns the span of this `Ident`, encompassing the entire string returned
883 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
884 pub fn span(&self) -> Span {
888 /// Configures the span of this `Ident`, possibly changing its hygiene context.
889 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
890 pub fn set_span(&mut self, span: Span) {
891 self.0 = self.0.with_span(span.0);
895 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
896 // based on it (the reverse of the usual relationship between the two).
897 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
898 impl ToString for Ident {
899 fn to_string(&self) -> String {
900 TokenStream::from(TokenTree::from(self.clone())).to_string()
904 /// Prints the identifier as a string that should be losslessly convertible
905 /// back into the same identifier.
906 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
907 impl fmt::Display for Ident {
908 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
909 f.write_str(&self.to_string())
913 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
914 impl fmt::Debug for Ident {
915 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
916 f.debug_struct("Ident")
917 .field("ident", &self.to_string())
918 .field("span", &self.span())
923 /// A literal string (`"hello"`), byte string (`b"hello"`),
924 /// character (`'a'`), byte character (`b'a'`), an integer or floating point number
925 /// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
926 /// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
928 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
929 pub struct Literal(bridge::client::Literal);
931 macro_rules! suffixed_int_literals {
932 ($($name:ident => $kind:ident,)*) => ($(
933 /// Creates a new suffixed integer literal with the specified value.
935 /// This function will create an integer like `1u32` where the integer
936 /// value specified is the first part of the token and the integral is
937 /// also suffixed at the end.
938 /// Literals created from negative numbers may not survive round-trips through
939 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
941 /// Literals created through this method have the `Span::call_site()`
942 /// span by default, which can be configured with the `set_span` method
944 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
945 pub fn $name(n: $kind) -> Literal {
946 Literal(bridge::client::Literal::typed_integer(&n.to_string(), stringify!($kind)))
951 macro_rules! unsuffixed_int_literals {
952 ($($name:ident => $kind:ident,)*) => ($(
953 /// Creates a new unsuffixed integer literal with the specified value.
955 /// This function will create an integer like `1` where the integer
956 /// value specified is the first part of the token. No suffix is
957 /// specified on this token, meaning that invocations like
958 /// `Literal::i8_unsuffixed(1)` are equivalent to
959 /// `Literal::u32_unsuffixed(1)`.
960 /// Literals created from negative numbers may not survive rountrips through
961 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
963 /// Literals created through this method have the `Span::call_site()`
964 /// span by default, which can be configured with the `set_span` method
966 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
967 pub fn $name(n: $kind) -> Literal {
968 Literal(bridge::client::Literal::integer(&n.to_string()))
974 suffixed_int_literals! {
979 u128_suffixed => u128,
980 usize_suffixed => usize,
985 i128_suffixed => i128,
986 isize_suffixed => isize,
989 unsuffixed_int_literals! {
991 u16_unsuffixed => u16,
992 u32_unsuffixed => u32,
993 u64_unsuffixed => u64,
994 u128_unsuffixed => u128,
995 usize_unsuffixed => usize,
997 i16_unsuffixed => i16,
998 i32_unsuffixed => i32,
999 i64_unsuffixed => i64,
1000 i128_unsuffixed => i128,
1001 isize_unsuffixed => isize,
1004 /// Creates a new unsuffixed floating-point literal.
1006 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1007 /// the float's value is emitted directly into the token but no suffix is
1008 /// used, so it may be inferred to be a `f64` later in the compiler.
1009 /// Literals created from negative numbers may not survive rountrips through
1010 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1014 /// This function requires that the specified float is finite, for
1015 /// example if it is infinity or NaN this function will panic.
1016 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1017 pub fn f32_unsuffixed(n: f32) -> Literal {
1019 panic!("Invalid float literal {}", n);
1021 Literal(bridge::client::Literal::float(&n.to_string()))
1024 /// Creates a new suffixed floating-point literal.
1026 /// This constructor will create a literal like `1.0f32` where the value
1027 /// specified is the preceding part of the token and `f32` is the suffix of
1028 /// the token. This token will always be inferred to be an `f32` in the
1030 /// Literals created from negative numbers may not survive rountrips through
1031 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1035 /// This function requires that the specified float is finite, for
1036 /// example if it is infinity or NaN this function will panic.
1037 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1038 pub fn f32_suffixed(n: f32) -> Literal {
1040 panic!("Invalid float literal {}", n);
1042 Literal(bridge::client::Literal::f32(&n.to_string()))
1045 /// Creates a new unsuffixed floating-point literal.
1047 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1048 /// the float's value is emitted directly into the token but no suffix is
1049 /// used, so it may be inferred to be a `f64` later in the compiler.
1050 /// Literals created from negative numbers may not survive rountrips through
1051 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1055 /// This function requires that the specified float is finite, for
1056 /// example if it is infinity or NaN this function will panic.
1057 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1058 pub fn f64_unsuffixed(n: f64) -> Literal {
1060 panic!("Invalid float literal {}", n);
1062 Literal(bridge::client::Literal::float(&n.to_string()))
1065 /// Creates a new suffixed floating-point literal.
1067 /// This constructor will create a literal like `1.0f64` where the value
1068 /// specified is the preceding part of the token and `f64` is the suffix of
1069 /// the token. This token will always be inferred to be an `f64` in the
1071 /// Literals created from negative numbers may not survive rountrips through
1072 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1076 /// This function requires that the specified float is finite, for
1077 /// example if it is infinity or NaN this function will panic.
1078 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1079 pub fn f64_suffixed(n: f64) -> Literal {
1081 panic!("Invalid float literal {}", n);
1083 Literal(bridge::client::Literal::f64(&n.to_string()))
1087 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1088 pub fn string(string: &str) -> Literal {
1089 Literal(bridge::client::Literal::string(string))
1092 /// Character literal.
1093 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1094 pub fn character(ch: char) -> Literal {
1095 Literal(bridge::client::Literal::character(ch))
1098 /// Byte string literal.
1099 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1100 pub fn byte_string(bytes: &[u8]) -> Literal {
1101 Literal(bridge::client::Literal::byte_string(bytes))
1104 /// Returns the span encompassing this literal.
1105 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1106 pub fn span(&self) -> Span {
1110 /// Configures the span associated for this literal.
1111 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1112 pub fn set_span(&mut self, span: Span) {
1113 self.0.set_span(span.0);
1116 /// Returns a `Span` that is a subset of `self.span()` containing only the
1117 /// source bytes in range `range`. Returns `None` if the would-be trimmed
1118 /// span is outside the bounds of `self`.
1119 // FIXME(SergioBenitez): check that the byte range starts and ends at a
1120 // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1121 // occur elsewhere when the source text is printed.
1122 // FIXME(SergioBenitez): there is no way for the user to know what
1123 // `self.span()` actually maps to, so this method can currently only be
1124 // called blindly. For example, `to_string()` for the character 'c' returns
1125 // "'\u{63}'"; there is no way for the user to know whether the source text
1126 // was 'c' or whether it was '\u{63}'.
1127 #[unstable(feature = "proc_macro_span", issue = "54725")]
1128 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1129 // HACK(eddyb) something akin to `Option::cloned`, but for `Bound<&T>`.
1130 fn cloned_bound<T: Clone>(bound: Bound<&T>) -> Bound<T> {
1132 Bound::Included(x) => Bound::Included(x.clone()),
1133 Bound::Excluded(x) => Bound::Excluded(x.clone()),
1134 Bound::Unbounded => Bound::Unbounded,
1138 self.0.subspan(cloned_bound(range.start_bound()), cloned_bound(range.end_bound())).map(Span)
1142 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
1143 // based on it (the reverse of the usual relationship between the two).
1144 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
1145 impl ToString for Literal {
1146 fn to_string(&self) -> String {
1147 TokenStream::from(TokenTree::from(self.clone())).to_string()
1151 /// Prints the literal as a string that should be losslessly convertible
1152 /// back into the same literal (except for possible rounding for floating point literals).
1153 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1154 impl fmt::Display for Literal {
1155 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1156 f.write_str(&self.to_string())
1160 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1161 impl fmt::Debug for Literal {
1162 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1167 /// Tracked access to environment variables.
1168 #[unstable(feature = "proc_macro_tracked_env", issue = "74690")]
1169 pub mod tracked_env {
1170 use std::env::{self, VarError};
1171 use std::ffi::OsStr;
1173 /// Retrieve an environment variable and add it to build dependency info.
1174 /// Build system executing the compiler will know that the variable was accessed during
1175 /// compilation, and will be able to rerun the build when the value of that variable changes.
1176 /// Besides the dependency tracking this function should be equivalent to `env::var` from the
1177 /// standard library, except that the argument must be UTF-8.
1178 #[unstable(feature = "proc_macro_tracked_env", issue = "74690")]
1179 pub fn var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1180 let key: &str = key.as_ref();
1181 let value = env::var(key);
1182 crate::bridge::client::FreeFunctions::track_env_var(key, value.as_deref().ok());