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