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