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(maybe_uninit_write_slice)]
26#![feature(negative_impls)]
27#![feature(panic_can_unwind)]
28#![feature(restricted_std)]
29#![feature(rustc_attrs)]
30#![feature(stmt_expr_attributes)]
31#![feature(extend_one)]
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 = "27812")]
41#[doc(hidden)]
42pub mod bridge;
43
44mod diagnostic;
45mod escape;
46mod to_tokens;
47
48use core::ops::BitOr;
49use std::ffi::CStr;
50use std::ops::{Range, RangeBounds};
51use std::path::PathBuf;
52use std::str::FromStr;
53use std::{error, fmt};
54
55#[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
56pub use diagnostic::{Diagnostic, Level, MultiSpan};
57#[unstable(feature = "proc_macro_value", issue = "136652")]
58pub use rustc_literal_escaper::EscapeError;
59use rustc_literal_escaper::{MixedUnit, unescape_byte_str, unescape_c_str, unescape_str};
60#[unstable(feature = "proc_macro_totokens", issue = "130977")]
61pub use to_tokens::ToTokens;
62
63use crate::escape::{EscapeOptions, escape_bytes};
64
65#[unstable(feature = "proc_macro_value", issue = "136652")]
67#[derive(Debug, PartialEq, Eq)]
68pub enum ConversionErrorKind {
69    FailedToUnescape(EscapeError),
71    InvalidLiteralKind,
73}
74
75#[stable(feature = "proc_macro_is_available", since = "1.57.0")]
89pub fn is_available() -> bool {
90    bridge::client::is_available()
91}
92
93#[cfg_attr(feature = "rustc-dep-of-std", rustc_diagnostic_item = "TokenStream")]
101#[stable(feature = "proc_macro_lib", since = "1.15.0")]
102#[derive(Clone)]
103pub struct TokenStream(Option<bridge::client::TokenStream>);
104
105#[stable(feature = "proc_macro_lib", since = "1.15.0")]
106impl !Send for TokenStream {}
107#[stable(feature = "proc_macro_lib", since = "1.15.0")]
108impl !Sync for TokenStream {}
109
110#[stable(feature = "proc_macro_lib", since = "1.15.0")]
112#[non_exhaustive]
113#[derive(Debug)]
114pub struct LexError;
115
116#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
117impl fmt::Display for LexError {
118    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119        f.write_str("cannot parse string into token stream")
120    }
121}
122
123#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
124impl error::Error for LexError {}
125
126#[stable(feature = "proc_macro_lib", since = "1.15.0")]
127impl !Send for LexError {}
128#[stable(feature = "proc_macro_lib", since = "1.15.0")]
129impl !Sync for LexError {}
130
131#[unstable(feature = "proc_macro_expand", issue = "90765")]
133#[non_exhaustive]
134#[derive(Debug)]
135pub struct ExpandError;
136
137#[unstable(feature = "proc_macro_expand", issue = "90765")]
138impl fmt::Display for ExpandError {
139    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140        f.write_str("macro expansion failed")
141    }
142}
143
144#[unstable(feature = "proc_macro_expand", issue = "90765")]
145impl error::Error for ExpandError {}
146
147#[unstable(feature = "proc_macro_expand", issue = "90765")]
148impl !Send for ExpandError {}
149
150#[unstable(feature = "proc_macro_expand", issue = "90765")]
151impl !Sync for ExpandError {}
152
153impl TokenStream {
154    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
156    pub fn new() -> TokenStream {
157        TokenStream(None)
158    }
159
160    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
162    pub fn is_empty(&self) -> bool {
163        self.0.as_ref().map(|h| h.is_empty()).unwrap_or(true)
164    }
165
166    #[unstable(feature = "proc_macro_expand", issue = "90765")]
177    pub fn expand_expr(&self) -> Result<TokenStream, ExpandError> {
178        let stream = self.0.as_ref().ok_or(ExpandError)?;
179        match bridge::client::TokenStream::expand_expr(stream) {
180            Ok(stream) => Ok(TokenStream(Some(stream))),
181            Err(_) => Err(ExpandError),
182        }
183    }
184}
185
186#[stable(feature = "proc_macro_lib", since = "1.15.0")]
194impl FromStr for TokenStream {
195    type Err = LexError;
196
197    fn from_str(src: &str) -> Result<TokenStream, LexError> {
198        Ok(TokenStream(Some(bridge::client::TokenStream::from_str(src))))
199    }
200}
201
202#[stable(feature = "proc_macro_lib", since = "1.15.0")]
214impl fmt::Display for TokenStream {
215    #[allow(clippy::recursive_format_impl)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
217        match &self.0 {
218            Some(ts) => write!(f, "{}", ts.to_string()),
219            None => Ok(()),
220        }
221    }
222}
223
224#[stable(feature = "proc_macro_lib", since = "1.15.0")]
226impl fmt::Debug for TokenStream {
227    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228        f.write_str("TokenStream ")?;
229        f.debug_list().entries(self.clone()).finish()
230    }
231}
232
233#[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
234impl Default for TokenStream {
235    fn default() -> Self {
236        TokenStream::new()
237    }
238}
239
240#[unstable(feature = "proc_macro_quote", issue = "54722")]
241pub use quote::{HasIterator, RepInterp, ThereIsNoIteratorInRepetition, ext, quote, quote_span};
242
243fn tree_to_bridge_tree(
244    tree: TokenTree,
245) -> bridge::TokenTree<bridge::client::TokenStream, bridge::client::Span, bridge::client::Symbol> {
246    match tree {
247        TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
248        TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
249        TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
250        TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
251    }
252}
253
254#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
256impl From<TokenTree> for TokenStream {
257    fn from(tree: TokenTree) -> TokenStream {
258        TokenStream(Some(bridge::client::TokenStream::from_token_tree(tree_to_bridge_tree(tree))))
259    }
260}
261
262struct ConcatTreesHelper {
265    trees: Vec<
266        bridge::TokenTree<
267            bridge::client::TokenStream,
268            bridge::client::Span,
269            bridge::client::Symbol,
270        >,
271    >,
272}
273
274impl ConcatTreesHelper {
275    fn new(capacity: usize) -> Self {
276        ConcatTreesHelper { trees: Vec::with_capacity(capacity) }
277    }
278
279    fn push(&mut self, tree: TokenTree) {
280        self.trees.push(tree_to_bridge_tree(tree));
281    }
282
283    fn build(self) -> TokenStream {
284        if self.trees.is_empty() {
285            TokenStream(None)
286        } else {
287            TokenStream(Some(bridge::client::TokenStream::concat_trees(None, self.trees)))
288        }
289    }
290
291    fn append_to(self, stream: &mut TokenStream) {
292        if self.trees.is_empty() {
293            return;
294        }
295        stream.0 = Some(bridge::client::TokenStream::concat_trees(stream.0.take(), self.trees))
296    }
297}
298
299struct ConcatStreamsHelper {
302    streams: Vec<bridge::client::TokenStream>,
303}
304
305impl ConcatStreamsHelper {
306    fn new(capacity: usize) -> Self {
307        ConcatStreamsHelper { streams: Vec::with_capacity(capacity) }
308    }
309
310    fn push(&mut self, stream: TokenStream) {
311        if let Some(stream) = stream.0 {
312            self.streams.push(stream);
313        }
314    }
315
316    fn build(mut self) -> TokenStream {
317        if self.streams.len() <= 1 {
318            TokenStream(self.streams.pop())
319        } else {
320            TokenStream(Some(bridge::client::TokenStream::concat_streams(None, self.streams)))
321        }
322    }
323
324    fn append_to(mut self, stream: &mut TokenStream) {
325        if self.streams.is_empty() {
326            return;
327        }
328        let base = stream.0.take();
329        if base.is_none() && self.streams.len() == 1 {
330            stream.0 = self.streams.pop();
331        } else {
332            stream.0 = Some(bridge::client::TokenStream::concat_streams(base, self.streams));
333        }
334    }
335}
336
337#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
339impl FromIterator<TokenTree> for TokenStream {
340    fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
341        let iter = trees.into_iter();
342        let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
343        iter.for_each(|tree| builder.push(tree));
344        builder.build()
345    }
346}
347
348#[stable(feature = "proc_macro_lib", since = "1.15.0")]
351impl FromIterator<TokenStream> for TokenStream {
352    fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
353        let iter = streams.into_iter();
354        let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
355        iter.for_each(|stream| builder.push(stream));
356        builder.build()
357    }
358}
359
360#[stable(feature = "token_stream_extend", since = "1.30.0")]
361impl Extend<TokenTree> for TokenStream {
362    fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
363        let iter = trees.into_iter();
364        let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
365        iter.for_each(|tree| builder.push(tree));
366        builder.append_to(self);
367    }
368}
369
370#[stable(feature = "token_stream_extend", since = "1.30.0")]
371impl Extend<TokenStream> for TokenStream {
372    fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
373        let iter = streams.into_iter();
374        let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
375        iter.for_each(|stream| builder.push(stream));
376        builder.append_to(self);
377    }
378}
379
380#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
382pub mod token_stream {
383    use crate::{Group, Ident, Literal, Punct, TokenStream, TokenTree, bridge};
384
385    #[derive(Clone)]
389    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
390    pub struct IntoIter(
391        std::vec::IntoIter<
392            bridge::TokenTree<
393                bridge::client::TokenStream,
394                bridge::client::Span,
395                bridge::client::Symbol,
396            >,
397        >,
398    );
399
400    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
401    impl Iterator for IntoIter {
402        type Item = TokenTree;
403
404        fn next(&mut self) -> Option<TokenTree> {
405            self.0.next().map(|tree| match tree {
406                bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
407                bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
408                bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
409                bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
410            })
411        }
412
413        fn size_hint(&self) -> (usize, Option<usize>) {
414            self.0.size_hint()
415        }
416
417        fn count(self) -> usize {
418            self.0.count()
419        }
420    }
421
422    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
423    impl IntoIterator for TokenStream {
424        type Item = TokenTree;
425        type IntoIter = IntoIter;
426
427        fn into_iter(self) -> IntoIter {
428            IntoIter(self.0.map(|v| v.into_trees()).unwrap_or_default().into_iter())
429        }
430    }
431}
432
433#[unstable(feature = "proc_macro_quote", issue = "54722")]
440#[allow_internal_unstable(proc_macro_def_site, proc_macro_internals, proc_macro_totokens)]
441#[rustc_builtin_macro]
442pub macro quote($($t:tt)*) {
443    }
445
446#[unstable(feature = "proc_macro_internals", issue = "27812")]
447#[doc(hidden)]
448mod quote;
449
450#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
452#[derive(Copy, Clone)]
453pub struct Span(bridge::client::Span);
454
455#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
456impl !Send for Span {}
457#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
458impl !Sync for Span {}
459
460macro_rules! diagnostic_method {
461    ($name:ident, $level:expr) => {
462        #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
465        pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
466            Diagnostic::spanned(self, $level, message)
467        }
468    };
469}
470
471impl Span {
472    #[unstable(feature = "proc_macro_def_site", issue = "54724")]
474    pub fn def_site() -> Span {
475        Span(bridge::client::Span::def_site())
476    }
477
478    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
483    pub fn call_site() -> Span {
484        Span(bridge::client::Span::call_site())
485    }
486
487    #[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
492    pub fn mixed_site() -> Span {
493        Span(bridge::client::Span::mixed_site())
494    }
495
496    #[unstable(feature = "proc_macro_span", issue = "54725")]
499    pub fn parent(&self) -> Option<Span> {
500        self.0.parent().map(Span)
501    }
502
503    #[unstable(feature = "proc_macro_span", issue = "54725")]
507    pub fn source(&self) -> Span {
508        Span(self.0.source())
509    }
510
511    #[unstable(feature = "proc_macro_span", issue = "54725")]
513    pub fn byte_range(&self) -> Range<usize> {
514        self.0.byte_range()
515    }
516
517    #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
519    pub fn start(&self) -> Span {
520        Span(self.0.start())
521    }
522
523    #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
525    pub fn end(&self) -> Span {
526        Span(self.0.end())
527    }
528
529    #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
533    pub fn line(&self) -> usize {
534        self.0.line()
535    }
536
537    #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
541    pub fn column(&self) -> usize {
542        self.0.column()
543    }
544
545    #[stable(feature = "proc_macro_span_file", since = "1.88.0")]
550    pub fn file(&self) -> String {
551        self.0.file()
552    }
553
554    #[stable(feature = "proc_macro_span_file", since = "1.88.0")]
560    pub fn local_file(&self) -> Option<PathBuf> {
561        self.0.local_file().map(|s| PathBuf::from(s))
562    }
563
564    #[unstable(feature = "proc_macro_span", issue = "54725")]
568    pub fn join(&self, other: Span) -> Option<Span> {
569        self.0.join(other.0).map(Span)
570    }
571
572    #[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
575    pub fn resolved_at(&self, other: Span) -> Span {
576        Span(self.0.resolved_at(other.0))
577    }
578
579    #[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
582    pub fn located_at(&self, other: Span) -> Span {
583        other.resolved_at(*self)
584    }
585
586    #[unstable(feature = "proc_macro_span", issue = "54725")]
588    pub fn eq(&self, other: &Span) -> bool {
589        self.0 == other.0
590    }
591
592    #[stable(feature = "proc_macro_source_text", since = "1.66.0")]
600    pub fn source_text(&self) -> Option<String> {
601        self.0.source_text()
602    }
603
604    #[doc(hidden)]
606    #[unstable(feature = "proc_macro_internals", issue = "27812")]
607    pub fn save_span(&self) -> usize {
608        self.0.save_span()
609    }
610
611    #[doc(hidden)]
613    #[unstable(feature = "proc_macro_internals", issue = "27812")]
614    pub fn recover_proc_macro_span(id: usize) -> Span {
615        Span(bridge::client::Span::recover_proc_macro_span(id))
616    }
617
618    diagnostic_method!(error, Level::Error);
619    diagnostic_method!(warning, Level::Warning);
620    diagnostic_method!(note, Level::Note);
621    diagnostic_method!(help, Level::Help);
622}
623
624#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
626impl fmt::Debug for Span {
627    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
628        self.0.fmt(f)
629    }
630}
631
632#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
634#[derive(Clone)]
635pub enum TokenTree {
636    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
638    Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
639    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
641    Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
642    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
644    Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
645    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
647    Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
648}
649
650#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
651impl !Send for TokenTree {}
652#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
653impl !Sync for TokenTree {}
654
655impl TokenTree {
656    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
659    pub fn span(&self) -> Span {
660        match *self {
661            TokenTree::Group(ref t) => t.span(),
662            TokenTree::Ident(ref t) => t.span(),
663            TokenTree::Punct(ref t) => t.span(),
664            TokenTree::Literal(ref t) => t.span(),
665        }
666    }
667
668    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
674    pub fn set_span(&mut self, span: Span) {
675        match *self {
676            TokenTree::Group(ref mut t) => t.set_span(span),
677            TokenTree::Ident(ref mut t) => t.set_span(span),
678            TokenTree::Punct(ref mut t) => t.set_span(span),
679            TokenTree::Literal(ref mut t) => t.set_span(span),
680        }
681    }
682}
683
684#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
686impl fmt::Debug for TokenTree {
687    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
688        match *self {
691            TokenTree::Group(ref tt) => tt.fmt(f),
692            TokenTree::Ident(ref tt) => tt.fmt(f),
693            TokenTree::Punct(ref tt) => tt.fmt(f),
694            TokenTree::Literal(ref tt) => tt.fmt(f),
695        }
696    }
697}
698
699#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
700impl From<Group> for TokenTree {
701    fn from(g: Group) -> TokenTree {
702        TokenTree::Group(g)
703    }
704}
705
706#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
707impl From<Ident> for TokenTree {
708    fn from(g: Ident) -> TokenTree {
709        TokenTree::Ident(g)
710    }
711}
712
713#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
714impl From<Punct> for TokenTree {
715    fn from(g: Punct) -> TokenTree {
716        TokenTree::Punct(g)
717    }
718}
719
720#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
721impl From<Literal> for TokenTree {
722    fn from(g: Literal) -> TokenTree {
723        TokenTree::Literal(g)
724    }
725}
726
727#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
739impl fmt::Display for TokenTree {
740    #[allow(clippy::recursive_format_impl)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
742        match self {
743            TokenTree::Group(t) => write!(f, "{t}"),
744            TokenTree::Ident(t) => write!(f, "{t}"),
745            TokenTree::Punct(t) => write!(f, "{t}"),
746            TokenTree::Literal(t) => write!(f, "{t}"),
747        }
748    }
749}
750
751#[derive(Clone)]
755#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
756pub struct Group(bridge::Group<bridge::client::TokenStream, bridge::client::Span>);
757
758#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
759impl !Send for Group {}
760#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
761impl !Sync for Group {}
762
763#[derive(Copy, Clone, Debug, PartialEq, Eq)]
765#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
766pub enum Delimiter {
767    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
769    Parenthesis,
770    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
772    Brace,
773    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
775    Bracket,
776    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
794    None,
795}
796
797impl Group {
798    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
804    pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
805        Group(bridge::Group {
806            delimiter,
807            stream: stream.0,
808            span: bridge::DelimSpan::from_single(Span::call_site().0),
809        })
810    }
811
812    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
814    pub fn delimiter(&self) -> Delimiter {
815        self.0.delimiter
816    }
817
818    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
823    pub fn stream(&self) -> TokenStream {
824        TokenStream(self.0.stream.clone())
825    }
826
827    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
835    pub fn span(&self) -> Span {
836        Span(self.0.span.entire)
837    }
838
839    #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
846    pub fn span_open(&self) -> Span {
847        Span(self.0.span.open)
848    }
849
850    #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
857    pub fn span_close(&self) -> Span {
858        Span(self.0.span.close)
859    }
860
861    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
868    pub fn set_span(&mut self, span: Span) {
869        self.0.span = bridge::DelimSpan::from_single(span.0);
870    }
871}
872
873#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
877impl fmt::Display for Group {
878    #[allow(clippy::recursive_format_impl)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
880        write!(f, "{}", TokenStream::from(TokenTree::from(self.clone())))
881    }
882}
883
884#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
885impl fmt::Debug for Group {
886    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
887        f.debug_struct("Group")
888            .field("delimiter", &self.delimiter())
889            .field("stream", &self.stream())
890            .field("span", &self.span())
891            .finish()
892    }
893}
894
895#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
900#[derive(Clone)]
901pub struct Punct(bridge::Punct<bridge::client::Span>);
902
903#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
904impl !Send for Punct {}
905#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
906impl !Sync for Punct {}
907
908#[derive(Copy, Clone, Debug, PartialEq, Eq)]
911#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
912pub enum Spacing {
913    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
925    Joint,
926    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
933    Alone,
934}
935
936impl Punct {
937    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
944    pub fn new(ch: char, spacing: Spacing) -> Punct {
945        const LEGAL_CHARS: &[char] = &[
946            '=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
947            ':', '#', '$', '?', '\'',
948        ];
949        if !LEGAL_CHARS.contains(&ch) {
950            panic!("unsupported character `{:?}`", ch);
951        }
952        Punct(bridge::Punct {
953            ch: ch as u8,
954            joint: spacing == Spacing::Joint,
955            span: Span::call_site().0,
956        })
957    }
958
959    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
961    pub fn as_char(&self) -> char {
962        self.0.ch as char
963    }
964
965    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
969    pub fn spacing(&self) -> Spacing {
970        if self.0.joint { Spacing::Joint } else { Spacing::Alone }
971    }
972
973    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
975    pub fn span(&self) -> Span {
976        Span(self.0.span)
977    }
978
979    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
981    pub fn set_span(&mut self, span: Span) {
982        self.0.span = span.0;
983    }
984}
985
986#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
989impl fmt::Display for Punct {
990    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
991        write!(f, "{}", self.as_char())
992    }
993}
994
995#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
996impl fmt::Debug for Punct {
997    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
998        f.debug_struct("Punct")
999            .field("ch", &self.as_char())
1000            .field("spacing", &self.spacing())
1001            .field("span", &self.span())
1002            .finish()
1003    }
1004}
1005
1006#[stable(feature = "proc_macro_punct_eq", since = "1.50.0")]
1007impl PartialEq<char> for Punct {
1008    fn eq(&self, rhs: &char) -> bool {
1009        self.as_char() == *rhs
1010    }
1011}
1012
1013#[stable(feature = "proc_macro_punct_eq_flipped", since = "1.52.0")]
1014impl PartialEq<Punct> for char {
1015    fn eq(&self, rhs: &Punct) -> bool {
1016        *self == rhs.as_char()
1017    }
1018}
1019
1020#[derive(Clone)]
1022#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1023pub struct Ident(bridge::Ident<bridge::client::Span, bridge::client::Symbol>);
1024
1025impl Ident {
1026    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1046    pub fn new(string: &str, span: Span) -> Ident {
1047        Ident(bridge::Ident {
1048            sym: bridge::client::Symbol::new_ident(string, false),
1049            is_raw: false,
1050            span: span.0,
1051        })
1052    }
1053
1054    #[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
1059    pub fn new_raw(string: &str, span: Span) -> Ident {
1060        Ident(bridge::Ident {
1061            sym: bridge::client::Symbol::new_ident(string, true),
1062            is_raw: true,
1063            span: span.0,
1064        })
1065    }
1066
1067    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1070    pub fn span(&self) -> Span {
1071        Span(self.0.span)
1072    }
1073
1074    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1076    pub fn set_span(&mut self, span: Span) {
1077        self.0.span = span.0;
1078    }
1079}
1080
1081#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1084impl fmt::Display for Ident {
1085    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1086        if self.0.is_raw {
1087            f.write_str("r#")?;
1088        }
1089        fmt::Display::fmt(&self.0.sym, f)
1090    }
1091}
1092
1093#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1094impl fmt::Debug for Ident {
1095    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1096        f.debug_struct("Ident")
1097            .field("ident", &self.to_string())
1098            .field("span", &self.span())
1099            .finish()
1100    }
1101}
1102
1103#[derive(Clone)]
1108#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1109pub struct Literal(bridge::Literal<bridge::client::Span, bridge::client::Symbol>);
1110
1111macro_rules! suffixed_int_literals {
1112    ($($name:ident => $kind:ident,)*) => ($(
1113        #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1125        pub fn $name(n: $kind) -> Literal {
1126            Literal(bridge::Literal {
1127                kind: bridge::LitKind::Integer,
1128                symbol: bridge::client::Symbol::new(&n.to_string()),
1129                suffix: Some(bridge::client::Symbol::new(stringify!($kind))),
1130                span: Span::call_site().0,
1131            })
1132        }
1133    )*)
1134}
1135
1136macro_rules! unsuffixed_int_literals {
1137    ($($name:ident => $kind:ident,)*) => ($(
1138        #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1152        pub fn $name(n: $kind) -> Literal {
1153            Literal(bridge::Literal {
1154                kind: bridge::LitKind::Integer,
1155                symbol: bridge::client::Symbol::new(&n.to_string()),
1156                suffix: None,
1157                span: Span::call_site().0,
1158            })
1159        }
1160    )*)
1161}
1162
1163impl Literal {
1164    fn new(kind: bridge::LitKind, value: &str, suffix: Option<&str>) -> Self {
1165        Literal(bridge::Literal {
1166            kind,
1167            symbol: bridge::client::Symbol::new(value),
1168            suffix: suffix.map(bridge::client::Symbol::new),
1169            span: Span::call_site().0,
1170        })
1171    }
1172
1173    suffixed_int_literals! {
1174        u8_suffixed => u8,
1175        u16_suffixed => u16,
1176        u32_suffixed => u32,
1177        u64_suffixed => u64,
1178        u128_suffixed => u128,
1179        usize_suffixed => usize,
1180        i8_suffixed => i8,
1181        i16_suffixed => i16,
1182        i32_suffixed => i32,
1183        i64_suffixed => i64,
1184        i128_suffixed => i128,
1185        isize_suffixed => isize,
1186    }
1187
1188    unsuffixed_int_literals! {
1189        u8_unsuffixed => u8,
1190        u16_unsuffixed => u16,
1191        u32_unsuffixed => u32,
1192        u64_unsuffixed => u64,
1193        u128_unsuffixed => u128,
1194        usize_unsuffixed => usize,
1195        i8_unsuffixed => i8,
1196        i16_unsuffixed => i16,
1197        i32_unsuffixed => i32,
1198        i64_unsuffixed => i64,
1199        i128_unsuffixed => i128,
1200        isize_unsuffixed => isize,
1201    }
1202
1203    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1216    pub fn f32_unsuffixed(n: f32) -> Literal {
1217        if !n.is_finite() {
1218            panic!("Invalid float literal {n}");
1219        }
1220        let mut repr = n.to_string();
1221        if !repr.contains('.') {
1222            repr.push_str(".0");
1223        }
1224        Literal::new(bridge::LitKind::Float, &repr, None)
1225    }
1226
1227    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1241    pub fn f32_suffixed(n: f32) -> Literal {
1242        if !n.is_finite() {
1243            panic!("Invalid float literal {n}");
1244        }
1245        Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f32"))
1246    }
1247
1248    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1261    pub fn f64_unsuffixed(n: f64) -> Literal {
1262        if !n.is_finite() {
1263            panic!("Invalid float literal {n}");
1264        }
1265        let mut repr = n.to_string();
1266        if !repr.contains('.') {
1267            repr.push_str(".0");
1268        }
1269        Literal::new(bridge::LitKind::Float, &repr, None)
1270    }
1271
1272    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1286    pub fn f64_suffixed(n: f64) -> Literal {
1287        if !n.is_finite() {
1288            panic!("Invalid float literal {n}");
1289        }
1290        Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f64"))
1291    }
1292
1293    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1295    pub fn string(string: &str) -> Literal {
1296        let escape = EscapeOptions {
1297            escape_single_quote: false,
1298            escape_double_quote: true,
1299            escape_nonascii: false,
1300        };
1301        let repr = escape_bytes(string.as_bytes(), escape);
1302        Literal::new(bridge::LitKind::Str, &repr, None)
1303    }
1304
1305    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1307    pub fn character(ch: char) -> Literal {
1308        let escape = EscapeOptions {
1309            escape_single_quote: true,
1310            escape_double_quote: false,
1311            escape_nonascii: false,
1312        };
1313        let repr = escape_bytes(ch.encode_utf8(&mut [0u8; 4]).as_bytes(), escape);
1314        Literal::new(bridge::LitKind::Char, &repr, None)
1315    }
1316
1317    #[stable(feature = "proc_macro_byte_character", since = "1.79.0")]
1319    pub fn byte_character(byte: u8) -> Literal {
1320        let escape = EscapeOptions {
1321            escape_single_quote: true,
1322            escape_double_quote: false,
1323            escape_nonascii: true,
1324        };
1325        let repr = escape_bytes(&[byte], escape);
1326        Literal::new(bridge::LitKind::Byte, &repr, None)
1327    }
1328
1329    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1331    pub fn byte_string(bytes: &[u8]) -> Literal {
1332        let escape = EscapeOptions {
1333            escape_single_quote: false,
1334            escape_double_quote: true,
1335            escape_nonascii: true,
1336        };
1337        let repr = escape_bytes(bytes, escape);
1338        Literal::new(bridge::LitKind::ByteStr, &repr, None)
1339    }
1340
1341    #[stable(feature = "proc_macro_c_str_literals", since = "1.79.0")]
1343    pub fn c_string(string: &CStr) -> Literal {
1344        let escape = EscapeOptions {
1345            escape_single_quote: false,
1346            escape_double_quote: true,
1347            escape_nonascii: false,
1348        };
1349        let repr = escape_bytes(string.to_bytes(), escape);
1350        Literal::new(bridge::LitKind::CStr, &repr, None)
1351    }
1352
1353    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1355    pub fn span(&self) -> Span {
1356        Span(self.0.span)
1357    }
1358
1359    #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1361    pub fn set_span(&mut self, span: Span) {
1362        self.0.span = span.0;
1363    }
1364
1365    #[unstable(feature = "proc_macro_span", issue = "54725")]
1377    pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1378        self.0.span.subspan(range.start_bound().cloned(), range.end_bound().cloned()).map(Span)
1379    }
1380
1381    fn with_symbol_and_suffix<R>(&self, f: impl FnOnce(&str, &str) -> R) -> R {
1382        self.0.symbol.with(|symbol| match self.0.suffix {
1383            Some(suffix) => suffix.with(|suffix| f(symbol, suffix)),
1384            None => f(symbol, ""),
1385        })
1386    }
1387
1388    fn with_stringify_parts<R>(&self, f: impl FnOnce(&[&str]) -> R) -> R {
1393        fn get_hashes_str(num: u8) -> &'static str {
1397            const HASHES: &str = "\
1398            ################################################################\
1399            ################################################################\
1400            ################################################################\
1401            ################################################################\
1402            ";
1403            const _: () = assert!(HASHES.len() == 256);
1404            &HASHES[..num as usize]
1405        }
1406
1407        self.with_symbol_and_suffix(|symbol, suffix| match self.0.kind {
1408            bridge::LitKind::Byte => f(&["b'", symbol, "'", suffix]),
1409            bridge::LitKind::Char => f(&["'", symbol, "'", suffix]),
1410            bridge::LitKind::Str => f(&["\"", symbol, "\"", suffix]),
1411            bridge::LitKind::StrRaw(n) => {
1412                let hashes = get_hashes_str(n);
1413                f(&["r", hashes, "\"", symbol, "\"", hashes, suffix])
1414            }
1415            bridge::LitKind::ByteStr => f(&["b\"", symbol, "\"", suffix]),
1416            bridge::LitKind::ByteStrRaw(n) => {
1417                let hashes = get_hashes_str(n);
1418                f(&["br", hashes, "\"", symbol, "\"", hashes, suffix])
1419            }
1420            bridge::LitKind::CStr => f(&["c\"", symbol, "\"", suffix]),
1421            bridge::LitKind::CStrRaw(n) => {
1422                let hashes = get_hashes_str(n);
1423                f(&["cr", hashes, "\"", symbol, "\"", hashes, suffix])
1424            }
1425
1426            bridge::LitKind::Integer | bridge::LitKind::Float | bridge::LitKind::ErrWithGuar => {
1427                f(&[symbol, suffix])
1428            }
1429        })
1430    }
1431
1432    #[unstable(feature = "proc_macro_value", issue = "136652")]
1434    pub fn str_value(&self) -> Result<String, ConversionErrorKind> {
1435        self.0.symbol.with(|symbol| match self.0.kind {
1436            bridge::LitKind::Str => {
1437                if symbol.contains('\\') {
1438                    let mut buf = String::with_capacity(symbol.len());
1439                    let mut error = None;
1440                    unescape_str(
1444                        symbol,
1445                        #[inline(always)]
1446                        |_, c| match c {
1447                            Ok(c) => buf.push(c),
1448                            Err(err) => {
1449                                if err.is_fatal() {
1450                                    error = Some(ConversionErrorKind::FailedToUnescape(err));
1451                                }
1452                            }
1453                        },
1454                    );
1455                    if let Some(error) = error { Err(error) } else { Ok(buf) }
1456                } else {
1457                    Ok(symbol.to_string())
1458                }
1459            }
1460            bridge::LitKind::StrRaw(_) => Ok(symbol.to_string()),
1461            _ => Err(ConversionErrorKind::InvalidLiteralKind),
1462        })
1463    }
1464
1465    #[unstable(feature = "proc_macro_value", issue = "136652")]
1468    pub fn cstr_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1469        self.0.symbol.with(|symbol| match self.0.kind {
1470            bridge::LitKind::CStr => {
1471                let mut error = None;
1472                let mut buf = Vec::with_capacity(symbol.len());
1473
1474                unescape_c_str(symbol, |_span, res| match res {
1475                    Ok(MixedUnit::Char(c)) => {
1476                        buf.extend_from_slice(c.get().encode_utf8(&mut [0; 4]).as_bytes())
1477                    }
1478                    Ok(MixedUnit::HighByte(b)) => buf.push(b.get()),
1479                    Err(err) => {
1480                        if err.is_fatal() {
1481                            error = Some(ConversionErrorKind::FailedToUnescape(err));
1482                        }
1483                    }
1484                });
1485                if let Some(error) = error {
1486                    Err(error)
1487                } else {
1488                    buf.push(0);
1489                    Ok(buf)
1490                }
1491            }
1492            bridge::LitKind::CStrRaw(_) => {
1493                let mut buf = symbol.to_owned().into_bytes();
1497                buf.push(0);
1498                Ok(buf)
1499            }
1500            _ => Err(ConversionErrorKind::InvalidLiteralKind),
1501        })
1502    }
1503
1504    #[unstable(feature = "proc_macro_value", issue = "136652")]
1507    pub fn byte_str_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1508        self.0.symbol.with(|symbol| match self.0.kind {
1509            bridge::LitKind::ByteStr => {
1510                let mut buf = Vec::with_capacity(symbol.len());
1511                let mut error = None;
1512
1513                unescape_byte_str(symbol, |_, res| match res {
1514                    Ok(b) => buf.push(b),
1515                    Err(err) => {
1516                        if err.is_fatal() {
1517                            error = Some(ConversionErrorKind::FailedToUnescape(err));
1518                        }
1519                    }
1520                });
1521                if let Some(error) = error { Err(error) } else { Ok(buf) }
1522            }
1523            bridge::LitKind::ByteStrRaw(_) => {
1524                Ok(symbol.to_owned().into_bytes())
1527            }
1528            _ => Err(ConversionErrorKind::InvalidLiteralKind),
1529        })
1530    }
1531}
1532
1533#[stable(feature = "proc_macro_literal_parse", since = "1.54.0")]
1544impl FromStr for Literal {
1545    type Err = LexError;
1546
1547    fn from_str(src: &str) -> Result<Self, LexError> {
1548        match bridge::client::FreeFunctions::literal_from_str(src) {
1549            Ok(literal) => Ok(Literal(literal)),
1550            Err(()) => Err(LexError),
1551        }
1552    }
1553}
1554
1555#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1558impl fmt::Display for Literal {
1559    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1560        self.with_stringify_parts(|parts| {
1561            for part in parts {
1562                fmt::Display::fmt(part, f)?;
1563            }
1564            Ok(())
1565        })
1566    }
1567}
1568
1569#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1570impl fmt::Debug for Literal {
1571    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1572        f.debug_struct("Literal")
1573            .field("kind", &format_args!("{:?}", self.0.kind))
1575            .field("symbol", &self.0.symbol)
1576            .field("suffix", &format_args!("{:?}", self.0.suffix))
1578            .field("span", &self.0.span)
1579            .finish()
1580    }
1581}
1582
1583#[unstable(feature = "proc_macro_tracked_env", issue = "99515")]
1585pub mod tracked_env {
1586    use std::env::{self, VarError};
1587    use std::ffi::OsStr;
1588
1589    #[unstable(feature = "proc_macro_tracked_env", issue = "99515")]
1595    pub fn var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1596        let key: &str = key.as_ref();
1597        let value = crate::bridge::client::FreeFunctions::injected_env_var(key)
1598            .map_or_else(|| env::var(key), Ok);
1599        crate::bridge::client::FreeFunctions::track_env_var(key, value.as_deref().ok());
1600        value
1601    }
1602}
1603
1604#[unstable(feature = "track_path", issue = "99515")]
1606pub mod tracked_path {
1607
1608    #[unstable(feature = "track_path", issue = "99515")]
1612    pub fn path<P: AsRef<str>>(path: P) {
1613        let path: &str = path.as_ref();
1614        crate::bridge::client::FreeFunctions::track_path(path);
1615    }
1616}