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