1#![stable(feature = "proc_macro_lib", since = "1.15.0")]
13#![deny(missing_docs)]
14#![doc(
15 html_playground_url = "https://play.rust-lang.org/",
16 issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/",
17 test(no_crate_inject, attr(deny(warnings))),
18 test(attr(allow(dead_code, deprecated, unused_variables, unused_mut)))
19)]
20#![doc(rust_logo)]
21#![feature(rustdoc_internals)]
22#![feature(staged_api)]
23#![feature(allow_internal_unstable)]
24#![feature(decl_macro)]
25#![feature(negative_impls)]
26#![feature(panic_can_unwind)]
27#![feature(restricted_std)]
28#![feature(rustc_attrs)]
29#![feature(extend_one)]
30#![feature(mem_conjure_zst)]
31#![feature(f16)]
32#![recursion_limit = "256"]
33#![allow(internal_features)]
34#![deny(ffi_unwind_calls)]
35#![allow(rustc::internal)] #![warn(rustdoc::unescaped_backticks)]
37#![warn(unreachable_pub)]
38#![deny(unsafe_op_in_unsafe_fn)]
39
40#[unstable(feature = "proc_macro_internals", issue = "none")]
41#[doc(hidden)]
42pub mod bridge;
43
44mod diagnostic;
45mod escape;
46mod to_tokens;
47
48use core::convert::From;
49use core::ops::BitOr;
50use std::borrow::Cow;
51use std::ffi::CStr;
52use std::ops::{Range, RangeBounds};
53use std::path::PathBuf;
54use std::str::FromStr;
55use std::{error, fmt};
56
57#[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
58pub use diagnostic::{Diagnostic, Level, MultiSpan};
59use rustc_literal_escaper::{
60 MixedUnit, unescape_byte, unescape_byte_str, unescape_c_str, unescape_char, unescape_str,
61};
62#[unstable(feature = "proc_macro_totokens", issue = "130977")]
63pub use to_tokens::ToTokens;
64
65use crate::bridge::client::Methods as BridgeMethods;
66use crate::escape::{EscapeOptions, escape_bytes};
67
68#[unstable(feature = "proc_macro_value", issue = "136652")]
70#[derive(Debug, PartialEq, Eq)]
71#[non_exhaustive]
72pub enum EscapeError {
73 ZeroChars,
75 MoreThanOneChar,
77
78 LoneSlash,
80 InvalidEscape,
82 BareCarriageReturn,
84 BareCarriageReturnInRawString,
86 EscapeOnlyChar,
88
89 TooShortHexEscape,
91 InvalidCharInHexEscape,
93 OutOfRangeHexEscape,
95
96 NoBraceInUnicodeEscape,
98 InvalidCharInUnicodeEscape,
100 EmptyUnicodeEscape,
102 UnclosedUnicodeEscape,
104 LeadingUnderscoreUnicodeEscape,
106 OverlongUnicodeEscape,
108 LoneSurrogateUnicodeEscape,
110 OutOfRangeUnicodeEscape,
112
113 UnicodeEscapeInByte,
115 NonAsciiCharInByte,
117
118 NulInCStr,
120
121 UnskippedWhitespaceWarning,
124
125 MultipleSkippedLinesWarning,
127}
128
129#[unstable(feature = "proc_macro_value", issue = "136652")]
130#[doc(hidden)]
131impl From<rustc_literal_escaper::EscapeError> for EscapeError {
132 fn from(value: rustc_literal_escaper::EscapeError) -> Self {
133 use rustc_literal_escaper::EscapeError as EE;
134
135 match value {
136 EE::ZeroChars => Self::ZeroChars,
137 EE::MoreThanOneChar => Self::MoreThanOneChar,
138 EE::LoneSlash => Self::LoneSlash,
139 EE::InvalidEscape => Self::InvalidEscape,
140 EE::BareCarriageReturn => Self::BareCarriageReturn,
141 EE::BareCarriageReturnInRawString => Self::BareCarriageReturnInRawString,
142 EE::EscapeOnlyChar => Self::EscapeOnlyChar,
143 EE::TooShortHexEscape => Self::TooShortHexEscape,
144 EE::InvalidCharInHexEscape => Self::InvalidCharInHexEscape,
145 EE::OutOfRangeHexEscape => Self::OutOfRangeHexEscape,
146 EE::NoBraceInUnicodeEscape => Self::NoBraceInUnicodeEscape,
147 EE::InvalidCharInUnicodeEscape => Self::InvalidCharInUnicodeEscape,
148 EE::EmptyUnicodeEscape => Self::EmptyUnicodeEscape,
149 EE::UnclosedUnicodeEscape => Self::UnclosedUnicodeEscape,
150 EE::LeadingUnderscoreUnicodeEscape => Self::LeadingUnderscoreUnicodeEscape,
151 EE::OverlongUnicodeEscape => Self::OverlongUnicodeEscape,
152 EE::LoneSurrogateUnicodeEscape => Self::LoneSurrogateUnicodeEscape,
153 EE::OutOfRangeUnicodeEscape => Self::OutOfRangeUnicodeEscape,
154 EE::UnicodeEscapeInByte => Self::UnicodeEscapeInByte,
155 EE::NonAsciiCharInByte => Self::NonAsciiCharInByte,
156 EE::NulInCStr => Self::NulInCStr,
157 EE::UnskippedWhitespaceWarning => Self::UnskippedWhitespaceWarning,
158 EE::MultipleSkippedLinesWarning => Self::MultipleSkippedLinesWarning,
159 }
160 }
161}
162
163#[unstable(feature = "proc_macro_value", issue = "136652")]
164impl error::Error for EscapeError {}
165
166#[unstable(feature = "proc_macro_value", issue = "136652")]
167impl fmt::Display for EscapeError {
168 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169 f.write_str(match self {
170 Self::ZeroChars => "zero chars",
171 Self::MoreThanOneChar => "more than one char",
172 Self::LoneSlash => "lone slash",
173 Self::InvalidEscape => "invalid escape",
174 Self::BareCarriageReturn => "bare carriage return",
175 Self::BareCarriageReturnInRawString => "bare carriage return in raw string",
176 Self::EscapeOnlyChar => "escape only char",
177 Self::TooShortHexEscape => "too short hex escape",
178 Self::InvalidCharInHexEscape => "invalid char in hex escape",
179 Self::OutOfRangeHexEscape => "out of range hex escape",
180 Self::NoBraceInUnicodeEscape => "no brace in unicode escape",
181 Self::InvalidCharInUnicodeEscape => "invalid char in unicode escape",
182 Self::EmptyUnicodeEscape => "empty unicode escape",
183 Self::UnclosedUnicodeEscape => "unclosed unicode escape",
184 Self::LeadingUnderscoreUnicodeEscape => "leading underscore unicode escape",
185 Self::OverlongUnicodeEscape => "overlong unicode escape",
186 Self::LoneSurrogateUnicodeEscape => "lone surrogate unicode escape",
187 Self::OutOfRangeUnicodeEscape => "out of range unicode escape",
188 Self::UnicodeEscapeInByte => "unicode escape in byte",
189 Self::NonAsciiCharInByte => "non ascii char in byte",
190 Self::NulInCStr => "nul in CStr",
191 Self::UnskippedWhitespaceWarning => "unskipped whitespace warning",
192 Self::MultipleSkippedLinesWarning => "multiple skipped lines warning",
193 })
194 }
195}
196
197#[unstable(feature = "proc_macro_value", issue = "136652")]
199#[derive(Debug, PartialEq, Eq)]
200#[non_exhaustive]
201pub enum ConversionErrorKind {
202 FailedToUnescape(EscapeError),
204 InvalidLiteralKind,
206}
207
208#[stable(feature = "proc_macro_is_available", since = "1.57.0")]
222pub fn is_available() -> bool {
223 bridge::client::is_available()
224}
225
226#[cfg_attr(feature = "rustc-dep-of-std", rustc_diagnostic_item = "TokenStream")]
234#[stable(feature = "proc_macro_lib", since = "1.15.0")]
235#[derive(Clone)]
236pub struct TokenStream(Option<bridge::client::TokenStream>);
237
238#[stable(feature = "proc_macro_lib", since = "1.15.0")]
239impl !Send for TokenStream {}
240#[stable(feature = "proc_macro_lib", since = "1.15.0")]
241impl !Sync for TokenStream {}
242
243#[stable(feature = "proc_macro_lib", since = "1.15.0")]
248#[non_exhaustive]
249#[derive(Debug)]
250pub struct LexError(String);
251
252#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
253impl fmt::Display for LexError {
254 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255 f.write_str(&self.0)
256 }
257}
258
259#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
260impl error::Error for LexError {}
261
262#[stable(feature = "proc_macro_lib", since = "1.15.0")]
263impl !Send for LexError {}
264#[stable(feature = "proc_macro_lib", since = "1.15.0")]
265impl !Sync for LexError {}
266
267#[unstable(feature = "proc_macro_expand", issue = "90765")]
269#[non_exhaustive]
270#[derive(Debug)]
271pub struct ExpandError;
272
273#[unstable(feature = "proc_macro_expand", issue = "90765")]
274impl fmt::Display for ExpandError {
275 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276 f.write_str("macro expansion failed")
277 }
278}
279
280#[unstable(feature = "proc_macro_expand", issue = "90765")]
281impl error::Error for ExpandError {}
282
283#[unstable(feature = "proc_macro_expand", issue = "90765")]
284impl !Send for ExpandError {}
285
286#[unstable(feature = "proc_macro_expand", issue = "90765")]
287impl !Sync for ExpandError {}
288
289impl TokenStream {
290 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
292 pub fn new() -> TokenStream {
293 TokenStream(None)
294 }
295
296 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
298 pub fn is_empty(&self) -> bool {
299 self.0.as_ref().map(BridgeMethods::ts_is_empty).unwrap_or(true)
300 }
301
302 #[unstable(feature = "proc_macro_expand", issue = "90765")]
313 pub fn expand_expr(&self) -> Result<TokenStream, ExpandError> {
314 let stream = self.0.as_ref().ok_or(ExpandError)?;
315 match BridgeMethods::ts_expand_expr(stream) {
316 Ok(stream) => Ok(TokenStream(Some(stream))),
317 Err(_) => Err(ExpandError),
318 }
319 }
320}
321
322#[stable(feature = "proc_macro_lib", since = "1.15.0")]
330impl FromStr for TokenStream {
331 type Err = LexError;
332
333 fn from_str(src: &str) -> Result<TokenStream, LexError> {
334 Ok(TokenStream(Some(BridgeMethods::ts_from_str(src).map_err(LexError)?)))
335 }
336}
337
338#[stable(feature = "proc_macro_lib", since = "1.15.0")]
350impl fmt::Display for TokenStream {
351 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
352 match &self.0 {
353 Some(ts) => write!(f, "{}", BridgeMethods::ts_to_string(ts)),
354 None => Ok(()),
355 }
356 }
357}
358
359#[stable(feature = "proc_macro_lib", since = "1.15.0")]
361impl fmt::Debug for TokenStream {
362 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
363 f.write_str("TokenStream ")?;
364 f.debug_list().entries(self.clone()).finish()
365 }
366}
367
368#[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
369impl Default for TokenStream {
370 fn default() -> Self {
371 TokenStream::new()
372 }
373}
374
375#[unstable(feature = "proc_macro_quote", issue = "54722")]
376pub use quote::{HasIterator, RepInterp, ThereIsNoIteratorInRepetition, ext, quote, quote_span};
377
378fn tree_to_bridge_tree(
379 tree: TokenTree,
380) -> bridge::TokenTree<bridge::client::TokenStream, bridge::client::Span, bridge::client::Symbol> {
381 match tree {
382 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
383 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
384 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
385 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
386 }
387}
388
389#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
391impl From<TokenTree> for TokenStream {
392 fn from(tree: TokenTree) -> TokenStream {
393 TokenStream(Some(BridgeMethods::ts_from_token_tree(tree_to_bridge_tree(tree))))
394 }
395}
396
397struct ConcatTreesHelper {
400 trees: Vec<
401 bridge::TokenTree<
402 bridge::client::TokenStream,
403 bridge::client::Span,
404 bridge::client::Symbol,
405 >,
406 >,
407}
408
409impl ConcatTreesHelper {
410 fn new(capacity: usize) -> Self {
411 ConcatTreesHelper { trees: Vec::with_capacity(capacity) }
412 }
413
414 fn push(&mut self, tree: TokenTree) {
415 self.trees.push(tree_to_bridge_tree(tree));
416 }
417
418 fn build(self) -> TokenStream {
419 if self.trees.is_empty() {
420 TokenStream(None)
421 } else {
422 TokenStream(Some(BridgeMethods::ts_concat_trees(None, self.trees)))
423 }
424 }
425
426 fn append_to(self, stream: &mut TokenStream) {
427 if self.trees.is_empty() {
428 return;
429 }
430 stream.0 = Some(BridgeMethods::ts_concat_trees(stream.0.take(), self.trees))
431 }
432}
433
434struct ConcatStreamsHelper {
437 streams: Vec<bridge::client::TokenStream>,
438}
439
440impl ConcatStreamsHelper {
441 fn new(capacity: usize) -> Self {
442 ConcatStreamsHelper { streams: Vec::with_capacity(capacity) }
443 }
444
445 fn push(&mut self, stream: TokenStream) {
446 if let Some(stream) = stream.0 {
447 self.streams.push(stream);
448 }
449 }
450
451 fn build(mut self) -> TokenStream {
452 if self.streams.len() <= 1 {
453 TokenStream(self.streams.pop())
454 } else {
455 TokenStream(Some(BridgeMethods::ts_concat_streams(None, self.streams)))
456 }
457 }
458
459 fn append_to(mut self, stream: &mut TokenStream) {
460 if self.streams.is_empty() {
461 return;
462 }
463 let base = stream.0.take();
464 if base.is_none() && self.streams.len() == 1 {
465 stream.0 = self.streams.pop();
466 } else {
467 stream.0 = Some(BridgeMethods::ts_concat_streams(base, self.streams));
468 }
469 }
470}
471
472#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
474impl FromIterator<TokenTree> for TokenStream {
475 fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
476 let iter = trees.into_iter();
477 let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
478 iter.for_each(|tree| builder.push(tree));
479 builder.build()
480 }
481}
482
483#[stable(feature = "proc_macro_lib", since = "1.15.0")]
486impl FromIterator<TokenStream> for TokenStream {
487 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
488 let iter = streams.into_iter();
489 let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
490 iter.for_each(|stream| builder.push(stream));
491 builder.build()
492 }
493}
494
495#[stable(feature = "token_stream_extend", since = "1.30.0")]
496impl Extend<TokenTree> for TokenStream {
497 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
498 let iter = trees.into_iter();
499 let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
500 iter.for_each(|tree| builder.push(tree));
501 builder.append_to(self);
502 }
503}
504
505#[stable(feature = "token_stream_extend", since = "1.30.0")]
506impl Extend<TokenStream> for TokenStream {
507 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
508 let iter = streams.into_iter();
509 let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
510 iter.for_each(|stream| builder.push(stream));
511 builder.append_to(self);
512 }
513}
514
515macro_rules! extend_items {
516 ($($item:ident)*) => {
517 $(
518 #[stable(feature = "token_stream_extend_ts_items", since = "1.92.0")]
519 impl Extend<$item> for TokenStream {
520 fn extend<T: IntoIterator<Item = $item>>(&mut self, iter: T) {
521 self.extend(iter.into_iter().map(TokenTree::$item));
522 }
523 }
524 )*
525 };
526}
527
528extend_items!(Group Literal Punct Ident);
529
530#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
532pub mod token_stream {
533 use crate::{BridgeMethods, Group, Ident, Literal, Punct, TokenStream, TokenTree, bridge};
534
535 #[derive(Clone)]
539 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
540 pub struct IntoIter(
541 std::vec::IntoIter<
542 bridge::TokenTree<
543 bridge::client::TokenStream,
544 bridge::client::Span,
545 bridge::client::Symbol,
546 >,
547 >,
548 );
549
550 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
551 impl Iterator for IntoIter {
552 type Item = TokenTree;
553
554 fn next(&mut self) -> Option<TokenTree> {
555 self.0.next().map(|tree| match tree {
556 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
557 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
558 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
559 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
560 })
561 }
562
563 fn size_hint(&self) -> (usize, Option<usize>) {
564 self.0.size_hint()
565 }
566
567 fn count(self) -> usize {
568 self.0.count()
569 }
570 }
571
572 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
573 impl IntoIterator for TokenStream {
574 type Item = TokenTree;
575 type IntoIter = IntoIter;
576
577 fn into_iter(self) -> IntoIter {
578 IntoIter(self.0.map(BridgeMethods::ts_into_trees).unwrap_or_default().into_iter())
579 }
580 }
581}
582
583#[unstable(feature = "proc_macro_quote", issue = "54722")]
590#[allow_internal_unstable(proc_macro_def_site, proc_macro_internals, proc_macro_totokens)]
591#[rustc_builtin_macro]
592pub macro quote($($t:tt)*) {
593 }
595
596#[unstable(feature = "proc_macro_internals", issue = "none")]
597#[doc(hidden)]
598mod quote;
599
600#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
602#[derive(Copy, Clone)]
603pub struct Span(bridge::client::Span);
604
605#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
606impl !Send for Span {}
607#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
608impl !Sync for Span {}
609
610macro_rules! diagnostic_method {
611 ($name:ident, $level:expr) => {
612 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
615 pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
616 Diagnostic::spanned(self, $level, message)
617 }
618 };
619}
620
621impl Span {
622 #[unstable(feature = "proc_macro_def_site", issue = "54724")]
624 pub fn def_site() -> Span {
625 Span(bridge::client::Span::def_site())
626 }
627
628 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
633 pub fn call_site() -> Span {
634 Span(bridge::client::Span::call_site())
635 }
636
637 #[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
642 pub fn mixed_site() -> Span {
643 Span(bridge::client::Span::mixed_site())
644 }
645
646 #[unstable(feature = "proc_macro_span", issue = "54725")]
649 pub fn parent(&self) -> Option<Span> {
650 BridgeMethods::span_parent(self.0).map(Span)
651 }
652
653 #[unstable(feature = "proc_macro_span", issue = "54725")]
657 pub fn source(&self) -> Span {
658 Span(BridgeMethods::span_source(self.0))
659 }
660
661 #[unstable(feature = "proc_macro_span", issue = "54725")]
663 pub fn byte_range(&self) -> Range<usize> {
664 BridgeMethods::span_byte_range(self.0)
665 }
666
667 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
669 pub fn start(&self) -> Span {
670 Span(BridgeMethods::span_start(self.0))
671 }
672
673 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
675 pub fn end(&self) -> Span {
676 Span(BridgeMethods::span_end(self.0))
677 }
678
679 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
683 pub fn line(&self) -> usize {
684 BridgeMethods::span_line(self.0)
685 }
686
687 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
691 pub fn column(&self) -> usize {
692 BridgeMethods::span_column(self.0)
693 }
694
695 #[stable(feature = "proc_macro_span_file", since = "1.88.0")]
700 pub fn file(&self) -> String {
701 BridgeMethods::span_file(self.0)
702 }
703
704 #[stable(feature = "proc_macro_span_file", since = "1.88.0")]
710 pub fn local_file(&self) -> Option<PathBuf> {
711 BridgeMethods::span_local_file(self.0).map(PathBuf::from)
712 }
713
714 #[unstable(feature = "proc_macro_span", issue = "54725")]
718 pub fn join(&self, other: Span) -> Option<Span> {
719 BridgeMethods::span_join(self.0, other.0).map(Span)
720 }
721
722 #[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
725 pub fn resolved_at(&self, other: Span) -> Span {
726 Span(BridgeMethods::span_resolved_at(self.0, other.0))
727 }
728
729 #[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
732 pub fn located_at(&self, other: Span) -> Span {
733 other.resolved_at(*self)
734 }
735
736 #[unstable(feature = "proc_macro_span", issue = "54725")]
738 pub fn eq(&self, other: &Span) -> bool {
739 self.0 == other.0
740 }
741
742 #[stable(feature = "proc_macro_source_text", since = "1.66.0")]
750 pub fn source_text(&self) -> Option<String> {
751 BridgeMethods::span_source_text(self.0)
752 }
753
754 #[doc(hidden)]
756 #[unstable(feature = "proc_macro_internals", issue = "none")]
757 pub fn save_span(&self) -> usize {
758 BridgeMethods::span_save_span(self.0)
759 }
760
761 #[doc(hidden)]
763 #[unstable(feature = "proc_macro_internals", issue = "none")]
764 pub fn recover_proc_macro_span(id: usize) -> Span {
765 Span(BridgeMethods::span_recover_proc_macro_span(id))
766 }
767
768 diagnostic_method!(error, Level::Error);
769 diagnostic_method!(warning, Level::Warning);
770 diagnostic_method!(note, Level::Note);
771 diagnostic_method!(help, Level::Help);
772}
773
774#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
776impl fmt::Debug for Span {
777 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
778 self.0.fmt(f)
779 }
780}
781
782#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
784#[derive(Clone)]
785pub enum TokenTree {
786 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
788 Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
789 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
791 Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
792 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
794 Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
795 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
797 Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
798}
799
800#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
801impl !Send for TokenTree {}
802#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
803impl !Sync for TokenTree {}
804
805impl TokenTree {
806 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
809 pub fn span(&self) -> Span {
810 match *self {
811 TokenTree::Group(ref t) => t.span(),
812 TokenTree::Ident(ref t) => t.span(),
813 TokenTree::Punct(ref t) => t.span(),
814 TokenTree::Literal(ref t) => t.span(),
815 }
816 }
817
818 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
824 pub fn set_span(&mut self, span: Span) {
825 match *self {
826 TokenTree::Group(ref mut t) => t.set_span(span),
827 TokenTree::Ident(ref mut t) => t.set_span(span),
828 TokenTree::Punct(ref mut t) => t.set_span(span),
829 TokenTree::Literal(ref mut t) => t.set_span(span),
830 }
831 }
832}
833
834#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
836impl fmt::Debug for TokenTree {
837 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
838 match *self {
841 TokenTree::Group(ref tt) => tt.fmt(f),
842 TokenTree::Ident(ref tt) => tt.fmt(f),
843 TokenTree::Punct(ref tt) => tt.fmt(f),
844 TokenTree::Literal(ref tt) => tt.fmt(f),
845 }
846 }
847}
848
849#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
850impl From<Group> for TokenTree {
851 fn from(g: Group) -> TokenTree {
852 TokenTree::Group(g)
853 }
854}
855
856#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
857impl From<Ident> for TokenTree {
858 fn from(g: Ident) -> TokenTree {
859 TokenTree::Ident(g)
860 }
861}
862
863#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
864impl From<Punct> for TokenTree {
865 fn from(g: Punct) -> TokenTree {
866 TokenTree::Punct(g)
867 }
868}
869
870#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
871impl From<Literal> for TokenTree {
872 fn from(g: Literal) -> TokenTree {
873 TokenTree::Literal(g)
874 }
875}
876
877#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
889impl fmt::Display for TokenTree {
890 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
891 match self {
892 TokenTree::Group(t) => write!(f, "{t}"),
893 TokenTree::Ident(t) => write!(f, "{t}"),
894 TokenTree::Punct(t) => write!(f, "{t}"),
895 TokenTree::Literal(t) => write!(f, "{t}"),
896 }
897 }
898}
899
900#[derive(Clone)]
904#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
905pub struct Group(bridge::Group<bridge::client::TokenStream, bridge::client::Span>);
906
907#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
908impl !Send for Group {}
909#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
910impl !Sync for Group {}
911
912#[derive(Copy, Clone, Debug, PartialEq, Eq)]
914#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
915pub enum Delimiter {
916 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
918 Parenthesis,
919 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
921 Brace,
922 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
924 Bracket,
925 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
943 None,
944}
945
946impl Group {
947 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
953 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
954 Group(bridge::Group {
955 delimiter,
956 stream: stream.0,
957 span: bridge::DelimSpan::from_single(Span::call_site().0),
958 })
959 }
960
961 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
963 pub fn delimiter(&self) -> Delimiter {
964 self.0.delimiter
965 }
966
967 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
972 pub fn stream(&self) -> TokenStream {
973 TokenStream(self.0.stream.clone())
974 }
975
976 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
984 pub fn span(&self) -> Span {
985 Span(self.0.span.entire)
986 }
987
988 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
995 pub fn span_open(&self) -> Span {
996 Span(self.0.span.open)
997 }
998
999 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
1006 pub fn span_close(&self) -> Span {
1007 Span(self.0.span.close)
1008 }
1009
1010 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1017 pub fn set_span(&mut self, span: Span) {
1018 self.0.span = bridge::DelimSpan::from_single(span.0);
1019 }
1020}
1021
1022#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1026impl fmt::Display for Group {
1027 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1028 write!(f, "{}", TokenStream::from(TokenTree::from(self.clone())))
1029 }
1030}
1031
1032#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1033impl fmt::Debug for Group {
1034 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1035 f.debug_struct("Group")
1036 .field("delimiter", &self.delimiter())
1037 .field("stream", &self.stream())
1038 .field("span", &self.span())
1039 .finish()
1040 }
1041}
1042
1043#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1048#[derive(Clone)]
1049pub struct Punct(bridge::Punct<bridge::client::Span>);
1050
1051#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1052impl !Send for Punct {}
1053#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1054impl !Sync for Punct {}
1055
1056#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1059#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1060pub enum Spacing {
1061 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1073 Joint,
1074 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1081 Alone,
1082}
1083
1084impl Punct {
1085 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1092 pub fn new(ch: char, spacing: Spacing) -> Punct {
1093 const LEGAL_CHARS: &[char] = &[
1094 '=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
1095 ':', '#', '$', '?', '\'',
1096 ];
1097 if !LEGAL_CHARS.contains(&ch) {
1098 panic!("unsupported character `{:?}`", ch);
1099 }
1100 Punct(bridge::Punct {
1101 ch: ch as u8,
1102 joint: spacing == Spacing::Joint,
1103 span: Span::call_site().0,
1104 })
1105 }
1106
1107 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1109 pub fn as_char(&self) -> char {
1110 self.0.ch as char
1111 }
1112
1113 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1117 pub fn spacing(&self) -> Spacing {
1118 if self.0.joint { Spacing::Joint } else { Spacing::Alone }
1119 }
1120
1121 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1123 pub fn span(&self) -> Span {
1124 Span(self.0.span)
1125 }
1126
1127 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1129 pub fn set_span(&mut self, span: Span) {
1130 self.0.span = span.0;
1131 }
1132}
1133
1134#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1137impl fmt::Display for Punct {
1138 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1139 write!(f, "{}", self.as_char())
1140 }
1141}
1142
1143#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1144impl fmt::Debug for Punct {
1145 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1146 f.debug_struct("Punct")
1147 .field("ch", &self.as_char())
1148 .field("spacing", &self.spacing())
1149 .field("span", &self.span())
1150 .finish()
1151 }
1152}
1153
1154#[stable(feature = "proc_macro_punct_eq", since = "1.50.0")]
1155impl PartialEq<char> for Punct {
1156 fn eq(&self, rhs: &char) -> bool {
1157 self.as_char() == *rhs
1158 }
1159}
1160
1161#[stable(feature = "proc_macro_punct_eq_flipped", since = "1.52.0")]
1162impl PartialEq<Punct> for char {
1163 fn eq(&self, rhs: &Punct) -> bool {
1164 *self == rhs.as_char()
1165 }
1166}
1167
1168#[derive(Clone)]
1170#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1171pub struct Ident(bridge::Ident<bridge::client::Span, bridge::client::Symbol>);
1172
1173impl Ident {
1174 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1198 pub fn new(string: &str, span: Span) -> Ident {
1199 Ident(bridge::Ident {
1200 sym: bridge::client::Symbol::new_ident(string, false),
1201 is_raw: false,
1202 span: span.0,
1203 })
1204 }
1205
1206 #[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
1211 pub fn new_raw(string: &str, span: Span) -> Ident {
1212 Ident(bridge::Ident {
1213 sym: bridge::client::Symbol::new_ident(string, true),
1214 is_raw: true,
1215 span: span.0,
1216 })
1217 }
1218
1219 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1222 pub fn span(&self) -> Span {
1223 Span(self.0.span)
1224 }
1225
1226 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1228 pub fn set_span(&mut self, span: Span) {
1229 self.0.span = span.0;
1230 }
1231}
1232
1233#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1236impl fmt::Display for Ident {
1237 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1238 if self.0.is_raw {
1239 f.write_str("r#")?;
1240 }
1241 fmt::Display::fmt(&self.0.sym, f)
1242 }
1243}
1244
1245#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1246impl fmt::Debug for Ident {
1247 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1248 f.debug_struct("Ident")
1249 .field("ident", &self.to_string())
1250 .field("span", &self.span())
1251 .finish()
1252 }
1253}
1254
1255#[derive(Clone)]
1260#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1261pub struct Literal(bridge::Literal<bridge::client::Span, bridge::client::Symbol>);
1262
1263macro_rules! suffixed_int_literals {
1264 ($($name:ident => $kind:ident,)*) => ($(
1265 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1277 pub fn $name(n: $kind) -> Literal {
1278 Literal(bridge::Literal {
1279 kind: bridge::LitKind::Integer,
1280 symbol: bridge::client::Symbol::new(&n.to_string()),
1281 suffix: Some(bridge::client::Symbol::new(stringify!($kind))),
1282 span: Span::call_site().0,
1283 })
1284 }
1285 )*)
1286}
1287
1288macro_rules! unsuffixed_int_literals {
1289 ($($name:ident => $kind:ident,)*) => ($(
1290 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1304 pub fn $name(n: $kind) -> Literal {
1305 Literal(bridge::Literal {
1306 kind: bridge::LitKind::Integer,
1307 symbol: bridge::client::Symbol::new(&n.to_string()),
1308 suffix: None,
1309 span: Span::call_site().0,
1310 })
1311 }
1312 )*)
1313}
1314
1315macro_rules! integer_values {
1316 ($($nb:ident => $fn_name:ident,)+) => {
1317 $(
1318 #[doc = concat!(
1319 "Returns the unescaped `",
1320 stringify!($nb),
1321 "` value if the literal is a `",
1322 stringify!($nb),
1323 "` or if it's an \"unmarked\" integer which doesn't overflow.")]
1324 #[unstable(feature = "proc_macro_value", issue = "136652")]
1325 pub fn $fn_name(&self) -> Result<$nb, ConversionErrorKind> {
1326 if self.0.kind != bridge::LitKind::Integer {
1327 return Err(ConversionErrorKind::InvalidLiteralKind);
1328 }
1329 self.with_symbol_and_suffix(|symbol, suffix| {
1330 match suffix {
1331 stringify!($nb) | "" => {
1332 let symbol = strip_underscores(symbol);
1333 let (number, base) = parse_number(&symbol);
1334 $nb::from_str_radix(&number, base as u32).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
1335 }
1336 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1337 }
1338 })
1339 }
1340 )+
1341 }
1342}
1343
1344macro_rules! float_values {
1345 ($($nb:ident => $fn_name:ident,)+) => {
1346 $(
1347 #[doc = concat!(
1348 "Returns the unescaped `",
1349 stringify!($nb),
1350 "` value if the literal is a `",
1351 stringify!($nb),
1352 "` or if it's an \"unmarked\" float which doesn't overflow.")]
1353 #[unstable(feature = "proc_macro_value", issue = "136652")]
1354 pub fn $fn_name(&self) -> Result<$nb, ConversionErrorKind> {
1355 if self.0.kind != bridge::LitKind::Float {
1356 return Err(ConversionErrorKind::InvalidLiteralKind);
1357 }
1358 self.with_symbol_and_suffix(|symbol, suffix| {
1359 match suffix {
1360 stringify!($nb) | "" => {
1361 let number = strip_underscores(symbol);
1362 $nb::from_str(&number).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
1363 }
1364 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1365 }
1366 })
1367 }
1368 )+
1369 }
1370}
1371
1372impl Literal {
1373 fn new(kind: bridge::LitKind, value: &str, suffix: Option<&str>) -> Self {
1374 Literal(bridge::Literal {
1375 kind,
1376 symbol: bridge::client::Symbol::new(value),
1377 suffix: suffix.map(bridge::client::Symbol::new),
1378 span: Span::call_site().0,
1379 })
1380 }
1381
1382 suffixed_int_literals! {
1383 u8_suffixed => u8,
1384 u16_suffixed => u16,
1385 u32_suffixed => u32,
1386 u64_suffixed => u64,
1387 u128_suffixed => u128,
1388 usize_suffixed => usize,
1389 i8_suffixed => i8,
1390 i16_suffixed => i16,
1391 i32_suffixed => i32,
1392 i64_suffixed => i64,
1393 i128_suffixed => i128,
1394 isize_suffixed => isize,
1395 }
1396
1397 unsuffixed_int_literals! {
1398 u8_unsuffixed => u8,
1399 u16_unsuffixed => u16,
1400 u32_unsuffixed => u32,
1401 u64_unsuffixed => u64,
1402 u128_unsuffixed => u128,
1403 usize_unsuffixed => usize,
1404 i8_unsuffixed => i8,
1405 i16_unsuffixed => i16,
1406 i32_unsuffixed => i32,
1407 i64_unsuffixed => i64,
1408 i128_unsuffixed => i128,
1409 isize_unsuffixed => isize,
1410 }
1411
1412 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1425 pub fn f32_unsuffixed(n: f32) -> Literal {
1426 if !n.is_finite() {
1427 panic!("Invalid float literal {n}");
1428 }
1429 let mut repr = n.to_string();
1430 if !repr.contains('.') {
1431 repr.push_str(".0");
1432 }
1433 Literal::new(bridge::LitKind::Float, &repr, None)
1434 }
1435
1436 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1450 pub fn f32_suffixed(n: f32) -> Literal {
1451 if !n.is_finite() {
1452 panic!("Invalid float literal {n}");
1453 }
1454 Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f32"))
1455 }
1456
1457 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1470 pub fn f64_unsuffixed(n: f64) -> Literal {
1471 if !n.is_finite() {
1472 panic!("Invalid float literal {n}");
1473 }
1474 let mut repr = n.to_string();
1475 if !repr.contains('.') {
1476 repr.push_str(".0");
1477 }
1478 Literal::new(bridge::LitKind::Float, &repr, None)
1479 }
1480
1481 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1495 pub fn f64_suffixed(n: f64) -> Literal {
1496 if !n.is_finite() {
1497 panic!("Invalid float literal {n}");
1498 }
1499 Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f64"))
1500 }
1501
1502 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1504 pub fn string(string: &str) -> Literal {
1505 let escape = EscapeOptions {
1506 escape_single_quote: false,
1507 escape_double_quote: true,
1508 escape_nonascii: false,
1509 };
1510 let repr = escape_bytes(string.as_bytes(), escape);
1511 Literal::new(bridge::LitKind::Str, &repr, None)
1512 }
1513
1514 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1516 pub fn character(ch: char) -> Literal {
1517 let escape = EscapeOptions {
1518 escape_single_quote: true,
1519 escape_double_quote: false,
1520 escape_nonascii: false,
1521 };
1522 let repr = escape_bytes(ch.encode_utf8(&mut [0u8; 4]).as_bytes(), escape);
1523 Literal::new(bridge::LitKind::Char, &repr, None)
1524 }
1525
1526 #[stable(feature = "proc_macro_byte_character", since = "1.79.0")]
1528 pub fn byte_character(byte: u8) -> Literal {
1529 let escape = EscapeOptions {
1530 escape_single_quote: true,
1531 escape_double_quote: false,
1532 escape_nonascii: true,
1533 };
1534 let repr = escape_bytes(&[byte], escape);
1535 Literal::new(bridge::LitKind::Byte, &repr, None)
1536 }
1537
1538 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1540 pub fn byte_string(bytes: &[u8]) -> Literal {
1541 let escape = EscapeOptions {
1542 escape_single_quote: false,
1543 escape_double_quote: true,
1544 escape_nonascii: true,
1545 };
1546 let repr = escape_bytes(bytes, escape);
1547 Literal::new(bridge::LitKind::ByteStr, &repr, None)
1548 }
1549
1550 #[stable(feature = "proc_macro_c_str_literals", since = "1.79.0")]
1552 pub fn c_string(string: &CStr) -> Literal {
1553 let escape = EscapeOptions {
1554 escape_single_quote: false,
1555 escape_double_quote: true,
1556 escape_nonascii: false,
1557 };
1558 let repr = escape_bytes(string.to_bytes(), escape);
1559 Literal::new(bridge::LitKind::CStr, &repr, None)
1560 }
1561
1562 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1564 pub fn span(&self) -> Span {
1565 Span(self.0.span)
1566 }
1567
1568 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1570 pub fn set_span(&mut self, span: Span) {
1571 self.0.span = span.0;
1572 }
1573
1574 #[unstable(feature = "proc_macro_span", issue = "54725")]
1586 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1587 BridgeMethods::span_subspan(
1588 self.0.span,
1589 range.start_bound().cloned(),
1590 range.end_bound().cloned(),
1591 )
1592 .map(Span)
1593 }
1594
1595 fn with_symbol_and_suffix<R>(&self, f: impl FnOnce(&str, &str) -> R) -> R {
1596 self.0.symbol.with(|symbol| match self.0.suffix {
1597 Some(suffix) => suffix.with(|suffix| f(symbol, suffix)),
1598 None => f(symbol, ""),
1599 })
1600 }
1601
1602 fn with_stringify_parts<R>(&self, f: impl FnOnce(&[&str]) -> R) -> R {
1607 fn get_hashes_str(num: u8) -> &'static str {
1611 const HASHES: &str = "\
1612 ################################################################\
1613 ################################################################\
1614 ################################################################\
1615 ################################################################\
1616 ";
1617 const _: () = assert!(HASHES.len() == 256);
1618 &HASHES[..num as usize]
1619 }
1620
1621 self.with_symbol_and_suffix(|symbol, suffix| match self.0.kind {
1622 bridge::LitKind::Byte => f(&["b'", symbol, "'", suffix]),
1623 bridge::LitKind::Char => f(&["'", symbol, "'", suffix]),
1624 bridge::LitKind::Str => f(&["\"", symbol, "\"", suffix]),
1625 bridge::LitKind::StrRaw(n) => {
1626 let hashes = get_hashes_str(n);
1627 f(&["r", hashes, "\"", symbol, "\"", hashes, suffix])
1628 }
1629 bridge::LitKind::ByteStr => f(&["b\"", symbol, "\"", suffix]),
1630 bridge::LitKind::ByteStrRaw(n) => {
1631 let hashes = get_hashes_str(n);
1632 f(&["br", hashes, "\"", symbol, "\"", hashes, suffix])
1633 }
1634 bridge::LitKind::CStr => f(&["c\"", symbol, "\"", suffix]),
1635 bridge::LitKind::CStrRaw(n) => {
1636 let hashes = get_hashes_str(n);
1637 f(&["cr", hashes, "\"", symbol, "\"", hashes, suffix])
1638 }
1639
1640 bridge::LitKind::Integer | bridge::LitKind::Float | bridge::LitKind::ErrWithGuar => {
1641 f(&[symbol, suffix])
1642 }
1643 })
1644 }
1645
1646 #[unstable(feature = "proc_macro_value", issue = "136652")]
1648 pub fn byte_character_value(&self) -> Result<u8, ConversionErrorKind> {
1649 self.0.symbol.with(|symbol| match self.0.kind {
1650 bridge::LitKind::Byte => unescape_byte(symbol)
1651 .map_err(|err| ConversionErrorKind::FailedToUnescape(err.into())),
1652 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1653 })
1654 }
1655
1656 #[unstable(feature = "proc_macro_value", issue = "136652")]
1658 pub fn character_value(&self) -> Result<char, ConversionErrorKind> {
1659 self.0.symbol.with(|symbol| match self.0.kind {
1660 bridge::LitKind::Char => unescape_char(symbol)
1661 .map_err(|err| ConversionErrorKind::FailedToUnescape(err.into())),
1662 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1663 })
1664 }
1665
1666 #[unstable(feature = "proc_macro_value", issue = "136652")]
1668 pub fn str_value(&self) -> Result<String, ConversionErrorKind> {
1669 self.0.symbol.with(|symbol| match self.0.kind {
1670 bridge::LitKind::Str => {
1671 if symbol.contains('\\') {
1672 let mut buf = String::with_capacity(symbol.len());
1673 let mut error = None;
1674 unescape_str(
1678 symbol,
1679 #[inline(always)]
1680 |_, c| match c {
1681 Ok(c) => buf.push(c),
1682 Err(err) => {
1683 if err.is_fatal() {
1684 error = Some(ConversionErrorKind::FailedToUnescape(err.into()));
1685 }
1686 }
1687 },
1688 );
1689 if let Some(error) = error { Err(error) } else { Ok(buf) }
1690 } else {
1691 Ok(symbol.to_string())
1692 }
1693 }
1694 bridge::LitKind::StrRaw(_) => Ok(symbol.to_string()),
1695 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1696 })
1697 }
1698
1699 #[unstable(feature = "proc_macro_value", issue = "136652")]
1702 pub fn cstr_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1703 self.0.symbol.with(|symbol| match self.0.kind {
1704 bridge::LitKind::CStr => {
1705 let mut error = None;
1706 let mut buf = Vec::with_capacity(symbol.len());
1707
1708 unescape_c_str(symbol, |_span, res| match res {
1709 Ok(MixedUnit::Char(c)) => {
1710 buf.extend_from_slice(c.get().encode_utf8(&mut [0; 4]).as_bytes())
1711 }
1712 Ok(MixedUnit::HighByte(b)) => buf.push(b.get()),
1713 Err(err) => {
1714 if err.is_fatal() {
1715 error = Some(ConversionErrorKind::FailedToUnescape(err.into()));
1716 }
1717 }
1718 });
1719 if let Some(error) = error {
1720 Err(error)
1721 } else {
1722 buf.push(0);
1723 Ok(buf)
1724 }
1725 }
1726 bridge::LitKind::CStrRaw(_) => {
1727 let mut buf = symbol.to_owned().into_bytes();
1731 buf.push(0);
1732 Ok(buf)
1733 }
1734 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1735 })
1736 }
1737
1738 #[unstable(feature = "proc_macro_value", issue = "136652")]
1741 pub fn byte_str_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1742 self.0.symbol.with(|symbol| match self.0.kind {
1743 bridge::LitKind::ByteStr => {
1744 let mut buf = Vec::with_capacity(symbol.len());
1745 let mut error = None;
1746
1747 unescape_byte_str(symbol, |_, res| match res {
1748 Ok(b) => buf.push(b),
1749 Err(err) => {
1750 if err.is_fatal() {
1751 error = Some(ConversionErrorKind::FailedToUnescape(err.into()));
1752 }
1753 }
1754 });
1755 if let Some(error) = error { Err(error) } else { Ok(buf) }
1756 }
1757 bridge::LitKind::ByteStrRaw(_) => {
1758 Ok(symbol.to_owned().into_bytes())
1761 }
1762 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1763 })
1764 }
1765
1766 integer_values! {
1767 u8 => u8_value,
1768 u16 => u16_value,
1769 u32 => u32_value,
1770 u64 => u64_value,
1771 u128 => u128_value,
1772 i8 => i8_value,
1773 i16 => i16_value,
1774 i32 => i32_value,
1775 i64 => i64_value,
1776 i128 => i128_value,
1777 }
1778
1779 float_values! {
1780 f16 => f16_value,
1781 f32 => f32_value,
1782 f64 => f64_value,
1783 }
1787}
1788
1789#[repr(u32)]
1790#[derive(PartialEq, Eq)]
1791enum Base {
1792 Decimal = 10,
1793 Binary = 2,
1794 Octal = 8,
1795 Hexadecimal = 16,
1796}
1797
1798fn parse_number(value: &str) -> (&str, Base) {
1799 let mut iter = value.as_bytes().iter().copied();
1800 let Some(first_digit) = iter.next() else {
1801 return ("0", Base::Decimal);
1802 };
1803 let Some(second_digit) = iter.next() else {
1804 return (value, Base::Decimal);
1805 };
1806
1807 let mut base = Base::Decimal;
1808 if first_digit == b'0' {
1809 match second_digit {
1811 b'b' => {
1812 base = Base::Binary;
1813 }
1814 b'o' => {
1815 base = Base::Octal;
1816 }
1817 b'x' => {
1818 base = Base::Hexadecimal;
1819 }
1820 _ => {}
1821 }
1822 }
1823
1824 let offset = if base == Base::Decimal { 0 } else { 2 };
1825
1826 (&value[offset..], base)
1827}
1828
1829fn strip_underscores(value_s: &str) -> Cow<'_, str> {
1830 let value = value_s.as_bytes();
1831 if value.iter().copied().all(|c| c != b'_' && c != b'f') {
1832 return Cow::Borrowed(value_s);
1833 }
1834 let mut output = String::with_capacity(value.len());
1835 for c in value.iter().copied() {
1836 if c != b'_' {
1837 output.push(c as char);
1838 }
1839 }
1840 Cow::Owned(output)
1841}
1842
1843#[stable(feature = "proc_macro_literal_parse", since = "1.54.0")]
1854impl FromStr for Literal {
1855 type Err = LexError;
1856
1857 fn from_str(src: &str) -> Result<Self, LexError> {
1858 match BridgeMethods::literal_from_str(src) {
1859 Ok(literal) => Ok(Literal(literal)),
1860 Err(msg) => Err(LexError(msg)),
1861 }
1862 }
1863}
1864
1865#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1868impl fmt::Display for Literal {
1869 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1870 self.with_stringify_parts(|parts| {
1871 for part in parts {
1872 fmt::Display::fmt(part, f)?;
1873 }
1874 Ok(())
1875 })
1876 }
1877}
1878
1879#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1880impl fmt::Debug for Literal {
1881 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1882 f.debug_struct("Literal")
1883 .field("kind", &format_args!("{:?}", self.0.kind))
1885 .field("symbol", &self.0.symbol)
1886 .field("suffix", &format_args!("{:?}", self.0.suffix))
1888 .field("span", &self.0.span)
1889 .finish()
1890 }
1891}
1892
1893#[unstable(
1894 feature = "proc_macro_tracked_path",
1895 issue = "99515",
1896 implied_by = "proc_macro_tracked_env"
1897)]
1898pub mod tracked {
1900 use std::env::{self, VarError};
1901 use std::ffi::OsStr;
1902 use std::path::Path;
1903
1904 use crate::BridgeMethods;
1905
1906 #[unstable(feature = "proc_macro_tracked_env", issue = "99515")]
1912 pub fn env_var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1913 let key: &str = key.as_ref();
1914 let value = BridgeMethods::injected_env_var(key).map_or_else(|| env::var(key), Ok);
1915 BridgeMethods::track_env_var(key, value.as_deref().ok());
1916 value
1917 }
1918
1919 #[unstable(feature = "proc_macro_tracked_path", issue = "99515")]
1923 pub fn path<P: AsRef<Path>>(path: P) {
1924 let path: &str = path.as_ref().to_str().unwrap();
1925 BridgeMethods::track_path(path);
1926 }
1927}