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(f16)]
31#![recursion_limit = "256"]
32#![allow(internal_features)]
33#![deny(ffi_unwind_calls)]
34#![allow(rustc::internal)] #![warn(rustdoc::unescaped_backticks)]
36#![warn(unreachable_pub)]
37#![deny(unsafe_op_in_unsafe_fn)]
38
39#[unstable(feature = "proc_macro_internals", issue = "none")]
40#[doc(hidden)]
41pub mod bridge;
42
43mod diagnostic;
44mod escape;
45mod to_tokens;
46
47use core::convert::From;
48use core::ops::BitOr;
49use std::borrow::Cow;
50use std::ffi::{CStr, CString};
51use std::ops::{Range, RangeBounds};
52use std::path::PathBuf;
53use std::str::FromStr;
54use std::{error, fmt};
55
56#[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
57pub use diagnostic::{Diagnostic, Level, MultiSpan};
58use rustc_literal_escaper::{
59 MixedUnit, unescape_byte, unescape_byte_str, unescape_c_str, unescape_char, unescape_str,
60};
61#[unstable(feature = "proc_macro_totokens", issue = "130977")]
62pub use to_tokens::ToTokens;
63
64use crate::bridge::client::Methods as BridgeMethods;
65use crate::escape::{EscapeOptions, escape_bytes};
66
67#[derive(Debug, PartialEq, Eq)]
69#[unstable(feature = "proc_macro_value", issue = "136652")]
70pub struct EscapeError {
71 kind: EscapeErrorKind,
72}
73
74#[unstable(feature = "proc_macro_value", issue = "136652")]
75impl error::Error for EscapeError {}
76
77#[unstable(feature = "proc_macro_value", issue = "136652")]
78impl fmt::Display for EscapeError {
79 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80 fmt::Display::fmt(&self.kind, f)
81 }
82}
83
84#[unstable(feature = "proc_macro_value", issue = "136652")]
85#[doc(hidden)]
86impl From<rustc_literal_escaper::EscapeError> for EscapeError {
87 fn from(value: rustc_literal_escaper::EscapeError) -> Self {
88 use rustc_literal_escaper::EscapeError as EE;
89
90 let kind = match value {
91 EE::ZeroChars => EscapeErrorKind::ZeroChars,
92 EE::MoreThanOneChar => EscapeErrorKind::MoreThanOneChar,
93 EE::LoneSlash => EscapeErrorKind::LoneSlash,
94 EE::InvalidEscape => EscapeErrorKind::InvalidEscape,
95 EE::BareCarriageReturn => EscapeErrorKind::BareCarriageReturn,
96 EE::BareCarriageReturnInRawString => EscapeErrorKind::BareCarriageReturnInRawString,
97 EE::EscapeOnlyChar => EscapeErrorKind::EscapeOnlyChar,
98 EE::TooShortHexEscape => EscapeErrorKind::TooShortHexEscape,
99 EE::InvalidCharInHexEscape => EscapeErrorKind::InvalidCharInHexEscape,
100 EE::OutOfRangeHexEscape => EscapeErrorKind::OutOfRangeHexEscape,
101 EE::NoBraceInUnicodeEscape => EscapeErrorKind::NoBraceInUnicodeEscape,
102 EE::InvalidCharInUnicodeEscape => EscapeErrorKind::InvalidCharInUnicodeEscape,
103 EE::EmptyUnicodeEscape => EscapeErrorKind::EmptyUnicodeEscape,
104 EE::UnclosedUnicodeEscape => EscapeErrorKind::UnclosedUnicodeEscape,
105 EE::LeadingUnderscoreUnicodeEscape => EscapeErrorKind::LeadingUnderscoreUnicodeEscape,
106 EE::OverlongUnicodeEscape => EscapeErrorKind::OverlongUnicodeEscape,
107 EE::LoneSurrogateUnicodeEscape => EscapeErrorKind::LoneSurrogateUnicodeEscape,
108 EE::OutOfRangeUnicodeEscape => EscapeErrorKind::OutOfRangeUnicodeEscape,
109 EE::UnicodeEscapeInByte => EscapeErrorKind::UnicodeEscapeInByte,
110 EE::NonAsciiCharInByte => EscapeErrorKind::NonAsciiCharInByte,
111 EE::NulInCStr => EscapeErrorKind::NulInCStr,
112 EE::UnskippedWhitespaceWarning => EscapeErrorKind::UnskippedWhitespaceWarning,
113 EE::MultipleSkippedLinesWarning => EscapeErrorKind::MultipleSkippedLinesWarning,
114 };
115 Self { kind }
116 }
117}
118
119#[derive(Debug, PartialEq, Eq)]
121#[non_exhaustive]
122enum EscapeErrorKind {
123 ZeroChars,
125 MoreThanOneChar,
127
128 LoneSlash,
130 InvalidEscape,
132 BareCarriageReturn,
134 BareCarriageReturnInRawString,
136 EscapeOnlyChar,
138
139 TooShortHexEscape,
141 InvalidCharInHexEscape,
143 OutOfRangeHexEscape,
145
146 NoBraceInUnicodeEscape,
148 InvalidCharInUnicodeEscape,
150 EmptyUnicodeEscape,
152 UnclosedUnicodeEscape,
154 LeadingUnderscoreUnicodeEscape,
156 OverlongUnicodeEscape,
158 LoneSurrogateUnicodeEscape,
160 OutOfRangeUnicodeEscape,
162
163 UnicodeEscapeInByte,
165 NonAsciiCharInByte,
167
168 NulInCStr,
170
171 UnskippedWhitespaceWarning,
174
175 MultipleSkippedLinesWarning,
177}
178
179impl error::Error for EscapeErrorKind {}
180
181impl fmt::Display for EscapeErrorKind {
182 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183 f.write_str(match self {
184 Self::ZeroChars => "zero chars",
185 Self::MoreThanOneChar => "more than one char",
186 Self::LoneSlash => "lone slash",
187 Self::InvalidEscape => "invalid escape",
188 Self::BareCarriageReturn => "bare carriage return",
189 Self::BareCarriageReturnInRawString => "bare carriage return in raw string",
190 Self::EscapeOnlyChar => "escape only char",
191 Self::TooShortHexEscape => "too short hex escape",
192 Self::InvalidCharInHexEscape => "invalid char in hex escape",
193 Self::OutOfRangeHexEscape => "out of range hex escape",
194 Self::NoBraceInUnicodeEscape => "no brace in unicode escape",
195 Self::InvalidCharInUnicodeEscape => "invalid char in unicode escape",
196 Self::EmptyUnicodeEscape => "empty unicode escape",
197 Self::UnclosedUnicodeEscape => "unclosed unicode escape",
198 Self::LeadingUnderscoreUnicodeEscape => "leading underscore unicode escape",
199 Self::OverlongUnicodeEscape => "overlong unicode escape",
200 Self::LoneSurrogateUnicodeEscape => "lone surrogate unicode escape",
201 Self::OutOfRangeUnicodeEscape => "out of range unicode escape",
202 Self::UnicodeEscapeInByte => "unicode escape in byte",
203 Self::NonAsciiCharInByte => "non ascii char in byte",
204 Self::NulInCStr => "nul in CStr",
205 Self::UnskippedWhitespaceWarning => "unskipped whitespace warning",
206 Self::MultipleSkippedLinesWarning => "multiple skipped lines warning",
207 })
208 }
209}
210
211#[unstable(feature = "proc_macro_value", issue = "136652")]
213#[derive(Debug, PartialEq, Eq)]
214#[non_exhaustive]
215pub enum ConversionErrorKind {
216 FailedToUnescape(EscapeError),
218 InvalidLiteralKind,
220}
221
222#[stable(feature = "proc_macro_is_available", since = "1.57.0")]
236pub fn is_available() -> bool {
237 bridge::client::is_available()
238}
239
240#[cfg_attr(feature = "rustc-dep-of-std", rustc_diagnostic_item = "TokenStream")]
248#[stable(feature = "proc_macro_lib", since = "1.15.0")]
249#[derive(Clone)]
250pub struct TokenStream(Option<bridge::client::TokenStream>);
251
252#[stable(feature = "proc_macro_lib", since = "1.15.0")]
253impl !Send for TokenStream {}
254#[stable(feature = "proc_macro_lib", since = "1.15.0")]
255impl !Sync for TokenStream {}
256
257#[stable(feature = "proc_macro_lib", since = "1.15.0")]
262#[derive(Debug)]
263pub struct LexError(String);
264
265#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
266impl fmt::Display for LexError {
267 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268 f.write_str(&self.0)
269 }
270}
271
272#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
273impl error::Error for LexError {}
274
275#[stable(feature = "proc_macro_lib", since = "1.15.0")]
276impl !Send for LexError {}
277#[stable(feature = "proc_macro_lib", since = "1.15.0")]
278impl !Sync for LexError {}
279
280#[unstable(feature = "proc_macro_expand", issue = "90765")]
282#[non_exhaustive]
283#[derive(Debug)]
284pub struct ExpandError;
285
286#[unstable(feature = "proc_macro_expand", issue = "90765")]
287impl fmt::Display for ExpandError {
288 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
289 f.write_str("macro expansion failed")
290 }
291}
292
293#[unstable(feature = "proc_macro_expand", issue = "90765")]
294impl error::Error for ExpandError {}
295
296#[unstable(feature = "proc_macro_expand", issue = "90765")]
297impl !Send for ExpandError {}
298
299#[unstable(feature = "proc_macro_expand", issue = "90765")]
300impl !Sync for ExpandError {}
301
302impl TokenStream {
303 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
305 pub fn new() -> TokenStream {
306 TokenStream(None)
307 }
308
309 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
311 pub fn is_empty(&self) -> bool {
312 self.0.as_ref().map(BridgeMethods::ts_is_empty).unwrap_or(true)
313 }
314
315 #[unstable(feature = "proc_macro_expand", issue = "90765")]
326 pub fn expand_expr(&self) -> Result<TokenStream, ExpandError> {
327 let stream = self.0.as_ref().ok_or(ExpandError)?;
328 match BridgeMethods::ts_expand_expr(stream) {
329 Ok(stream) => Ok(TokenStream(Some(stream))),
330 Err(_) => Err(ExpandError),
331 }
332 }
333}
334
335#[stable(feature = "proc_macro_lib", since = "1.15.0")]
343impl FromStr for TokenStream {
344 type Err = LexError;
345
346 fn from_str(src: &str) -> Result<TokenStream, LexError> {
347 Ok(TokenStream(Some(BridgeMethods::ts_from_str(src).map_err(LexError)?)))
348 }
349}
350
351#[stable(feature = "proc_macro_lib", since = "1.15.0")]
363impl fmt::Display for TokenStream {
364 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
365 match &self.0 {
366 Some(ts) => write!(f, "{}", BridgeMethods::ts_to_string(ts)),
367 None => Ok(()),
368 }
369 }
370}
371
372#[stable(feature = "proc_macro_lib", since = "1.15.0")]
374impl fmt::Debug for TokenStream {
375 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
376 f.write_str("TokenStream ")?;
377 f.debug_list().entries(self.clone()).finish()
378 }
379}
380
381#[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
382impl Default for TokenStream {
383 fn default() -> Self {
384 TokenStream::new()
385 }
386}
387
388#[unstable(feature = "proc_macro_quote", issue = "54722")]
389pub use quote::{HasIterator, RepInterp, ThereIsNoIteratorInRepetition, ext, quote, quote_span};
390
391fn tree_to_bridge_tree(
392 tree: TokenTree,
393) -> bridge::TokenTree<bridge::client::TokenStream, bridge::client::Span, bridge::client::Symbol> {
394 match tree {
395 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
396 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
397 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
398 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
399 }
400}
401
402#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
404impl From<TokenTree> for TokenStream {
405 fn from(tree: TokenTree) -> TokenStream {
406 TokenStream(Some(BridgeMethods::ts_from_token_tree(tree_to_bridge_tree(tree))))
407 }
408}
409
410struct ConcatTreesHelper {
413 trees: Vec<
414 bridge::TokenTree<
415 bridge::client::TokenStream,
416 bridge::client::Span,
417 bridge::client::Symbol,
418 >,
419 >,
420}
421
422impl ConcatTreesHelper {
423 fn new(capacity: usize) -> Self {
424 ConcatTreesHelper { trees: Vec::with_capacity(capacity) }
425 }
426
427 fn push(&mut self, tree: TokenTree) {
428 self.trees.push(tree_to_bridge_tree(tree));
429 }
430
431 fn build(self) -> TokenStream {
432 if self.trees.is_empty() {
433 TokenStream(None)
434 } else {
435 TokenStream(Some(BridgeMethods::ts_concat_trees(None, self.trees)))
436 }
437 }
438
439 fn append_to(self, stream: &mut TokenStream) {
440 if self.trees.is_empty() {
441 return;
442 }
443 stream.0 = Some(BridgeMethods::ts_concat_trees(stream.0.take(), self.trees))
444 }
445}
446
447struct ConcatStreamsHelper {
450 streams: Vec<bridge::client::TokenStream>,
451}
452
453impl ConcatStreamsHelper {
454 fn new(capacity: usize) -> Self {
455 ConcatStreamsHelper { streams: Vec::with_capacity(capacity) }
456 }
457
458 fn push(&mut self, stream: TokenStream) {
459 if let Some(stream) = stream.0 {
460 self.streams.push(stream);
461 }
462 }
463
464 fn build(mut self) -> TokenStream {
465 if self.streams.len() <= 1 {
466 TokenStream(self.streams.pop())
467 } else {
468 TokenStream(Some(BridgeMethods::ts_concat_streams(None, self.streams)))
469 }
470 }
471
472 fn append_to(mut self, stream: &mut TokenStream) {
473 if self.streams.is_empty() {
474 return;
475 }
476 let base = stream.0.take();
477 if base.is_none() && self.streams.len() == 1 {
478 stream.0 = self.streams.pop();
479 } else {
480 stream.0 = Some(BridgeMethods::ts_concat_streams(base, self.streams));
481 }
482 }
483}
484
485#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
487impl FromIterator<TokenTree> for TokenStream {
488 fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
489 let iter = trees.into_iter();
490 let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
491 iter.for_each(|tree| builder.push(tree));
492 builder.build()
493 }
494}
495
496#[stable(feature = "proc_macro_lib", since = "1.15.0")]
499impl FromIterator<TokenStream> for TokenStream {
500 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
501 let iter = streams.into_iter();
502 let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
503 iter.for_each(|stream| builder.push(stream));
504 builder.build()
505 }
506}
507
508#[stable(feature = "token_stream_extend", since = "1.30.0")]
509impl Extend<TokenTree> for TokenStream {
510 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
511 let iter = trees.into_iter();
512 let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
513 iter.for_each(|tree| builder.push(tree));
514 builder.append_to(self);
515 }
516}
517
518#[stable(feature = "token_stream_extend", since = "1.30.0")]
519impl Extend<TokenStream> for TokenStream {
520 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
521 let iter = streams.into_iter();
522 let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
523 iter.for_each(|stream| builder.push(stream));
524 builder.append_to(self);
525 }
526}
527
528macro_rules! extend_items {
529 ($($item:ident)*) => {
530 $(
531 #[stable(feature = "token_stream_extend_ts_items", since = "1.92.0")]
532 impl Extend<$item> for TokenStream {
533 fn extend<I: IntoIterator<Item = $item>>(&mut self, iter: I) {
534 self.extend(iter.into_iter().map(TokenTree::$item));
535 }
536 }
537 )*
538 };
539}
540
541extend_items!(Group Literal Punct Ident);
542
543#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
545pub mod token_stream {
546 use crate::{BridgeMethods, Group, Ident, Literal, Punct, TokenStream, TokenTree, bridge};
547
548 #[derive(Clone)]
552 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
553 pub struct IntoIter(
554 std::vec::IntoIter<
555 bridge::TokenTree<
556 bridge::client::TokenStream,
557 bridge::client::Span,
558 bridge::client::Symbol,
559 >,
560 >,
561 );
562
563 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
564 impl Iterator for IntoIter {
565 type Item = TokenTree;
566
567 fn next(&mut self) -> Option<TokenTree> {
568 self.0.next().map(|tree| match tree {
569 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
570 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
571 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
572 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
573 })
574 }
575
576 fn size_hint(&self) -> (usize, Option<usize>) {
577 self.0.size_hint()
578 }
579
580 fn count(self) -> usize {
581 self.0.count()
582 }
583 }
584
585 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
586 impl IntoIterator for TokenStream {
587 type Item = TokenTree;
588 type IntoIter = IntoIter;
589
590 fn into_iter(self) -> IntoIter {
591 IntoIter(self.0.map(BridgeMethods::ts_into_trees).unwrap_or_default().into_iter())
592 }
593 }
594}
595
596#[unstable(feature = "proc_macro_quote", issue = "54722")]
603#[allow_internal_unstable(proc_macro_def_site, proc_macro_internals, proc_macro_totokens)]
604#[rustc_builtin_macro]
605pub macro quote($($t:tt)*) {
606 }
608
609#[unstable(feature = "proc_macro_internals", issue = "none")]
610#[doc(hidden)]
611mod quote;
612
613#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
615#[derive(Copy, Clone)]
616pub struct Span(bridge::client::Span);
617
618#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
619impl !Send for Span {}
620#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
621impl !Sync for Span {}
622
623macro_rules! diagnostic_method {
624 ($name:ident, $level:expr) => {
625 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
628 pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
629 Diagnostic::spanned(self, $level, message)
630 }
631 };
632}
633
634impl Span {
635 #[unstable(feature = "proc_macro_def_site", issue = "54724")]
637 pub fn def_site() -> Span {
638 Span(bridge::client::Span::def_site())
639 }
640
641 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
646 pub fn call_site() -> Span {
647 Span(bridge::client::Span::call_site())
648 }
649
650 #[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
655 pub fn mixed_site() -> Span {
656 Span(bridge::client::Span::mixed_site())
657 }
658
659 #[unstable(feature = "proc_macro_span", issue = "54725")]
662 pub fn parent(&self) -> Option<Span> {
663 BridgeMethods::span_parent(self.0).map(Span)
664 }
665
666 #[unstable(feature = "proc_macro_span", issue = "54725")]
670 pub fn source(&self) -> Span {
671 Span(BridgeMethods::span_source(self.0))
672 }
673
674 #[unstable(feature = "proc_macro_span", issue = "54725")]
676 pub fn byte_range(&self) -> Range<usize> {
677 BridgeMethods::span_byte_range(self.0)
678 }
679
680 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
682 pub fn start(&self) -> Span {
683 Span(BridgeMethods::span_start(self.0))
684 }
685
686 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
688 pub fn end(&self) -> Span {
689 Span(BridgeMethods::span_end(self.0))
690 }
691
692 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
696 pub fn line(&self) -> usize {
697 BridgeMethods::span_line(self.0)
698 }
699
700 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
704 pub fn column(&self) -> usize {
705 BridgeMethods::span_column(self.0)
706 }
707
708 #[stable(feature = "proc_macro_span_file", since = "1.88.0")]
713 pub fn file(&self) -> String {
714 BridgeMethods::span_file(self.0)
715 }
716
717 #[stable(feature = "proc_macro_span_file", since = "1.88.0")]
723 pub fn local_file(&self) -> Option<PathBuf> {
724 BridgeMethods::span_local_file(self.0).map(PathBuf::from)
725 }
726
727 #[unstable(feature = "proc_macro_span", issue = "54725")]
731 pub fn join(&self, other: Span) -> Option<Span> {
732 BridgeMethods::span_join(self.0, other.0).map(Span)
733 }
734
735 #[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
738 pub fn resolved_at(&self, other: Span) -> Span {
739 Span(BridgeMethods::span_resolved_at(self.0, other.0))
740 }
741
742 #[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
745 pub fn located_at(&self, other: Span) -> Span {
746 other.resolved_at(*self)
747 }
748
749 #[unstable(feature = "proc_macro_span", issue = "54725")]
751 pub fn eq(&self, other: &Span) -> bool {
752 self.0 == other.0
753 }
754
755 #[stable(feature = "proc_macro_source_text", since = "1.66.0")]
763 pub fn source_text(&self) -> Option<String> {
764 BridgeMethods::span_source_text(self.0)
765 }
766
767 #[doc(hidden)]
769 #[unstable(feature = "proc_macro_internals", issue = "none")]
770 pub fn save_span(&self) -> usize {
771 BridgeMethods::span_save_span(self.0)
772 }
773
774 #[doc(hidden)]
776 #[unstable(feature = "proc_macro_internals", issue = "none")]
777 pub fn recover_proc_macro_span(id: usize) -> Span {
778 Span(BridgeMethods::span_recover_proc_macro_span(id))
779 }
780
781 diagnostic_method!(error, Level::Error);
782 diagnostic_method!(warning, Level::Warning);
783 diagnostic_method!(note, Level::Note);
784 diagnostic_method!(help, Level::Help);
785}
786
787#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
789impl fmt::Debug for Span {
790 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
791 self.0.fmt(f)
792 }
793}
794
795#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
797#[derive(Clone)]
798pub enum TokenTree {
799 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
801 Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
802 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
804 Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
805 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
807 Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
808 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
810 Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
811}
812
813#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
814impl !Send for TokenTree {}
815#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
816impl !Sync for TokenTree {}
817
818impl TokenTree {
819 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
822 pub fn span(&self) -> Span {
823 match *self {
824 TokenTree::Group(ref t) => t.span(),
825 TokenTree::Ident(ref t) => t.span(),
826 TokenTree::Punct(ref t) => t.span(),
827 TokenTree::Literal(ref t) => t.span(),
828 }
829 }
830
831 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
837 pub fn set_span(&mut self, span: Span) {
838 match *self {
839 TokenTree::Group(ref mut t) => t.set_span(span),
840 TokenTree::Ident(ref mut t) => t.set_span(span),
841 TokenTree::Punct(ref mut t) => t.set_span(span),
842 TokenTree::Literal(ref mut t) => t.set_span(span),
843 }
844 }
845}
846
847#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
849impl fmt::Debug for TokenTree {
850 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
851 match *self {
854 TokenTree::Group(ref tt) => tt.fmt(f),
855 TokenTree::Ident(ref tt) => tt.fmt(f),
856 TokenTree::Punct(ref tt) => tt.fmt(f),
857 TokenTree::Literal(ref tt) => tt.fmt(f),
858 }
859 }
860}
861
862#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
863impl From<Group> for TokenTree {
864 fn from(g: Group) -> TokenTree {
865 TokenTree::Group(g)
866 }
867}
868
869#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
870impl From<Ident> for TokenTree {
871 fn from(g: Ident) -> TokenTree {
872 TokenTree::Ident(g)
873 }
874}
875
876#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
877impl From<Punct> for TokenTree {
878 fn from(g: Punct) -> TokenTree {
879 TokenTree::Punct(g)
880 }
881}
882
883#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
884impl From<Literal> for TokenTree {
885 fn from(g: Literal) -> TokenTree {
886 TokenTree::Literal(g)
887 }
888}
889
890#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
902impl fmt::Display for TokenTree {
903 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
904 match self {
905 TokenTree::Group(t) => write!(f, "{t}"),
906 TokenTree::Ident(t) => write!(f, "{t}"),
907 TokenTree::Punct(t) => write!(f, "{t}"),
908 TokenTree::Literal(t) => write!(f, "{t}"),
909 }
910 }
911}
912
913#[derive(Clone)]
917#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
918pub struct Group(bridge::Group<bridge::client::TokenStream, bridge::client::Span>);
919
920#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
921impl !Send for Group {}
922#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
923impl !Sync for Group {}
924
925#[derive(Copy, Clone, Debug, PartialEq, Eq)]
927#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
928pub enum Delimiter {
929 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
931 Parenthesis,
932 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
934 Brace,
935 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
937 Bracket,
938 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
956 None,
957}
958
959impl Group {
960 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
966 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
967 Group(bridge::Group {
968 delimiter,
969 stream: stream.0,
970 span: bridge::DelimSpan::from_single(Span::call_site().0),
971 })
972 }
973
974 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
976 pub fn delimiter(&self) -> Delimiter {
977 self.0.delimiter
978 }
979
980 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
985 pub fn stream(&self) -> TokenStream {
986 TokenStream(self.0.stream.clone())
987 }
988
989 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
997 pub fn span(&self) -> Span {
998 Span(self.0.span.entire)
999 }
1000
1001 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
1008 pub fn span_open(&self) -> Span {
1009 Span(self.0.span.open)
1010 }
1011
1012 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
1019 pub fn span_close(&self) -> Span {
1020 Span(self.0.span.close)
1021 }
1022
1023 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1030 pub fn set_span(&mut self, span: Span) {
1031 self.0.span = bridge::DelimSpan::from_single(span.0);
1032 }
1033}
1034
1035#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1039impl fmt::Display for Group {
1040 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1041 write!(f, "{}", TokenStream::from(TokenTree::from(self.clone())))
1042 }
1043}
1044
1045#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1046impl fmt::Debug for Group {
1047 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1048 f.debug_struct("Group")
1049 .field("delimiter", &self.delimiter())
1050 .field("stream", &self.stream())
1051 .field("span", &self.span())
1052 .finish()
1053 }
1054}
1055
1056#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1061#[derive(Clone)]
1062pub struct Punct(bridge::Punct<bridge::client::Span>);
1063
1064#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1065impl !Send for Punct {}
1066#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1067impl !Sync for Punct {}
1068
1069#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1072#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1073pub enum Spacing {
1074 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1086 Joint,
1087 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1094 Alone,
1095}
1096
1097impl Punct {
1098 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1105 pub fn new(ch: char, spacing: Spacing) -> Punct {
1106 const LEGAL_CHARS: &[char] = &[
1107 '=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
1108 ':', '#', '$', '?', '\'',
1109 ];
1110 if !LEGAL_CHARS.contains(&ch) {
1111 panic!("unsupported character `{:?}`", ch);
1112 }
1113 Punct(bridge::Punct {
1114 ch: ch as u8,
1115 joint: spacing == Spacing::Joint,
1116 span: Span::call_site().0,
1117 })
1118 }
1119
1120 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1122 pub fn as_char(&self) -> char {
1123 self.0.ch as char
1124 }
1125
1126 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1130 pub fn spacing(&self) -> Spacing {
1131 if self.0.joint { Spacing::Joint } else { Spacing::Alone }
1132 }
1133
1134 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1136 pub fn span(&self) -> Span {
1137 Span(self.0.span)
1138 }
1139
1140 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1142 pub fn set_span(&mut self, span: Span) {
1143 self.0.span = span.0;
1144 }
1145}
1146
1147#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1150impl fmt::Display for Punct {
1151 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1152 write!(f, "{}", self.as_char())
1153 }
1154}
1155
1156#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1157impl fmt::Debug for Punct {
1158 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1159 f.debug_struct("Punct")
1160 .field("ch", &self.as_char())
1161 .field("spacing", &self.spacing())
1162 .field("span", &self.span())
1163 .finish()
1164 }
1165}
1166
1167#[stable(feature = "proc_macro_punct_eq", since = "1.50.0")]
1168impl PartialEq<char> for Punct {
1169 fn eq(&self, rhs: &char) -> bool {
1170 self.as_char() == *rhs
1171 }
1172}
1173
1174#[stable(feature = "proc_macro_punct_eq_flipped", since = "1.52.0")]
1175impl PartialEq<Punct> for char {
1176 fn eq(&self, rhs: &Punct) -> bool {
1177 *self == rhs.as_char()
1178 }
1179}
1180
1181#[derive(Clone)]
1183#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1184pub struct Ident(bridge::Ident<bridge::client::Span, bridge::client::Symbol>);
1185
1186impl Ident {
1187 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1211 pub fn new(string: &str, span: Span) -> Ident {
1212 Ident(bridge::Ident {
1213 sym: bridge::client::Symbol::new_ident(string, false),
1214 kind: bridge::IdentKind::Normal,
1215 span: span.0,
1216 })
1217 }
1218
1219 #[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
1224 pub fn new_raw(string: &str, span: Span) -> Ident {
1225 Ident(bridge::Ident {
1226 sym: bridge::client::Symbol::new_ident(string, true),
1227 kind: bridge::IdentKind::Raw,
1228 span: span.0,
1229 })
1230 }
1231
1232 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1235 pub fn span(&self) -> Span {
1236 Span(self.0.span)
1237 }
1238
1239 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1241 pub fn set_span(&mut self, span: Span) {
1242 self.0.span = span.0;
1243 }
1244}
1245
1246#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1249impl fmt::Display for Ident {
1250 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1251 if let Some(prefix) = self.0.kind.prefix() {
1252 f.write_str(prefix)?;
1253 }
1254 fmt::Display::fmt(&self.0.sym, f)
1255 }
1256}
1257
1258#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1259impl fmt::Debug for Ident {
1260 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1261 f.debug_struct("Ident")
1262 .field("ident", &self.to_string())
1263 .field("span", &self.span())
1264 .finish()
1265 }
1266}
1267
1268#[derive(Clone)]
1273#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1274pub struct Literal(bridge::Literal<bridge::client::Span, bridge::client::Symbol>);
1275
1276macro_rules! suffixed_int_literals {
1277 ($($name:ident => $kind:ident,)*) => ($(
1278 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1290 pub fn $name(n: $kind) -> Literal {
1291 Literal(bridge::Literal {
1292 kind: bridge::LitKind::Integer,
1293 symbol: bridge::client::Symbol::new(&n.to_string()),
1294 suffix: Some(bridge::client::Symbol::new(stringify!($kind))),
1295 span: Span::call_site().0,
1296 })
1297 }
1298 )*)
1299}
1300
1301macro_rules! unsuffixed_int_literals {
1302 ($($name:ident => $kind:ident,)*) => ($(
1303 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1317 pub fn $name(n: $kind) -> Literal {
1318 Literal(bridge::Literal {
1319 kind: bridge::LitKind::Integer,
1320 symbol: bridge::client::Symbol::new(&n.to_string()),
1321 suffix: None,
1322 span: Span::call_site().0,
1323 })
1324 }
1325 )*)
1326}
1327
1328macro_rules! integer_values {
1329 ($($nb:ident => $fn_name:ident,)+) => {
1330 $(
1331 #[doc = concat!(
1332 "Returns the unescaped `",
1333 stringify!($nb),
1334 "` value if the literal is a `",
1335 stringify!($nb),
1336 "` or if it's an \"unmarked\" integer which doesn't overflow.")]
1337 #[unstable(feature = "proc_macro_value", issue = "136652")]
1338 pub fn $fn_name(&self) -> Result<$nb, ConversionErrorKind> {
1339 if self.0.kind != bridge::LitKind::Integer {
1340 return Err(ConversionErrorKind::InvalidLiteralKind);
1341 }
1342 self.with_symbol_and_suffix(|symbol, suffix| {
1343 match suffix {
1344 stringify!($nb) | "" => {
1345 let symbol = strip_underscores(symbol);
1346 let (number, base) = parse_number(&symbol);
1347 $nb::from_str_radix(&number, base as u32).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
1348 }
1349 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1350 }
1351 })
1352 }
1353 )+
1354 }
1355}
1356
1357macro_rules! float_values {
1358 ($($nb:ident => $fn_name:ident,)+) => {
1359 $(
1360 #[doc = concat!(
1361 "Returns the unescaped `",
1362 stringify!($nb),
1363 "` value if the literal is a `",
1364 stringify!($nb),
1365 "` or if it's an \"unmarked\" float which doesn't overflow.")]
1366 #[unstable(feature = "proc_macro_value", issue = "136652")]
1367 pub fn $fn_name(&self) -> Result<$nb, ConversionErrorKind> {
1368 if self.0.kind != bridge::LitKind::Float {
1369 return Err(ConversionErrorKind::InvalidLiteralKind);
1370 }
1371 self.with_symbol_and_suffix(|symbol, suffix| {
1372 match suffix {
1373 stringify!($nb) | "" => {
1374 let number = strip_underscores(symbol);
1375 $nb::from_str(&number).map_err(|_| ConversionErrorKind::InvalidLiteralKind)
1376 }
1377 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1378 }
1379 })
1380 }
1381 )+
1382 }
1383}
1384
1385impl Literal {
1386 fn new(kind: bridge::LitKind, value: &str, suffix: Option<&str>) -> Self {
1387 Literal(bridge::Literal {
1388 kind,
1389 symbol: bridge::client::Symbol::new(value),
1390 suffix: suffix.map(bridge::client::Symbol::new),
1391 span: Span::call_site().0,
1392 })
1393 }
1394
1395 suffixed_int_literals! {
1396 u8_suffixed => u8,
1397 u16_suffixed => u16,
1398 u32_suffixed => u32,
1399 u64_suffixed => u64,
1400 u128_suffixed => u128,
1401 usize_suffixed => usize,
1402 i8_suffixed => i8,
1403 i16_suffixed => i16,
1404 i32_suffixed => i32,
1405 i64_suffixed => i64,
1406 i128_suffixed => i128,
1407 isize_suffixed => isize,
1408 }
1409
1410 unsuffixed_int_literals! {
1411 u8_unsuffixed => u8,
1412 u16_unsuffixed => u16,
1413 u32_unsuffixed => u32,
1414 u64_unsuffixed => u64,
1415 u128_unsuffixed => u128,
1416 usize_unsuffixed => usize,
1417 i8_unsuffixed => i8,
1418 i16_unsuffixed => i16,
1419 i32_unsuffixed => i32,
1420 i64_unsuffixed => i64,
1421 i128_unsuffixed => i128,
1422 isize_unsuffixed => isize,
1423 }
1424
1425 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1438 pub fn f32_unsuffixed(n: f32) -> Literal {
1439 if !n.is_finite() {
1440 panic!("Invalid float literal {n}");
1441 }
1442 let mut repr = n.to_string();
1443 if !repr.contains('.') {
1444 repr.push_str(".0");
1445 }
1446 Literal::new(bridge::LitKind::Float, &repr, None)
1447 }
1448
1449 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1463 pub fn f32_suffixed(n: f32) -> Literal {
1464 if !n.is_finite() {
1465 panic!("Invalid float literal {n}");
1466 }
1467 Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f32"))
1468 }
1469
1470 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1483 pub fn f64_unsuffixed(n: f64) -> Literal {
1484 if !n.is_finite() {
1485 panic!("Invalid float literal {n}");
1486 }
1487 let mut repr = n.to_string();
1488 if !repr.contains('.') {
1489 repr.push_str(".0");
1490 }
1491 Literal::new(bridge::LitKind::Float, &repr, None)
1492 }
1493
1494 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1508 pub fn f64_suffixed(n: f64) -> Literal {
1509 if !n.is_finite() {
1510 panic!("Invalid float literal {n}");
1511 }
1512 Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f64"))
1513 }
1514
1515 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1517 pub fn string(string: &str) -> Literal {
1518 let escape = EscapeOptions {
1519 escape_single_quote: false,
1520 escape_double_quote: true,
1521 escape_nonascii: false,
1522 };
1523 let repr = escape_bytes(string.as_bytes(), escape);
1524 Literal::new(bridge::LitKind::Str, &repr, None)
1525 }
1526
1527 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1529 pub fn character(ch: char) -> Literal {
1530 let escape = EscapeOptions {
1531 escape_single_quote: true,
1532 escape_double_quote: false,
1533 escape_nonascii: false,
1534 };
1535 let repr = escape_bytes(ch.encode_utf8(&mut [0u8; 4]).as_bytes(), escape);
1536 Literal::new(bridge::LitKind::Char, &repr, None)
1537 }
1538
1539 #[stable(feature = "proc_macro_byte_character", since = "1.79.0")]
1541 pub fn byte_character(byte: u8) -> Literal {
1542 let escape = EscapeOptions {
1543 escape_single_quote: true,
1544 escape_double_quote: false,
1545 escape_nonascii: true,
1546 };
1547 let repr = escape_bytes(&[byte], escape);
1548 Literal::new(bridge::LitKind::Byte, &repr, None)
1549 }
1550
1551 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1553 pub fn byte_string(bytes: &[u8]) -> Literal {
1554 let escape = EscapeOptions {
1555 escape_single_quote: false,
1556 escape_double_quote: true,
1557 escape_nonascii: true,
1558 };
1559 let repr = escape_bytes(bytes, escape);
1560 Literal::new(bridge::LitKind::ByteStr, &repr, None)
1561 }
1562
1563 #[stable(feature = "proc_macro_c_str_literals", since = "1.79.0")]
1565 pub fn c_string(string: &CStr) -> Literal {
1566 let escape = EscapeOptions {
1567 escape_single_quote: false,
1568 escape_double_quote: true,
1569 escape_nonascii: false,
1570 };
1571 let repr = escape_bytes(string.to_bytes(), escape);
1572 Literal::new(bridge::LitKind::CStr, &repr, None)
1573 }
1574
1575 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1577 pub fn span(&self) -> Span {
1578 Span(self.0.span)
1579 }
1580
1581 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1583 pub fn set_span(&mut self, span: Span) {
1584 self.0.span = span.0;
1585 }
1586
1587 #[unstable(feature = "proc_macro_span", issue = "54725")]
1599 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1600 BridgeMethods::span_subspan(
1601 self.0.span,
1602 range.start_bound().cloned(),
1603 range.end_bound().cloned(),
1604 )
1605 .map(Span)
1606 }
1607
1608 fn with_symbol_and_suffix<R>(&self, f: impl FnOnce(&str, &str) -> R) -> R {
1609 self.0.symbol.with(|symbol| match self.0.suffix {
1610 Some(suffix) => suffix.with(|suffix| f(symbol, suffix)),
1611 None => f(symbol, ""),
1612 })
1613 }
1614
1615 fn with_stringify_parts<R>(&self, f: impl FnOnce(&[&str]) -> R) -> R {
1620 fn get_hashes_str(num: u8) -> &'static str {
1624 const HASHES: &str = "\
1625 ################################################################\
1626 ################################################################\
1627 ################################################################\
1628 ################################################################\
1629 ";
1630 const _: () = assert!(HASHES.len() == 256);
1631 &HASHES[..num as usize]
1632 }
1633
1634 self.with_symbol_and_suffix(|symbol, suffix| match self.0.kind {
1635 bridge::LitKind::Byte => f(&["b'", symbol, "'", suffix]),
1636 bridge::LitKind::Char => f(&["'", symbol, "'", suffix]),
1637 bridge::LitKind::Str => f(&["\"", symbol, "\"", suffix]),
1638 bridge::LitKind::StrRaw(n) => {
1639 let hashes = get_hashes_str(n);
1640 f(&["r", hashes, "\"", symbol, "\"", hashes, suffix])
1641 }
1642 bridge::LitKind::ByteStr => f(&["b\"", symbol, "\"", suffix]),
1643 bridge::LitKind::ByteStrRaw(n) => {
1644 let hashes = get_hashes_str(n);
1645 f(&["br", hashes, "\"", symbol, "\"", hashes, suffix])
1646 }
1647 bridge::LitKind::CStr => f(&["c\"", symbol, "\"", suffix]),
1648 bridge::LitKind::CStrRaw(n) => {
1649 let hashes = get_hashes_str(n);
1650 f(&["cr", hashes, "\"", symbol, "\"", hashes, suffix])
1651 }
1652
1653 bridge::LitKind::Integer | bridge::LitKind::Float | bridge::LitKind::ErrWithGuar => {
1654 f(&[symbol, suffix])
1655 }
1656 })
1657 }
1658
1659 #[unstable(feature = "proc_macro_value", issue = "136652")]
1661 pub fn byte_character_value(&self) -> Result<u8, ConversionErrorKind> {
1662 self.0.symbol.with(|symbol| match self.0.kind {
1663 bridge::LitKind::Byte => unescape_byte(symbol)
1664 .map_err(|err| ConversionErrorKind::FailedToUnescape(err.into())),
1665 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1666 })
1667 }
1668
1669 #[unstable(feature = "proc_macro_value", issue = "136652")]
1671 pub fn character_value(&self) -> Result<char, ConversionErrorKind> {
1672 self.0.symbol.with(|symbol| match self.0.kind {
1673 bridge::LitKind::Char => unescape_char(symbol)
1674 .map_err(|err| ConversionErrorKind::FailedToUnescape(err.into())),
1675 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1676 })
1677 }
1678
1679 #[unstable(feature = "proc_macro_value", issue = "136652")]
1681 pub fn str_value(&self) -> Result<String, ConversionErrorKind> {
1682 self.0.symbol.with(|symbol| match self.0.kind {
1683 bridge::LitKind::Str => {
1684 if symbol.contains('\\') {
1685 let mut buf = String::with_capacity(symbol.len());
1686 let mut error = None;
1687 unescape_str(
1691 symbol,
1692 #[inline(always)]
1693 |_, c| match c {
1694 Ok(c) => buf.push(c),
1695 Err(err) => {
1696 if err.is_fatal() {
1697 error = Some(ConversionErrorKind::FailedToUnescape(err.into()));
1698 }
1699 }
1700 },
1701 );
1702 if let Some(error) = error { Err(error) } else { Ok(buf) }
1703 } else {
1704 Ok(symbol.to_string())
1705 }
1706 }
1707 bridge::LitKind::StrRaw(_) => Ok(symbol.to_string()),
1708 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1709 })
1710 }
1711
1712 #[unstable(feature = "proc_macro_value", issue = "136652")]
1715 pub fn cstr_value(&self) -> Result<CString, ConversionErrorKind> {
1716 self.0.symbol.with(|symbol| match self.0.kind {
1717 bridge::LitKind::CStr => {
1718 let mut error = None;
1719 let mut buf = Vec::with_capacity(symbol.len());
1720
1721 unescape_c_str(symbol, |_span, res| match res {
1722 Ok(MixedUnit::Char(c)) => {
1723 buf.extend_from_slice(c.get().encode_utf8(&mut [0; 4]).as_bytes())
1724 }
1725 Ok(MixedUnit::HighByte(b)) => buf.push(b.get()),
1726 Err(err) => {
1727 if err.is_fatal() {
1728 error = Some(ConversionErrorKind::FailedToUnescape(err.into()));
1729 }
1730 }
1731 });
1732 if let Some(error) = error {
1733 Err(error)
1734 } else {
1735 buf.push(0);
1736 unsafe { Ok(CString::from_vec_with_nul_unchecked(buf)) }
1739 }
1740 }
1741 bridge::LitKind::CStrRaw(_) => {
1742 Ok(CString::new(symbol.to_owned()).expect("invalid cstr literal"))
1746 }
1747 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1748 })
1749 }
1750
1751 #[unstable(feature = "proc_macro_value", issue = "136652")]
1754 pub fn byte_str_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1755 self.0.symbol.with(|symbol| match self.0.kind {
1756 bridge::LitKind::ByteStr => {
1757 let mut buf = Vec::with_capacity(symbol.len());
1758 let mut error = None;
1759
1760 unescape_byte_str(symbol, |_, res| match res {
1761 Ok(b) => buf.push(b),
1762 Err(err) => {
1763 if err.is_fatal() {
1764 error = Some(ConversionErrorKind::FailedToUnescape(err.into()));
1765 }
1766 }
1767 });
1768 if let Some(error) = error { Err(error) } else { Ok(buf) }
1769 }
1770 bridge::LitKind::ByteStrRaw(_) => {
1771 Ok(symbol.to_owned().into_bytes())
1774 }
1775 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1776 })
1777 }
1778
1779 integer_values! {
1780 u8 => u8_value,
1781 u16 => u16_value,
1782 u32 => u32_value,
1783 u64 => u64_value,
1784 u128 => u128_value,
1785 i8 => i8_value,
1786 i16 => i16_value,
1787 i32 => i32_value,
1788 i64 => i64_value,
1789 i128 => i128_value,
1790 }
1791
1792 float_values! {
1793 f16 => f16_value,
1794 f32 => f32_value,
1795 f64 => f64_value,
1796 }
1800}
1801
1802#[repr(u32)]
1803#[derive(PartialEq, Eq)]
1804enum Base {
1805 Decimal = 10,
1806 Binary = 2,
1807 Octal = 8,
1808 Hexadecimal = 16,
1809}
1810
1811fn parse_number(value: &str) -> (&str, Base) {
1812 let mut iter = value.as_bytes().iter().copied();
1813 let Some(first_digit) = iter.next() else {
1814 return ("0", Base::Decimal);
1815 };
1816 let Some(second_digit) = iter.next() else {
1817 return (value, Base::Decimal);
1818 };
1819
1820 let mut base = Base::Decimal;
1821 if first_digit == b'0' {
1822 match second_digit {
1824 b'b' => {
1825 base = Base::Binary;
1826 }
1827 b'o' => {
1828 base = Base::Octal;
1829 }
1830 b'x' => {
1831 base = Base::Hexadecimal;
1832 }
1833 _ => {}
1834 }
1835 }
1836
1837 let offset = if base == Base::Decimal { 0 } else { 2 };
1838
1839 (&value[offset..], base)
1840}
1841
1842fn strip_underscores(value_s: &str) -> Cow<'_, str> {
1843 let value = value_s.as_bytes();
1844 if value.iter().copied().all(|c| c != b'_' && c != b'f') {
1845 return Cow::Borrowed(value_s);
1846 }
1847 let mut output = String::with_capacity(value.len());
1848 for c in value.iter().copied() {
1849 if c != b'_' {
1850 output.push(c as char);
1851 }
1852 }
1853 Cow::Owned(output)
1854}
1855
1856#[stable(feature = "proc_macro_literal_parse", since = "1.54.0")]
1867impl FromStr for Literal {
1868 type Err = LexError;
1869
1870 fn from_str(src: &str) -> Result<Self, LexError> {
1871 match BridgeMethods::literal_from_str(src) {
1872 Ok(literal) => Ok(Literal(literal)),
1873 Err(msg) => Err(LexError(msg)),
1874 }
1875 }
1876}
1877
1878#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1881impl fmt::Display for Literal {
1882 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1883 self.with_stringify_parts(|parts| {
1884 for part in parts {
1885 fmt::Display::fmt(part, f)?;
1886 }
1887 Ok(())
1888 })
1889 }
1890}
1891
1892#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1893impl fmt::Debug for Literal {
1894 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1895 f.debug_struct("Literal")
1896 .field("kind", &format_args!("{:?}", self.0.kind))
1898 .field("symbol", &self.0.symbol)
1899 .field("suffix", &format_args!("{:?}", self.0.suffix))
1901 .field("span", &self.0.span)
1902 .finish()
1903 }
1904}
1905
1906#[unstable(
1907 feature = "proc_macro_tracked_path",
1908 issue = "99515",
1909 implied_by = "proc_macro_tracked_env"
1910)]
1911pub mod tracked {
1913 use std::env::{self, VarError};
1914 use std::ffi::OsStr;
1915 use std::path::Path;
1916
1917 use crate::BridgeMethods;
1918
1919 #[unstable(feature = "proc_macro_tracked_env", issue = "99515")]
1925 pub fn env_var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1926 let key: &str = key.as_ref();
1927 let value = env::var(key);
1928 BridgeMethods::track_env_var(key, value.as_deref().ok());
1929 value
1930 }
1931
1932 #[unstable(feature = "proc_macro_tracked_path", issue = "99515")]
1936 pub fn path<P: AsRef<Path>>(path: P) {
1937 let path: &str = path.as_ref().to_str().unwrap();
1938 BridgeMethods::track_path(path);
1939 }
1940}