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