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