1 //! A support library for macro authors when defining new macros.
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]`.
8 //! See [the book] for more.
10 //! [the book]: ../book/ch19-06-macros.html#procedural-macros-for-generating-code-from-attributes
17 pub use diagnostic::{Diagnostic, Level, MultiSpan};
19 use std::cmp::Ordering;
20 use std::ops::RangeBounds;
21 use std::path::PathBuf;
22 use std::str::FromStr;
23 use std::{error, fmt, iter, mem};
25 /// Determines whether proc_macro has been made accessible to the currently
28 /// The proc_macro crate is only intended for use inside the implementation of
29 /// procedural macros. All the functions in this crate panic if invoked from
30 /// outside of a procedural macro, such as from a build script or unit test or
31 /// ordinary Rust binary.
33 /// With consideration for Rust libraries that are designed to support both
34 /// macro and non-macro use cases, `proc_macro::is_available()` provides a
35 /// non-panicking way to detect whether the infrastructure required to use the
36 /// API of proc_macro is presently available. Returns true if invoked from
37 /// inside of a procedural macro, false if invoked from any other binary.
38 pub fn is_available() -> bool {
39 bridge::Bridge::is_available()
42 /// The main type provided by this crate, representing an abstract stream of
43 /// tokens, or, more specifically, a sequence of token trees.
44 /// The type provide interfaces for iterating over those token trees and, conversely,
45 /// collecting a number of token trees into one stream.
47 /// This is both the input and output of `#[proc_macro]`, `#[proc_macro_attribute]`
48 /// and `#[proc_macro_derive]` definitions.
50 pub struct TokenStream(bridge::client::TokenStream);
52 /// Error returned from `TokenStream::from_str`.
57 impl fmt::Display for LexError {
58 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59 f.write_str("cannot parse string into token stream")
63 impl error::Error for LexError {}
65 /// Error returned from `TokenStream::expand_expr`.
68 pub struct ExpandError;
70 impl fmt::Display for ExpandError {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 f.write_str("macro expansion failed")
76 impl error::Error for ExpandError {}
79 /// Returns an empty `TokenStream` containing no token trees.
80 pub fn new() -> TokenStream {
81 TokenStream(bridge::client::TokenStream::new())
84 /// Checks if this `TokenStream` is empty.
85 pub fn is_empty(&self) -> bool {
89 /// Parses this `TokenStream` as an expression and attempts to expand any
90 /// macros within it. Returns the expanded `TokenStream`.
92 /// Currently only expressions expanding to literals will succeed, although
93 /// this may be relaxed in the future.
95 /// NOTE: In error conditions, `expand_expr` may leave macros unexpanded,
96 /// report an error, failing compilation, and/or return an `Err(..)`. The
97 /// specific behavior for any error condition, and what conditions are
98 /// considered errors, is unspecified and may change in the future.
99 pub fn expand_expr(&self) -> Result<TokenStream, ExpandError> {
100 match bridge::client::TokenStream::expand_expr(&self.0) {
101 Ok(stream) => Ok(TokenStream(stream)),
102 Err(_) => Err(ExpandError),
107 /// Attempts to break the string into tokens and parse those tokens into a token stream.
108 /// May fail for a number of reasons, for example, if the string contains unbalanced delimiters
109 /// or characters not existing in the language.
110 /// All tokens in the parsed stream get `Span::call_site()` spans.
112 /// NOTE: some errors may cause panics instead of returning `LexError`. We reserve the right to
113 /// change these errors into `LexError`s later.
114 impl FromStr for TokenStream {
117 fn from_str(src: &str) -> Result<TokenStream, LexError> {
118 Ok(TokenStream(bridge::client::TokenStream::from_str(src)))
122 /// Prints the token stream as a string that is supposed to be losslessly convertible back
123 /// into the same token stream (modulo spans), except for possibly `TokenTree::Group`s
124 /// with `Delimiter::None` delimiters and negative numeric literals.
125 impl fmt::Display for TokenStream {
126 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127 f.write_str(&self.to_string())
131 /// Prints token in a form convenient for debugging.
132 impl fmt::Debug for TokenStream {
133 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134 f.write_str("TokenStream ")?;
135 f.debug_list().entries(self.clone()).finish()
139 impl Default for TokenStream {
140 fn default() -> Self {
145 pub use quote::{quote, quote_span};
147 /// Creates a token stream containing a single token tree.
148 impl From<TokenTree> for TokenStream {
149 fn from(tree: TokenTree) -> TokenStream {
150 TokenStream(bridge::client::TokenStream::from_token_tree(match tree {
151 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
152 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
153 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
154 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
159 /// Collects a number of token trees into a single stream.
160 impl iter::FromIterator<TokenTree> for TokenStream {
161 fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
162 trees.into_iter().map(TokenStream::from).collect()
166 /// A "flattening" operation on token streams, collects token trees
167 /// from multiple token streams into a single stream.
168 impl iter::FromIterator<TokenStream> for TokenStream {
169 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
170 let mut builder = bridge::client::TokenStreamBuilder::new();
171 streams.into_iter().for_each(|stream| builder.push(stream.0));
172 TokenStream(builder.build())
176 impl Extend<TokenTree> for TokenStream {
177 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
178 self.extend(trees.into_iter().map(TokenStream::from));
182 impl Extend<TokenStream> for TokenStream {
183 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
184 // FIXME(eddyb) Use an optimized implementation if/when possible.
185 *self = iter::once(mem::replace(self, Self::new())).chain(streams).collect();
189 /// Public implementation details for the `TokenStream` type, such as iterators.
190 pub mod token_stream {
191 use super::{bridge, Group, Ident, Literal, Punct, TokenStream, TokenTree};
193 /// An iterator over `TokenStream`'s `TokenTree`s.
194 /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups,
195 /// and returns whole groups as token trees.
197 pub struct IntoIter(bridge::client::TokenStreamIter);
199 impl Iterator for IntoIter {
200 type Item = TokenTree;
202 fn next(&mut self) -> Option<TokenTree> {
203 self.0.next().map(|tree| match tree {
204 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
205 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
206 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
207 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
212 impl IntoIterator for TokenStream {
213 type Item = TokenTree;
214 type IntoIter = IntoIter;
216 fn into_iter(self) -> IntoIter {
217 IntoIter(self.0.into_iter())
222 /// `quote!(..)` accepts arbitrary tokens and expands into a `TokenStream` describing the input.
223 /// For example, `quote!(a + b)` will produce an expression, that, when evaluated, constructs
224 /// the `TokenStream` `[Ident("a"), Punct('+', Alone), Ident("b")]`.
226 /// Unquoting is done with `$`, and works by taking the single next ident as the unquoted term.
227 /// To quote `$` itself, use `$$`.
228 //pub macro quote($($t:tt)*) {
229 //[> compiler built-in <]
235 /// A region of source code, along with macro expansion information.
236 #[derive(Copy, Clone)]
237 pub struct Span(bridge::client::Span);
239 macro_rules! diagnostic_method {
240 ($name:ident, $level:expr) => {
241 /// Creates a new `Diagnostic` with the given `message` at the span
243 pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
244 Diagnostic::spanned(self, $level, message)
250 /// A span that resolves at the macro definition site.
251 pub fn def_site() -> Span {
252 Span(bridge::client::Span::def_site())
255 /// The span of the invocation of the current procedural macro.
256 /// Identifiers created with this span will be resolved as if they were written
257 /// directly at the macro call location (call-site hygiene) and other code
258 /// at the macro call site will be able to refer to them as well.
259 pub fn call_site() -> Span {
260 Span(bridge::client::Span::call_site())
263 /// A span that represents `macro_rules` hygiene, and sometimes resolves at the macro
264 /// definition site (local variables, labels, `$crate`) and sometimes at the macro
265 /// call site (everything else).
266 /// The span location is taken from the call-site.
267 pub fn mixed_site() -> Span {
268 Span(bridge::client::Span::mixed_site())
271 /// The original source file into which this span points.
272 pub fn source_file(&self) -> SourceFile {
273 SourceFile(self.0.source_file())
276 /// The `Span` for the tokens in the previous macro expansion from which
277 /// `self` was generated from, if any.
278 pub fn parent(&self) -> Option<Span> {
279 self.0.parent().map(Span)
282 /// The span for the origin source code that `self` was generated from. If
283 /// this `Span` wasn't generated from other macro expansions then the return
284 /// value is the same as `*self`.
285 pub fn source(&self) -> Span {
286 Span(self.0.source())
289 /// Gets the starting line/column in the source file for this span.
290 pub fn start(&self) -> LineColumn {
291 self.0.start().add_1_to_column()
294 /// Gets the ending line/column in the source file for this span.
295 pub fn end(&self) -> LineColumn {
296 self.0.end().add_1_to_column()
299 /// Creates an empty span pointing to directly before this span.
300 pub fn before(&self) -> Span {
301 Span(self.0.before())
304 /// Creates an empty span pointing to directly after this span.
305 pub fn after(&self) -> Span {
309 /// Creates a new span encompassing `self` and `other`.
311 /// Returns `None` if `self` and `other` are from different files.
312 pub fn join(&self, other: Span) -> Option<Span> {
313 self.0.join(other.0).map(Span)
316 /// Creates a new span with the same line/column information as `self` but
317 /// that resolves symbols as though it were at `other`.
318 pub fn resolved_at(&self, other: Span) -> Span {
319 Span(self.0.resolved_at(other.0))
322 /// Creates a new span with the same name resolution behavior as `self` but
323 /// with the line/column information of `other`.
324 pub fn located_at(&self, other: Span) -> Span {
325 other.resolved_at(*self)
328 /// Compares to spans to see if they're equal.
329 pub fn eq(&self, other: &Span) -> bool {
333 /// Returns the source text behind a span. This preserves the original source
334 /// code, including spaces and comments. It only returns a result if the span
335 /// corresponds to real source code.
337 /// Note: The observable result of a macro should only rely on the tokens and
338 /// not on this source text. The result of this function is a best effort to
339 /// be used for diagnostics only.
340 pub fn source_text(&self) -> Option<String> {
344 // Used by the implementation of `Span::quote`
346 pub fn save_span(&self) -> usize {
350 // Used by the implementation of `Span::quote`
352 pub fn recover_proc_macro_span(id: usize) -> Span {
353 Span(bridge::client::Span::recover_proc_macro_span(id))
356 diagnostic_method!(error, Level::Error);
357 diagnostic_method!(warning, Level::Warning);
358 diagnostic_method!(note, Level::Note);
359 diagnostic_method!(help, Level::Help);
362 /// Prints a span in a form convenient for debugging.
363 impl fmt::Debug for Span {
364 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
369 /// A line-column pair representing the start or end of a `Span`.
370 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
371 pub struct LineColumn {
372 /// The 1-indexed line in the source file on which the span starts or ends (inclusive).
374 /// The 1-indexed column (number of bytes in UTF-8 encoding) in the source
375 /// file on which the span starts or ends (inclusive).
380 fn add_1_to_column(self) -> Self {
381 LineColumn { line: self.line, column: self.column + 1 }
385 impl Ord for LineColumn {
386 fn cmp(&self, other: &Self) -> Ordering {
387 self.line.cmp(&other.line).then(self.column.cmp(&other.column))
391 impl PartialOrd for LineColumn {
392 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
393 Some(self.cmp(other))
397 /// The source file of a given `Span`.
399 pub struct SourceFile(bridge::client::SourceFile);
402 /// Gets the path to this source file.
405 /// If the code span associated with this `SourceFile` was generated by an external macro, this
406 /// macro, this might not be an actual path on the filesystem. Use [`is_real`] to check.
408 /// Also note that even if `is_real` returns `true`, if `--remap-path-prefix` was passed on
409 /// the command line, the path as given might not actually be valid.
411 /// [`is_real`]: Self::is_real
412 pub fn path(&self) -> PathBuf {
413 PathBuf::from(self.0.path())
416 /// Returns `true` if this source file is a real source file, and not generated by an external
417 /// macro's expansion.
418 pub fn is_real(&self) -> bool {
419 // This is a hack until intercrate spans are implemented and we can have real source files
420 // for spans generated in external macros.
421 // https://github.com/rust-lang/rust/pull/43604#issuecomment-333334368
426 impl fmt::Debug for SourceFile {
427 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
428 f.debug_struct("SourceFile")
429 .field("path", &self.path())
430 .field("is_real", &self.is_real())
435 impl PartialEq for SourceFile {
436 fn eq(&self, other: &Self) -> bool {
441 impl Eq for SourceFile {}
443 /// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
446 /// A token stream surrounded by bracket delimiters.
450 /// A single punctuation character (`+`, `,`, `$`, etc.).
452 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
457 /// Returns the span of this tree, delegating to the `span` method of
458 /// the contained token or a delimited stream.
459 pub fn span(&self) -> Span {
461 TokenTree::Group(ref t) => t.span(),
462 TokenTree::Ident(ref t) => t.span(),
463 TokenTree::Punct(ref t) => t.span(),
464 TokenTree::Literal(ref t) => t.span(),
468 /// Configures the span for *only this token*.
470 /// Note that if this token is a `Group` then this method will not configure
471 /// the span of each of the internal tokens, this will simply delegate to
472 /// the `set_span` method of each variant.
473 pub fn set_span(&mut self, span: Span) {
475 TokenTree::Group(ref mut t) => t.set_span(span),
476 TokenTree::Ident(ref mut t) => t.set_span(span),
477 TokenTree::Punct(ref mut t) => t.set_span(span),
478 TokenTree::Literal(ref mut t) => t.set_span(span),
483 /// Prints token tree in a form convenient for debugging.
484 impl fmt::Debug for TokenTree {
485 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
486 // Each of these has the name in the struct type in the derived debug,
487 // so don't bother with an extra layer of indirection
489 TokenTree::Group(ref tt) => tt.fmt(f),
490 TokenTree::Ident(ref tt) => tt.fmt(f),
491 TokenTree::Punct(ref tt) => tt.fmt(f),
492 TokenTree::Literal(ref tt) => tt.fmt(f),
497 impl From<Group> for TokenTree {
498 fn from(g: Group) -> TokenTree {
503 impl From<Ident> for TokenTree {
504 fn from(g: Ident) -> TokenTree {
509 impl From<Punct> for TokenTree {
510 fn from(g: Punct) -> TokenTree {
515 impl From<Literal> for TokenTree {
516 fn from(g: Literal) -> TokenTree {
517 TokenTree::Literal(g)
521 /// Prints the token tree as a string that is supposed to be losslessly convertible back
522 /// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
523 /// with `Delimiter::None` delimiters and negative numeric literals.
524 impl fmt::Display for TokenTree {
525 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
526 f.write_str(&self.to_string())
530 /// A delimited token stream.
532 /// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
534 pub struct Group(bridge::client::Group);
536 /// Describes how a sequence of token trees is delimited.
537 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
546 /// An implicit delimiter, that may, for example, appear around tokens coming from a
547 /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
548 /// `$var * 3` where `$var` is `1 + 2`.
549 /// Implicit delimiters might not survive roundtrip of a token stream through a string.
554 /// Creates a new `Group` with the given delimiter and token stream.
556 /// This constructor will set the span for this group to
557 /// `Span::call_site()`. To change the span you can use the `set_span`
559 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
560 Group(bridge::client::Group::new(delimiter, stream.0))
563 /// Returns the delimiter of this `Group`
564 pub fn delimiter(&self) -> Delimiter {
568 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
570 /// Note that the returned token stream does not include the delimiter
572 pub fn stream(&self) -> TokenStream {
573 TokenStream(self.0.stream())
576 /// Returns the span for the delimiters of this token stream, spanning the
580 /// pub fn span(&self) -> Span {
583 pub fn span(&self) -> Span {
587 /// Returns the span pointing to the opening delimiter of this group.
590 /// pub fn span_open(&self) -> Span {
593 pub fn span_open(&self) -> Span {
594 Span(self.0.span_open())
597 /// Returns the span pointing to the closing delimiter of this group.
600 /// pub fn span_close(&self) -> Span {
603 pub fn span_close(&self) -> Span {
604 Span(self.0.span_close())
607 /// Configures the span for this `Group`'s delimiters, but not its internal
610 /// This method will **not** set the span of all the internal tokens spanned
611 /// by this group, but rather it will only set the span of the delimiter
612 /// tokens at the level of the `Group`.
613 pub fn set_span(&mut self, span: Span) {
614 self.0.set_span(span.0);
618 /// Prints the group as a string that should be losslessly convertible back
619 /// into the same group (modulo spans), except for possibly `TokenTree::Group`s
620 /// with `Delimiter::None` delimiters.
621 impl fmt::Display for Group {
622 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
623 f.write_str(&self.to_string())
627 impl fmt::Debug for Group {
628 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
629 f.debug_struct("Group")
630 .field("delimiter", &self.delimiter())
631 .field("stream", &self.stream())
632 .field("span", &self.span())
637 /// A `Punct` is a single punctuation character such as `+`, `-` or `#`.
639 /// Multi-character operators like `+=` are represented as two instances of `Punct` with different
640 /// forms of `Spacing` returned.
642 pub struct Punct(bridge::client::Punct);
644 /// Describes whether a `Punct` is followed immediately by another `Punct` ([`Spacing::Joint`]) or
645 /// by a different token or whitespace ([`Spacing::Alone`]).
646 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
648 /// A `Punct` is not immediately followed by another `Punct`.
649 /// E.g. `+` is `Alone` in `+ =`, `+ident` and `+()`.
651 /// A `Punct` is immediately followed by another `Punct`.
652 /// E.g. `+` is `Joint` in `+=` and `++`.
654 /// Additionally, single quote `'` can join with identifiers to form lifetimes: `'ident`.
659 /// Creates a new `Punct` from the given character and spacing.
660 /// The `ch` argument must be a valid punctuation character permitted by the language,
661 /// otherwise the function will panic.
663 /// The returned `Punct` will have the default span of `Span::call_site()`
664 /// which can be further configured with the `set_span` method below.
665 pub fn new(ch: char, spacing: Spacing) -> Punct {
666 Punct(bridge::client::Punct::new(ch, spacing))
669 /// Returns the value of this punctuation character as `char`.
670 pub fn as_char(&self) -> char {
674 /// Returns the spacing of this punctuation character, indicating whether it's immediately
675 /// followed by another `Punct` in the token stream, so they can potentially be combined into
676 /// a multi-character operator (`Joint`), or it's followed by some other token or whitespace
677 /// (`Alone`) so the operator has certainly ended.
678 pub fn spacing(&self) -> Spacing {
682 /// Returns the span for this punctuation character.
683 pub fn span(&self) -> Span {
687 /// Configure the span for this punctuation character.
688 pub fn set_span(&mut self, span: Span) {
689 self.0 = self.0.with_span(span.0);
693 /// Prints the punctuation character as a string that should be losslessly convertible
694 /// back into the same character.
695 impl fmt::Display for Punct {
696 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
697 f.write_str(&self.to_string())
701 impl fmt::Debug for Punct {
702 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
703 f.debug_struct("Punct")
704 .field("ch", &self.as_char())
705 .field("spacing", &self.spacing())
706 .field("span", &self.span())
711 impl PartialEq<char> for Punct {
712 fn eq(&self, rhs: &char) -> bool {
713 self.as_char() == *rhs
717 impl PartialEq<Punct> for char {
718 fn eq(&self, rhs: &Punct) -> bool {
719 *self == rhs.as_char()
723 /// An identifier (`ident`).
725 pub struct Ident(bridge::client::Ident);
728 /// Creates a new `Ident` with the given `string` as well as the specified
730 /// The `string` argument must be a valid identifier permitted by the
731 /// language (including keywords, e.g. `self` or `fn`). Otherwise, the function will panic.
733 /// Note that `span`, currently in rustc, configures the hygiene information
734 /// for this identifier.
736 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
737 /// meaning that identifiers created with this span will be resolved as if they were written
738 /// directly at the location of the macro call, and other code at the macro call site will be
739 /// able to refer to them as well.
741 /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
742 /// meaning that identifiers created with this span will be resolved at the location of the
743 /// macro definition and other code at the macro call site will not be able to refer to them.
745 /// Due to the current importance of hygiene this constructor, unlike other
746 /// tokens, requires a `Span` to be specified at construction.
747 pub fn new(string: &str, span: Span) -> Ident {
748 Ident(bridge::client::Ident::new(string, span.0, false))
751 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
752 /// The `string` argument be a valid identifier permitted by the language
753 /// (including keywords, e.g. `fn`). Keywords which are usable in path segments
754 /// (e.g. `self`, `super`) are not supported, and will cause a panic.
755 pub fn new_raw(string: &str, span: Span) -> Ident {
756 Ident(bridge::client::Ident::new(string, span.0, true))
759 /// Returns the span of this `Ident`, encompassing the entire string returned
760 /// by [`to_string`](Self::to_string).
761 pub fn span(&self) -> Span {
765 /// Configures the span of this `Ident`, possibly changing its hygiene context.
766 pub fn set_span(&mut self, span: Span) {
767 self.0 = self.0.with_span(span.0);
771 /// Prints the identifier as a string that should be losslessly convertible
772 /// back into the same identifier.
773 impl fmt::Display for Ident {
774 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
775 f.write_str(&self.to_string())
779 impl fmt::Debug for Ident {
780 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
781 f.debug_struct("Ident")
782 .field("ident", &self.to_string())
783 .field("span", &self.span())
788 /// A literal string (`"hello"`), byte string (`b"hello"`),
789 /// character (`'a'`), byte character (`b'a'`), an integer or floating point number
790 /// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
791 /// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
793 pub struct Literal(bridge::client::Literal);
795 macro_rules! suffixed_int_literals {
796 ($($name:ident => $kind:ident,)*) => ($(
797 /// Creates a new suffixed integer literal with the specified value.
799 /// This function will create an integer like `1u32` where the integer
800 /// value specified is the first part of the token and the integral is
801 /// also suffixed at the end.
802 /// Literals created from negative numbers might not survive round-trips through
803 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
805 /// Literals created through this method have the `Span::call_site()`
806 /// span by default, which can be configured with the `set_span` method
808 pub fn $name(n: $kind) -> Literal {
809 Literal(bridge::client::Literal::typed_integer(&n.to_string(), stringify!($kind)))
814 macro_rules! unsuffixed_int_literals {
815 ($($name:ident => $kind:ident,)*) => ($(
816 /// Creates a new unsuffixed integer literal with the specified value.
818 /// This function will create an integer like `1` where the integer
819 /// value specified is the first part of the token. No suffix is
820 /// specified on this token, meaning that invocations like
821 /// `Literal::i8_unsuffixed(1)` are equivalent to
822 /// `Literal::u32_unsuffixed(1)`.
823 /// Literals created from negative numbers might not survive rountrips through
824 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
826 /// Literals created through this method have the `Span::call_site()`
827 /// span by default, which can be configured with the `set_span` method
829 pub fn $name(n: $kind) -> Literal {
830 Literal(bridge::client::Literal::integer(&n.to_string()))
836 suffixed_int_literals! {
841 u128_suffixed => u128,
842 usize_suffixed => usize,
847 i128_suffixed => i128,
848 isize_suffixed => isize,
851 unsuffixed_int_literals! {
853 u16_unsuffixed => u16,
854 u32_unsuffixed => u32,
855 u64_unsuffixed => u64,
856 u128_unsuffixed => u128,
857 usize_unsuffixed => usize,
859 i16_unsuffixed => i16,
860 i32_unsuffixed => i32,
861 i64_unsuffixed => i64,
862 i128_unsuffixed => i128,
863 isize_unsuffixed => isize,
866 /// Creates a new unsuffixed floating-point literal.
868 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
869 /// the float's value is emitted directly into the token but no suffix is
870 /// used, so it may be inferred to be a `f64` later in the compiler.
871 /// Literals created from negative numbers might not survive rountrips through
872 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
876 /// This function requires that the specified float is finite, for
877 /// example if it is infinity or NaN this function will panic.
878 pub fn f32_unsuffixed(n: f32) -> Literal {
880 panic!("Invalid float literal {}", n);
882 let mut repr = n.to_string();
883 if !repr.contains('.') {
886 Literal(bridge::client::Literal::float(&repr))
889 /// Creates a new suffixed floating-point literal.
891 /// This constructor will create a literal like `1.0f32` where the value
892 /// specified is the preceding part of the token and `f32` is the suffix of
893 /// the token. This token will always be inferred to be an `f32` in the
895 /// Literals created from negative numbers might not survive rountrips through
896 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
900 /// This function requires that the specified float is finite, for
901 /// example if it is infinity or NaN this function will panic.
902 pub fn f32_suffixed(n: f32) -> Literal {
904 panic!("Invalid float literal {}", n);
906 Literal(bridge::client::Literal::f32(&n.to_string()))
909 /// Creates a new unsuffixed floating-point literal.
911 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
912 /// the float's value is emitted directly into the token but no suffix is
913 /// used, so it may be inferred to be a `f64` later in the compiler.
914 /// Literals created from negative numbers might not survive rountrips through
915 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
919 /// This function requires that the specified float is finite, for
920 /// example if it is infinity or NaN this function will panic.
921 pub fn f64_unsuffixed(n: f64) -> Literal {
923 panic!("Invalid float literal {}", n);
925 let mut repr = n.to_string();
926 if !repr.contains('.') {
929 Literal(bridge::client::Literal::float(&repr))
932 /// Creates a new suffixed floating-point literal.
934 /// This constructor will create a literal like `1.0f64` where the value
935 /// specified is the preceding part of the token and `f64` is the suffix of
936 /// the token. This token will always be inferred to be an `f64` in the
938 /// Literals created from negative numbers might not survive rountrips through
939 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
943 /// This function requires that the specified float is finite, for
944 /// example if it is infinity or NaN this function will panic.
945 pub fn f64_suffixed(n: f64) -> Literal {
947 panic!("Invalid float literal {}", n);
949 Literal(bridge::client::Literal::f64(&n.to_string()))
953 pub fn string(string: &str) -> Literal {
954 Literal(bridge::client::Literal::string(string))
957 /// Character literal.
958 pub fn character(ch: char) -> Literal {
959 Literal(bridge::client::Literal::character(ch))
962 /// Byte string literal.
963 pub fn byte_string(bytes: &[u8]) -> Literal {
964 Literal(bridge::client::Literal::byte_string(bytes))
967 /// Returns the span encompassing this literal.
968 pub fn span(&self) -> Span {
972 /// Configures the span associated for this literal.
973 pub fn set_span(&mut self, span: Span) {
974 self.0.set_span(span.0);
977 /// Returns a `Span` that is a subset of `self.span()` containing only the
978 /// source bytes in range `range`. Returns `None` if the would-be trimmed
979 /// span is outside the bounds of `self`.
980 // FIXME(SergioBenitez): check that the byte range starts and ends at a
981 // UTF-8 boundary of the source. otherwise, it's likely that a panic will
982 // occur elsewhere when the source text is printed.
983 // FIXME(SergioBenitez): there is no way for the user to know what
984 // `self.span()` actually maps to, so this method can currently only be
985 // called blindly. For example, `to_string()` for the character 'c' returns
986 // "'\u{63}'"; there is no way for the user to know whether the source text
987 // was 'c' or whether it was '\u{63}'.
988 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
989 self.0.subspan(range.start_bound().cloned(), range.end_bound().cloned()).map(Span)
993 /// Parse a single literal from its stringified representation.
995 /// In order to parse successfully, the input string must not contain anything
996 /// but the literal token. Specifically, it must not contain whitespace or
997 /// comments in addition to the literal.
999 /// The resulting literal token will have a `Span::call_site()` span.
1001 /// NOTE: some errors may cause panics instead of returning `LexError`. We
1002 /// reserve the right to change these errors into `LexError`s later.
1003 impl FromStr for Literal {
1004 type Err = LexError;
1006 fn from_str(src: &str) -> Result<Self, LexError> {
1007 match bridge::client::Literal::from_str(src) {
1008 Ok(literal) => Ok(Literal(literal)),
1009 Err(()) => Err(LexError),
1014 /// Prints the literal as a string that should be losslessly convertible
1015 /// back into the same literal (except for possible rounding for floating point literals).
1016 impl fmt::Display for Literal {
1017 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1018 f.write_str(&self.to_string())
1022 impl fmt::Debug for Literal {
1023 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1028 /// Tracked access to environment variables.
1029 pub mod tracked_env {
1030 use std::env::{self, VarError};
1031 use std::ffi::OsStr;
1033 /// Retrieve an environment variable and add it to build dependency info.
1034 /// Build system executing the compiler will know that the variable was accessed during
1035 /// compilation, and will be able to rerun the build when the value of that variable changes.
1036 /// Besides the dependency tracking this function should be equivalent to `env::var` from the
1037 /// standard library, except that the argument must be UTF-8.
1038 pub fn var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1039 let key: &str = key.as_ref();
1040 let value = env::var(key);
1041 super::bridge::client::FreeFunctions::track_env_var(key, value.as_deref().ok());
1046 /// Tracked access to additional files.
1047 pub mod tracked_path {
1049 /// Track a file explicitly.
1051 /// Commonly used for tracking asset preprocessing.
1052 pub fn path<P: AsRef<str>>(path: P) {
1053 let path: &str = path.as_ref();
1054 super::bridge::client::FreeFunctions::track_path(path);