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