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