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