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(extend_one)]
31#![recursion_limit = "256"]
32#![allow(internal_features)]
33#![deny(ffi_unwind_calls)]
34#![warn(rustdoc::unescaped_backticks)]
35#![warn(unreachable_pub)]
36
37#[unstable(feature = "proc_macro_internals", issue = "27812")]
38#[doc(hidden)]
39pub mod bridge;
40
41mod diagnostic;
42mod escape;
43mod to_tokens;
44
45use std::ffi::CStr;
46use std::ops::{Range, RangeBounds};
47use std::path::PathBuf;
48use std::str::FromStr;
49use std::{error, fmt};
50
51#[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
52pub use diagnostic::{Diagnostic, Level, MultiSpan};
53#[unstable(feature = "proc_macro_totokens", issue = "130977")]
54pub use to_tokens::ToTokens;
55
56use crate::escape::{EscapeOptions, escape_bytes};
57
58#[stable(feature = "proc_macro_is_available", since = "1.57.0")]
72pub fn is_available() -> bool {
73 bridge::client::is_available()
74}
75
76#[rustc_diagnostic_item = "TokenStream"]
84#[stable(feature = "proc_macro_lib", since = "1.15.0")]
85#[derive(Clone)]
86pub struct TokenStream(Option<bridge::client::TokenStream>);
87
88#[stable(feature = "proc_macro_lib", since = "1.15.0")]
89impl !Send for TokenStream {}
90#[stable(feature = "proc_macro_lib", since = "1.15.0")]
91impl !Sync for TokenStream {}
92
93#[stable(feature = "proc_macro_lib", since = "1.15.0")]
95#[non_exhaustive]
96#[derive(Debug)]
97pub struct LexError;
98
99#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
100impl fmt::Display for LexError {
101 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102 f.write_str("cannot parse string into token stream")
103 }
104}
105
106#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
107impl error::Error for LexError {}
108
109#[stable(feature = "proc_macro_lib", since = "1.15.0")]
110impl !Send for LexError {}
111#[stable(feature = "proc_macro_lib", since = "1.15.0")]
112impl !Sync for LexError {}
113
114#[unstable(feature = "proc_macro_expand", issue = "90765")]
116#[non_exhaustive]
117#[derive(Debug)]
118pub struct ExpandError;
119
120#[unstable(feature = "proc_macro_expand", issue = "90765")]
121impl fmt::Display for ExpandError {
122 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123 f.write_str("macro expansion failed")
124 }
125}
126
127#[unstable(feature = "proc_macro_expand", issue = "90765")]
128impl error::Error for ExpandError {}
129
130#[unstable(feature = "proc_macro_expand", issue = "90765")]
131impl !Send for ExpandError {}
132
133#[unstable(feature = "proc_macro_expand", issue = "90765")]
134impl !Sync for ExpandError {}
135
136impl TokenStream {
137 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
139 pub fn new() -> TokenStream {
140 TokenStream(None)
141 }
142
143 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
145 pub fn is_empty(&self) -> bool {
146 self.0.as_ref().map(|h| h.is_empty()).unwrap_or(true)
147 }
148
149 #[unstable(feature = "proc_macro_expand", issue = "90765")]
160 pub fn expand_expr(&self) -> Result<TokenStream, ExpandError> {
161 let stream = self.0.as_ref().ok_or(ExpandError)?;
162 match bridge::client::TokenStream::expand_expr(stream) {
163 Ok(stream) => Ok(TokenStream(Some(stream))),
164 Err(_) => Err(ExpandError),
165 }
166 }
167}
168
169#[stable(feature = "proc_macro_lib", since = "1.15.0")]
177impl FromStr for TokenStream {
178 type Err = LexError;
179
180 fn from_str(src: &str) -> Result<TokenStream, LexError> {
181 Ok(TokenStream(Some(bridge::client::TokenStream::from_str(src))))
182 }
183}
184
185#[stable(feature = "proc_macro_lib", since = "1.15.0")]
197impl fmt::Display for TokenStream {
198 #[allow(clippy::recursive_format_impl)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
200 match &self.0 {
201 Some(ts) => write!(f, "{}", ts.to_string()),
202 None => Ok(()),
203 }
204 }
205}
206
207#[stable(feature = "proc_macro_lib", since = "1.15.0")]
209impl fmt::Debug for TokenStream {
210 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
211 f.write_str("TokenStream ")?;
212 f.debug_list().entries(self.clone()).finish()
213 }
214}
215
216#[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
217impl Default for TokenStream {
218 fn default() -> Self {
219 TokenStream::new()
220 }
221}
222
223#[unstable(feature = "proc_macro_quote", issue = "54722")]
224pub use quote::{quote, quote_span};
225
226fn tree_to_bridge_tree(
227 tree: TokenTree,
228) -> bridge::TokenTree<bridge::client::TokenStream, bridge::client::Span, bridge::client::Symbol> {
229 match tree {
230 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
231 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
232 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
233 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
234 }
235}
236
237#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
239impl From<TokenTree> for TokenStream {
240 fn from(tree: TokenTree) -> TokenStream {
241 TokenStream(Some(bridge::client::TokenStream::from_token_tree(tree_to_bridge_tree(tree))))
242 }
243}
244
245struct ConcatTreesHelper {
248 trees: Vec<
249 bridge::TokenTree<
250 bridge::client::TokenStream,
251 bridge::client::Span,
252 bridge::client::Symbol,
253 >,
254 >,
255}
256
257impl ConcatTreesHelper {
258 fn new(capacity: usize) -> Self {
259 ConcatTreesHelper { trees: Vec::with_capacity(capacity) }
260 }
261
262 fn push(&mut self, tree: TokenTree) {
263 self.trees.push(tree_to_bridge_tree(tree));
264 }
265
266 fn build(self) -> TokenStream {
267 if self.trees.is_empty() {
268 TokenStream(None)
269 } else {
270 TokenStream(Some(bridge::client::TokenStream::concat_trees(None, self.trees)))
271 }
272 }
273
274 fn append_to(self, stream: &mut TokenStream) {
275 if self.trees.is_empty() {
276 return;
277 }
278 stream.0 = Some(bridge::client::TokenStream::concat_trees(stream.0.take(), self.trees))
279 }
280}
281
282struct ConcatStreamsHelper {
285 streams: Vec<bridge::client::TokenStream>,
286}
287
288impl ConcatStreamsHelper {
289 fn new(capacity: usize) -> Self {
290 ConcatStreamsHelper { streams: Vec::with_capacity(capacity) }
291 }
292
293 fn push(&mut self, stream: TokenStream) {
294 if let Some(stream) = stream.0 {
295 self.streams.push(stream);
296 }
297 }
298
299 fn build(mut self) -> TokenStream {
300 if self.streams.len() <= 1 {
301 TokenStream(self.streams.pop())
302 } else {
303 TokenStream(Some(bridge::client::TokenStream::concat_streams(None, self.streams)))
304 }
305 }
306
307 fn append_to(mut self, stream: &mut TokenStream) {
308 if self.streams.is_empty() {
309 return;
310 }
311 let base = stream.0.take();
312 if base.is_none() && self.streams.len() == 1 {
313 stream.0 = self.streams.pop();
314 } else {
315 stream.0 = Some(bridge::client::TokenStream::concat_streams(base, self.streams));
316 }
317 }
318}
319
320#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
322impl FromIterator<TokenTree> for TokenStream {
323 fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
324 let iter = trees.into_iter();
325 let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
326 iter.for_each(|tree| builder.push(tree));
327 builder.build()
328 }
329}
330
331#[stable(feature = "proc_macro_lib", since = "1.15.0")]
334impl FromIterator<TokenStream> for TokenStream {
335 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
336 let iter = streams.into_iter();
337 let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
338 iter.for_each(|stream| builder.push(stream));
339 builder.build()
340 }
341}
342
343#[stable(feature = "token_stream_extend", since = "1.30.0")]
344impl Extend<TokenTree> for TokenStream {
345 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
346 let iter = trees.into_iter();
347 let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
348 iter.for_each(|tree| builder.push(tree));
349 builder.append_to(self);
350 }
351}
352
353#[stable(feature = "token_stream_extend", since = "1.30.0")]
354impl Extend<TokenStream> for TokenStream {
355 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
356 let iter = streams.into_iter();
357 let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
358 iter.for_each(|stream| builder.push(stream));
359 builder.append_to(self);
360 }
361}
362
363#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
365pub mod token_stream {
366 use crate::{Group, Ident, Literal, Punct, TokenStream, TokenTree, bridge};
367
368 #[derive(Clone)]
372 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
373 pub struct IntoIter(
374 std::vec::IntoIter<
375 bridge::TokenTree<
376 bridge::client::TokenStream,
377 bridge::client::Span,
378 bridge::client::Symbol,
379 >,
380 >,
381 );
382
383 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
384 impl Iterator for IntoIter {
385 type Item = TokenTree;
386
387 fn next(&mut self) -> Option<TokenTree> {
388 self.0.next().map(|tree| match tree {
389 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
390 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
391 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
392 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
393 })
394 }
395
396 fn size_hint(&self) -> (usize, Option<usize>) {
397 self.0.size_hint()
398 }
399
400 fn count(self) -> usize {
401 self.0.count()
402 }
403 }
404
405 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
406 impl IntoIterator for TokenStream {
407 type Item = TokenTree;
408 type IntoIter = IntoIter;
409
410 fn into_iter(self) -> IntoIter {
411 IntoIter(self.0.map(|v| v.into_trees()).unwrap_or_default().into_iter())
412 }
413 }
414}
415
416#[unstable(feature = "proc_macro_quote", issue = "54722")]
423#[allow_internal_unstable(proc_macro_def_site, proc_macro_internals, proc_macro_totokens)]
424#[rustc_builtin_macro]
425pub macro quote($($t:tt)*) {
426 }
428
429#[unstable(feature = "proc_macro_internals", issue = "27812")]
430#[doc(hidden)]
431mod quote;
432
433#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
435#[derive(Copy, Clone)]
436pub struct Span(bridge::client::Span);
437
438#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
439impl !Send for Span {}
440#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
441impl !Sync for Span {}
442
443macro_rules! diagnostic_method {
444 ($name:ident, $level:expr) => {
445 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
448 pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
449 Diagnostic::spanned(self, $level, message)
450 }
451 };
452}
453
454impl Span {
455 #[unstable(feature = "proc_macro_def_site", issue = "54724")]
457 pub fn def_site() -> Span {
458 Span(bridge::client::Span::def_site())
459 }
460
461 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
466 pub fn call_site() -> Span {
467 Span(bridge::client::Span::call_site())
468 }
469
470 #[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
475 pub fn mixed_site() -> Span {
476 Span(bridge::client::Span::mixed_site())
477 }
478
479 #[unstable(feature = "proc_macro_span", issue = "54725")]
481 pub fn source_file(&self) -> SourceFile {
482 SourceFile(self.0.source_file())
483 }
484
485 #[unstable(feature = "proc_macro_span", issue = "54725")]
488 pub fn parent(&self) -> Option<Span> {
489 self.0.parent().map(Span)
490 }
491
492 #[unstable(feature = "proc_macro_span", issue = "54725")]
496 pub fn source(&self) -> Span {
497 Span(self.0.source())
498 }
499
500 #[unstable(feature = "proc_macro_span", issue = "54725")]
502 pub fn byte_range(&self) -> Range<usize> {
503 self.0.byte_range()
504 }
505
506 #[unstable(feature = "proc_macro_span", issue = "54725")]
508 pub fn start(&self) -> Span {
509 Span(self.0.start())
510 }
511
512 #[unstable(feature = "proc_macro_span", issue = "54725")]
514 pub fn end(&self) -> Span {
515 Span(self.0.end())
516 }
517
518 #[unstable(feature = "proc_macro_span", issue = "54725")]
522 pub fn line(&self) -> usize {
523 self.0.line()
524 }
525
526 #[unstable(feature = "proc_macro_span", issue = "54725")]
530 pub fn column(&self) -> usize {
531 self.0.column()
532 }
533
534 #[unstable(feature = "proc_macro_span", issue = "54725")]
538 pub fn join(&self, other: Span) -> Option<Span> {
539 self.0.join(other.0).map(Span)
540 }
541
542 #[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
545 pub fn resolved_at(&self, other: Span) -> Span {
546 Span(self.0.resolved_at(other.0))
547 }
548
549 #[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
552 pub fn located_at(&self, other: Span) -> Span {
553 other.resolved_at(*self)
554 }
555
556 #[unstable(feature = "proc_macro_span", issue = "54725")]
558 pub fn eq(&self, other: &Span) -> bool {
559 self.0 == other.0
560 }
561
562 #[stable(feature = "proc_macro_source_text", since = "1.66.0")]
570 pub fn source_text(&self) -> Option<String> {
571 self.0.source_text()
572 }
573
574 #[doc(hidden)]
576 #[unstable(feature = "proc_macro_internals", issue = "27812")]
577 pub fn save_span(&self) -> usize {
578 self.0.save_span()
579 }
580
581 #[doc(hidden)]
583 #[unstable(feature = "proc_macro_internals", issue = "27812")]
584 pub fn recover_proc_macro_span(id: usize) -> Span {
585 Span(bridge::client::Span::recover_proc_macro_span(id))
586 }
587
588 diagnostic_method!(error, Level::Error);
589 diagnostic_method!(warning, Level::Warning);
590 diagnostic_method!(note, Level::Note);
591 diagnostic_method!(help, Level::Help);
592}
593
594#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
596impl fmt::Debug for Span {
597 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
598 self.0.fmt(f)
599 }
600}
601
602#[unstable(feature = "proc_macro_span", issue = "54725")]
604#[derive(Clone)]
605pub struct SourceFile(bridge::client::SourceFile);
606
607impl SourceFile {
608 #[unstable(feature = "proc_macro_span", issue = "54725")]
619 pub fn path(&self) -> PathBuf {
620 PathBuf::from(self.0.path())
621 }
622
623 #[unstable(feature = "proc_macro_span", issue = "54725")]
626 pub fn is_real(&self) -> bool {
627 self.0.is_real()
631 }
632}
633
634#[unstable(feature = "proc_macro_span", issue = "54725")]
635impl fmt::Debug for SourceFile {
636 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
637 f.debug_struct("SourceFile")
638 .field("path", &self.path())
639 .field("is_real", &self.is_real())
640 .finish()
641 }
642}
643
644#[unstable(feature = "proc_macro_span", issue = "54725")]
645impl PartialEq for SourceFile {
646 fn eq(&self, other: &Self) -> bool {
647 self.0.eq(&other.0)
648 }
649}
650
651#[unstable(feature = "proc_macro_span", issue = "54725")]
652impl Eq for SourceFile {}
653
654#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
656#[derive(Clone)]
657pub enum TokenTree {
658 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
660 Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
661 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
663 Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
664 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
666 Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
667 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
669 Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
670}
671
672#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
673impl !Send for TokenTree {}
674#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
675impl !Sync for TokenTree {}
676
677impl TokenTree {
678 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
681 pub fn span(&self) -> Span {
682 match *self {
683 TokenTree::Group(ref t) => t.span(),
684 TokenTree::Ident(ref t) => t.span(),
685 TokenTree::Punct(ref t) => t.span(),
686 TokenTree::Literal(ref t) => t.span(),
687 }
688 }
689
690 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
696 pub fn set_span(&mut self, span: Span) {
697 match *self {
698 TokenTree::Group(ref mut t) => t.set_span(span),
699 TokenTree::Ident(ref mut t) => t.set_span(span),
700 TokenTree::Punct(ref mut t) => t.set_span(span),
701 TokenTree::Literal(ref mut t) => t.set_span(span),
702 }
703 }
704}
705
706#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
708impl fmt::Debug for TokenTree {
709 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
710 match *self {
713 TokenTree::Group(ref tt) => tt.fmt(f),
714 TokenTree::Ident(ref tt) => tt.fmt(f),
715 TokenTree::Punct(ref tt) => tt.fmt(f),
716 TokenTree::Literal(ref tt) => tt.fmt(f),
717 }
718 }
719}
720
721#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
722impl From<Group> for TokenTree {
723 fn from(g: Group) -> TokenTree {
724 TokenTree::Group(g)
725 }
726}
727
728#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
729impl From<Ident> for TokenTree {
730 fn from(g: Ident) -> TokenTree {
731 TokenTree::Ident(g)
732 }
733}
734
735#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
736impl From<Punct> for TokenTree {
737 fn from(g: Punct) -> TokenTree {
738 TokenTree::Punct(g)
739 }
740}
741
742#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
743impl From<Literal> for TokenTree {
744 fn from(g: Literal) -> TokenTree {
745 TokenTree::Literal(g)
746 }
747}
748
749#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
761impl fmt::Display for TokenTree {
762 #[allow(clippy::recursive_format_impl)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
764 match self {
765 TokenTree::Group(t) => write!(f, "{t}"),
766 TokenTree::Ident(t) => write!(f, "{t}"),
767 TokenTree::Punct(t) => write!(f, "{t}"),
768 TokenTree::Literal(t) => write!(f, "{t}"),
769 }
770 }
771}
772
773#[derive(Clone)]
777#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
778pub struct Group(bridge::Group<bridge::client::TokenStream, bridge::client::Span>);
779
780#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
781impl !Send for Group {}
782#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
783impl !Sync for Group {}
784
785#[derive(Copy, Clone, Debug, PartialEq, Eq)]
787#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
788pub enum Delimiter {
789 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
791 Parenthesis,
792 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
794 Brace,
795 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
797 Bracket,
798 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
816 None,
817}
818
819impl Group {
820 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
826 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
827 Group(bridge::Group {
828 delimiter,
829 stream: stream.0,
830 span: bridge::DelimSpan::from_single(Span::call_site().0),
831 })
832 }
833
834 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
836 pub fn delimiter(&self) -> Delimiter {
837 self.0.delimiter
838 }
839
840 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
845 pub fn stream(&self) -> TokenStream {
846 TokenStream(self.0.stream.clone())
847 }
848
849 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
857 pub fn span(&self) -> Span {
858 Span(self.0.span.entire)
859 }
860
861 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
868 pub fn span_open(&self) -> Span {
869 Span(self.0.span.open)
870 }
871
872 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
879 pub fn span_close(&self) -> Span {
880 Span(self.0.span.close)
881 }
882
883 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
890 pub fn set_span(&mut self, span: Span) {
891 self.0.span = bridge::DelimSpan::from_single(span.0);
892 }
893}
894
895#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
899impl fmt::Display for Group {
900 #[allow(clippy::recursive_format_impl)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
902 write!(f, "{}", TokenStream::from(TokenTree::from(self.clone())))
903 }
904}
905
906#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
907impl fmt::Debug for Group {
908 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
909 f.debug_struct("Group")
910 .field("delimiter", &self.delimiter())
911 .field("stream", &self.stream())
912 .field("span", &self.span())
913 .finish()
914 }
915}
916
917#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
922#[derive(Clone)]
923pub struct Punct(bridge::Punct<bridge::client::Span>);
924
925#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
926impl !Send for Punct {}
927#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
928impl !Sync for Punct {}
929
930#[derive(Copy, Clone, Debug, PartialEq, Eq)]
933#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
934pub enum Spacing {
935 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
947 Joint,
948 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
955 Alone,
956}
957
958impl Punct {
959 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
966 pub fn new(ch: char, spacing: Spacing) -> Punct {
967 const LEGAL_CHARS: &[char] = &[
968 '=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
969 ':', '#', '$', '?', '\'',
970 ];
971 if !LEGAL_CHARS.contains(&ch) {
972 panic!("unsupported character `{:?}`", ch);
973 }
974 Punct(bridge::Punct {
975 ch: ch as u8,
976 joint: spacing == Spacing::Joint,
977 span: Span::call_site().0,
978 })
979 }
980
981 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
983 pub fn as_char(&self) -> char {
984 self.0.ch as char
985 }
986
987 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
991 pub fn spacing(&self) -> Spacing {
992 if self.0.joint { Spacing::Joint } else { Spacing::Alone }
993 }
994
995 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
997 pub fn span(&self) -> Span {
998 Span(self.0.span)
999 }
1000
1001 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1003 pub fn set_span(&mut self, span: Span) {
1004 self.0.span = span.0;
1005 }
1006}
1007
1008#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1011impl fmt::Display for Punct {
1012 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1013 write!(f, "{}", self.as_char())
1014 }
1015}
1016
1017#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1018impl fmt::Debug for Punct {
1019 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1020 f.debug_struct("Punct")
1021 .field("ch", &self.as_char())
1022 .field("spacing", &self.spacing())
1023 .field("span", &self.span())
1024 .finish()
1025 }
1026}
1027
1028#[stable(feature = "proc_macro_punct_eq", since = "1.50.0")]
1029impl PartialEq<char> for Punct {
1030 fn eq(&self, rhs: &char) -> bool {
1031 self.as_char() == *rhs
1032 }
1033}
1034
1035#[stable(feature = "proc_macro_punct_eq_flipped", since = "1.52.0")]
1036impl PartialEq<Punct> for char {
1037 fn eq(&self, rhs: &Punct) -> bool {
1038 *self == rhs.as_char()
1039 }
1040}
1041
1042#[derive(Clone)]
1044#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1045pub struct Ident(bridge::Ident<bridge::client::Span, bridge::client::Symbol>);
1046
1047impl Ident {
1048 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1068 pub fn new(string: &str, span: Span) -> Ident {
1069 Ident(bridge::Ident {
1070 sym: bridge::client::Symbol::new_ident(string, false),
1071 is_raw: false,
1072 span: span.0,
1073 })
1074 }
1075
1076 #[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
1081 pub fn new_raw(string: &str, span: Span) -> Ident {
1082 Ident(bridge::Ident {
1083 sym: bridge::client::Symbol::new_ident(string, true),
1084 is_raw: true,
1085 span: span.0,
1086 })
1087 }
1088
1089 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1092 pub fn span(&self) -> Span {
1093 Span(self.0.span)
1094 }
1095
1096 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1098 pub fn set_span(&mut self, span: Span) {
1099 self.0.span = span.0;
1100 }
1101}
1102
1103#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1106impl fmt::Display for Ident {
1107 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1108 if self.0.is_raw {
1109 f.write_str("r#")?;
1110 }
1111 fmt::Display::fmt(&self.0.sym, f)
1112 }
1113}
1114
1115#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1116impl fmt::Debug for Ident {
1117 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1118 f.debug_struct("Ident")
1119 .field("ident", &self.to_string())
1120 .field("span", &self.span())
1121 .finish()
1122 }
1123}
1124
1125#[derive(Clone)]
1130#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1131pub struct Literal(bridge::Literal<bridge::client::Span, bridge::client::Symbol>);
1132
1133macro_rules! suffixed_int_literals {
1134 ($($name:ident => $kind:ident,)*) => ($(
1135 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1147 pub fn $name(n: $kind) -> Literal {
1148 Literal(bridge::Literal {
1149 kind: bridge::LitKind::Integer,
1150 symbol: bridge::client::Symbol::new(&n.to_string()),
1151 suffix: Some(bridge::client::Symbol::new(stringify!($kind))),
1152 span: Span::call_site().0,
1153 })
1154 }
1155 )*)
1156}
1157
1158macro_rules! unsuffixed_int_literals {
1159 ($($name:ident => $kind:ident,)*) => ($(
1160 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1174 pub fn $name(n: $kind) -> Literal {
1175 Literal(bridge::Literal {
1176 kind: bridge::LitKind::Integer,
1177 symbol: bridge::client::Symbol::new(&n.to_string()),
1178 suffix: None,
1179 span: Span::call_site().0,
1180 })
1181 }
1182 )*)
1183}
1184
1185impl Literal {
1186 fn new(kind: bridge::LitKind, value: &str, suffix: Option<&str>) -> Self {
1187 Literal(bridge::Literal {
1188 kind,
1189 symbol: bridge::client::Symbol::new(value),
1190 suffix: suffix.map(bridge::client::Symbol::new),
1191 span: Span::call_site().0,
1192 })
1193 }
1194
1195 suffixed_int_literals! {
1196 u8_suffixed => u8,
1197 u16_suffixed => u16,
1198 u32_suffixed => u32,
1199 u64_suffixed => u64,
1200 u128_suffixed => u128,
1201 usize_suffixed => usize,
1202 i8_suffixed => i8,
1203 i16_suffixed => i16,
1204 i32_suffixed => i32,
1205 i64_suffixed => i64,
1206 i128_suffixed => i128,
1207 isize_suffixed => isize,
1208 }
1209
1210 unsuffixed_int_literals! {
1211 u8_unsuffixed => u8,
1212 u16_unsuffixed => u16,
1213 u32_unsuffixed => u32,
1214 u64_unsuffixed => u64,
1215 u128_unsuffixed => u128,
1216 usize_unsuffixed => usize,
1217 i8_unsuffixed => i8,
1218 i16_unsuffixed => i16,
1219 i32_unsuffixed => i32,
1220 i64_unsuffixed => i64,
1221 i128_unsuffixed => i128,
1222 isize_unsuffixed => isize,
1223 }
1224
1225 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1238 pub fn f32_unsuffixed(n: f32) -> Literal {
1239 if !n.is_finite() {
1240 panic!("Invalid float literal {n}");
1241 }
1242 let mut repr = n.to_string();
1243 if !repr.contains('.') {
1244 repr.push_str(".0");
1245 }
1246 Literal::new(bridge::LitKind::Float, &repr, None)
1247 }
1248
1249 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1263 pub fn f32_suffixed(n: f32) -> Literal {
1264 if !n.is_finite() {
1265 panic!("Invalid float literal {n}");
1266 }
1267 Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f32"))
1268 }
1269
1270 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1283 pub fn f64_unsuffixed(n: f64) -> Literal {
1284 if !n.is_finite() {
1285 panic!("Invalid float literal {n}");
1286 }
1287 let mut repr = n.to_string();
1288 if !repr.contains('.') {
1289 repr.push_str(".0");
1290 }
1291 Literal::new(bridge::LitKind::Float, &repr, None)
1292 }
1293
1294 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1308 pub fn f64_suffixed(n: f64) -> Literal {
1309 if !n.is_finite() {
1310 panic!("Invalid float literal {n}");
1311 }
1312 Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f64"))
1313 }
1314
1315 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1317 pub fn string(string: &str) -> Literal {
1318 let escape = EscapeOptions {
1319 escape_single_quote: false,
1320 escape_double_quote: true,
1321 escape_nonascii: false,
1322 };
1323 let repr = escape_bytes(string.as_bytes(), escape);
1324 Literal::new(bridge::LitKind::Str, &repr, None)
1325 }
1326
1327 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1329 pub fn character(ch: char) -> Literal {
1330 let escape = EscapeOptions {
1331 escape_single_quote: true,
1332 escape_double_quote: false,
1333 escape_nonascii: false,
1334 };
1335 let repr = escape_bytes(ch.encode_utf8(&mut [0u8; 4]).as_bytes(), escape);
1336 Literal::new(bridge::LitKind::Char, &repr, None)
1337 }
1338
1339 #[stable(feature = "proc_macro_byte_character", since = "1.79.0")]
1341 pub fn byte_character(byte: u8) -> Literal {
1342 let escape = EscapeOptions {
1343 escape_single_quote: true,
1344 escape_double_quote: false,
1345 escape_nonascii: true,
1346 };
1347 let repr = escape_bytes(&[byte], escape);
1348 Literal::new(bridge::LitKind::Byte, &repr, None)
1349 }
1350
1351 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1353 pub fn byte_string(bytes: &[u8]) -> Literal {
1354 let escape = EscapeOptions {
1355 escape_single_quote: false,
1356 escape_double_quote: true,
1357 escape_nonascii: true,
1358 };
1359 let repr = escape_bytes(bytes, escape);
1360 Literal::new(bridge::LitKind::ByteStr, &repr, None)
1361 }
1362
1363 #[stable(feature = "proc_macro_c_str_literals", since = "1.79.0")]
1365 pub fn c_string(string: &CStr) -> Literal {
1366 let escape = EscapeOptions {
1367 escape_single_quote: false,
1368 escape_double_quote: true,
1369 escape_nonascii: false,
1370 };
1371 let repr = escape_bytes(string.to_bytes(), escape);
1372 Literal::new(bridge::LitKind::CStr, &repr, None)
1373 }
1374
1375 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1377 pub fn span(&self) -> Span {
1378 Span(self.0.span)
1379 }
1380
1381 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1383 pub fn set_span(&mut self, span: Span) {
1384 self.0.span = span.0;
1385 }
1386
1387 #[unstable(feature = "proc_macro_span", issue = "54725")]
1399 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1400 self.0.span.subspan(range.start_bound().cloned(), range.end_bound().cloned()).map(Span)
1401 }
1402
1403 fn with_symbol_and_suffix<R>(&self, f: impl FnOnce(&str, &str) -> R) -> R {
1404 self.0.symbol.with(|symbol| match self.0.suffix {
1405 Some(suffix) => suffix.with(|suffix| f(symbol, suffix)),
1406 None => f(symbol, ""),
1407 })
1408 }
1409
1410 fn with_stringify_parts<R>(&self, f: impl FnOnce(&[&str]) -> R) -> R {
1415 fn get_hashes_str(num: u8) -> &'static str {
1419 const HASHES: &str = "\
1420 ################################################################\
1421 ################################################################\
1422 ################################################################\
1423 ################################################################\
1424 ";
1425 const _: () = assert!(HASHES.len() == 256);
1426 &HASHES[..num as usize]
1427 }
1428
1429 self.with_symbol_and_suffix(|symbol, suffix| match self.0.kind {
1430 bridge::LitKind::Byte => f(&["b'", symbol, "'", suffix]),
1431 bridge::LitKind::Char => f(&["'", symbol, "'", suffix]),
1432 bridge::LitKind::Str => f(&["\"", symbol, "\"", suffix]),
1433 bridge::LitKind::StrRaw(n) => {
1434 let hashes = get_hashes_str(n);
1435 f(&["r", hashes, "\"", symbol, "\"", hashes, suffix])
1436 }
1437 bridge::LitKind::ByteStr => f(&["b\"", symbol, "\"", suffix]),
1438 bridge::LitKind::ByteStrRaw(n) => {
1439 let hashes = get_hashes_str(n);
1440 f(&["br", hashes, "\"", symbol, "\"", hashes, suffix])
1441 }
1442 bridge::LitKind::CStr => f(&["c\"", symbol, "\"", suffix]),
1443 bridge::LitKind::CStrRaw(n) => {
1444 let hashes = get_hashes_str(n);
1445 f(&["cr", hashes, "\"", symbol, "\"", hashes, suffix])
1446 }
1447
1448 bridge::LitKind::Integer | bridge::LitKind::Float | bridge::LitKind::ErrWithGuar => {
1449 f(&[symbol, suffix])
1450 }
1451 })
1452 }
1453}
1454
1455#[stable(feature = "proc_macro_literal_parse", since = "1.54.0")]
1466impl FromStr for Literal {
1467 type Err = LexError;
1468
1469 fn from_str(src: &str) -> Result<Self, LexError> {
1470 match bridge::client::FreeFunctions::literal_from_str(src) {
1471 Ok(literal) => Ok(Literal(literal)),
1472 Err(()) => Err(LexError),
1473 }
1474 }
1475}
1476
1477#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1480impl fmt::Display for Literal {
1481 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1482 self.with_stringify_parts(|parts| {
1483 for part in parts {
1484 fmt::Display::fmt(part, f)?;
1485 }
1486 Ok(())
1487 })
1488 }
1489}
1490
1491#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1492impl fmt::Debug for Literal {
1493 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1494 f.debug_struct("Literal")
1495 .field("kind", &format_args!("{:?}", self.0.kind))
1497 .field("symbol", &self.0.symbol)
1498 .field("suffix", &format_args!("{:?}", self.0.suffix))
1500 .field("span", &self.0.span)
1501 .finish()
1502 }
1503}
1504
1505#[unstable(feature = "proc_macro_tracked_env", issue = "99515")]
1507pub mod tracked_env {
1508 use std::env::{self, VarError};
1509 use std::ffi::OsStr;
1510
1511 #[unstable(feature = "proc_macro_tracked_env", issue = "99515")]
1517 pub fn var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1518 let key: &str = key.as_ref();
1519 let value = crate::bridge::client::FreeFunctions::injected_env_var(key)
1520 .map_or_else(|| env::var(key), Ok);
1521 crate::bridge::client::FreeFunctions::track_env_var(key, value.as_deref().ok());
1522 value
1523 }
1524}
1525
1526#[unstable(feature = "track_path", issue = "99515")]
1528pub mod tracked_path {
1529
1530 #[unstable(feature = "track_path", issue = "99515")]
1534 pub fn path<P: AsRef<str>>(path: P) {
1535 let path: &str = path.as_ref();
1536 crate::bridge::client::FreeFunctions::track_path(path);
1537 }
1538}