]> git.lizzy.rs Git - rust.git/blob - src/libproc_macro/lib.rs
Rollup merge of #71459 - divergentdave:pointer-offset-0x, r=RalfJung
[rust.git] / src / libproc_macro / lib.rs
1 //! A support library for macro authors when defining new macros.
2 //!
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]`.
7 //!
8 //! See [the book] for more.
9 //!
10 //! [the book]: ../book/ch19-06-macros.html#procedural-macros-for-generating-code-from-attributes
11
12 #![stable(feature = "proc_macro_lib", since = "1.15.0")]
13 #![deny(missing_docs)]
14 #![doc(
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)))
20 )]
21 #![feature(nll)]
22 #![feature(staged_api)]
23 #![feature(allow_internal_unstable)]
24 #![feature(decl_macro)]
25 #![feature(extern_types)]
26 #![feature(in_band_lifetimes)]
27 #![cfg_attr(not(bootstrap), feature(negative_impls))]
28 #![feature(optin_builtin_traits)]
29 #![feature(rustc_attrs)]
30 #![cfg_attr(bootstrap, feature(specialization))]
31 #![cfg_attr(not(bootstrap), feature(min_specialization))]
32 #![recursion_limit = "256"]
33
34 #[unstable(feature = "proc_macro_internals", issue = "27812")]
35 #[doc(hidden)]
36 pub mod bridge;
37
38 mod diagnostic;
39
40 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
41 pub use diagnostic::{Diagnostic, Level, MultiSpan};
42
43 use std::ops::{Bound, RangeBounds};
44 use std::path::PathBuf;
45 use std::str::FromStr;
46 use std::{error, fmt, iter, mem};
47
48 /// Determines whether proc_macro has been made accessible to the currently
49 /// running program.
50 ///
51 /// The proc_macro crate is only intended for use inside the implementation of
52 /// procedural macros. All the functions in this crate panic if invoked from
53 /// outside of a procedural macro, such as from a build script or unit test or
54 /// ordinary Rust binary.
55 ///
56 /// With consideration for Rust libraries that are designed to support both
57 /// macro and non-macro use cases, `proc_macro::is_available()` provides a
58 /// non-panicking way to detect whether the infrastructure required to use the
59 /// API of proc_macro is presently available. Returns true if invoked from
60 /// inside of a procedural macro, false if invoked from any other binary.
61 #[unstable(feature = "proc_macro_is_available", issue = "71436")]
62 pub fn is_available() -> bool {
63     bridge::Bridge::is_available()
64 }
65
66 /// The main type provided by this crate, representing an abstract stream of
67 /// tokens, or, more specifically, a sequence of token trees.
68 /// The type provide interfaces for iterating over those token trees and, conversely,
69 /// collecting a number of token trees into one stream.
70 ///
71 /// This is both the input and output of `#[proc_macro]`, `#[proc_macro_attribute]`
72 /// and `#[proc_macro_derive]` definitions.
73 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
74 #[derive(Clone)]
75 pub struct TokenStream(bridge::client::TokenStream);
76
77 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
78 impl !Send for TokenStream {}
79 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
80 impl !Sync for TokenStream {}
81
82 /// Error returned from `TokenStream::from_str`.
83 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
84 #[derive(Debug)]
85 pub struct LexError {
86     _inner: (),
87 }
88
89 #[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
90 impl fmt::Display for LexError {
91     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92         f.write_str("cannot parse string into token stream")
93     }
94 }
95
96 #[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
97 impl error::Error for LexError {}
98
99 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
100 impl !Send for LexError {}
101 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
102 impl !Sync for LexError {}
103
104 impl TokenStream {
105     /// Returns an empty `TokenStream` containing no token trees.
106     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
107     pub fn new() -> TokenStream {
108         TokenStream(bridge::client::TokenStream::new())
109     }
110
111     /// Checks if this `TokenStream` is empty.
112     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
113     pub fn is_empty(&self) -> bool {
114         self.0.is_empty()
115     }
116 }
117
118 /// Attempts to break the string into tokens and parse those tokens into a token stream.
119 /// May fail for a number of reasons, for example, if the string contains unbalanced delimiters
120 /// or characters not existing in the language.
121 /// All tokens in the parsed stream get `Span::call_site()` spans.
122 ///
123 /// NOTE: some errors may cause panics instead of returning `LexError`. We reserve the right to
124 /// change these errors into `LexError`s later.
125 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
126 impl FromStr for TokenStream {
127     type Err = LexError;
128
129     fn from_str(src: &str) -> Result<TokenStream, LexError> {
130         Ok(TokenStream(bridge::client::TokenStream::from_str(src)))
131     }
132 }
133
134 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
135 // based on it (the reverse of the usual relationship between the two).
136 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
137 impl ToString for TokenStream {
138     fn to_string(&self) -> String {
139         self.0.to_string()
140     }
141 }
142
143 /// Prints the token stream as a string that is supposed to be losslessly convertible back
144 /// into the same token stream (modulo spans), except for possibly `TokenTree::Group`s
145 /// with `Delimiter::None` delimiters and negative numeric literals.
146 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
147 impl fmt::Display for TokenStream {
148     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149         f.write_str(&self.to_string())
150     }
151 }
152
153 /// Prints token in a form convenient for debugging.
154 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
155 impl fmt::Debug for TokenStream {
156     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157         f.write_str("TokenStream ")?;
158         f.debug_list().entries(self.clone()).finish()
159     }
160 }
161
162 #[unstable(feature = "proc_macro_quote", issue = "54722")]
163 pub use quote::{quote, quote_span};
164
165 /// Creates a token stream containing a single token tree.
166 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
167 impl From<TokenTree> for TokenStream {
168     fn from(tree: TokenTree) -> TokenStream {
169         TokenStream(bridge::client::TokenStream::from_token_tree(match tree {
170             TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
171             TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
172             TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
173             TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
174         }))
175     }
176 }
177
178 /// Collects a number of token trees into a single stream.
179 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
180 impl iter::FromIterator<TokenTree> for TokenStream {
181     fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
182         trees.into_iter().map(TokenStream::from).collect()
183     }
184 }
185
186 /// A "flattening" operation on token streams, collects token trees
187 /// from multiple token streams into a single stream.
188 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
189 impl iter::FromIterator<TokenStream> for TokenStream {
190     fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
191         let mut builder = bridge::client::TokenStreamBuilder::new();
192         streams.into_iter().for_each(|stream| builder.push(stream.0));
193         TokenStream(builder.build())
194     }
195 }
196
197 #[stable(feature = "token_stream_extend", since = "1.30.0")]
198 impl Extend<TokenTree> for TokenStream {
199     fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
200         self.extend(trees.into_iter().map(TokenStream::from));
201     }
202 }
203
204 #[stable(feature = "token_stream_extend", since = "1.30.0")]
205 impl Extend<TokenStream> for TokenStream {
206     fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
207         // FIXME(eddyb) Use an optimized implementation if/when possible.
208         *self = iter::once(mem::replace(self, Self::new())).chain(streams).collect();
209     }
210 }
211
212 /// Public implementation details for the `TokenStream` type, such as iterators.
213 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
214 pub mod token_stream {
215     use crate::{bridge, Group, Ident, Literal, Punct, TokenStream, TokenTree};
216
217     /// An iterator over `TokenStream`'s `TokenTree`s.
218     /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups,
219     /// and returns whole groups as token trees.
220     #[derive(Clone)]
221     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
222     pub struct IntoIter(bridge::client::TokenStreamIter);
223
224     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
225     impl Iterator for IntoIter {
226         type Item = TokenTree;
227
228         fn next(&mut self) -> Option<TokenTree> {
229             self.0.next().map(|tree| match tree {
230                 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
231                 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
232                 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
233                 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
234             })
235         }
236     }
237
238     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
239     impl IntoIterator for TokenStream {
240         type Item = TokenTree;
241         type IntoIter = IntoIter;
242
243         fn into_iter(self) -> IntoIter {
244             IntoIter(self.0.into_iter())
245         }
246     }
247 }
248
249 /// `quote!(..)` accepts arbitrary tokens and expands into a `TokenStream` describing the input.
250 /// For example, `quote!(a + b)` will produce a expression, that, when evaluated, constructs
251 /// the `TokenStream` `[Ident("a"), Punct('+', Alone), Ident("b")]`.
252 ///
253 /// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
254 /// To quote `$` itself, use `$$`.
255 #[unstable(feature = "proc_macro_quote", issue = "54722")]
256 #[allow_internal_unstable(proc_macro_def_site)]
257 #[rustc_builtin_macro]
258 pub macro quote($($t:tt)*) {
259     /* compiler built-in */
260 }
261
262 #[unstable(feature = "proc_macro_internals", issue = "27812")]
263 #[doc(hidden)]
264 mod quote;
265
266 /// A region of source code, along with macro expansion information.
267 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
268 #[derive(Copy, Clone)]
269 pub struct Span(bridge::client::Span);
270
271 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
272 impl !Send for Span {}
273 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
274 impl !Sync for Span {}
275
276 macro_rules! diagnostic_method {
277     ($name:ident, $level:expr) => (
278         /// Creates a new `Diagnostic` with the given `message` at the span
279         /// `self`.
280         #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
281         pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
282             Diagnostic::spanned(self, $level, message)
283         }
284     )
285 }
286
287 impl Span {
288     /// A span that resolves at the macro definition site.
289     #[unstable(feature = "proc_macro_def_site", issue = "54724")]
290     pub fn def_site() -> Span {
291         Span(bridge::client::Span::def_site())
292     }
293
294     /// The span of the invocation of the current procedural macro.
295     /// Identifiers created with this span will be resolved as if they were written
296     /// directly at the macro call location (call-site hygiene) and other code
297     /// at the macro call site will be able to refer to them as well.
298     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
299     pub fn call_site() -> Span {
300         Span(bridge::client::Span::call_site())
301     }
302
303     /// A span that represents `macro_rules` hygiene, and sometimes resolves at the macro
304     /// definition site (local variables, labels, `$crate`) and sometimes at the macro
305     /// call site (everything else).
306     /// The span location is taken from the call-site.
307     #[unstable(feature = "proc_macro_mixed_site", issue = "65049")]
308     pub fn mixed_site() -> Span {
309         Span(bridge::client::Span::mixed_site())
310     }
311
312     /// The original source file into which this span points.
313     #[unstable(feature = "proc_macro_span", issue = "54725")]
314     pub fn source_file(&self) -> SourceFile {
315         SourceFile(self.0.source_file())
316     }
317
318     /// The `Span` for the tokens in the previous macro expansion from which
319     /// `self` was generated from, if any.
320     #[unstable(feature = "proc_macro_span", issue = "54725")]
321     pub fn parent(&self) -> Option<Span> {
322         self.0.parent().map(Span)
323     }
324
325     /// The span for the origin source code that `self` was generated from. If
326     /// this `Span` wasn't generated from other macro expansions then the return
327     /// value is the same as `*self`.
328     #[unstable(feature = "proc_macro_span", issue = "54725")]
329     pub fn source(&self) -> Span {
330         Span(self.0.source())
331     }
332
333     /// Gets the starting line/column in the source file for this span.
334     #[unstable(feature = "proc_macro_span", issue = "54725")]
335     pub fn start(&self) -> LineColumn {
336         self.0.start()
337     }
338
339     /// Gets the ending line/column in the source file for this span.
340     #[unstable(feature = "proc_macro_span", issue = "54725")]
341     pub fn end(&self) -> LineColumn {
342         self.0.end()
343     }
344
345     /// Creates a new span encompassing `self` and `other`.
346     ///
347     /// Returns `None` if `self` and `other` are from different files.
348     #[unstable(feature = "proc_macro_span", issue = "54725")]
349     pub fn join(&self, other: Span) -> Option<Span> {
350         self.0.join(other.0).map(Span)
351     }
352
353     /// Creates a new span with the same line/column information as `self` but
354     /// that resolves symbols as though it were at `other`.
355     #[unstable(feature = "proc_macro_span", issue = "54725")]
356     pub fn resolved_at(&self, other: Span) -> Span {
357         Span(self.0.resolved_at(other.0))
358     }
359
360     /// Creates a new span with the same name resolution behavior as `self` but
361     /// with the line/column information of `other`.
362     #[unstable(feature = "proc_macro_span", issue = "54725")]
363     pub fn located_at(&self, other: Span) -> Span {
364         other.resolved_at(*self)
365     }
366
367     /// Compares to spans to see if they're equal.
368     #[unstable(feature = "proc_macro_span", issue = "54725")]
369     pub fn eq(&self, other: &Span) -> bool {
370         self.0 == other.0
371     }
372
373     /// Returns the source text behind a span. This preserves the original source
374     /// code, including spaces and comments. It only returns a result if the span
375     /// corresponds to real source code.
376     ///
377     /// Note: The observable result of a macro should only rely on the tokens and
378     /// not on this source text. The result of this function is a best effort to
379     /// be used for diagnostics only.
380     #[unstable(feature = "proc_macro_span", issue = "54725")]
381     pub fn source_text(&self) -> Option<String> {
382         self.0.source_text()
383     }
384
385     diagnostic_method!(error, Level::Error);
386     diagnostic_method!(warning, Level::Warning);
387     diagnostic_method!(note, Level::Note);
388     diagnostic_method!(help, Level::Help);
389 }
390
391 /// Prints a span in a form convenient for debugging.
392 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
393 impl fmt::Debug for Span {
394     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
395         self.0.fmt(f)
396     }
397 }
398
399 /// A line-column pair representing the start or end of a `Span`.
400 #[unstable(feature = "proc_macro_span", issue = "54725")]
401 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
402 pub struct LineColumn {
403     /// The 1-indexed line in the source file on which the span starts or ends (inclusive).
404     #[unstable(feature = "proc_macro_span", issue = "54725")]
405     pub line: usize,
406     /// The 0-indexed column (in UTF-8 characters) in the source file on which
407     /// the span starts or ends (inclusive).
408     #[unstable(feature = "proc_macro_span", issue = "54725")]
409     pub column: usize,
410 }
411
412 #[unstable(feature = "proc_macro_span", issue = "54725")]
413 impl !Send for LineColumn {}
414 #[unstable(feature = "proc_macro_span", issue = "54725")]
415 impl !Sync for LineColumn {}
416
417 /// The source file of a given `Span`.
418 #[unstable(feature = "proc_macro_span", issue = "54725")]
419 #[derive(Clone)]
420 pub struct SourceFile(bridge::client::SourceFile);
421
422 impl SourceFile {
423     /// Gets the path to this source file.
424     ///
425     /// ### Note
426     /// If the code span associated with this `SourceFile` was generated by an external macro, this
427     /// macro, this may not be an actual path on the filesystem. Use [`is_real`] to check.
428     ///
429     /// Also note that even if `is_real` returns `true`, if `--remap-path-prefix` was passed on
430     /// the command line, the path as given may not actually be valid.
431     ///
432     /// [`is_real`]: #method.is_real
433     #[unstable(feature = "proc_macro_span", issue = "54725")]
434     pub fn path(&self) -> PathBuf {
435         PathBuf::from(self.0.path())
436     }
437
438     /// Returns `true` if this source file is a real source file, and not generated by an external
439     /// macro's expansion.
440     #[unstable(feature = "proc_macro_span", issue = "54725")]
441     pub fn is_real(&self) -> bool {
442         // This is a hack until intercrate spans are implemented and we can have real source files
443         // for spans generated in external macros.
444         // https://github.com/rust-lang/rust/pull/43604#issuecomment-333334368
445         self.0.is_real()
446     }
447 }
448
449 #[unstable(feature = "proc_macro_span", issue = "54725")]
450 impl fmt::Debug for SourceFile {
451     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
452         f.debug_struct("SourceFile")
453             .field("path", &self.path())
454             .field("is_real", &self.is_real())
455             .finish()
456     }
457 }
458
459 #[unstable(feature = "proc_macro_span", issue = "54725")]
460 impl PartialEq for SourceFile {
461     fn eq(&self, other: &Self) -> bool {
462         self.0.eq(&other.0)
463     }
464 }
465
466 #[unstable(feature = "proc_macro_span", issue = "54725")]
467 impl Eq for SourceFile {}
468
469 /// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
470 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
471 #[derive(Clone)]
472 pub enum TokenTree {
473     /// A token stream surrounded by bracket delimiters.
474     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
475     Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
476     /// An identifier.
477     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
478     Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
479     /// A single punctuation character (`+`, `,`, `$`, etc.).
480     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
481     Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
482     /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
483     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
484     Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
485 }
486
487 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
488 impl !Send for TokenTree {}
489 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
490 impl !Sync for TokenTree {}
491
492 impl TokenTree {
493     /// Returns the span of this tree, delegating to the `span` method of
494     /// the contained token or a delimited stream.
495     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
496     pub fn span(&self) -> Span {
497         match *self {
498             TokenTree::Group(ref t) => t.span(),
499             TokenTree::Ident(ref t) => t.span(),
500             TokenTree::Punct(ref t) => t.span(),
501             TokenTree::Literal(ref t) => t.span(),
502         }
503     }
504
505     /// Configures the span for *only this token*.
506     ///
507     /// Note that if this token is a `Group` then this method will not configure
508     /// the span of each of the internal tokens, this will simply delegate to
509     /// the `set_span` method of each variant.
510     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
511     pub fn set_span(&mut self, span: Span) {
512         match *self {
513             TokenTree::Group(ref mut t) => t.set_span(span),
514             TokenTree::Ident(ref mut t) => t.set_span(span),
515             TokenTree::Punct(ref mut t) => t.set_span(span),
516             TokenTree::Literal(ref mut t) => t.set_span(span),
517         }
518     }
519 }
520
521 /// Prints token tree in a form convenient for debugging.
522 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
523 impl fmt::Debug for TokenTree {
524     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
525         // Each of these has the name in the struct type in the derived debug,
526         // so don't bother with an extra layer of indirection
527         match *self {
528             TokenTree::Group(ref tt) => tt.fmt(f),
529             TokenTree::Ident(ref tt) => tt.fmt(f),
530             TokenTree::Punct(ref tt) => tt.fmt(f),
531             TokenTree::Literal(ref tt) => tt.fmt(f),
532         }
533     }
534 }
535
536 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
537 impl From<Group> for TokenTree {
538     fn from(g: Group) -> TokenTree {
539         TokenTree::Group(g)
540     }
541 }
542
543 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
544 impl From<Ident> for TokenTree {
545     fn from(g: Ident) -> TokenTree {
546         TokenTree::Ident(g)
547     }
548 }
549
550 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
551 impl From<Punct> for TokenTree {
552     fn from(g: Punct) -> TokenTree {
553         TokenTree::Punct(g)
554     }
555 }
556
557 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
558 impl From<Literal> for TokenTree {
559     fn from(g: Literal) -> TokenTree {
560         TokenTree::Literal(g)
561     }
562 }
563
564 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
565 // based on it (the reverse of the usual relationship between the two).
566 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
567 impl ToString for TokenTree {
568     fn to_string(&self) -> String {
569         match *self {
570             TokenTree::Group(ref t) => t.to_string(),
571             TokenTree::Ident(ref t) => t.to_string(),
572             TokenTree::Punct(ref t) => t.to_string(),
573             TokenTree::Literal(ref t) => t.to_string(),
574         }
575     }
576 }
577
578 /// Prints the token tree as a string that is supposed to be losslessly convertible back
579 /// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
580 /// with `Delimiter::None` delimiters and negative numeric literals.
581 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
582 impl fmt::Display for TokenTree {
583     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
584         f.write_str(&self.to_string())
585     }
586 }
587
588 /// A delimited token stream.
589 ///
590 /// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
591 #[derive(Clone)]
592 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
593 pub struct Group(bridge::client::Group);
594
595 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
596 impl !Send for Group {}
597 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
598 impl !Sync for Group {}
599
600 /// Describes how a sequence of token trees is delimited.
601 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
602 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
603 pub enum Delimiter {
604     /// `( ... )`
605     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
606     Parenthesis,
607     /// `{ ... }`
608     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
609     Brace,
610     /// `[ ... ]`
611     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
612     Bracket,
613     /// `Ø ... Ã˜`
614     /// An implicit delimiter, that may, for example, appear around tokens coming from a
615     /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
616     /// `$var * 3` where `$var` is `1 + 2`.
617     /// Implicit delimiters may not survive roundtrip of a token stream through a string.
618     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
619     None,
620 }
621
622 impl Group {
623     /// Creates a new `Group` with the given delimiter and token stream.
624     ///
625     /// This constructor will set the span for this group to
626     /// `Span::call_site()`. To change the span you can use the `set_span`
627     /// method below.
628     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
629     pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
630         Group(bridge::client::Group::new(delimiter, stream.0))
631     }
632
633     /// Returns the delimiter of this `Group`
634     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
635     pub fn delimiter(&self) -> Delimiter {
636         self.0.delimiter()
637     }
638
639     /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
640     ///
641     /// Note that the returned token stream does not include the delimiter
642     /// returned above.
643     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
644     pub fn stream(&self) -> TokenStream {
645         TokenStream(self.0.stream())
646     }
647
648     /// Returns the span for the delimiters of this token stream, spanning the
649     /// entire `Group`.
650     ///
651     /// ```text
652     /// pub fn span(&self) -> Span {
653     ///            ^^^^^^^
654     /// ```
655     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
656     pub fn span(&self) -> Span {
657         Span(self.0.span())
658     }
659
660     /// Returns the span pointing to the opening delimiter of this group.
661     ///
662     /// ```text
663     /// pub fn span_open(&self) -> Span {
664     ///                 ^
665     /// ```
666     #[unstable(feature = "proc_macro_span", issue = "54725")]
667     pub fn span_open(&self) -> Span {
668         Span(self.0.span_open())
669     }
670
671     /// Returns the span pointing to the closing delimiter of this group.
672     ///
673     /// ```text
674     /// pub fn span_close(&self) -> Span {
675     ///                        ^
676     /// ```
677     #[unstable(feature = "proc_macro_span", issue = "54725")]
678     pub fn span_close(&self) -> Span {
679         Span(self.0.span_close())
680     }
681
682     /// Configures the span for this `Group`'s delimiters, but not its internal
683     /// tokens.
684     ///
685     /// This method will **not** set the span of all the internal tokens spanned
686     /// by this group, but rather it will only set the span of the delimiter
687     /// tokens at the level of the `Group`.
688     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
689     pub fn set_span(&mut self, span: Span) {
690         self.0.set_span(span.0);
691     }
692 }
693
694 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
695 // based on it (the reverse of the usual relationship between the two).
696 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
697 impl ToString for Group {
698     fn to_string(&self) -> String {
699         TokenStream::from(TokenTree::from(self.clone())).to_string()
700     }
701 }
702
703 /// Prints the group as a string that should be losslessly convertible back
704 /// into the same group (modulo spans), except for possibly `TokenTree::Group`s
705 /// with `Delimiter::None` delimiters.
706 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
707 impl fmt::Display for Group {
708     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
709         f.write_str(&self.to_string())
710     }
711 }
712
713 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
714 impl fmt::Debug for Group {
715     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
716         f.debug_struct("Group")
717             .field("delimiter", &self.delimiter())
718             .field("stream", &self.stream())
719             .field("span", &self.span())
720             .finish()
721     }
722 }
723
724 /// An `Punct` is an single punctuation character like `+`, `-` or `#`.
725 ///
726 /// Multi-character operators like `+=` are represented as two instances of `Punct` with different
727 /// forms of `Spacing` returned.
728 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
729 #[derive(Clone)]
730 pub struct Punct(bridge::client::Punct);
731
732 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
733 impl !Send for Punct {}
734 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
735 impl !Sync for Punct {}
736
737 /// Whether an `Punct` is followed immediately by another `Punct` or
738 /// followed by another token or whitespace.
739 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
740 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
741 pub enum Spacing {
742     /// e.g., `+` is `Alone` in `+ =`, `+ident` or `+()`.
743     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
744     Alone,
745     /// e.g., `+` is `Joint` in `+=` or `'#`.
746     /// Additionally, single quote `'` can join with identifiers to form lifetimes `'ident`.
747     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
748     Joint,
749 }
750
751 impl Punct {
752     /// Creates a new `Punct` from the given character and spacing.
753     /// The `ch` argument must be a valid punctuation character permitted by the language,
754     /// otherwise the function will panic.
755     ///
756     /// The returned `Punct` will have the default span of `Span::call_site()`
757     /// which can be further configured with the `set_span` method below.
758     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
759     pub fn new(ch: char, spacing: Spacing) -> Punct {
760         Punct(bridge::client::Punct::new(ch, spacing))
761     }
762
763     /// Returns the value of this punctuation character as `char`.
764     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
765     pub fn as_char(&self) -> char {
766         self.0.as_char()
767     }
768
769     /// Returns the spacing of this punctuation character, indicating whether it's immediately
770     /// followed by another `Punct` in the token stream, so they can potentially be combined into
771     /// a multi-character operator (`Joint`), or it's followed by some other token or whitespace
772     /// (`Alone`) so the operator has certainly ended.
773     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
774     pub fn spacing(&self) -> Spacing {
775         self.0.spacing()
776     }
777
778     /// Returns the span for this punctuation character.
779     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
780     pub fn span(&self) -> Span {
781         Span(self.0.span())
782     }
783
784     /// Configure the span for this punctuation character.
785     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
786     pub fn set_span(&mut self, span: Span) {
787         self.0 = self.0.with_span(span.0);
788     }
789 }
790
791 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
792 // based on it (the reverse of the usual relationship between the two).
793 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
794 impl ToString for Punct {
795     fn to_string(&self) -> String {
796         TokenStream::from(TokenTree::from(self.clone())).to_string()
797     }
798 }
799
800 /// Prints the punctuation character as a string that should be losslessly convertible
801 /// back into the same character.
802 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
803 impl fmt::Display for Punct {
804     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
805         f.write_str(&self.to_string())
806     }
807 }
808
809 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
810 impl fmt::Debug for Punct {
811     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
812         f.debug_struct("Punct")
813             .field("ch", &self.as_char())
814             .field("spacing", &self.spacing())
815             .field("span", &self.span())
816             .finish()
817     }
818 }
819
820 /// An identifier (`ident`).
821 #[derive(Clone)]
822 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
823 pub struct Ident(bridge::client::Ident);
824
825 impl Ident {
826     /// Creates a new `Ident` with the given `string` as well as the specified
827     /// `span`.
828     /// The `string` argument must be a valid identifier permitted by the
829     /// language, otherwise the function will panic.
830     ///
831     /// Note that `span`, currently in rustc, configures the hygiene information
832     /// for this identifier.
833     ///
834     /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
835     /// meaning that identifiers created with this span will be resolved as if they were written
836     /// directly at the location of the macro call, and other code at the macro call site will be
837     /// able to refer to them as well.
838     ///
839     /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
840     /// meaning that identifiers created with this span will be resolved at the location of the
841     /// macro definition and other code at the macro call site will not be able to refer to them.
842     ///
843     /// Due to the current importance of hygiene this constructor, unlike other
844     /// tokens, requires a `Span` to be specified at construction.
845     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
846     pub fn new(string: &str, span: Span) -> Ident {
847         Ident(bridge::client::Ident::new(string, span.0, false))
848     }
849
850     /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
851     #[unstable(feature = "proc_macro_raw_ident", issue = "54723")]
852     pub fn new_raw(string: &str, span: Span) -> Ident {
853         Ident(bridge::client::Ident::new(string, span.0, true))
854     }
855
856     /// Returns the span of this `Ident`, encompassing the entire string returned
857     /// by `as_str`.
858     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
859     pub fn span(&self) -> Span {
860         Span(self.0.span())
861     }
862
863     /// Configures the span of this `Ident`, possibly changing its hygiene context.
864     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
865     pub fn set_span(&mut self, span: Span) {
866         self.0 = self.0.with_span(span.0);
867     }
868 }
869
870 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
871 // based on it (the reverse of the usual relationship between the two).
872 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
873 impl ToString for Ident {
874     fn to_string(&self) -> String {
875         TokenStream::from(TokenTree::from(self.clone())).to_string()
876     }
877 }
878
879 /// Prints the identifier as a string that should be losslessly convertible
880 /// back into the same identifier.
881 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
882 impl fmt::Display for Ident {
883     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
884         f.write_str(&self.to_string())
885     }
886 }
887
888 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
889 impl fmt::Debug for Ident {
890     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
891         f.debug_struct("Ident")
892             .field("ident", &self.to_string())
893             .field("span", &self.span())
894             .finish()
895     }
896 }
897
898 /// A literal string (`"hello"`), byte string (`b"hello"`),
899 /// character (`'a'`), byte character (`b'a'`), an integer or floating point number
900 /// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
901 /// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
902 #[derive(Clone)]
903 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
904 pub struct Literal(bridge::client::Literal);
905
906 macro_rules! suffixed_int_literals {
907     ($($name:ident => $kind:ident,)*) => ($(
908         /// Creates a new suffixed integer literal with the specified value.
909         ///
910         /// This function will create an integer like `1u32` where the integer
911         /// value specified is the first part of the token and the integral is
912         /// also suffixed at the end.
913         /// Literals created from negative numbers may not survive round-trips through
914         /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
915         ///
916         /// Literals created through this method have the `Span::call_site()`
917         /// span by default, which can be configured with the `set_span` method
918         /// below.
919         #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
920         pub fn $name(n: $kind) -> Literal {
921             Literal(bridge::client::Literal::typed_integer(&n.to_string(), stringify!($kind)))
922         }
923     )*)
924 }
925
926 macro_rules! unsuffixed_int_literals {
927     ($($name:ident => $kind:ident,)*) => ($(
928         /// Creates a new unsuffixed integer literal with the specified value.
929         ///
930         /// This function will create an integer like `1` where the integer
931         /// value specified is the first part of the token. No suffix is
932         /// specified on this token, meaning that invocations like
933         /// `Literal::i8_unsuffixed(1)` are equivalent to
934         /// `Literal::u32_unsuffixed(1)`.
935         /// Literals created from negative numbers may not survive rountrips through
936         /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
937         ///
938         /// Literals created through this method have the `Span::call_site()`
939         /// span by default, which can be configured with the `set_span` method
940         /// below.
941         #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
942         pub fn $name(n: $kind) -> Literal {
943             Literal(bridge::client::Literal::integer(&n.to_string()))
944         }
945     )*)
946 }
947
948 impl Literal {
949     suffixed_int_literals! {
950         u8_suffixed => u8,
951         u16_suffixed => u16,
952         u32_suffixed => u32,
953         u64_suffixed => u64,
954         u128_suffixed => u128,
955         usize_suffixed => usize,
956         i8_suffixed => i8,
957         i16_suffixed => i16,
958         i32_suffixed => i32,
959         i64_suffixed => i64,
960         i128_suffixed => i128,
961         isize_suffixed => isize,
962     }
963
964     unsuffixed_int_literals! {
965         u8_unsuffixed => u8,
966         u16_unsuffixed => u16,
967         u32_unsuffixed => u32,
968         u64_unsuffixed => u64,
969         u128_unsuffixed => u128,
970         usize_unsuffixed => usize,
971         i8_unsuffixed => i8,
972         i16_unsuffixed => i16,
973         i32_unsuffixed => i32,
974         i64_unsuffixed => i64,
975         i128_unsuffixed => i128,
976         isize_unsuffixed => isize,
977     }
978
979     /// Creates a new unsuffixed floating-point literal.
980     ///
981     /// This constructor is similar to those like `Literal::i8_unsuffixed` where
982     /// the float's value is emitted directly into the token but no suffix is
983     /// used, so it may be inferred to be a `f64` later in the compiler.
984     /// Literals created from negative numbers may not survive rountrips through
985     /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
986     ///
987     /// # Panics
988     ///
989     /// This function requires that the specified float is finite, for
990     /// example if it is infinity or NaN this function will panic.
991     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
992     pub fn f32_unsuffixed(n: f32) -> Literal {
993         if !n.is_finite() {
994             panic!("Invalid float literal {}", n);
995         }
996         Literal(bridge::client::Literal::float(&n.to_string()))
997     }
998
999     /// Creates a new suffixed floating-point literal.
1000     ///
1001     /// This constructor will create a literal like `1.0f32` where the value
1002     /// specified is the preceding part of the token and `f32` is the suffix of
1003     /// the token. This token will always be inferred to be an `f32` in the
1004     /// compiler.
1005     /// Literals created from negative numbers may not survive rountrips through
1006     /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1007     ///
1008     /// # Panics
1009     ///
1010     /// This function requires that the specified float is finite, for
1011     /// example if it is infinity or NaN this function will panic.
1012     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1013     pub fn f32_suffixed(n: f32) -> Literal {
1014         if !n.is_finite() {
1015             panic!("Invalid float literal {}", n);
1016         }
1017         Literal(bridge::client::Literal::f32(&n.to_string()))
1018     }
1019
1020     /// Creates a new unsuffixed floating-point literal.
1021     ///
1022     /// This constructor is similar to those like `Literal::i8_unsuffixed` where
1023     /// the float's value is emitted directly into the token but no suffix is
1024     /// used, so it may be inferred to be a `f64` later in the compiler.
1025     /// Literals created from negative numbers may not survive rountrips through
1026     /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1027     ///
1028     /// # Panics
1029     ///
1030     /// This function requires that the specified float is finite, for
1031     /// example if it is infinity or NaN this function will panic.
1032     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1033     pub fn f64_unsuffixed(n: f64) -> Literal {
1034         if !n.is_finite() {
1035             panic!("Invalid float literal {}", n);
1036         }
1037         Literal(bridge::client::Literal::float(&n.to_string()))
1038     }
1039
1040     /// Creates a new suffixed floating-point literal.
1041     ///
1042     /// This constructor will create a literal like `1.0f64` where the value
1043     /// specified is the preceding part of the token and `f64` is the suffix of
1044     /// the token. This token will always be inferred to be an `f64` in the
1045     /// compiler.
1046     /// Literals created from negative numbers may not survive rountrips through
1047     /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1048     ///
1049     /// # Panics
1050     ///
1051     /// This function requires that the specified float is finite, for
1052     /// example if it is infinity or NaN this function will panic.
1053     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1054     pub fn f64_suffixed(n: f64) -> Literal {
1055         if !n.is_finite() {
1056             panic!("Invalid float literal {}", n);
1057         }
1058         Literal(bridge::client::Literal::f64(&n.to_string()))
1059     }
1060
1061     /// String literal.
1062     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1063     pub fn string(string: &str) -> Literal {
1064         Literal(bridge::client::Literal::string(string))
1065     }
1066
1067     /// Character literal.
1068     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1069     pub fn character(ch: char) -> Literal {
1070         Literal(bridge::client::Literal::character(ch))
1071     }
1072
1073     /// Byte string literal.
1074     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1075     pub fn byte_string(bytes: &[u8]) -> Literal {
1076         Literal(bridge::client::Literal::byte_string(bytes))
1077     }
1078
1079     /// Returns the span encompassing this literal.
1080     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1081     pub fn span(&self) -> Span {
1082         Span(self.0.span())
1083     }
1084
1085     /// Configures the span associated for this literal.
1086     #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1087     pub fn set_span(&mut self, span: Span) {
1088         self.0.set_span(span.0);
1089     }
1090
1091     /// Returns a `Span` that is a subset of `self.span()` containing only the
1092     /// source bytes in range `range`. Returns `None` if the would-be trimmed
1093     /// span is outside the bounds of `self`.
1094     // FIXME(SergioBenitez): check that the byte range starts and ends at a
1095     // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1096     // occur elsewhere when the source text is printed.
1097     // FIXME(SergioBenitez): there is no way for the user to know what
1098     // `self.span()` actually maps to, so this method can currently only be
1099     // called blindly. For example, `to_string()` for the character 'c' returns
1100     // "'\u{63}'"; there is no way for the user to know whether the source text
1101     // was 'c' or whether it was '\u{63}'.
1102     #[unstable(feature = "proc_macro_span", issue = "54725")]
1103     pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1104         // HACK(eddyb) something akin to `Option::cloned`, but for `Bound<&T>`.
1105         fn cloned_bound<T: Clone>(bound: Bound<&T>) -> Bound<T> {
1106             match bound {
1107                 Bound::Included(x) => Bound::Included(x.clone()),
1108                 Bound::Excluded(x) => Bound::Excluded(x.clone()),
1109                 Bound::Unbounded => Bound::Unbounded,
1110             }
1111         }
1112
1113         self.0.subspan(cloned_bound(range.start_bound()), cloned_bound(range.end_bound())).map(Span)
1114     }
1115 }
1116
1117 // N.B., the bridge only provides `to_string`, implement `fmt::Display`
1118 // based on it (the reverse of the usual relationship between the two).
1119 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
1120 impl ToString for Literal {
1121     fn to_string(&self) -> String {
1122         TokenStream::from(TokenTree::from(self.clone())).to_string()
1123     }
1124 }
1125
1126 /// Prints the literal as a string that should be losslessly convertible
1127 /// back into the same literal (except for possible rounding for floating point literals).
1128 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1129 impl fmt::Display for Literal {
1130     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1131         f.write_str(&self.to_string())
1132     }
1133 }
1134
1135 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1136 impl fmt::Debug for Literal {
1137     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1138         // FIXME(eddyb) `Literal` should not expose internal `Debug` impls.
1139         self.0.fmt(f)
1140     }
1141 }