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