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