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