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#[derive(Debug)]
249pub struct LexError(String);
250
251#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
252impl fmt::Display for LexError {
253 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
254 f.write_str(&self.0)
255 }
256}
257
258#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
259impl error::Error for LexError {}
260
261#[stable(feature = "proc_macro_lib", since = "1.15.0")]
262impl !Send for LexError {}
263#[stable(feature = "proc_macro_lib", since = "1.15.0")]
264impl !Sync for LexError {}
265
266#[unstable(feature = "proc_macro_expand", issue = "90765")]
268#[non_exhaustive]
269#[derive(Debug)]
270pub struct ExpandError;
271
272#[unstable(feature = "proc_macro_expand", issue = "90765")]
273impl fmt::Display for ExpandError {
274 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
275 f.write_str("macro expansion failed")
276 }
277}
278
279#[unstable(feature = "proc_macro_expand", issue = "90765")]
280impl error::Error for ExpandError {}
281
282#[unstable(feature = "proc_macro_expand", issue = "90765")]
283impl !Send for ExpandError {}
284
285#[unstable(feature = "proc_macro_expand", issue = "90765")]
286impl !Sync for ExpandError {}
287
288impl TokenStream {
289 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
291 pub fn new() -> TokenStream {
292 TokenStream(None)
293 }
294
295 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
297 pub fn is_empty(&self) -> bool {
298 self.0.as_ref().map(BridgeMethods::ts_is_empty).unwrap_or(true)
299 }
300
301 #[unstable(feature = "proc_macro_expand", issue = "90765")]
312 pub fn expand_expr(&self) -> Result<TokenStream, ExpandError> {
313 let stream = self.0.as_ref().ok_or(ExpandError)?;
314 match BridgeMethods::ts_expand_expr(stream) {
315 Ok(stream) => Ok(TokenStream(Some(stream))),
316 Err(_) => Err(ExpandError),
317 }
318 }
319}
320
321#[stable(feature = "proc_macro_lib", since = "1.15.0")]
329impl FromStr for TokenStream {
330 type Err = LexError;
331
332 fn from_str(src: &str) -> Result<TokenStream, LexError> {
333 Ok(TokenStream(Some(BridgeMethods::ts_from_str(src).map_err(LexError)?)))
334 }
335}
336
337#[stable(feature = "proc_macro_lib", since = "1.15.0")]
349impl fmt::Display for TokenStream {
350 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
351 match &self.0 {
352 Some(ts) => write!(f, "{}", BridgeMethods::ts_to_string(ts)),
353 None => Ok(()),
354 }
355 }
356}
357
358#[stable(feature = "proc_macro_lib", since = "1.15.0")]
360impl fmt::Debug for TokenStream {
361 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
362 f.write_str("TokenStream ")?;
363 f.debug_list().entries(self.clone()).finish()
364 }
365}
366
367#[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
368impl Default for TokenStream {
369 fn default() -> Self {
370 TokenStream::new()
371 }
372}
373
374#[unstable(feature = "proc_macro_quote", issue = "54722")]
375pub use quote::{HasIterator, RepInterp, ThereIsNoIteratorInRepetition, ext, quote, quote_span};
376
377fn tree_to_bridge_tree(
378 tree: TokenTree,
379) -> bridge::TokenTree<bridge::client::TokenStream, bridge::client::Span, bridge::client::Symbol> {
380 match tree {
381 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
382 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
383 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
384 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
385 }
386}
387
388#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
390impl From<TokenTree> for TokenStream {
391 fn from(tree: TokenTree) -> TokenStream {
392 TokenStream(Some(BridgeMethods::ts_from_token_tree(tree_to_bridge_tree(tree))))
393 }
394}
395
396struct ConcatTreesHelper {
399 trees: Vec<
400 bridge::TokenTree<
401 bridge::client::TokenStream,
402 bridge::client::Span,
403 bridge::client::Symbol,
404 >,
405 >,
406}
407
408impl ConcatTreesHelper {
409 fn new(capacity: usize) -> Self {
410 ConcatTreesHelper { trees: Vec::with_capacity(capacity) }
411 }
412
413 fn push(&mut self, tree: TokenTree) {
414 self.trees.push(tree_to_bridge_tree(tree));
415 }
416
417 fn build(self) -> TokenStream {
418 if self.trees.is_empty() {
419 TokenStream(None)
420 } else {
421 TokenStream(Some(BridgeMethods::ts_concat_trees(None, self.trees)))
422 }
423 }
424
425 fn append_to(self, stream: &mut TokenStream) {
426 if self.trees.is_empty() {
427 return;
428 }
429 stream.0 = Some(BridgeMethods::ts_concat_trees(stream.0.take(), self.trees))
430 }
431}
432
433struct ConcatStreamsHelper {
436 streams: Vec<bridge::client::TokenStream>,
437}
438
439impl ConcatStreamsHelper {
440 fn new(capacity: usize) -> Self {
441 ConcatStreamsHelper { streams: Vec::with_capacity(capacity) }
442 }
443
444 fn push(&mut self, stream: TokenStream) {
445 if let Some(stream) = stream.0 {
446 self.streams.push(stream);
447 }
448 }
449
450 fn build(mut self) -> TokenStream {
451 if self.streams.len() <= 1 {
452 TokenStream(self.streams.pop())
453 } else {
454 TokenStream(Some(BridgeMethods::ts_concat_streams(None, self.streams)))
455 }
456 }
457
458 fn append_to(mut self, stream: &mut TokenStream) {
459 if self.streams.is_empty() {
460 return;
461 }
462 let base = stream.0.take();
463 if base.is_none() && self.streams.len() == 1 {
464 stream.0 = self.streams.pop();
465 } else {
466 stream.0 = Some(BridgeMethods::ts_concat_streams(base, self.streams));
467 }
468 }
469}
470
471#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
473impl FromIterator<TokenTree> for TokenStream {
474 fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
475 let iter = trees.into_iter();
476 let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
477 iter.for_each(|tree| builder.push(tree));
478 builder.build()
479 }
480}
481
482#[stable(feature = "proc_macro_lib", since = "1.15.0")]
485impl FromIterator<TokenStream> for TokenStream {
486 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
487 let iter = streams.into_iter();
488 let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
489 iter.for_each(|stream| builder.push(stream));
490 builder.build()
491 }
492}
493
494#[stable(feature = "token_stream_extend", since = "1.30.0")]
495impl Extend<TokenTree> for TokenStream {
496 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
497 let iter = trees.into_iter();
498 let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
499 iter.for_each(|tree| builder.push(tree));
500 builder.append_to(self);
501 }
502}
503
504#[stable(feature = "token_stream_extend", since = "1.30.0")]
505impl Extend<TokenStream> for TokenStream {
506 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
507 let iter = streams.into_iter();
508 let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
509 iter.for_each(|stream| builder.push(stream));
510 builder.append_to(self);
511 }
512}
513
514macro_rules! extend_items {
515 ($($item:ident)*) => {
516 $(
517 #[stable(feature = "token_stream_extend_ts_items", since = "1.92.0")]
518 impl Extend<$item> for TokenStream {
519 fn extend<T: IntoIterator<Item = $item>>(&mut self, iter: T) {
520 self.extend(iter.into_iter().map(TokenTree::$item));
521 }
522 }
523 )*
524 };
525}
526
527extend_items!(Group Literal Punct Ident);
528
529#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
531pub mod token_stream {
532 use crate::{BridgeMethods, Group, Ident, Literal, Punct, TokenStream, TokenTree, bridge};
533
534 #[derive(Clone)]
538 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
539 pub struct IntoIter(
540 std::vec::IntoIter<
541 bridge::TokenTree<
542 bridge::client::TokenStream,
543 bridge::client::Span,
544 bridge::client::Symbol,
545 >,
546 >,
547 );
548
549 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
550 impl Iterator for IntoIter {
551 type Item = TokenTree;
552
553 fn next(&mut self) -> Option<TokenTree> {
554 self.0.next().map(|tree| match tree {
555 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
556 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
557 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
558 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
559 })
560 }
561
562 fn size_hint(&self) -> (usize, Option<usize>) {
563 self.0.size_hint()
564 }
565
566 fn count(self) -> usize {
567 self.0.count()
568 }
569 }
570
571 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
572 impl IntoIterator for TokenStream {
573 type Item = TokenTree;
574 type IntoIter = IntoIter;
575
576 fn into_iter(self) -> IntoIter {
577 IntoIter(self.0.map(BridgeMethods::ts_into_trees).unwrap_or_default().into_iter())
578 }
579 }
580}
581
582#[unstable(feature = "proc_macro_quote", issue = "54722")]
589#[allow_internal_unstable(proc_macro_def_site, proc_macro_internals, proc_macro_totokens)]
590#[rustc_builtin_macro]
591pub macro quote($($t:tt)*) {
592 }
594
595#[unstable(feature = "proc_macro_internals", issue = "none")]
596#[doc(hidden)]
597mod quote;
598
599#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
601#[derive(Copy, Clone)]
602pub struct Span(bridge::client::Span);
603
604#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
605impl !Send for Span {}
606#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
607impl !Sync for Span {}
608
609macro_rules! diagnostic_method {
610 ($name:ident, $level:expr) => {
611 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
614 pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
615 Diagnostic::spanned(self, $level, message)
616 }
617 };
618}
619
620impl Span {
621 #[unstable(feature = "proc_macro_def_site", issue = "54724")]
623 pub fn def_site() -> Span {
624 Span(bridge::client::Span::def_site())
625 }
626
627 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
632 pub fn call_site() -> Span {
633 Span(bridge::client::Span::call_site())
634 }
635
636 #[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
641 pub fn mixed_site() -> Span {
642 Span(bridge::client::Span::mixed_site())
643 }
644
645 #[unstable(feature = "proc_macro_span", issue = "54725")]
648 pub fn parent(&self) -> Option<Span> {
649 BridgeMethods::span_parent(self.0).map(Span)
650 }
651
652 #[unstable(feature = "proc_macro_span", issue = "54725")]
656 pub fn source(&self) -> Span {
657 Span(BridgeMethods::span_source(self.0))
658 }
659
660 #[unstable(feature = "proc_macro_span", issue = "54725")]
662 pub fn byte_range(&self) -> Range<usize> {
663 BridgeMethods::span_byte_range(self.0)
664 }
665
666 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
668 pub fn start(&self) -> Span {
669 Span(BridgeMethods::span_start(self.0))
670 }
671
672 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
674 pub fn end(&self) -> Span {
675 Span(BridgeMethods::span_end(self.0))
676 }
677
678 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
682 pub fn line(&self) -> usize {
683 BridgeMethods::span_line(self.0)
684 }
685
686 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
690 pub fn column(&self) -> usize {
691 BridgeMethods::span_column(self.0)
692 }
693
694 #[stable(feature = "proc_macro_span_file", since = "1.88.0")]
699 pub fn file(&self) -> String {
700 BridgeMethods::span_file(self.0)
701 }
702
703 #[stable(feature = "proc_macro_span_file", since = "1.88.0")]
709 pub fn local_file(&self) -> Option<PathBuf> {
710 BridgeMethods::span_local_file(self.0).map(PathBuf::from)
711 }
712
713 #[unstable(feature = "proc_macro_span", issue = "54725")]
717 pub fn join(&self, other: Span) -> Option<Span> {
718 BridgeMethods::span_join(self.0, other.0).map(Span)
719 }
720
721 #[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
724 pub fn resolved_at(&self, other: Span) -> Span {
725 Span(BridgeMethods::span_resolved_at(self.0, other.0))
726 }
727
728 #[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
731 pub fn located_at(&self, other: Span) -> Span {
732 other.resolved_at(*self)
733 }
734
735 #[unstable(feature = "proc_macro_span", issue = "54725")]
737 pub fn eq(&self, other: &Span) -> bool {
738 self.0 == other.0
739 }
740
741 #[stable(feature = "proc_macro_source_text", since = "1.66.0")]
749 pub fn source_text(&self) -> Option<String> {
750 BridgeMethods::span_source_text(self.0)
751 }
752
753 #[doc(hidden)]
755 #[unstable(feature = "proc_macro_internals", issue = "none")]
756 pub fn save_span(&self) -> usize {
757 BridgeMethods::span_save_span(self.0)
758 }
759
760 #[doc(hidden)]
762 #[unstable(feature = "proc_macro_internals", issue = "none")]
763 pub fn recover_proc_macro_span(id: usize) -> Span {
764 Span(BridgeMethods::span_recover_proc_macro_span(id))
765 }
766
767 diagnostic_method!(error, Level::Error);
768 diagnostic_method!(warning, Level::Warning);
769 diagnostic_method!(note, Level::Note);
770 diagnostic_method!(help, Level::Help);
771}
772
773#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
775impl fmt::Debug for Span {
776 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
777 self.0.fmt(f)
778 }
779}
780
781#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
783#[derive(Clone)]
784pub enum TokenTree {
785 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
787 Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
788 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
790 Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
791 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
793 Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
794 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
796 Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
797}
798
799#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
800impl !Send for TokenTree {}
801#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
802impl !Sync for TokenTree {}
803
804impl TokenTree {
805 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
808 pub fn span(&self) -> Span {
809 match *self {
810 TokenTree::Group(ref t) => t.span(),
811 TokenTree::Ident(ref t) => t.span(),
812 TokenTree::Punct(ref t) => t.span(),
813 TokenTree::Literal(ref t) => t.span(),
814 }
815 }
816
817 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
823 pub fn set_span(&mut self, span: Span) {
824 match *self {
825 TokenTree::Group(ref mut t) => t.set_span(span),
826 TokenTree::Ident(ref mut t) => t.set_span(span),
827 TokenTree::Punct(ref mut t) => t.set_span(span),
828 TokenTree::Literal(ref mut t) => t.set_span(span),
829 }
830 }
831}
832
833#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
835impl fmt::Debug for TokenTree {
836 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
837 match *self {
840 TokenTree::Group(ref tt) => tt.fmt(f),
841 TokenTree::Ident(ref tt) => tt.fmt(f),
842 TokenTree::Punct(ref tt) => tt.fmt(f),
843 TokenTree::Literal(ref tt) => tt.fmt(f),
844 }
845 }
846}
847
848#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
849impl From<Group> for TokenTree {
850 fn from(g: Group) -> TokenTree {
851 TokenTree::Group(g)
852 }
853}
854
855#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
856impl From<Ident> for TokenTree {
857 fn from(g: Ident) -> TokenTree {
858 TokenTree::Ident(g)
859 }
860}
861
862#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
863impl From<Punct> for TokenTree {
864 fn from(g: Punct) -> TokenTree {
865 TokenTree::Punct(g)
866 }
867}
868
869#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
870impl From<Literal> for TokenTree {
871 fn from(g: Literal) -> TokenTree {
872 TokenTree::Literal(g)
873 }
874}
875
876#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
888impl fmt::Display for TokenTree {
889 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
890 match self {
891 TokenTree::Group(t) => write!(f, "{t}"),
892 TokenTree::Ident(t) => write!(f, "{t}"),
893 TokenTree::Punct(t) => write!(f, "{t}"),
894 TokenTree::Literal(t) => write!(f, "{t}"),
895 }
896 }
897}
898
899#[derive(Clone)]
903#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
904pub struct Group(bridge::Group<bridge::client::TokenStream, bridge::client::Span>);
905
906#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
907impl !Send for Group {}
908#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
909impl !Sync for Group {}
910
911#[derive(Copy, Clone, Debug, PartialEq, Eq)]
913#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
914pub enum Delimiter {
915 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
917 Parenthesis,
918 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
920 Brace,
921 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
923 Bracket,
924 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
942 None,
943}
944
945impl Group {
946 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
952 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
953 Group(bridge::Group {
954 delimiter,
955 stream: stream.0,
956 span: bridge::DelimSpan::from_single(Span::call_site().0),
957 })
958 }
959
960 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
962 pub fn delimiter(&self) -> Delimiter {
963 self.0.delimiter
964 }
965
966 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
971 pub fn stream(&self) -> TokenStream {
972 TokenStream(self.0.stream.clone())
973 }
974
975 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
983 pub fn span(&self) -> Span {
984 Span(self.0.span.entire)
985 }
986
987 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
994 pub fn span_open(&self) -> Span {
995 Span(self.0.span.open)
996 }
997
998 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
1005 pub fn span_close(&self) -> Span {
1006 Span(self.0.span.close)
1007 }
1008
1009 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1016 pub fn set_span(&mut self, span: Span) {
1017 self.0.span = bridge::DelimSpan::from_single(span.0);
1018 }
1019}
1020
1021#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1025impl fmt::Display for Group {
1026 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1027 write!(f, "{}", TokenStream::from(TokenTree::from(self.clone())))
1028 }
1029}
1030
1031#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1032impl fmt::Debug for Group {
1033 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1034 f.debug_struct("Group")
1035 .field("delimiter", &self.delimiter())
1036 .field("stream", &self.stream())
1037 .field("span", &self.span())
1038 .finish()
1039 }
1040}
1041
1042#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1047#[derive(Clone)]
1048pub struct Punct(bridge::Punct<bridge::client::Span>);
1049
1050#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1051impl !Send for Punct {}
1052#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1053impl !Sync for Punct {}
1054
1055#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1058#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1059pub enum Spacing {
1060 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1072 Joint,
1073 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1080 Alone,
1081}
1082
1083impl Punct {
1084 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1091 pub fn new(ch: char, spacing: Spacing) -> Punct {
1092 const LEGAL_CHARS: &[char] = &[
1093 '=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
1094 ':', '#', '$', '?', '\'',
1095 ];
1096 if !LEGAL_CHARS.contains(&ch) {
1097 panic!("unsupported character `{:?}`", ch);
1098 }
1099 Punct(bridge::Punct {
1100 ch: ch as u8,
1101 joint: spacing == Spacing::Joint,
1102 span: Span::call_site().0,
1103 })
1104 }
1105
1106 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1108 pub fn as_char(&self) -> char {
1109 self.0.ch as char
1110 }
1111
1112 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1116 pub fn spacing(&self) -> Spacing {
1117 if self.0.joint { Spacing::Joint } else { Spacing::Alone }
1118 }
1119
1120 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1122 pub fn span(&self) -> Span {
1123 Span(self.0.span)
1124 }
1125
1126 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1128 pub fn set_span(&mut self, span: Span) {
1129 self.0.span = span.0;
1130 }
1131}
1132
1133#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1136impl fmt::Display for Punct {
1137 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1138 write!(f, "{}", self.as_char())
1139 }
1140}
1141
1142#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1143impl fmt::Debug for Punct {
1144 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1145 f.debug_struct("Punct")
1146 .field("ch", &self.as_char())
1147 .field("spacing", &self.spacing())
1148 .field("span", &self.span())
1149 .finish()
1150 }
1151}
1152
1153#[stable(feature = "proc_macro_punct_eq", since = "1.50.0")]
1154impl PartialEq<char> for Punct {
1155 fn eq(&self, rhs: &char) -> bool {
1156 self.as_char() == *rhs
1157 }
1158}
1159
1160#[stable(feature = "proc_macro_punct_eq_flipped", since = "1.52.0")]
1161impl PartialEq<Punct> for char {
1162 fn eq(&self, rhs: &Punct) -> bool {
1163 *self == rhs.as_char()
1164 }
1165}
1166
1167#[derive(Clone)]
1169#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1170pub struct Ident(bridge::Ident<bridge::client::Span, bridge::client::Symbol>);
1171
1172impl Ident {
1173 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1197 pub fn new(string: &str, span: Span) -> Ident {
1198 Ident(bridge::Ident {
1199 sym: bridge::client::Symbol::new_ident(string, false),
1200 is_raw: false,
1201 span: span.0,
1202 })
1203 }
1204
1205 #[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
1210 pub fn new_raw(string: &str, span: Span) -> Ident {
1211 Ident(bridge::Ident {
1212 sym: bridge::client::Symbol::new_ident(string, true),
1213 is_raw: true,
1214 span: span.0,
1215 })
1216 }
1217
1218 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1221 pub fn span(&self) -> Span {
1222 Span(self.0.span)
1223 }
1224
1225 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1227 pub fn set_span(&mut self, span: Span) {
1228 self.0.span = span.0;
1229 }
1230}
1231
1232#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1235impl fmt::Display for Ident {
1236 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1237 if self.0.is_raw {
1238 f.write_str("r#")?;
1239 }
1240 fmt::Display::fmt(&self.0.sym, f)
1241 }
1242}
1243
1244#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1245impl fmt::Debug for Ident {
1246 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1247 f.debug_struct("Ident")
1248 .field("ident", &self.to_string())
1249 .field("span", &self.span())
1250 .finish()
1251 }
1252}
1253
1254#[derive(Clone)]
1259#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1260pub struct Literal(bridge::Literal<bridge::client::Span, bridge::client::Symbol>);
1261
1262macro_rules! suffixed_int_literals {
1263 ($($name:ident => $kind:ident,)*) => ($(
1264 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1276 pub fn $name(n: $kind) -> Literal {
1277 Literal(bridge::Literal {
1278 kind: bridge::LitKind::Integer,
1279 symbol: bridge::client::Symbol::new(&n.to_string()),
1280 suffix: Some(bridge::client::Symbol::new(stringify!($kind))),
1281 span: Span::call_site().0,
1282 })
1283 }
1284 )*)
1285}
1286
1287macro_rules! unsuffixed_int_literals {
1288 ($($name:ident => $kind:ident,)*) => ($(
1289 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1303 pub fn $name(n: $kind) -> Literal {
1304 Literal(bridge::Literal {
1305 kind: bridge::LitKind::Integer,
1306 symbol: bridge::client::Symbol::new(&n.to_string()),
1307 suffix: None,
1308 span: Span::call_site().0,
1309 })
1310 }
1311 )*)
1312}
1313
1314macro_rules! integer_values {
1315 ($($nb:ident => $fn_name:ident,)+) => {
1316 $(
1317 #[doc = concat!(
1318 "Returns the unescaped `",
1319 stringify!($nb),
1320 "` value if the literal is a `",
1321 stringify!($nb),
1322 "` or if it's an \"unmarked\" integer which doesn't overflow.")]
1323 #[unstable(feature = "proc_macro_value", issue = "136652")]
1324 pub fn $fn_name(&self) -> Result<$nb, ConversionErrorKind> {
1325 if self.0.kind != bridge::LitKind::Integer {
1326 return Err(ConversionErrorKind::InvalidLiteralKind);
1327 }
1328 self.with_symbol_and_suffix(|symbol, suffix| {
1329 match suffix {
1330 stringify!($nb) | "" => {
1331 let symbol = strip_underscores(symbol);
1332 let (number, base) = parse_number(&symbol);
1333 $nb::from_str_radix(&number, base as u32).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
1334 }
1335 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1336 }
1337 })
1338 }
1339 )+
1340 }
1341}
1342
1343macro_rules! float_values {
1344 ($($nb:ident => $fn_name:ident,)+) => {
1345 $(
1346 #[doc = concat!(
1347 "Returns the unescaped `",
1348 stringify!($nb),
1349 "` value if the literal is a `",
1350 stringify!($nb),
1351 "` or if it's an \"unmarked\" float which doesn't overflow.")]
1352 #[unstable(feature = "proc_macro_value", issue = "136652")]
1353 pub fn $fn_name(&self) -> Result<$nb, ConversionErrorKind> {
1354 if self.0.kind != bridge::LitKind::Float {
1355 return Err(ConversionErrorKind::InvalidLiteralKind);
1356 }
1357 self.with_symbol_and_suffix(|symbol, suffix| {
1358 match suffix {
1359 stringify!($nb) | "" => {
1360 let number = strip_underscores(symbol);
1361 $nb::from_str(&number).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
1362 }
1363 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1364 }
1365 })
1366 }
1367 )+
1368 }
1369}
1370
1371impl Literal {
1372 fn new(kind: bridge::LitKind, value: &str, suffix: Option<&str>) -> Self {
1373 Literal(bridge::Literal {
1374 kind,
1375 symbol: bridge::client::Symbol::new(value),
1376 suffix: suffix.map(bridge::client::Symbol::new),
1377 span: Span::call_site().0,
1378 })
1379 }
1380
1381 suffixed_int_literals! {
1382 u8_suffixed => u8,
1383 u16_suffixed => u16,
1384 u32_suffixed => u32,
1385 u64_suffixed => u64,
1386 u128_suffixed => u128,
1387 usize_suffixed => usize,
1388 i8_suffixed => i8,
1389 i16_suffixed => i16,
1390 i32_suffixed => i32,
1391 i64_suffixed => i64,
1392 i128_suffixed => i128,
1393 isize_suffixed => isize,
1394 }
1395
1396 unsuffixed_int_literals! {
1397 u8_unsuffixed => u8,
1398 u16_unsuffixed => u16,
1399 u32_unsuffixed => u32,
1400 u64_unsuffixed => u64,
1401 u128_unsuffixed => u128,
1402 usize_unsuffixed => usize,
1403 i8_unsuffixed => i8,
1404 i16_unsuffixed => i16,
1405 i32_unsuffixed => i32,
1406 i64_unsuffixed => i64,
1407 i128_unsuffixed => i128,
1408 isize_unsuffixed => isize,
1409 }
1410
1411 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1424 pub fn f32_unsuffixed(n: f32) -> Literal {
1425 if !n.is_finite() {
1426 panic!("Invalid float literal {n}");
1427 }
1428 let mut repr = n.to_string();
1429 if !repr.contains('.') {
1430 repr.push_str(".0");
1431 }
1432 Literal::new(bridge::LitKind::Float, &repr, None)
1433 }
1434
1435 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1449 pub fn f32_suffixed(n: f32) -> Literal {
1450 if !n.is_finite() {
1451 panic!("Invalid float literal {n}");
1452 }
1453 Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f32"))
1454 }
1455
1456 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1469 pub fn f64_unsuffixed(n: f64) -> Literal {
1470 if !n.is_finite() {
1471 panic!("Invalid float literal {n}");
1472 }
1473 let mut repr = n.to_string();
1474 if !repr.contains('.') {
1475 repr.push_str(".0");
1476 }
1477 Literal::new(bridge::LitKind::Float, &repr, None)
1478 }
1479
1480 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1494 pub fn f64_suffixed(n: f64) -> Literal {
1495 if !n.is_finite() {
1496 panic!("Invalid float literal {n}");
1497 }
1498 Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f64"))
1499 }
1500
1501 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1503 pub fn string(string: &str) -> Literal {
1504 let escape = EscapeOptions {
1505 escape_single_quote: false,
1506 escape_double_quote: true,
1507 escape_nonascii: false,
1508 };
1509 let repr = escape_bytes(string.as_bytes(), escape);
1510 Literal::new(bridge::LitKind::Str, &repr, None)
1511 }
1512
1513 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1515 pub fn character(ch: char) -> Literal {
1516 let escape = EscapeOptions {
1517 escape_single_quote: true,
1518 escape_double_quote: false,
1519 escape_nonascii: false,
1520 };
1521 let repr = escape_bytes(ch.encode_utf8(&mut [0u8; 4]).as_bytes(), escape);
1522 Literal::new(bridge::LitKind::Char, &repr, None)
1523 }
1524
1525 #[stable(feature = "proc_macro_byte_character", since = "1.79.0")]
1527 pub fn byte_character(byte: u8) -> Literal {
1528 let escape = EscapeOptions {
1529 escape_single_quote: true,
1530 escape_double_quote: false,
1531 escape_nonascii: true,
1532 };
1533 let repr = escape_bytes(&[byte], escape);
1534 Literal::new(bridge::LitKind::Byte, &repr, None)
1535 }
1536
1537 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1539 pub fn byte_string(bytes: &[u8]) -> Literal {
1540 let escape = EscapeOptions {
1541 escape_single_quote: false,
1542 escape_double_quote: true,
1543 escape_nonascii: true,
1544 };
1545 let repr = escape_bytes(bytes, escape);
1546 Literal::new(bridge::LitKind::ByteStr, &repr, None)
1547 }
1548
1549 #[stable(feature = "proc_macro_c_str_literals", since = "1.79.0")]
1551 pub fn c_string(string: &CStr) -> Literal {
1552 let escape = EscapeOptions {
1553 escape_single_quote: false,
1554 escape_double_quote: true,
1555 escape_nonascii: false,
1556 };
1557 let repr = escape_bytes(string.to_bytes(), escape);
1558 Literal::new(bridge::LitKind::CStr, &repr, None)
1559 }
1560
1561 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1563 pub fn span(&self) -> Span {
1564 Span(self.0.span)
1565 }
1566
1567 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1569 pub fn set_span(&mut self, span: Span) {
1570 self.0.span = span.0;
1571 }
1572
1573 #[unstable(feature = "proc_macro_span", issue = "54725")]
1585 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1586 BridgeMethods::span_subspan(
1587 self.0.span,
1588 range.start_bound().cloned(),
1589 range.end_bound().cloned(),
1590 )
1591 .map(Span)
1592 }
1593
1594 fn with_symbol_and_suffix<R>(&self, f: impl FnOnce(&str, &str) -> R) -> R {
1595 self.0.symbol.with(|symbol| match self.0.suffix {
1596 Some(suffix) => suffix.with(|suffix| f(symbol, suffix)),
1597 None => f(symbol, ""),
1598 })
1599 }
1600
1601 fn with_stringify_parts<R>(&self, f: impl FnOnce(&[&str]) -> R) -> R {
1606 fn get_hashes_str(num: u8) -> &'static str {
1610 const HASHES: &str = "\
1611 ################################################################\
1612 ################################################################\
1613 ################################################################\
1614 ################################################################\
1615 ";
1616 const _: () = assert!(HASHES.len() == 256);
1617 &HASHES[..num as usize]
1618 }
1619
1620 self.with_symbol_and_suffix(|symbol, suffix| match self.0.kind {
1621 bridge::LitKind::Byte => f(&["b'", symbol, "'", suffix]),
1622 bridge::LitKind::Char => f(&["'", symbol, "'", suffix]),
1623 bridge::LitKind::Str => f(&["\"", symbol, "\"", suffix]),
1624 bridge::LitKind::StrRaw(n) => {
1625 let hashes = get_hashes_str(n);
1626 f(&["r", hashes, "\"", symbol, "\"", hashes, suffix])
1627 }
1628 bridge::LitKind::ByteStr => f(&["b\"", symbol, "\"", suffix]),
1629 bridge::LitKind::ByteStrRaw(n) => {
1630 let hashes = get_hashes_str(n);
1631 f(&["br", hashes, "\"", symbol, "\"", hashes, suffix])
1632 }
1633 bridge::LitKind::CStr => f(&["c\"", symbol, "\"", suffix]),
1634 bridge::LitKind::CStrRaw(n) => {
1635 let hashes = get_hashes_str(n);
1636 f(&["cr", hashes, "\"", symbol, "\"", hashes, suffix])
1637 }
1638
1639 bridge::LitKind::Integer | bridge::LitKind::Float | bridge::LitKind::ErrWithGuar => {
1640 f(&[symbol, suffix])
1641 }
1642 })
1643 }
1644
1645 #[unstable(feature = "proc_macro_value", issue = "136652")]
1647 pub fn byte_character_value(&self) -> Result<u8, ConversionErrorKind> {
1648 self.0.symbol.with(|symbol| match self.0.kind {
1649 bridge::LitKind::Byte => unescape_byte(symbol)
1650 .map_err(|err| ConversionErrorKind::FailedToUnescape(err.into())),
1651 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1652 })
1653 }
1654
1655 #[unstable(feature = "proc_macro_value", issue = "136652")]
1657 pub fn character_value(&self) -> Result<char, ConversionErrorKind> {
1658 self.0.symbol.with(|symbol| match self.0.kind {
1659 bridge::LitKind::Char => unescape_char(symbol)
1660 .map_err(|err| ConversionErrorKind::FailedToUnescape(err.into())),
1661 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1662 })
1663 }
1664
1665 #[unstable(feature = "proc_macro_value", issue = "136652")]
1667 pub fn str_value(&self) -> Result<String, ConversionErrorKind> {
1668 self.0.symbol.with(|symbol| match self.0.kind {
1669 bridge::LitKind::Str => {
1670 if symbol.contains('\\') {
1671 let mut buf = String::with_capacity(symbol.len());
1672 let mut error = None;
1673 unescape_str(
1677 symbol,
1678 #[inline(always)]
1679 |_, c| match c {
1680 Ok(c) => buf.push(c),
1681 Err(err) => {
1682 if err.is_fatal() {
1683 error = Some(ConversionErrorKind::FailedToUnescape(err.into()));
1684 }
1685 }
1686 },
1687 );
1688 if let Some(error) = error { Err(error) } else { Ok(buf) }
1689 } else {
1690 Ok(symbol.to_string())
1691 }
1692 }
1693 bridge::LitKind::StrRaw(_) => Ok(symbol.to_string()),
1694 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1695 })
1696 }
1697
1698 #[unstable(feature = "proc_macro_value", issue = "136652")]
1701 pub fn cstr_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1702 self.0.symbol.with(|symbol| match self.0.kind {
1703 bridge::LitKind::CStr => {
1704 let mut error = None;
1705 let mut buf = Vec::with_capacity(symbol.len());
1706
1707 unescape_c_str(symbol, |_span, res| match res {
1708 Ok(MixedUnit::Char(c)) => {
1709 buf.extend_from_slice(c.get().encode_utf8(&mut [0; 4]).as_bytes())
1710 }
1711 Ok(MixedUnit::HighByte(b)) => buf.push(b.get()),
1712 Err(err) => {
1713 if err.is_fatal() {
1714 error = Some(ConversionErrorKind::FailedToUnescape(err.into()));
1715 }
1716 }
1717 });
1718 if let Some(error) = error {
1719 Err(error)
1720 } else {
1721 buf.push(0);
1722 Ok(buf)
1723 }
1724 }
1725 bridge::LitKind::CStrRaw(_) => {
1726 let mut buf = symbol.to_owned().into_bytes();
1730 buf.push(0);
1731 Ok(buf)
1732 }
1733 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1734 })
1735 }
1736
1737 #[unstable(feature = "proc_macro_value", issue = "136652")]
1740 pub fn byte_str_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1741 self.0.symbol.with(|symbol| match self.0.kind {
1742 bridge::LitKind::ByteStr => {
1743 let mut buf = Vec::with_capacity(symbol.len());
1744 let mut error = None;
1745
1746 unescape_byte_str(symbol, |_, res| match res {
1747 Ok(b) => buf.push(b),
1748 Err(err) => {
1749 if err.is_fatal() {
1750 error = Some(ConversionErrorKind::FailedToUnescape(err.into()));
1751 }
1752 }
1753 });
1754 if let Some(error) = error { Err(error) } else { Ok(buf) }
1755 }
1756 bridge::LitKind::ByteStrRaw(_) => {
1757 Ok(symbol.to_owned().into_bytes())
1760 }
1761 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1762 })
1763 }
1764
1765 integer_values! {
1766 u8 => u8_value,
1767 u16 => u16_value,
1768 u32 => u32_value,
1769 u64 => u64_value,
1770 u128 => u128_value,
1771 i8 => i8_value,
1772 i16 => i16_value,
1773 i32 => i32_value,
1774 i64 => i64_value,
1775 i128 => i128_value,
1776 }
1777
1778 float_values! {
1779 f16 => f16_value,
1780 f32 => f32_value,
1781 f64 => f64_value,
1782 }
1786}
1787
1788#[repr(u32)]
1789#[derive(PartialEq, Eq)]
1790enum Base {
1791 Decimal = 10,
1792 Binary = 2,
1793 Octal = 8,
1794 Hexadecimal = 16,
1795}
1796
1797fn parse_number(value: &str) -> (&str, Base) {
1798 let mut iter = value.as_bytes().iter().copied();
1799 let Some(first_digit) = iter.next() else {
1800 return ("0", Base::Decimal);
1801 };
1802 let Some(second_digit) = iter.next() else {
1803 return (value, Base::Decimal);
1804 };
1805
1806 let mut base = Base::Decimal;
1807 if first_digit == b'0' {
1808 match second_digit {
1810 b'b' => {
1811 base = Base::Binary;
1812 }
1813 b'o' => {
1814 base = Base::Octal;
1815 }
1816 b'x' => {
1817 base = Base::Hexadecimal;
1818 }
1819 _ => {}
1820 }
1821 }
1822
1823 let offset = if base == Base::Decimal { 0 } else { 2 };
1824
1825 (&value[offset..], base)
1826}
1827
1828fn strip_underscores(value_s: &str) -> Cow<'_, str> {
1829 let value = value_s.as_bytes();
1830 if value.iter().copied().all(|c| c != b'_' && c != b'f') {
1831 return Cow::Borrowed(value_s);
1832 }
1833 let mut output = String::with_capacity(value.len());
1834 for c in value.iter().copied() {
1835 if c != b'_' {
1836 output.push(c as char);
1837 }
1838 }
1839 Cow::Owned(output)
1840}
1841
1842#[stable(feature = "proc_macro_literal_parse", since = "1.54.0")]
1853impl FromStr for Literal {
1854 type Err = LexError;
1855
1856 fn from_str(src: &str) -> Result<Self, LexError> {
1857 match BridgeMethods::literal_from_str(src) {
1858 Ok(literal) => Ok(Literal(literal)),
1859 Err(msg) => Err(LexError(msg)),
1860 }
1861 }
1862}
1863
1864#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1867impl fmt::Display for Literal {
1868 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1869 self.with_stringify_parts(|parts| {
1870 for part in parts {
1871 fmt::Display::fmt(part, f)?;
1872 }
1873 Ok(())
1874 })
1875 }
1876}
1877
1878#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1879impl fmt::Debug for Literal {
1880 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1881 f.debug_struct("Literal")
1882 .field("kind", &format_args!("{:?}", self.0.kind))
1884 .field("symbol", &self.0.symbol)
1885 .field("suffix", &format_args!("{:?}", self.0.suffix))
1887 .field("span", &self.0.span)
1888 .finish()
1889 }
1890}
1891
1892#[unstable(
1893 feature = "proc_macro_tracked_path",
1894 issue = "99515",
1895 implied_by = "proc_macro_tracked_env"
1896)]
1897pub mod tracked {
1899 use std::env::{self, VarError};
1900 use std::ffi::OsStr;
1901 use std::path::Path;
1902
1903 use crate::BridgeMethods;
1904
1905 #[unstable(feature = "proc_macro_tracked_env", issue = "99515")]
1911 pub fn env_var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1912 let key: &str = key.as_ref();
1913 let value = BridgeMethods::injected_env_var(key).map_or_else(|| env::var(key), Ok);
1914 BridgeMethods::track_env_var(key, value.as_deref().ok());
1915 value
1916 }
1917
1918 #[unstable(feature = "proc_macro_tracked_path", issue = "99515")]
1922 pub fn path<P: AsRef<Path>>(path: P) {
1923 let path: &str = path.as_ref().to_str().unwrap();
1924 BridgeMethods::track_path(path);
1925 }
1926}