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