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