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