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::client::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(Option<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 {
84 /// Checks if this `TokenStream` is empty.
85 pub fn is_empty(&self) -> bool {
86 self.0.as_ref().map(|h| h.is_empty()).unwrap_or(true)
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 let stream = self.0.as_ref().ok_or(ExpandError)?;
101 match bridge::client::TokenStream::expand_expr(stream) {
102 Ok(stream) => Ok(TokenStream(Some(stream))),
103 Err(_) => Err(ExpandError),
108 /// Attempts to break the string into tokens and parse those tokens into a token stream.
109 /// May fail for a number of reasons, for example, if the string contains unbalanced delimiters
110 /// or characters not existing in the language.
111 /// All tokens in the parsed stream get `Span::call_site()` spans.
113 /// NOTE: some errors may cause panics instead of returning `LexError`. We reserve the right to
114 /// change these errors into `LexError`s later.
115 impl FromStr for TokenStream {
118 fn from_str(src: &str) -> Result<TokenStream, LexError> {
119 Ok(TokenStream(Some(bridge::client::TokenStream::from_str(src))))
123 /// Prints the token stream as a string that is supposed to be losslessly convertible back
124 /// into the same token stream (modulo spans), except for possibly `TokenTree::Group`s
125 /// with `Delimiter::None` delimiters and negative numeric literals.
126 impl fmt::Display for TokenStream {
127 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128 f.write_str(&self.to_string())
132 /// Prints token in a form convenient for debugging.
133 impl fmt::Debug for TokenStream {
134 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135 f.write_str("TokenStream ")?;
136 f.debug_list().entries(self.clone()).finish()
140 impl Default for TokenStream {
141 fn default() -> Self {
146 pub use quote::{quote, quote_span};
148 fn tree_to_bridge_tree(
150 ) -> bridge::TokenTree<
151 bridge::client::TokenStream,
152 bridge::client::Span,
153 bridge::client::Ident,
154 bridge::client::Literal,
157 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
158 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
159 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
160 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
164 /// Creates a token stream containing a single token tree.
165 impl From<TokenTree> for TokenStream {
166 fn from(tree: TokenTree) -> TokenStream {
167 TokenStream(Some(bridge::client::TokenStream::from_token_tree(tree_to_bridge_tree(tree))))
171 /// Non-generic helper for implementing `FromIterator<TokenStream>` and
172 /// `Extend<TokenStream>` with less monomorphization in calling crates.
173 struct ConcatStreamsHelper {
174 streams: Vec<bridge::client::TokenStream>,
177 impl ConcatStreamsHelper {
178 fn new(capacity: usize) -> Self {
179 ConcatStreamsHelper { streams: Vec::with_capacity(capacity) }
182 fn push(&mut self, stream: TokenStream) {
183 if let Some(stream) = stream.0 {
184 self.streams.push(stream);
188 fn build(mut self) -> TokenStream {
189 if self.streams.len() <= 1 {
190 TokenStream(self.streams.pop())
192 TokenStream(Some(bridge::client::TokenStream::concat_streams(None, self.streams)))
196 fn append_to(mut self, stream: &mut TokenStream) {
197 if self.streams.is_empty() {
200 let base = stream.0.take();
201 if base.is_none() && self.streams.len() == 1 {
202 stream.0 = self.streams.pop();
204 stream.0 = Some(bridge::client::TokenStream::concat_streams(base, self.streams));
209 /// Collects a number of token trees into a single stream.
210 impl iter::FromIterator<TokenTree> for TokenStream {
211 fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
212 trees.into_iter().map(TokenStream::from).collect()
216 /// A "flattening" operation on token streams, collects token trees
217 /// from multiple token streams into a single stream.
218 impl iter::FromIterator<TokenStream> for TokenStream {
219 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
220 let iter = streams.into_iter();
221 let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
222 iter.for_each(|stream| builder.push(stream));
227 impl Extend<TokenTree> for TokenStream {
228 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
229 self.extend(trees.into_iter().map(TokenStream::from));
233 impl Extend<TokenStream> for TokenStream {
234 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
235 // FIXME(eddyb) Use an optimized implementation if/when possible.
236 *self = iter::once(mem::replace(self, Self::new())).chain(streams).collect();
240 /// Public implementation details for the `TokenStream` type, such as iterators.
241 pub mod token_stream {
242 use super::{bridge, Group, Ident, Literal, Punct, TokenStream, TokenTree};
244 /// An iterator over `TokenStream`'s `TokenTree`s.
245 /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups,
246 /// and returns whole groups as token trees.
251 bridge::client::TokenStream,
252 bridge::client::Span,
253 bridge::client::Ident,
254 bridge::client::Literal,
259 impl Iterator for IntoIter {
260 type Item = TokenTree;
262 fn next(&mut self) -> Option<TokenTree> {
263 self.0.next().map(|tree| match tree {
264 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
265 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
266 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
267 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
272 impl IntoIterator for TokenStream {
273 type Item = TokenTree;
274 type IntoIter = IntoIter;
276 fn into_iter(self) -> IntoIter {
277 IntoIter(self.0.map(|v| v.into_trees()).unwrap_or_default().into_iter())
285 /// A region of source code, along with macro expansion information.
286 #[derive(Copy, Clone)]
287 pub struct Span(bridge::client::Span);
289 macro_rules! diagnostic_method {
290 ($name:ident, $level:expr) => {
291 /// Creates a new `Diagnostic` with the given `message` at the span
293 pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
294 Diagnostic::spanned(self, $level, message)
300 /// A span that resolves at the macro definition site.
301 pub fn def_site() -> Span {
302 Span(bridge::client::Span::def_site())
305 /// The span of the invocation of the current procedural macro.
306 /// Identifiers created with this span will be resolved as if they were written
307 /// directly at the macro call location (call-site hygiene) and other code
308 /// at the macro call site will be able to refer to them as well.
309 pub fn call_site() -> Span {
310 Span(bridge::client::Span::call_site())
313 /// A span that represents `macro_rules` hygiene, and sometimes resolves at the macro
314 /// definition site (local variables, labels, `$crate`) and sometimes at the macro
315 /// call site (everything else).
316 /// The span location is taken from the call-site.
317 pub fn mixed_site() -> Span {
318 Span(bridge::client::Span::mixed_site())
321 /// The original source file into which this span points.
322 pub fn source_file(&self) -> SourceFile {
323 SourceFile(self.0.source_file())
326 /// The `Span` for the tokens in the previous macro expansion from which
327 /// `self` was generated from, if any.
328 pub fn parent(&self) -> Option<Span> {
329 self.0.parent().map(Span)
332 /// The span for the origin source code that `self` was generated from. If
333 /// this `Span` wasn't generated from other macro expansions then the return
334 /// value is the same as `*self`.
335 pub fn source(&self) -> Span {
336 Span(self.0.source())
339 /// Gets the starting line/column in the source file for this span.
340 pub fn start(&self) -> LineColumn {
341 self.0.start().add_1_to_column()
344 /// Gets the ending line/column in the source file for this span.
345 pub fn end(&self) -> LineColumn {
346 self.0.end().add_1_to_column()
349 /// Creates an empty span pointing to directly before this span.
350 pub fn before(&self) -> Span {
351 Span(self.0.before())
354 /// Creates an empty span pointing to directly after this span.
355 pub fn after(&self) -> Span {
359 /// Creates a new span encompassing `self` and `other`.
361 /// Returns `None` if `self` and `other` are from different files.
362 pub fn join(&self, other: Span) -> Option<Span> {
363 self.0.join(other.0).map(Span)
366 /// Creates a new span with the same line/column information as `self` but
367 /// that resolves symbols as though it were at `other`.
368 pub fn resolved_at(&self, other: Span) -> Span {
369 Span(self.0.resolved_at(other.0))
372 /// Creates a new span with the same name resolution behavior as `self` but
373 /// with the line/column information of `other`.
374 pub fn located_at(&self, other: Span) -> Span {
375 other.resolved_at(*self)
378 /// Compares to spans to see if they're equal.
379 pub fn eq(&self, other: &Span) -> bool {
383 /// Returns the source text behind a span. This preserves the original source
384 /// code, including spaces and comments. It only returns a result if the span
385 /// corresponds to real source code.
387 /// Note: The observable result of a macro should only rely on the tokens and
388 /// not on this source text. The result of this function is a best effort to
389 /// be used for diagnostics only.
390 pub fn source_text(&self) -> Option<String> {
394 // Used by the implementation of `Span::quote`
396 pub fn save_span(&self) -> usize {
400 // Used by the implementation of `Span::quote`
402 pub fn recover_proc_macro_span(id: usize) -> Span {
403 Span(bridge::client::Span::recover_proc_macro_span(id))
406 diagnostic_method!(error, Level::Error);
407 diagnostic_method!(warning, Level::Warning);
408 diagnostic_method!(note, Level::Note);
409 diagnostic_method!(help, Level::Help);
412 /// Prints a span in a form convenient for debugging.
413 impl fmt::Debug for Span {
414 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
419 /// A line-column pair representing the start or end of a `Span`.
420 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
421 pub struct LineColumn {
422 /// The 1-indexed line in the source file on which the span starts or ends (inclusive).
424 /// The 1-indexed column (number of bytes in UTF-8 encoding) in the source
425 /// file on which the span starts or ends (inclusive).
430 fn add_1_to_column(self) -> Self {
431 LineColumn { line: self.line, column: self.column + 1 }
435 impl Ord for LineColumn {
436 fn cmp(&self, other: &Self) -> Ordering {
437 self.line.cmp(&other.line).then(self.column.cmp(&other.column))
441 impl PartialOrd for LineColumn {
442 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
443 Some(self.cmp(other))
447 /// The source file of a given `Span`.
449 pub struct SourceFile(bridge::client::SourceFile);
452 /// Gets the path to this source file.
455 /// If the code span associated with this `SourceFile` was generated by an external macro, this
456 /// macro, this might not be an actual path on the filesystem. Use [`is_real`] to check.
458 /// Also note that even if `is_real` returns `true`, if `--remap-path-prefix` was passed on
459 /// the command line, the path as given might not actually be valid.
461 /// [`is_real`]: Self::is_real
462 pub fn path(&self) -> PathBuf {
463 PathBuf::from(self.0.path())
466 /// Returns `true` if this source file is a real source file, and not generated by an external
467 /// macro's expansion.
468 pub fn is_real(&self) -> bool {
469 // This is a hack until intercrate spans are implemented and we can have real source files
470 // for spans generated in external macros.
471 // https://github.com/rust-lang/rust/pull/43604#issuecomment-333334368
476 impl fmt::Debug for SourceFile {
477 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
478 f.debug_struct("SourceFile")
479 .field("path", &self.path())
480 .field("is_real", &self.is_real())
485 impl PartialEq for SourceFile {
486 fn eq(&self, other: &Self) -> bool {
491 impl Eq for SourceFile {}
493 /// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`).
496 /// A token stream surrounded by bracket delimiters.
500 /// A single punctuation character (`+`, `,`, `$`, etc.).
502 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
507 /// Returns the span of this tree, delegating to the `span` method of
508 /// the contained token or a delimited stream.
509 pub fn span(&self) -> Span {
511 TokenTree::Group(ref t) => t.span(),
512 TokenTree::Ident(ref t) => t.span(),
513 TokenTree::Punct(ref t) => t.span(),
514 TokenTree::Literal(ref t) => t.span(),
518 /// Configures the span for *only this token*.
520 /// Note that if this token is a `Group` then this method will not configure
521 /// the span of each of the internal tokens, this will simply delegate to
522 /// the `set_span` method of each variant.
523 pub fn set_span(&mut self, span: Span) {
525 TokenTree::Group(ref mut t) => t.set_span(span),
526 TokenTree::Ident(ref mut t) => t.set_span(span),
527 TokenTree::Punct(ref mut t) => t.set_span(span),
528 TokenTree::Literal(ref mut t) => t.set_span(span),
533 /// Prints token tree in a form convenient for debugging.
534 impl fmt::Debug for TokenTree {
535 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
536 // Each of these has the name in the struct type in the derived debug,
537 // so don't bother with an extra layer of indirection
539 TokenTree::Group(ref tt) => tt.fmt(f),
540 TokenTree::Ident(ref tt) => tt.fmt(f),
541 TokenTree::Punct(ref tt) => tt.fmt(f),
542 TokenTree::Literal(ref tt) => tt.fmt(f),
547 impl From<Group> for TokenTree {
548 fn from(g: Group) -> TokenTree {
553 impl From<Ident> for TokenTree {
554 fn from(g: Ident) -> TokenTree {
559 impl From<Punct> for TokenTree {
560 fn from(g: Punct) -> TokenTree {
565 impl From<Literal> for TokenTree {
566 fn from(g: Literal) -> TokenTree {
567 TokenTree::Literal(g)
571 /// Prints the token tree as a string that is supposed to be losslessly convertible back
572 /// into the same token tree (modulo spans), except for possibly `TokenTree::Group`s
573 /// with `Delimiter::None` delimiters and negative numeric literals.
574 impl fmt::Display for TokenTree {
575 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
576 f.write_str(&self.to_string())
580 /// A delimited token stream.
582 /// A `Group` internally contains a `TokenStream` which is surrounded by `Delimiter`s.
584 pub struct Group(bridge::Group<bridge::client::TokenStream, bridge::client::Span>);
586 /// Describes how a sequence of token trees is delimited.
587 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
596 /// An invisible delimiter, that may, for example, appear around tokens coming from a
597 /// "macro variable" `$var`. It is important to preserve operator priorities in cases like
598 /// `$var * 3` where `$var` is `1 + 2`.
599 /// Invisible delimiters might not survive roundtrip of a token stream through a string.
604 /// Creates a new `Group` with the given delimiter and token stream.
606 /// This constructor will set the span for this group to
607 /// `Span::call_site()`. To change the span you can use the `set_span`
609 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
610 Group(bridge::Group {
613 span: bridge::DelimSpan::from_single(Span::call_site().0),
617 /// Returns the delimiter of this `Group`
618 pub fn delimiter(&self) -> Delimiter {
622 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
624 /// Note that the returned token stream does not include the delimiter
626 pub fn stream(&self) -> TokenStream {
627 TokenStream(self.0.stream.clone())
630 /// Returns the span for the delimiters of this token stream, spanning the
634 /// pub fn span(&self) -> Span {
637 pub fn span(&self) -> Span {
638 Span(self.0.span.entire)
641 /// Returns the span pointing to the opening delimiter of this group.
644 /// pub fn span_open(&self) -> Span {
647 pub fn span_open(&self) -> Span {
648 Span(self.0.span.open)
651 /// Returns the span pointing to the closing delimiter of this group.
654 /// pub fn span_close(&self) -> Span {
657 pub fn span_close(&self) -> Span {
658 Span(self.0.span.close)
661 /// Configures the span for this `Group`'s delimiters, but not its internal
664 /// This method will **not** set the span of all the internal tokens spanned
665 /// by this group, but rather it will only set the span of the delimiter
666 /// tokens at the level of the `Group`.
667 pub fn set_span(&mut self, span: Span) {
668 self.0.span = bridge::DelimSpan::from_single(span.0);
672 /// Prints the group as a string that should be losslessly convertible back
673 /// into the same group (modulo spans), except for possibly `TokenTree::Group`s
674 /// with `Delimiter::None` delimiters.
675 impl fmt::Display for Group {
676 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
677 f.write_str(&self.to_string())
681 impl fmt::Debug for Group {
682 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
683 f.debug_struct("Group")
684 .field("delimiter", &self.delimiter())
685 .field("stream", &self.stream())
686 .field("span", &self.span())
691 /// A `Punct` is a single punctuation character such as `+`, `-` or `#`.
693 /// Multi-character operators like `+=` are represented as two instances of `Punct` with different
694 /// forms of `Spacing` returned.
696 pub struct Punct(bridge::Punct<bridge::client::Span>);
698 /// Describes whether a `Punct` is followed immediately by another `Punct` ([`Spacing::Joint`]) or
699 /// by a different token or whitespace ([`Spacing::Alone`]).
700 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
702 /// A `Punct` is not immediately followed by another `Punct`.
703 /// E.g. `+` is `Alone` in `+ =`, `+ident` and `+()`.
705 /// A `Punct` is immediately followed by another `Punct`.
706 /// E.g. `+` is `Joint` in `+=` and `++`.
708 /// Additionally, single quote `'` can join with identifiers to form lifetimes: `'ident`.
713 /// Creates a new `Punct` from the given character and spacing.
714 /// The `ch` argument must be a valid punctuation character permitted by the language,
715 /// otherwise the function will panic.
717 /// The returned `Punct` will have the default span of `Span::call_site()`
718 /// which can be further configured with the `set_span` method below.
719 pub fn new(ch: char, spacing: Spacing) -> Punct {
720 const LEGAL_CHARS: &[char] = &[
721 '=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
722 ':', '#', '$', '?', '\'',
724 if !LEGAL_CHARS.contains(&ch) {
725 panic!("unsupported character `{:?}`", ch);
727 Punct(bridge::Punct {
729 joint: spacing == Spacing::Joint,
730 span: Span::call_site().0,
734 /// Returns the value of this punctuation character as `char`.
735 pub fn as_char(&self) -> char {
739 /// Returns the spacing of this punctuation character, indicating whether it's immediately
740 /// followed by another `Punct` in the token stream, so they can potentially be combined into
741 /// a multi-character operator (`Joint`), or it's followed by some other token or whitespace
742 /// (`Alone`) so the operator has certainly ended.
743 pub fn spacing(&self) -> Spacing {
751 /// Returns the span for this punctuation character.
752 pub fn span(&self) -> Span {
756 /// Configure the span for this punctuation character.
757 pub fn set_span(&mut self, span: Span) {
758 self.0.span = span.0;
762 /// Prints the punctuation character as a string that should be losslessly convertible
763 /// back into the same character.
764 impl fmt::Display for Punct {
765 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
766 f.write_str(&self.to_string())
770 impl fmt::Debug for Punct {
771 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
772 f.debug_struct("Punct")
773 .field("ch", &self.as_char())
774 .field("spacing", &self.spacing())
775 .field("span", &self.span())
780 impl PartialEq<char> for Punct {
781 fn eq(&self, rhs: &char) -> bool {
782 self.as_char() == *rhs
786 impl PartialEq<Punct> for char {
787 fn eq(&self, rhs: &Punct) -> bool {
788 *self == rhs.as_char()
792 /// An identifier (`ident`).
794 pub struct Ident(bridge::client::Ident);
797 /// Creates a new `Ident` with the given `string` as well as the specified
799 /// The `string` argument must be a valid identifier permitted by the
800 /// language (including keywords, e.g. `self` or `fn`). Otherwise, the function will panic.
802 /// Note that `span`, currently in rustc, configures the hygiene information
803 /// for this identifier.
805 /// As of this time `Span::call_site()` explicitly opts-in to "call-site" hygiene
806 /// meaning that identifiers created with this span will be resolved as if they were written
807 /// directly at the location of the macro call, and other code at the macro call site will be
808 /// able to refer to them as well.
810 /// Later spans like `Span::def_site()` will allow to opt-in to "definition-site" hygiene
811 /// meaning that identifiers created with this span will be resolved at the location of the
812 /// macro definition and other code at the macro call site will not be able to refer to them.
814 /// Due to the current importance of hygiene this constructor, unlike other
815 /// tokens, requires a `Span` to be specified at construction.
816 pub fn new(string: &str, span: Span) -> Ident {
817 Ident(bridge::client::Ident::new(string, span.0, false))
820 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`).
821 /// The `string` argument be a valid identifier permitted by the language
822 /// (including keywords, e.g. `fn`). Keywords which are usable in path segments
823 /// (e.g. `self`, `super`) are not supported, and will cause a panic.
824 pub fn new_raw(string: &str, span: Span) -> Ident {
825 Ident(bridge::client::Ident::new(string, span.0, true))
828 /// Returns the span of this `Ident`, encompassing the entire string returned
829 /// by [`to_string`](Self::to_string).
830 pub fn span(&self) -> Span {
834 /// Configures the span of this `Ident`, possibly changing its hygiene context.
835 pub fn set_span(&mut self, span: Span) {
836 self.0 = self.0.with_span(span.0);
840 /// Prints the identifier as a string that should be losslessly convertible
841 /// back into the same identifier.
842 impl fmt::Display for Ident {
843 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
844 f.write_str(&self.to_string())
848 impl fmt::Debug for Ident {
849 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
850 f.debug_struct("Ident")
851 .field("ident", &self.to_string())
852 .field("span", &self.span())
857 /// A literal string (`"hello"`), byte string (`b"hello"`),
858 /// character (`'a'`), byte character (`b'a'`), an integer or floating point number
859 /// with or without a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
860 /// Boolean literals like `true` and `false` do not belong here, they are `Ident`s.
862 pub struct Literal(bridge::client::Literal);
864 macro_rules! suffixed_int_literals {
865 ($($name:ident => $kind:ident,)*) => ($(
866 /// Creates a new suffixed integer literal with the specified value.
868 /// This function will create an integer like `1u32` where the integer
869 /// value specified is the first part of the token and the integral is
870 /// also suffixed at the end.
871 /// Literals created from negative numbers might not survive round-trips through
872 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
874 /// Literals created through this method have the `Span::call_site()`
875 /// span by default, which can be configured with the `set_span` method
877 pub fn $name(n: $kind) -> Literal {
878 Literal(bridge::client::Literal::typed_integer(&n.to_string(), stringify!($kind)))
883 macro_rules! unsuffixed_int_literals {
884 ($($name:ident => $kind:ident,)*) => ($(
885 /// Creates a new unsuffixed integer literal with the specified value.
887 /// This function will create an integer like `1` where the integer
888 /// value specified is the first part of the token. No suffix is
889 /// specified on this token, meaning that invocations like
890 /// `Literal::i8_unsuffixed(1)` are equivalent to
891 /// `Literal::u32_unsuffixed(1)`.
892 /// Literals created from negative numbers might not survive rountrips through
893 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
895 /// Literals created through this method have the `Span::call_site()`
896 /// span by default, which can be configured with the `set_span` method
898 pub fn $name(n: $kind) -> Literal {
899 Literal(bridge::client::Literal::integer(&n.to_string()))
905 suffixed_int_literals! {
910 u128_suffixed => u128,
911 usize_suffixed => usize,
916 i128_suffixed => i128,
917 isize_suffixed => isize,
920 unsuffixed_int_literals! {
922 u16_unsuffixed => u16,
923 u32_unsuffixed => u32,
924 u64_unsuffixed => u64,
925 u128_unsuffixed => u128,
926 usize_unsuffixed => usize,
928 i16_unsuffixed => i16,
929 i32_unsuffixed => i32,
930 i64_unsuffixed => i64,
931 i128_unsuffixed => i128,
932 isize_unsuffixed => isize,
935 /// Creates a new unsuffixed floating-point literal.
937 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
938 /// the float's value is emitted directly into the token but no suffix is
939 /// used, so it may be inferred to be a `f64` later in the compiler.
940 /// Literals created from negative numbers might not survive rountrips through
941 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
945 /// This function requires that the specified float is finite, for
946 /// example if it is infinity or NaN this function will panic.
947 pub fn f32_unsuffixed(n: f32) -> Literal {
949 panic!("Invalid float literal {n}");
951 let mut repr = n.to_string();
952 if !repr.contains('.') {
955 Literal(bridge::client::Literal::float(&repr))
958 /// Creates a new suffixed floating-point literal.
960 /// This constructor will create a literal like `1.0f32` where the value
961 /// specified is the preceding part of the token and `f32` is the suffix of
962 /// the token. This token will always be inferred to be an `f32` in the
964 /// Literals created from negative numbers might not survive rountrips through
965 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
969 /// This function requires that the specified float is finite, for
970 /// example if it is infinity or NaN this function will panic.
971 pub fn f32_suffixed(n: f32) -> Literal {
973 panic!("Invalid float literal {n}");
975 Literal(bridge::client::Literal::f32(&n.to_string()))
978 /// Creates a new unsuffixed floating-point literal.
980 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
981 /// the float's value is emitted directly into the token but no suffix is
982 /// used, so it may be inferred to be a `f64` later in the compiler.
983 /// Literals created from negative numbers might not survive rountrips through
984 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
988 /// This function requires that the specified float is finite, for
989 /// example if it is infinity or NaN this function will panic.
990 pub fn f64_unsuffixed(n: f64) -> Literal {
992 panic!("Invalid float literal {n}");
994 let mut repr = n.to_string();
995 if !repr.contains('.') {
998 Literal(bridge::client::Literal::float(&repr))
1001 /// Creates a new suffixed floating-point literal.
1003 /// This constructor will create a literal like `1.0f64` where the value
1004 /// specified is the preceding part of the token and `f64` is the suffix of
1005 /// the token. This token will always be inferred to be an `f64` in the
1007 /// Literals created from negative numbers might not survive rountrips through
1008 /// `TokenStream` or strings and may be broken into two tokens (`-` and positive literal).
1012 /// This function requires that the specified float is finite, for
1013 /// example if it is infinity or NaN this function will panic.
1014 pub fn f64_suffixed(n: f64) -> Literal {
1016 panic!("Invalid float literal {n}");
1018 Literal(bridge::client::Literal::f64(&n.to_string()))
1022 pub fn string(string: &str) -> Literal {
1023 Literal(bridge::client::Literal::string(string))
1026 /// Character literal.
1027 pub fn character(ch: char) -> Literal {
1028 Literal(bridge::client::Literal::character(ch))
1031 /// Byte string literal.
1032 pub fn byte_string(bytes: &[u8]) -> Literal {
1033 Literal(bridge::client::Literal::byte_string(bytes))
1036 /// Returns the span encompassing this literal.
1037 pub fn span(&self) -> Span {
1041 /// Configures the span associated for this literal.
1042 pub fn set_span(&mut self, span: Span) {
1043 self.0.set_span(span.0);
1046 /// Returns a `Span` that is a subset of `self.span()` containing only the
1047 /// source bytes in range `range`. Returns `None` if the would-be trimmed
1048 /// span is outside the bounds of `self`.
1049 // FIXME(SergioBenitez): check that the byte range starts and ends at a
1050 // UTF-8 boundary of the source. otherwise, it's likely that a panic will
1051 // occur elsewhere when the source text is printed.
1052 // FIXME(SergioBenitez): there is no way for the user to know what
1053 // `self.span()` actually maps to, so this method can currently only be
1054 // called blindly. For example, `to_string()` for the character 'c' returns
1055 // "'\u{63}'"; there is no way for the user to know whether the source text
1056 // was 'c' or whether it was '\u{63}'.
1057 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1058 self.0.subspan(range.start_bound().cloned(), range.end_bound().cloned()).map(Span)
1062 /// Parse a single literal from its stringified representation.
1064 /// In order to parse successfully, the input string must not contain anything
1065 /// but the literal token. Specifically, it must not contain whitespace or
1066 /// comments in addition to the literal.
1068 /// The resulting literal token will have a `Span::call_site()` span.
1070 /// NOTE: some errors may cause panics instead of returning `LexError`. We
1071 /// reserve the right to change these errors into `LexError`s later.
1072 impl FromStr for Literal {
1073 type Err = LexError;
1075 fn from_str(src: &str) -> Result<Self, LexError> {
1076 match bridge::client::Literal::from_str(src) {
1077 Ok(literal) => Ok(Literal(literal)),
1078 Err(()) => Err(LexError),
1083 /// Prints the literal as a string that should be losslessly convertible
1084 /// back into the same literal (except for possible rounding for floating point literals).
1085 impl fmt::Display for Literal {
1086 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1087 f.write_str(&self.to_string())
1091 impl fmt::Debug for Literal {
1092 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1097 /// Tracked access to environment variables.
1098 pub mod tracked_env {
1099 use std::env::{self, VarError};
1100 use std::ffi::OsStr;
1102 /// Retrieve an environment variable and add it to build dependency info.
1103 /// Build system executing the compiler will know that the variable was accessed during
1104 /// compilation, and will be able to rerun the build when the value of that variable changes.
1105 /// Besides the dependency tracking this function should be equivalent to `env::var` from the
1106 /// standard library, except that the argument must be UTF-8.
1107 pub fn var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1108 let key: &str = key.as_ref();
1109 let value = env::var(key);
1110 super::bridge::client::FreeFunctions::track_env_var(key, value.as_deref().ok());
1115 /// Tracked access to additional files.
1116 pub mod tracked_path {
1118 /// Track a file explicitly.
1120 /// Commonly used for tracking asset preprocessing.
1121 pub fn path<P: AsRef<str>>(path: P) {
1122 let path: &str = path.as_ref();
1123 super::bridge::client::FreeFunctions::track_path(path);