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