proc_macro0/lib.rs
1#![allow(
2 clippy::cast_lossless,
3 clippy::cast_possible_truncation,
4 clippy::doc_markdown,
5 clippy::items_after_statements,
6 clippy::manual_assert,
7 clippy::must_use_candidate,
8 clippy::needless_doctest_main,
9 clippy::return_self_not_must_use,
10 clippy::shadow_unrelated,
11 clippy::trivially_copy_pass_by_ref,
12 clippy::unnecessary_wraps,
13 clippy::unused_self,
14 clippy::used_underscore_binding,
15 clippy::vec_init_then_push
16)]
17#![warn(unsafe_code)]
18#![feature(doc_auto_cfg, doc_cfg)]
19
20mod fallback;
21mod incompatible;
22mod parse;
23
24use crate::fallback as imp;
25
26use std::error::Error;
27use std::fmt::{self, Debug, Display};
28use std::hash::{Hash, Hasher};
29use std::iter::FromIterator;
30use std::ops::RangeBounds;
31use std::str::FromStr;
32use std::{cmp::Ordering, path::PathBuf};
33
34/// An abstract stream of tokens, or more concretely a sequence of token trees.
35///
36/// This type provides interfaces for iterating over token trees and for
37/// collecting token trees into one stream.
38///
39/// Token stream is both the input and output of `#[proc_macro]`,
40/// `#[proc_macro_attribute]` and `#[proc_macro_derive]` definitions.
41#[derive(Clone)]
42pub struct TokenStream {
43 inner: imp::TokenStream,
44}
45
46/// Error returned from `TokenStream::from_str`.
47pub struct LexError {
48 inner: imp::LexError,
49}
50
51impl TokenStream {
52 fn _new(inner: imp::TokenStream) -> Self {
53 TokenStream { inner }
54 }
55
56 fn _new_stable(inner: fallback::TokenStream) -> Self {
57 TokenStream { inner }
58 }
59
60 /// Returns an empty `TokenStream` containing no token trees.
61 pub fn new() -> Self {
62 TokenStream::_new(imp::TokenStream::new())
63 }
64
65 /// Checks if this `TokenStream` is empty.
66 pub fn is_empty(&self) -> bool {
67 self.inner.is_empty()
68 }
69}
70
71/// `TokenStream::default()` returns an empty stream,
72/// i.e. this is equivalent with `TokenStream::new()`.
73impl Default for TokenStream {
74 fn default() -> Self {
75 TokenStream::new()
76 }
77}
78
79/// Attempts to break the string into tokens and parse those tokens into a token
80/// stream.
81///
82/// May fail for a number of reasons, for example, if the string contains
83/// unbalanced delimiters or characters not existing in the language.
84///
85/// NOTE: Some errors may cause panics instead of returning `LexError`. We
86/// reserve the right to change these errors into `LexError`s later.
87impl FromStr for TokenStream {
88 type Err = LexError;
89
90 fn from_str(src: &str) -> Result<TokenStream, LexError> {
91 let e = src.parse().map_err(|e| LexError { inner: e })?;
92 Ok(TokenStream::_new(e))
93 }
94}
95
96impl From<TokenTree> for TokenStream {
97 fn from(token: TokenTree) -> Self {
98 TokenStream::_new(imp::TokenStream::from(token))
99 }
100}
101
102impl Extend<TokenTree> for TokenStream {
103 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, streams: I) {
104 self.inner.extend(streams);
105 }
106}
107
108impl Extend<TokenStream> for TokenStream {
109 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
110 self.inner
111 .extend(streams.into_iter().map(|stream| stream.inner));
112 }
113}
114
115/// Collects a number of token trees into a single stream.
116impl FromIterator<TokenTree> for TokenStream {
117 fn from_iter<I: IntoIterator<Item = TokenTree>>(streams: I) -> Self {
118 TokenStream::_new(streams.into_iter().collect())
119 }
120}
121impl FromIterator<TokenStream> for TokenStream {
122 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
123 TokenStream::_new(streams.into_iter().map(|i| i.inner).collect())
124 }
125}
126
127/// Prints the token stream as a string that is supposed to be losslessly
128/// convertible back into the same token stream (modulo spans), except for
129/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
130/// numeric literals.
131impl Display for TokenStream {
132 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
133 Display::fmt(&self.inner, f)
134 }
135}
136
137/// Prints token in a form convenient for debugging.
138impl Debug for TokenStream {
139 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
140 Debug::fmt(&self.inner, f)
141 }
142}
143
144impl LexError {
145 pub fn span(&self) -> Span {
146 Span::_new(self.inner.span())
147 }
148}
149
150impl Debug for LexError {
151 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
152 Debug::fmt(&self.inner, f)
153 }
154}
155
156impl Display for LexError {
157 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
158 Display::fmt(&self.inner, f)
159 }
160}
161
162impl Error for LexError {}
163
164/// The source file of a given `Span`.
165#[derive(Clone, PartialEq, Eq)]
166pub struct SourceFile {
167 inner: imp::SourceFile,
168}
169
170impl SourceFile {
171 fn _new(inner: imp::SourceFile) -> Self {
172 SourceFile { inner }
173 }
174
175 /// Get the path to this source file.
176 ///
177 /// ### Note
178 ///
179 /// If the code span associated with this `SourceFile` was generated by an
180 /// external macro, this may not be an actual path on the filesystem. Use
181 /// [`is_real`] to check.
182 ///
183 /// Also note that even if `is_real` returns `true`, if
184 /// `--remap-path-prefix` was passed on the command line, the path as given
185 /// may not actually be valid.
186 ///
187 /// [`is_real`]: #method.is_real
188 pub fn path(&self) -> PathBuf {
189 self.inner.path()
190 }
191
192 /// Returns `true` if this source file is a real source file, and not
193 /// generated by an external macro's expansion.
194 pub fn is_real(&self) -> bool {
195 self.inner.is_real()
196 }
197}
198
199impl Debug for SourceFile {
200 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
201 Debug::fmt(&self.inner, f)
202 }
203}
204
205/// A line-column pair representing the start or end of a `Span`.
206#[derive(Copy, Clone, Debug, PartialEq, Eq)]
207pub struct LineColumn {
208 /// The 1-indexed line in the source file on which the span starts or ends
209 /// (inclusive).
210 pub line: usize,
211 /// The 0-indexed column (in UTF-8 characters) in the source file on which
212 /// the span starts or ends (inclusive).
213 pub column: usize,
214}
215
216impl Ord for LineColumn {
217 fn cmp(&self, other: &Self) -> Ordering {
218 self.line
219 .cmp(&other.line)
220 .then(self.column.cmp(&other.column))
221 }
222}
223
224impl PartialOrd for LineColumn {
225 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
226 Some(self.cmp(other))
227 }
228}
229
230/// A region of source code, along with macro expansion information.
231#[derive(Copy, Clone, PartialEq, Eq)]
232pub struct Span {
233 inner: imp::Span,
234}
235
236impl Span {
237 fn _new(inner: imp::Span) -> Self {
238 Span { inner }
239 }
240
241 fn _new_stable(inner: fallback::Span) -> Self {
242 Span { inner }
243 }
244
245 /// The span of the invocation of the current procedural macro.
246 ///
247 /// Identifiers created with this span will be resolved as if they were
248 /// written directly at the macro call location (call-site hygiene) and
249 /// other code at the macro call site will be able to refer to them as well.
250 pub fn call_site() -> Self {
251 Span::_new(imp::Span::call_site())
252 }
253
254 /// The span located at the invocation of the procedural macro, but with
255 /// local variables, labels, and `$crate` resolved at the definition site
256 /// of the macro. This is the same hygiene behavior as `macro_rules`.
257 ///
258 /// This function requires Rust 1.45 or later.
259 pub fn mixed_site() -> Self {
260 Span::_new(imp::Span::mixed_site())
261 }
262
263 /// A span that resolves at the macro definition site.
264
265 pub fn def_site() -> Self {
266 Span::_new(imp::Span::def_site())
267 }
268
269 /// Creates a new span with the same line/column information as `self` but
270 /// that resolves symbols as though it were at `other`.
271 pub fn resolved_at(&self, other: Span) -> Span {
272 Span::_new(self.inner.resolved_at(other.inner))
273 }
274
275 /// Creates a new span with the same name resolution behavior as `self` but
276 /// with the line/column information of `other`.
277 pub fn located_at(&self, other: Span) -> Span {
278 Span::_new(self.inner.located_at(other.inner))
279 }
280
281 /// The original source file into which this span points.
282
283 pub fn source_file(&self) -> SourceFile {
284 SourceFile::_new(self.inner.source_file())
285 }
286
287 /// Get the starting line/column in the source file for this span.
288 ///
289 /// When executing in a procedural macro context, the returned line/column
290 /// are only meaningful if compiled with a nightly toolchain. The stable
291 /// toolchain does not have this information available. When executing
292 /// outside of a procedural macro, such as main.rs or build.rs, the
293 /// line/column are always meaningful regardless of toolchain.
294 pub fn start(&self) -> LineColumn {
295 let imp::LineColumn { line, column } = self.inner.start();
296 LineColumn { line, column }
297 }
298
299 /// Get the ending line/column in the source file for this span.
300 ///
301 /// When executing in a procedural macro context, the returned line/column
302 /// are only meaningful if compiled with a nightly toolchain. The stable
303 /// toolchain does not have this information available. When executing
304 /// outside of a procedural macro, such as main.rs or build.rs, the
305 /// line/column are always meaningful regardless of toolchain.
306 pub fn end(&self) -> LineColumn {
307 let imp::LineColumn { line, column } = self.inner.end();
308 LineColumn { line, column }
309 }
310
311 /// Create a new span encompassing `self` and `other`.
312 ///
313 /// Returns `None` if `self` and `other` are from different files.
314 pub fn join(&self, other: Span) -> Option<Span> {
315 self.inner.join(other.inner).map(Span::_new)
316 }
317
318 #[doc(hidden)]
319 #[allow(clippy::should_implement_trait)]
320 /// Compares two spans to see if they're equal.
321 pub fn eq(&self, other: &Span) -> bool {
322 self == other
323 }
324}
325
326/// Prints a span in a form convenient for debugging.
327impl Debug for Span {
328 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
329 Debug::fmt(&self.inner, f)
330 }
331}
332
333/// A single token or a delimited sequence of token trees (e.g. `[1, (), ..]`).
334#[derive(Clone)]
335pub enum TokenTree {
336 /// A token stream surrounded by bracket delimiters.
337 Group(Group),
338 /// An identifier.
339 Ident(Ident),
340 /// A single punctuation character (`+`, `,`, `$`, etc.).
341 Punct(Punct),
342 /// A literal character (`'a'`), string (`"hello"`), number (`2.3`), etc.
343 Literal(Literal),
344}
345
346impl TokenTree {
347 /// Returns the span of this tree, delegating to the `span` method of
348 /// the contained token or a delimited stream.
349 pub fn span(&self) -> Span {
350 match self {
351 TokenTree::Group(t) => t.span(),
352 TokenTree::Ident(t) => t.span(),
353 TokenTree::Punct(t) => t.span(),
354 TokenTree::Literal(t) => t.span(),
355 }
356 }
357
358 /// Configures the span for *only this token*.
359 ///
360 /// Note that if this token is a `Group` then this method will not configure
361 /// the span of each of the internal tokens, this will simply delegate to
362 /// the `set_span` method of each variant.
363 pub fn set_span(&mut self, span: Span) {
364 match self {
365 TokenTree::Group(t) => t.set_span(span),
366 TokenTree::Ident(t) => t.set_span(span),
367 TokenTree::Punct(t) => t.set_span(span),
368 TokenTree::Literal(t) => t.set_span(span),
369 }
370 }
371}
372
373impl From<Group> for TokenTree {
374 fn from(g: Group) -> TokenTree {
375 TokenTree::Group(g)
376 }
377}
378
379impl From<Ident> for TokenTree {
380 fn from(g: Ident) -> TokenTree {
381 TokenTree::Ident(g)
382 }
383}
384
385impl From<Punct> for TokenTree {
386 fn from(g: Punct) -> TokenTree {
387 TokenTree::Punct(g)
388 }
389}
390
391impl From<Literal> for TokenTree {
392 fn from(g: Literal) -> TokenTree {
393 TokenTree::Literal(g)
394 }
395}
396
397/// Prints the token tree as a string that is supposed to be losslessly
398/// convertible back into the same token tree (modulo spans), except for
399/// possibly `TokenTree::Group`s with `Delimiter::None` delimiters and negative
400/// numeric literals.
401impl Display for TokenTree {
402 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
403 match self {
404 TokenTree::Group(t) => Display::fmt(t, f),
405 TokenTree::Ident(t) => Display::fmt(t, f),
406 TokenTree::Punct(t) => Display::fmt(t, f),
407 TokenTree::Literal(t) => Display::fmt(t, f),
408 }
409 }
410}
411
412/// Prints token tree in a form convenient for debugging.
413impl Debug for TokenTree {
414 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
415 // Each of these has the name in the struct type in the derived debug,
416 // so don't bother with an extra layer of indirection
417 match self {
418 TokenTree::Group(t) => Debug::fmt(t, f),
419 TokenTree::Ident(t) => {
420 let mut debug = f.debug_struct("Ident");
421 debug.field("sym", &format_args!("{}", t));
422 imp::debug_span_field_if_nontrivial(&mut debug, t.span().inner);
423 debug.finish()
424 }
425 TokenTree::Punct(t) => Debug::fmt(t, f),
426 TokenTree::Literal(t) => Debug::fmt(t, f),
427 }
428 }
429}
430
431/// A delimited token stream.
432///
433/// A `Group` internally contains a `TokenStream` which is surrounded by
434/// `Delimiter`s.
435#[derive(Clone)]
436pub struct Group {
437 inner: imp::Group,
438}
439
440/// Describes how a sequence of token trees is delimited.
441#[derive(Copy, Clone, Debug, Eq, PartialEq)]
442pub enum Delimiter {
443 /// `( ... )`
444 Parenthesis,
445 /// `{ ... }`
446 Brace,
447 /// `[ ... ]`
448 Bracket,
449 /// `Ø ... Ø`
450 ///
451 /// An implicit delimiter, that may, for example, appear around tokens
452 /// coming from a "macro variable" `$var`. It is important to preserve
453 /// operator priorities in cases like `$var * 3` where `$var` is `1 + 2`.
454 /// Implicit delimiters may not survive roundtrip of a token stream through
455 /// a string.
456 None,
457}
458
459impl Group {
460 fn _new(inner: imp::Group) -> Self {
461 Group { inner }
462 }
463
464 fn _new_stable(inner: fallback::Group) -> Self {
465 Group { inner }
466 }
467
468 /// Creates a new `Group` with the given delimiter and token stream.
469 ///
470 /// This constructor will set the span for this group to
471 /// `Span::call_site()`. To change the span you can use the `set_span`
472 /// method below.
473 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Self {
474 Group {
475 inner: imp::Group::new(delimiter, stream.inner),
476 }
477 }
478
479 /// Returns the delimiter of this `Group`
480 pub fn delimiter(&self) -> Delimiter {
481 self.inner.delimiter()
482 }
483
484 /// Returns the `TokenStream` of tokens that are delimited in this `Group`.
485 ///
486 /// Note that the returned token stream does not include the delimiter
487 /// returned above.
488 pub fn stream(&self) -> TokenStream {
489 TokenStream::_new(self.inner.stream())
490 }
491
492 /// Returns the span for the delimiters of this token stream, spanning the
493 /// entire `Group`.
494 ///
495 /// ```text
496 /// pub fn span(&self) -> Span {
497 /// ^^^^^^^
498 /// ```
499 pub fn span(&self) -> Span {
500 Span::_new(self.inner.span())
501 }
502
503 /// Returns the span pointing to the opening delimiter of this group.
504 ///
505 /// ```text
506 /// pub fn span_open(&self) -> Span {
507 /// ^
508 /// ```
509 pub fn span_open(&self) -> Span {
510 Span::_new(self.inner.span_open())
511 }
512
513 /// Returns the span pointing to the closing delimiter of this group.
514 ///
515 /// ```text
516 /// pub fn span_close(&self) -> Span {
517 /// ^
518 /// ```
519 pub fn span_close(&self) -> Span {
520 Span::_new(self.inner.span_close())
521 }
522
523 /// Configures the span for this `Group`'s delimiters, but not its internal
524 /// tokens.
525 ///
526 /// This method will **not** set the span of all the internal tokens spanned
527 /// by this group, but rather it will only set the span of the delimiter
528 /// tokens at the level of the `Group`.
529 pub fn set_span(&mut self, span: Span) {
530 self.inner.set_span(span.inner);
531 }
532}
533
534/// Prints the group as a string that should be losslessly convertible back
535/// into the same group (modulo spans), except for possibly `TokenTree::Group`s
536/// with `Delimiter::None` delimiters.
537impl Display for Group {
538 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
539 Display::fmt(&self.inner, formatter)
540 }
541}
542
543impl Debug for Group {
544 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
545 Debug::fmt(&self.inner, formatter)
546 }
547}
548
549/// A `Punct` is a single punctuation character like `+`, `-` or `#`.
550///
551/// Multicharacter operators like `+=` are represented as two instances of
552/// `Punct` with different forms of `Spacing` returned.
553#[derive(Clone)]
554pub struct Punct {
555 ch: char,
556 spacing: Spacing,
557 span: Span,
558}
559
560/// Whether a `Punct` is followed immediately by another `Punct` or followed by
561/// another token or whitespace.
562#[derive(Copy, Clone, Debug, Eq, PartialEq)]
563pub enum Spacing {
564 /// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`.
565 Alone,
566 /// E.g. `+` is `Joint` in `+=` or `'` is `Joint` in `'#`.
567 ///
568 /// Additionally, single quote `'` can join with identifiers to form
569 /// lifetimes `'ident`.
570 Joint,
571}
572
573impl Punct {
574 /// Creates a new `Punct` from the given character and spacing.
575 ///
576 /// The `ch` argument must be a valid punctuation character permitted by the
577 /// language, otherwise the function will panic.
578 ///
579 /// The returned `Punct` will have the default span of `Span::call_site()`
580 /// which can be further configured with the `set_span` method below.
581 pub fn new(ch: char, spacing: Spacing) -> Self {
582 Punct {
583 ch,
584 spacing,
585 span: Span::call_site(),
586 }
587 }
588
589 /// Returns the value of this punctuation character as `char`.
590 pub fn as_char(&self) -> char {
591 self.ch
592 }
593
594 /// Returns the spacing of this punctuation character, indicating whether
595 /// it's immediately followed by another `Punct` in the token stream, so
596 /// they can potentially be combined into a multicharacter operator
597 /// (`Joint`), or it's followed by some other token or whitespace (`Alone`)
598 /// so the operator has certainly ended.
599 pub fn spacing(&self) -> Spacing {
600 self.spacing
601 }
602
603 /// Returns the span for this punctuation character.
604 pub fn span(&self) -> Span {
605 self.span
606 }
607
608 /// Configure the span for this punctuation character.
609 pub fn set_span(&mut self, span: Span) {
610 self.span = span;
611 }
612}
613
614/// Prints the punctuation character as a string that should be losslessly
615/// convertible back into the same character.
616impl Display for Punct {
617 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
618 Display::fmt(&self.ch, f)
619 }
620}
621
622impl Debug for Punct {
623 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
624 let mut debug = fmt.debug_struct("Punct");
625 debug.field("char", &self.ch);
626 debug.field("spacing", &self.spacing);
627 imp::debug_span_field_if_nontrivial(&mut debug, self.span.inner);
628 debug.finish()
629 }
630}
631
632/// A word of Rust code, which may be a keyword or legal variable name.
633///
634/// An identifier consists of at least one Unicode code point, the first of
635/// which has the XID_Start property and the rest of which have the XID_Continue
636/// property.
637///
638/// - The empty string is not an identifier. Use `Option<Ident>`.
639/// - A lifetime is not an identifier. Use `syn::Lifetime` instead.
640///
641/// An identifier constructed with `Ident::new` is permitted to be a Rust
642/// keyword, though parsing one through its [`Parse`] implementation rejects
643/// Rust keywords. Use `input.call(Ident::parse_any)` when parsing to match the
644/// behaviour of `Ident::new`.
645///
646/// [`Parse`]: https://docs.rs/syn/1.0/syn/parse/trait.Parse.html
647///
648/// # Examples
649///
650/// A new ident can be created from a string using the `Ident::new` function.
651/// A span must be provided explicitly which governs the name resolution
652/// behavior of the resulting identifier.
653///
654/// ```
655/// use proc_macro0::{Ident, Span};
656///
657/// fn main() {
658/// let call_ident = Ident::new("calligraphy", Span::call_site());
659///
660/// println!("{}", call_ident);
661/// }
662/// ```
663///
664/// A string representation of the ident is available through the `to_string()`
665/// method.
666///
667/// ```
668/// # use proc_macro0::{Ident, Span};
669/// #
670/// # let ident = Ident::new("another_identifier", Span::call_site());
671/// #
672/// // Examine the ident as a string.
673/// let ident_string = ident.to_string();
674/// if ident_string.len() > 60 {
675/// println!("Very long identifier: {}", ident_string)
676/// }
677/// ```
678#[derive(Clone)]
679pub struct Ident {
680 inner: imp::Ident,
681}
682
683impl Ident {
684 fn _new(inner: imp::Ident) -> Self {
685 Ident { inner }
686 }
687
688 /// Creates a new `Ident` with the given `string` as well as the specified
689 /// `span`.
690 ///
691 /// The `string` argument must be a valid identifier permitted by the
692 /// language, otherwise the function will panic.
693 ///
694 /// Note that `span`, currently in rustc, configures the hygiene information
695 /// for this identifier.
696 ///
697 /// As of this time `Span::call_site()` explicitly opts-in to "call-site"
698 /// hygiene meaning that identifiers created with this span will be resolved
699 /// as if they were written directly at the location of the macro call, and
700 /// other code at the macro call site will be able to refer to them as well.
701 ///
702 /// Later spans like `Span::def_site()` will allow to opt-in to
703 /// "definition-site" hygiene meaning that identifiers created with this
704 /// span will be resolved at the location of the macro definition and other
705 /// code at the macro call site will not be able to refer to them.
706 ///
707 /// Due to the current importance of hygiene this constructor, unlike other
708 /// tokens, requires a `Span` to be specified at construction.
709 ///
710 /// # Panics
711 ///
712 /// Panics if the input string is neither a keyword nor a legal variable
713 /// name. If you are not sure whether the string contains an identifier and
714 /// need to handle an error case, use
715 /// <a href="https://docs.rs/syn/1.0/syn/fn.parse_str.html"><code
716 /// style="padding-right:0;">syn::parse_str</code></a><code
717 /// style="padding-left:0;">::<Ident></code>
718 /// rather than `Ident::new`.
719 pub fn new(string: &str, span: Span) -> Self {
720 Ident::_new(imp::Ident::new(string, span.inner))
721 }
722
723 /// Same as `Ident::new`, but creates a raw identifier (`r#ident`). The
724 /// `string` argument must be a valid identifier permitted by the language
725 /// (including keywords, e.g. `fn`). Keywords which are usable in path
726 /// segments (e.g. `self`, `super`) are not supported, and will cause a
727 /// panic.
728 pub fn new_raw(string: &str, span: Span) -> Self {
729 Ident::_new_raw(string, span)
730 }
731
732 fn _new_raw(string: &str, span: Span) -> Self {
733 Ident::_new(imp::Ident::new_raw(string, span.inner))
734 }
735
736 /// Returns the span of this `Ident`.
737 pub fn span(&self) -> Span {
738 Span::_new(self.inner.span())
739 }
740
741 /// Configures the span of this `Ident`, possibly changing its hygiene
742 /// context.
743 pub fn set_span(&mut self, span: Span) {
744 self.inner.set_span(span.inner);
745 }
746}
747
748impl PartialEq for Ident {
749 fn eq(&self, other: &Ident) -> bool {
750 self.inner == other.inner
751 }
752}
753
754impl<T> PartialEq<T> for Ident
755where
756 T: ?Sized + AsRef<str>,
757{
758 fn eq(&self, other: &T) -> bool {
759 self.inner == other
760 }
761}
762
763impl Eq for Ident {}
764
765impl PartialOrd for Ident {
766 fn partial_cmp(&self, other: &Ident) -> Option<Ordering> {
767 Some(self.cmp(other))
768 }
769}
770
771impl Ord for Ident {
772 fn cmp(&self, other: &Ident) -> Ordering {
773 self.to_string().cmp(&other.to_string())
774 }
775}
776
777impl Hash for Ident {
778 fn hash<H: Hasher>(&self, hasher: &mut H) {
779 self.to_string().hash(hasher);
780 }
781}
782
783/// Prints the identifier as a string that should be losslessly convertible back
784/// into the same identifier.
785impl Display for Ident {
786 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
787 Display::fmt(&self.inner, f)
788 }
789}
790
791impl Debug for Ident {
792 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
793 Debug::fmt(&self.inner, f)
794 }
795}
796
797/// A literal string (`"hello"`), byte string (`b"hello"`), character (`'a'`),
798/// byte character (`b'a'`), an integer or floating point number with or without
799/// a suffix (`1`, `1u8`, `2.3`, `2.3f32`).
800///
801/// Boolean literals like `true` and `false` do not belong here, they are
802/// `Ident`s.
803#[derive(Clone)]
804pub struct Literal {
805 inner: imp::Literal,
806}
807
808macro_rules! suffixed_int_literals {
809 ($($name:ident => $kind:ident,)*) => ($(
810 /// Creates a new suffixed integer literal with the specified value.
811 ///
812 /// This function will create an integer like `1u32` where the integer
813 /// value specified is the first part of the token and the integral is
814 /// also suffixed at the end. Literals created from negative numbers may
815 /// not survive roundtrips through `TokenStream` or strings and may be
816 /// broken into two tokens (`-` and positive literal).
817 ///
818 /// Literals created through this method have the `Span::call_site()`
819 /// span by default, which can be configured with the `set_span` method
820 /// below.
821 pub fn $name(n: $kind) -> Literal {
822 Literal::_new(imp::Literal::$name(n))
823 }
824 )*)
825}
826
827macro_rules! unsuffixed_int_literals {
828 ($($name:ident => $kind:ident,)*) => ($(
829 /// Creates a new unsuffixed integer literal with the specified value.
830 ///
831 /// This function will create an integer like `1` where the integer
832 /// value specified is the first part of the token. No suffix is
833 /// specified on this token, meaning that invocations like
834 /// `Literal::i8_unsuffixed(1)` are equivalent to
835 /// `Literal::u32_unsuffixed(1)`. Literals created from negative numbers
836 /// may not survive roundtrips through `TokenStream` or strings and may
837 /// be broken into two tokens (`-` and positive literal).
838 ///
839 /// Literals created through this method have the `Span::call_site()`
840 /// span by default, which can be configured with the `set_span` method
841 /// below.
842 pub fn $name(n: $kind) -> Literal {
843 Literal::_new(imp::Literal::$name(n))
844 }
845 )*)
846}
847
848impl Literal {
849 fn _new(inner: imp::Literal) -> Self {
850 Literal { inner }
851 }
852
853 fn _new_stable(inner: fallback::Literal) -> Self {
854 Literal { inner }
855 }
856
857 suffixed_int_literals! {
858 u8_suffixed => u8,
859 u16_suffixed => u16,
860 u32_suffixed => u32,
861 u64_suffixed => u64,
862 u128_suffixed => u128,
863 usize_suffixed => usize,
864 i8_suffixed => i8,
865 i16_suffixed => i16,
866 i32_suffixed => i32,
867 i64_suffixed => i64,
868 i128_suffixed => i128,
869 isize_suffixed => isize,
870 }
871
872 unsuffixed_int_literals! {
873 u8_unsuffixed => u8,
874 u16_unsuffixed => u16,
875 u32_unsuffixed => u32,
876 u64_unsuffixed => u64,
877 u128_unsuffixed => u128,
878 usize_unsuffixed => usize,
879 i8_unsuffixed => i8,
880 i16_unsuffixed => i16,
881 i32_unsuffixed => i32,
882 i64_unsuffixed => i64,
883 i128_unsuffixed => i128,
884 isize_unsuffixed => isize,
885 }
886
887 /// Creates a new unsuffixed floating-point literal.
888 ///
889 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
890 /// the float's value is emitted directly into the token but no suffix is
891 /// used, so it may be inferred to be a `f64` later in the compiler.
892 /// Literals created from negative numbers may not survive roundtrips through
893 /// `TokenStream` or strings and may be broken into two tokens (`-` and
894 /// positive literal).
895 ///
896 /// # Panics
897 ///
898 /// This function requires that the specified float is finite, for example
899 /// if it is infinity or NaN this function will panic.
900 pub fn f64_unsuffixed(f: f64) -> Literal {
901 assert!(f.is_finite());
902 Literal::_new(imp::Literal::f64_unsuffixed(f))
903 }
904
905 /// Creates a new suffixed floating-point literal.
906 ///
907 /// This constructor will create a literal like `1.0f64` where the value
908 /// specified is the preceding part of the token and `f64` is the suffix of
909 /// the token. This token will always be inferred to be an `f64` in the
910 /// compiler. Literals created from negative numbers may not survive
911 /// roundtrips through `TokenStream` or strings and may be broken into two
912 /// tokens (`-` and positive literal).
913 ///
914 /// # Panics
915 ///
916 /// This function requires that the specified float is finite, for example
917 /// if it is infinity or NaN this function will panic.
918 pub fn f64_suffixed(f: f64) -> Literal {
919 assert!(f.is_finite());
920 Literal::_new(imp::Literal::f64_suffixed(f))
921 }
922
923 /// Creates a new unsuffixed floating-point literal.
924 ///
925 /// This constructor is similar to those like `Literal::i8_unsuffixed` where
926 /// the float's value is emitted directly into the token but no suffix is
927 /// used, so it may be inferred to be a `f64` later in the compiler.
928 /// Literals created from negative numbers may not survive roundtrips through
929 /// `TokenStream` or strings and may be broken into two tokens (`-` and
930 /// positive literal).
931 ///
932 /// # Panics
933 ///
934 /// This function requires that the specified float is finite, for example
935 /// if it is infinity or NaN this function will panic.
936 pub fn f32_unsuffixed(f: f32) -> Literal {
937 assert!(f.is_finite());
938 Literal::_new(imp::Literal::f32_unsuffixed(f))
939 }
940
941 /// Creates a new suffixed floating-point literal.
942 ///
943 /// This constructor will create a literal like `1.0f32` where the value
944 /// specified is the preceding part of the token and `f32` is the suffix of
945 /// the token. This token will always be inferred to be an `f32` in the
946 /// compiler. Literals created from negative numbers may not survive
947 /// roundtrips through `TokenStream` or strings and may be broken into two
948 /// tokens (`-` and positive literal).
949 ///
950 /// # Panics
951 ///
952 /// This function requires that the specified float is finite, for example
953 /// if it is infinity or NaN this function will panic.
954 pub fn f32_suffixed(f: f32) -> Literal {
955 assert!(f.is_finite());
956 Literal::_new(imp::Literal::f32_suffixed(f))
957 }
958
959 /// String literal.
960 pub fn string(string: &str) -> Literal {
961 Literal::_new(imp::Literal::string(string))
962 }
963
964 /// Character literal.
965 pub fn character(ch: char) -> Literal {
966 Literal::_new(imp::Literal::character(ch))
967 }
968
969 /// Byte string literal.
970 pub fn byte_string(s: &[u8]) -> Literal {
971 Literal::_new(imp::Literal::byte_string(s))
972 }
973
974 /// Returns the span encompassing this literal.
975 pub fn span(&self) -> Span {
976 Span::_new(self.inner.span())
977 }
978
979 /// Configures the span associated for this literal.
980 pub fn set_span(&mut self, span: Span) {
981 self.inner.set_span(span.inner);
982 }
983
984 /// Returns a `Span` that is a subset of `self.span()` containing only
985 /// the source bytes in range `range`. Returns `None` if the would-be
986 /// trimmed span is outside the bounds of `self`.
987 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
988 self.inner.subspan(range).map(Span::_new)
989 }
990}
991
992impl FromStr for Literal {
993 type Err = LexError;
994
995 fn from_str(repr: &str) -> Result<Self, LexError> {
996 repr.parse()
997 .map(Literal::_new)
998 .map_err(|inner| LexError { inner })
999 }
1000}
1001
1002impl Debug for Literal {
1003 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1004 Debug::fmt(&self.inner, f)
1005 }
1006}
1007
1008impl Display for Literal {
1009 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1010 Display::fmt(&self.inner, f)
1011 }
1012}
1013
1014/// Public implementation details for the `TokenStream` type, such as iterators.
1015#[doc(hidden)]
1016pub mod token_stream {
1017 use crate::{imp, TokenTree};
1018 use std::fmt::{self, Debug};
1019
1020 pub use crate::TokenStream;
1021
1022 /// An iterator over `TokenStream`'s `TokenTree`s.
1023 ///
1024 /// The iteration is "shallow", e.g. the iterator doesn't recurse into
1025 /// delimited groups, and returns whole groups as token trees.
1026 #[derive(Clone)]
1027 pub struct IntoIter {
1028 inner: imp::TokenTreeIter,
1029 }
1030
1031 impl Iterator for IntoIter {
1032 type Item = TokenTree;
1033
1034 fn next(&mut self) -> Option<TokenTree> {
1035 self.inner.next()
1036 }
1037 }
1038
1039 impl Debug for IntoIter {
1040 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1041 Debug::fmt(&self.inner, f)
1042 }
1043 }
1044
1045 impl IntoIterator for TokenStream {
1046 type Item = TokenTree;
1047 type IntoIter = IntoIter;
1048
1049 fn into_iter(self) -> IntoIter {
1050 IntoIter {
1051 inner: self.inner.into_iter(),
1052 }
1053 }
1054 }
1055}