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