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 std::ffi::CStr;
49use std::ops::{Range, RangeBounds};
50use std::path::PathBuf;
51use std::str::FromStr;
52use std::{error, fmt};
53
54#[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
55pub use diagnostic::{Diagnostic, Level, MultiSpan};
56#[unstable(feature = "proc_macro_value", issue = "136652")]
57pub use rustc_literal_escaper::EscapeError;
58use rustc_literal_escaper::{MixedUnit, Mode, byte_from_char, unescape_mixed, unescape_unicode};
59#[unstable(feature = "proc_macro_totokens", issue = "130977")]
60pub use to_tokens::ToTokens;
61
62use crate::escape::{EscapeOptions, escape_bytes};
63
64#[unstable(feature = "proc_macro_value", issue = "136652")]
66#[derive(Debug, PartialEq, Eq)]
67pub enum ConversionErrorKind {
68 FailedToUnescape(EscapeError),
70 InvalidLiteralKind,
72}
73
74#[stable(feature = "proc_macro_is_available", since = "1.57.0")]
88pub fn is_available() -> bool {
89 bridge::client::is_available()
90}
91
92#[cfg_attr(feature = "rustc-dep-of-std", rustc_diagnostic_item = "TokenStream")]
100#[stable(feature = "proc_macro_lib", since = "1.15.0")]
101#[derive(Clone)]
102pub struct TokenStream(Option<bridge::client::TokenStream>);
103
104#[stable(feature = "proc_macro_lib", since = "1.15.0")]
105impl !Send for TokenStream {}
106#[stable(feature = "proc_macro_lib", since = "1.15.0")]
107impl !Sync for TokenStream {}
108
109#[stable(feature = "proc_macro_lib", since = "1.15.0")]
111#[non_exhaustive]
112#[derive(Debug)]
113pub struct LexError;
114
115#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
116impl fmt::Display for LexError {
117 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118 f.write_str("cannot parse string into token stream")
119 }
120}
121
122#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
123impl error::Error for LexError {}
124
125#[stable(feature = "proc_macro_lib", since = "1.15.0")]
126impl !Send for LexError {}
127#[stable(feature = "proc_macro_lib", since = "1.15.0")]
128impl !Sync for LexError {}
129
130#[unstable(feature = "proc_macro_expand", issue = "90765")]
132#[non_exhaustive]
133#[derive(Debug)]
134pub struct ExpandError;
135
136#[unstable(feature = "proc_macro_expand", issue = "90765")]
137impl fmt::Display for ExpandError {
138 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139 f.write_str("macro expansion failed")
140 }
141}
142
143#[unstable(feature = "proc_macro_expand", issue = "90765")]
144impl error::Error for ExpandError {}
145
146#[unstable(feature = "proc_macro_expand", issue = "90765")]
147impl !Send for ExpandError {}
148
149#[unstable(feature = "proc_macro_expand", issue = "90765")]
150impl !Sync for ExpandError {}
151
152impl TokenStream {
153 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
155 pub fn new() -> TokenStream {
156 TokenStream(None)
157 }
158
159 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
161 pub fn is_empty(&self) -> bool {
162 self.0.as_ref().map(|h| h.is_empty()).unwrap_or(true)
163 }
164
165 #[unstable(feature = "proc_macro_expand", issue = "90765")]
176 pub fn expand_expr(&self) -> Result<TokenStream, ExpandError> {
177 let stream = self.0.as_ref().ok_or(ExpandError)?;
178 match bridge::client::TokenStream::expand_expr(stream) {
179 Ok(stream) => Ok(TokenStream(Some(stream))),
180 Err(_) => Err(ExpandError),
181 }
182 }
183}
184
185#[stable(feature = "proc_macro_lib", since = "1.15.0")]
193impl FromStr for TokenStream {
194 type Err = LexError;
195
196 fn from_str(src: &str) -> Result<TokenStream, LexError> {
197 Ok(TokenStream(Some(bridge::client::TokenStream::from_str(src))))
198 }
199}
200
201#[stable(feature = "proc_macro_lib", since = "1.15.0")]
213impl fmt::Display for TokenStream {
214 #[allow(clippy::recursive_format_impl)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216 match &self.0 {
217 Some(ts) => write!(f, "{}", ts.to_string()),
218 None => Ok(()),
219 }
220 }
221}
222
223#[stable(feature = "proc_macro_lib", since = "1.15.0")]
225impl fmt::Debug for TokenStream {
226 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
227 f.write_str("TokenStream ")?;
228 f.debug_list().entries(self.clone()).finish()
229 }
230}
231
232#[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
233impl Default for TokenStream {
234 fn default() -> Self {
235 TokenStream::new()
236 }
237}
238
239#[unstable(feature = "proc_macro_quote", issue = "54722")]
240pub use quote::{quote, quote_span};
241
242fn tree_to_bridge_tree(
243 tree: TokenTree,
244) -> bridge::TokenTree<bridge::client::TokenStream, bridge::client::Span, bridge::client::Symbol> {
245 match tree {
246 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
247 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
248 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
249 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
250 }
251}
252
253#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
255impl From<TokenTree> for TokenStream {
256 fn from(tree: TokenTree) -> TokenStream {
257 TokenStream(Some(bridge::client::TokenStream::from_token_tree(tree_to_bridge_tree(tree))))
258 }
259}
260
261struct ConcatTreesHelper {
264 trees: Vec<
265 bridge::TokenTree<
266 bridge::client::TokenStream,
267 bridge::client::Span,
268 bridge::client::Symbol,
269 >,
270 >,
271}
272
273impl ConcatTreesHelper {
274 fn new(capacity: usize) -> Self {
275 ConcatTreesHelper { trees: Vec::with_capacity(capacity) }
276 }
277
278 fn push(&mut self, tree: TokenTree) {
279 self.trees.push(tree_to_bridge_tree(tree));
280 }
281
282 fn build(self) -> TokenStream {
283 if self.trees.is_empty() {
284 TokenStream(None)
285 } else {
286 TokenStream(Some(bridge::client::TokenStream::concat_trees(None, self.trees)))
287 }
288 }
289
290 fn append_to(self, stream: &mut TokenStream) {
291 if self.trees.is_empty() {
292 return;
293 }
294 stream.0 = Some(bridge::client::TokenStream::concat_trees(stream.0.take(), self.trees))
295 }
296}
297
298struct ConcatStreamsHelper {
301 streams: Vec<bridge::client::TokenStream>,
302}
303
304impl ConcatStreamsHelper {
305 fn new(capacity: usize) -> Self {
306 ConcatStreamsHelper { streams: Vec::with_capacity(capacity) }
307 }
308
309 fn push(&mut self, stream: TokenStream) {
310 if let Some(stream) = stream.0 {
311 self.streams.push(stream);
312 }
313 }
314
315 fn build(mut self) -> TokenStream {
316 if self.streams.len() <= 1 {
317 TokenStream(self.streams.pop())
318 } else {
319 TokenStream(Some(bridge::client::TokenStream::concat_streams(None, self.streams)))
320 }
321 }
322
323 fn append_to(mut self, stream: &mut TokenStream) {
324 if self.streams.is_empty() {
325 return;
326 }
327 let base = stream.0.take();
328 if base.is_none() && self.streams.len() == 1 {
329 stream.0 = self.streams.pop();
330 } else {
331 stream.0 = Some(bridge::client::TokenStream::concat_streams(base, self.streams));
332 }
333 }
334}
335
336#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
338impl FromIterator<TokenTree> for TokenStream {
339 fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
340 let iter = trees.into_iter();
341 let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
342 iter.for_each(|tree| builder.push(tree));
343 builder.build()
344 }
345}
346
347#[stable(feature = "proc_macro_lib", since = "1.15.0")]
350impl FromIterator<TokenStream> for TokenStream {
351 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
352 let iter = streams.into_iter();
353 let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
354 iter.for_each(|stream| builder.push(stream));
355 builder.build()
356 }
357}
358
359#[stable(feature = "token_stream_extend", since = "1.30.0")]
360impl Extend<TokenTree> for TokenStream {
361 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
362 let iter = trees.into_iter();
363 let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
364 iter.for_each(|tree| builder.push(tree));
365 builder.append_to(self);
366 }
367}
368
369#[stable(feature = "token_stream_extend", since = "1.30.0")]
370impl Extend<TokenStream> for TokenStream {
371 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
372 let iter = streams.into_iter();
373 let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
374 iter.for_each(|stream| builder.push(stream));
375 builder.append_to(self);
376 }
377}
378
379#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
381pub mod token_stream {
382 use crate::{Group, Ident, Literal, Punct, TokenStream, TokenTree, bridge};
383
384 #[derive(Clone)]
388 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
389 pub struct IntoIter(
390 std::vec::IntoIter<
391 bridge::TokenTree<
392 bridge::client::TokenStream,
393 bridge::client::Span,
394 bridge::client::Symbol,
395 >,
396 >,
397 );
398
399 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
400 impl Iterator for IntoIter {
401 type Item = TokenTree;
402
403 fn next(&mut self) -> Option<TokenTree> {
404 self.0.next().map(|tree| match tree {
405 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
406 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
407 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
408 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
409 })
410 }
411
412 fn size_hint(&self) -> (usize, Option<usize>) {
413 self.0.size_hint()
414 }
415
416 fn count(self) -> usize {
417 self.0.count()
418 }
419 }
420
421 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
422 impl IntoIterator for TokenStream {
423 type Item = TokenTree;
424 type IntoIter = IntoIter;
425
426 fn into_iter(self) -> IntoIter {
427 IntoIter(self.0.map(|v| v.into_trees()).unwrap_or_default().into_iter())
428 }
429 }
430}
431
432#[unstable(feature = "proc_macro_quote", issue = "54722")]
439#[allow_internal_unstable(proc_macro_def_site, proc_macro_internals, proc_macro_totokens)]
440#[rustc_builtin_macro]
441pub macro quote($($t:tt)*) {
442 }
444
445#[unstable(feature = "proc_macro_internals", issue = "27812")]
446#[doc(hidden)]
447mod quote;
448
449#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
451#[derive(Copy, Clone)]
452pub struct Span(bridge::client::Span);
453
454#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
455impl !Send for Span {}
456#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
457impl !Sync for Span {}
458
459macro_rules! diagnostic_method {
460 ($name:ident, $level:expr) => {
461 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
464 pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
465 Diagnostic::spanned(self, $level, message)
466 }
467 };
468}
469
470impl Span {
471 #[unstable(feature = "proc_macro_def_site", issue = "54724")]
473 pub fn def_site() -> Span {
474 Span(bridge::client::Span::def_site())
475 }
476
477 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
482 pub fn call_site() -> Span {
483 Span(bridge::client::Span::call_site())
484 }
485
486 #[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
491 pub fn mixed_site() -> Span {
492 Span(bridge::client::Span::mixed_site())
493 }
494
495 #[unstable(feature = "proc_macro_span", issue = "54725")]
498 pub fn parent(&self) -> Option<Span> {
499 self.0.parent().map(Span)
500 }
501
502 #[unstable(feature = "proc_macro_span", issue = "54725")]
506 pub fn source(&self) -> Span {
507 Span(self.0.source())
508 }
509
510 #[unstable(feature = "proc_macro_span", issue = "54725")]
512 pub fn byte_range(&self) -> Range<usize> {
513 self.0.byte_range()
514 }
515
516 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
518 pub fn start(&self) -> Span {
519 Span(self.0.start())
520 }
521
522 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
524 pub fn end(&self) -> Span {
525 Span(self.0.end())
526 }
527
528 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
532 pub fn line(&self) -> usize {
533 self.0.line()
534 }
535
536 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
540 pub fn column(&self) -> usize {
541 self.0.column()
542 }
543
544 #[stable(feature = "proc_macro_span_file", since = "1.88.0")]
549 pub fn file(&self) -> String {
550 self.0.file()
551 }
552
553 #[stable(feature = "proc_macro_span_file", since = "1.88.0")]
559 pub fn local_file(&self) -> Option<PathBuf> {
560 self.0.local_file().map(|s| PathBuf::from(s))
561 }
562
563 #[unstable(feature = "proc_macro_span", issue = "54725")]
567 pub fn join(&self, other: Span) -> Option<Span> {
568 self.0.join(other.0).map(Span)
569 }
570
571 #[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
574 pub fn resolved_at(&self, other: Span) -> Span {
575 Span(self.0.resolved_at(other.0))
576 }
577
578 #[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
581 pub fn located_at(&self, other: Span) -> Span {
582 other.resolved_at(*self)
583 }
584
585 #[unstable(feature = "proc_macro_span", issue = "54725")]
587 pub fn eq(&self, other: &Span) -> bool {
588 self.0 == other.0
589 }
590
591 #[stable(feature = "proc_macro_source_text", since = "1.66.0")]
599 pub fn source_text(&self) -> Option<String> {
600 self.0.source_text()
601 }
602
603 #[doc(hidden)]
605 #[unstable(feature = "proc_macro_internals", issue = "27812")]
606 pub fn save_span(&self) -> usize {
607 self.0.save_span()
608 }
609
610 #[doc(hidden)]
612 #[unstable(feature = "proc_macro_internals", issue = "27812")]
613 pub fn recover_proc_macro_span(id: usize) -> Span {
614 Span(bridge::client::Span::recover_proc_macro_span(id))
615 }
616
617 diagnostic_method!(error, Level::Error);
618 diagnostic_method!(warning, Level::Warning);
619 diagnostic_method!(note, Level::Note);
620 diagnostic_method!(help, Level::Help);
621}
622
623#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
625impl fmt::Debug for Span {
626 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
627 self.0.fmt(f)
628 }
629}
630
631#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
633#[derive(Clone)]
634pub enum TokenTree {
635 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
637 Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
638 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
640 Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
641 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
643 Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
644 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
646 Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
647}
648
649#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
650impl !Send for TokenTree {}
651#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
652impl !Sync for TokenTree {}
653
654impl TokenTree {
655 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
658 pub fn span(&self) -> Span {
659 match *self {
660 TokenTree::Group(ref t) => t.span(),
661 TokenTree::Ident(ref t) => t.span(),
662 TokenTree::Punct(ref t) => t.span(),
663 TokenTree::Literal(ref t) => t.span(),
664 }
665 }
666
667 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
673 pub fn set_span(&mut self, span: Span) {
674 match *self {
675 TokenTree::Group(ref mut t) => t.set_span(span),
676 TokenTree::Ident(ref mut t) => t.set_span(span),
677 TokenTree::Punct(ref mut t) => t.set_span(span),
678 TokenTree::Literal(ref mut t) => t.set_span(span),
679 }
680 }
681}
682
683#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
685impl fmt::Debug for TokenTree {
686 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
687 match *self {
690 TokenTree::Group(ref tt) => tt.fmt(f),
691 TokenTree::Ident(ref tt) => tt.fmt(f),
692 TokenTree::Punct(ref tt) => tt.fmt(f),
693 TokenTree::Literal(ref tt) => tt.fmt(f),
694 }
695 }
696}
697
698#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
699impl From<Group> for TokenTree {
700 fn from(g: Group) -> TokenTree {
701 TokenTree::Group(g)
702 }
703}
704
705#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
706impl From<Ident> for TokenTree {
707 fn from(g: Ident) -> TokenTree {
708 TokenTree::Ident(g)
709 }
710}
711
712#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
713impl From<Punct> for TokenTree {
714 fn from(g: Punct) -> TokenTree {
715 TokenTree::Punct(g)
716 }
717}
718
719#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
720impl From<Literal> for TokenTree {
721 fn from(g: Literal) -> TokenTree {
722 TokenTree::Literal(g)
723 }
724}
725
726#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
738impl fmt::Display for TokenTree {
739 #[allow(clippy::recursive_format_impl)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
741 match self {
742 TokenTree::Group(t) => write!(f, "{t}"),
743 TokenTree::Ident(t) => write!(f, "{t}"),
744 TokenTree::Punct(t) => write!(f, "{t}"),
745 TokenTree::Literal(t) => write!(f, "{t}"),
746 }
747 }
748}
749
750#[derive(Clone)]
754#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
755pub struct Group(bridge::Group<bridge::client::TokenStream, bridge::client::Span>);
756
757#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
758impl !Send for Group {}
759#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
760impl !Sync for Group {}
761
762#[derive(Copy, Clone, Debug, PartialEq, Eq)]
764#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
765pub enum Delimiter {
766 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
768 Parenthesis,
769 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
771 Brace,
772 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
774 Bracket,
775 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
793 None,
794}
795
796impl Group {
797 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
803 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
804 Group(bridge::Group {
805 delimiter,
806 stream: stream.0,
807 span: bridge::DelimSpan::from_single(Span::call_site().0),
808 })
809 }
810
811 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
813 pub fn delimiter(&self) -> Delimiter {
814 self.0.delimiter
815 }
816
817 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
822 pub fn stream(&self) -> TokenStream {
823 TokenStream(self.0.stream.clone())
824 }
825
826 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
834 pub fn span(&self) -> Span {
835 Span(self.0.span.entire)
836 }
837
838 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
845 pub fn span_open(&self) -> Span {
846 Span(self.0.span.open)
847 }
848
849 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
856 pub fn span_close(&self) -> Span {
857 Span(self.0.span.close)
858 }
859
860 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
867 pub fn set_span(&mut self, span: Span) {
868 self.0.span = bridge::DelimSpan::from_single(span.0);
869 }
870}
871
872#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
876impl fmt::Display for Group {
877 #[allow(clippy::recursive_format_impl)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
879 write!(f, "{}", TokenStream::from(TokenTree::from(self.clone())))
880 }
881}
882
883#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
884impl fmt::Debug for Group {
885 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
886 f.debug_struct("Group")
887 .field("delimiter", &self.delimiter())
888 .field("stream", &self.stream())
889 .field("span", &self.span())
890 .finish()
891 }
892}
893
894#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
899#[derive(Clone)]
900pub struct Punct(bridge::Punct<bridge::client::Span>);
901
902#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
903impl !Send for Punct {}
904#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
905impl !Sync for Punct {}
906
907#[derive(Copy, Clone, Debug, PartialEq, Eq)]
910#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
911pub enum Spacing {
912 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
924 Joint,
925 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
932 Alone,
933}
934
935impl Punct {
936 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
943 pub fn new(ch: char, spacing: Spacing) -> Punct {
944 const LEGAL_CHARS: &[char] = &[
945 '=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
946 ':', '#', '$', '?', '\'',
947 ];
948 if !LEGAL_CHARS.contains(&ch) {
949 panic!("unsupported character `{:?}`", ch);
950 }
951 Punct(bridge::Punct {
952 ch: ch as u8,
953 joint: spacing == Spacing::Joint,
954 span: Span::call_site().0,
955 })
956 }
957
958 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
960 pub fn as_char(&self) -> char {
961 self.0.ch as char
962 }
963
964 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
968 pub fn spacing(&self) -> Spacing {
969 if self.0.joint { Spacing::Joint } else { Spacing::Alone }
970 }
971
972 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
974 pub fn span(&self) -> Span {
975 Span(self.0.span)
976 }
977
978 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
980 pub fn set_span(&mut self, span: Span) {
981 self.0.span = span.0;
982 }
983}
984
985#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
988impl fmt::Display for Punct {
989 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
990 write!(f, "{}", self.as_char())
991 }
992}
993
994#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
995impl fmt::Debug for Punct {
996 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
997 f.debug_struct("Punct")
998 .field("ch", &self.as_char())
999 .field("spacing", &self.spacing())
1000 .field("span", &self.span())
1001 .finish()
1002 }
1003}
1004
1005#[stable(feature = "proc_macro_punct_eq", since = "1.50.0")]
1006impl PartialEq<char> for Punct {
1007 fn eq(&self, rhs: &char) -> bool {
1008 self.as_char() == *rhs
1009 }
1010}
1011
1012#[stable(feature = "proc_macro_punct_eq_flipped", since = "1.52.0")]
1013impl PartialEq<Punct> for char {
1014 fn eq(&self, rhs: &Punct) -> bool {
1015 *self == rhs.as_char()
1016 }
1017}
1018
1019#[derive(Clone)]
1021#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1022pub struct Ident(bridge::Ident<bridge::client::Span, bridge::client::Symbol>);
1023
1024impl Ident {
1025 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1045 pub fn new(string: &str, span: Span) -> Ident {
1046 Ident(bridge::Ident {
1047 sym: bridge::client::Symbol::new_ident(string, false),
1048 is_raw: false,
1049 span: span.0,
1050 })
1051 }
1052
1053 #[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
1058 pub fn new_raw(string: &str, span: Span) -> Ident {
1059 Ident(bridge::Ident {
1060 sym: bridge::client::Symbol::new_ident(string, true),
1061 is_raw: true,
1062 span: span.0,
1063 })
1064 }
1065
1066 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1069 pub fn span(&self) -> Span {
1070 Span(self.0.span)
1071 }
1072
1073 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1075 pub fn set_span(&mut self, span: Span) {
1076 self.0.span = span.0;
1077 }
1078}
1079
1080#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1083impl fmt::Display for Ident {
1084 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1085 if self.0.is_raw {
1086 f.write_str("r#")?;
1087 }
1088 fmt::Display::fmt(&self.0.sym, f)
1089 }
1090}
1091
1092#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1093impl fmt::Debug for Ident {
1094 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1095 f.debug_struct("Ident")
1096 .field("ident", &self.to_string())
1097 .field("span", &self.span())
1098 .finish()
1099 }
1100}
1101
1102#[derive(Clone)]
1107#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1108pub struct Literal(bridge::Literal<bridge::client::Span, bridge::client::Symbol>);
1109
1110macro_rules! suffixed_int_literals {
1111 ($($name:ident => $kind:ident,)*) => ($(
1112 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1124 pub fn $name(n: $kind) -> Literal {
1125 Literal(bridge::Literal {
1126 kind: bridge::LitKind::Integer,
1127 symbol: bridge::client::Symbol::new(&n.to_string()),
1128 suffix: Some(bridge::client::Symbol::new(stringify!($kind))),
1129 span: Span::call_site().0,
1130 })
1131 }
1132 )*)
1133}
1134
1135macro_rules! unsuffixed_int_literals {
1136 ($($name:ident => $kind:ident,)*) => ($(
1137 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1151 pub fn $name(n: $kind) -> Literal {
1152 Literal(bridge::Literal {
1153 kind: bridge::LitKind::Integer,
1154 symbol: bridge::client::Symbol::new(&n.to_string()),
1155 suffix: None,
1156 span: Span::call_site().0,
1157 })
1158 }
1159 )*)
1160}
1161
1162impl Literal {
1163 fn new(kind: bridge::LitKind, value: &str, suffix: Option<&str>) -> Self {
1164 Literal(bridge::Literal {
1165 kind,
1166 symbol: bridge::client::Symbol::new(value),
1167 suffix: suffix.map(bridge::client::Symbol::new),
1168 span: Span::call_site().0,
1169 })
1170 }
1171
1172 suffixed_int_literals! {
1173 u8_suffixed => u8,
1174 u16_suffixed => u16,
1175 u32_suffixed => u32,
1176 u64_suffixed => u64,
1177 u128_suffixed => u128,
1178 usize_suffixed => usize,
1179 i8_suffixed => i8,
1180 i16_suffixed => i16,
1181 i32_suffixed => i32,
1182 i64_suffixed => i64,
1183 i128_suffixed => i128,
1184 isize_suffixed => isize,
1185 }
1186
1187 unsuffixed_int_literals! {
1188 u8_unsuffixed => u8,
1189 u16_unsuffixed => u16,
1190 u32_unsuffixed => u32,
1191 u64_unsuffixed => u64,
1192 u128_unsuffixed => u128,
1193 usize_unsuffixed => usize,
1194 i8_unsuffixed => i8,
1195 i16_unsuffixed => i16,
1196 i32_unsuffixed => i32,
1197 i64_unsuffixed => i64,
1198 i128_unsuffixed => i128,
1199 isize_unsuffixed => isize,
1200 }
1201
1202 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1215 pub fn f32_unsuffixed(n: f32) -> Literal {
1216 if !n.is_finite() {
1217 panic!("Invalid float literal {n}");
1218 }
1219 let mut repr = n.to_string();
1220 if !repr.contains('.') {
1221 repr.push_str(".0");
1222 }
1223 Literal::new(bridge::LitKind::Float, &repr, None)
1224 }
1225
1226 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1240 pub fn f32_suffixed(n: f32) -> Literal {
1241 if !n.is_finite() {
1242 panic!("Invalid float literal {n}");
1243 }
1244 Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f32"))
1245 }
1246
1247 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1260 pub fn f64_unsuffixed(n: f64) -> Literal {
1261 if !n.is_finite() {
1262 panic!("Invalid float literal {n}");
1263 }
1264 let mut repr = n.to_string();
1265 if !repr.contains('.') {
1266 repr.push_str(".0");
1267 }
1268 Literal::new(bridge::LitKind::Float, &repr, None)
1269 }
1270
1271 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1285 pub fn f64_suffixed(n: f64) -> Literal {
1286 if !n.is_finite() {
1287 panic!("Invalid float literal {n}");
1288 }
1289 Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f64"))
1290 }
1291
1292 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1294 pub fn string(string: &str) -> Literal {
1295 let escape = EscapeOptions {
1296 escape_single_quote: false,
1297 escape_double_quote: true,
1298 escape_nonascii: false,
1299 };
1300 let repr = escape_bytes(string.as_bytes(), escape);
1301 Literal::new(bridge::LitKind::Str, &repr, None)
1302 }
1303
1304 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1306 pub fn character(ch: char) -> Literal {
1307 let escape = EscapeOptions {
1308 escape_single_quote: true,
1309 escape_double_quote: false,
1310 escape_nonascii: false,
1311 };
1312 let repr = escape_bytes(ch.encode_utf8(&mut [0u8; 4]).as_bytes(), escape);
1313 Literal::new(bridge::LitKind::Char, &repr, None)
1314 }
1315
1316 #[stable(feature = "proc_macro_byte_character", since = "1.79.0")]
1318 pub fn byte_character(byte: u8) -> Literal {
1319 let escape = EscapeOptions {
1320 escape_single_quote: true,
1321 escape_double_quote: false,
1322 escape_nonascii: true,
1323 };
1324 let repr = escape_bytes(&[byte], escape);
1325 Literal::new(bridge::LitKind::Byte, &repr, None)
1326 }
1327
1328 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1330 pub fn byte_string(bytes: &[u8]) -> Literal {
1331 let escape = EscapeOptions {
1332 escape_single_quote: false,
1333 escape_double_quote: true,
1334 escape_nonascii: true,
1335 };
1336 let repr = escape_bytes(bytes, escape);
1337 Literal::new(bridge::LitKind::ByteStr, &repr, None)
1338 }
1339
1340 #[stable(feature = "proc_macro_c_str_literals", since = "1.79.0")]
1342 pub fn c_string(string: &CStr) -> Literal {
1343 let escape = EscapeOptions {
1344 escape_single_quote: false,
1345 escape_double_quote: true,
1346 escape_nonascii: false,
1347 };
1348 let repr = escape_bytes(string.to_bytes(), escape);
1349 Literal::new(bridge::LitKind::CStr, &repr, None)
1350 }
1351
1352 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1354 pub fn span(&self) -> Span {
1355 Span(self.0.span)
1356 }
1357
1358 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1360 pub fn set_span(&mut self, span: Span) {
1361 self.0.span = span.0;
1362 }
1363
1364 #[unstable(feature = "proc_macro_span", issue = "54725")]
1376 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1377 self.0.span.subspan(range.start_bound().cloned(), range.end_bound().cloned()).map(Span)
1378 }
1379
1380 fn with_symbol_and_suffix<R>(&self, f: impl FnOnce(&str, &str) -> R) -> R {
1381 self.0.symbol.with(|symbol| match self.0.suffix {
1382 Some(suffix) => suffix.with(|suffix| f(symbol, suffix)),
1383 None => f(symbol, ""),
1384 })
1385 }
1386
1387 fn with_stringify_parts<R>(&self, f: impl FnOnce(&[&str]) -> R) -> R {
1392 fn get_hashes_str(num: u8) -> &'static str {
1396 const HASHES: &str = "\
1397 ################################################################\
1398 ################################################################\
1399 ################################################################\
1400 ################################################################\
1401 ";
1402 const _: () = assert!(HASHES.len() == 256);
1403 &HASHES[..num as usize]
1404 }
1405
1406 self.with_symbol_and_suffix(|symbol, suffix| match self.0.kind {
1407 bridge::LitKind::Byte => f(&["b'", symbol, "'", suffix]),
1408 bridge::LitKind::Char => f(&["'", symbol, "'", suffix]),
1409 bridge::LitKind::Str => f(&["\"", symbol, "\"", suffix]),
1410 bridge::LitKind::StrRaw(n) => {
1411 let hashes = get_hashes_str(n);
1412 f(&["r", hashes, "\"", symbol, "\"", hashes, suffix])
1413 }
1414 bridge::LitKind::ByteStr => f(&["b\"", symbol, "\"", suffix]),
1415 bridge::LitKind::ByteStrRaw(n) => {
1416 let hashes = get_hashes_str(n);
1417 f(&["br", hashes, "\"", symbol, "\"", hashes, suffix])
1418 }
1419 bridge::LitKind::CStr => f(&["c\"", symbol, "\"", suffix]),
1420 bridge::LitKind::CStrRaw(n) => {
1421 let hashes = get_hashes_str(n);
1422 f(&["cr", hashes, "\"", symbol, "\"", hashes, suffix])
1423 }
1424
1425 bridge::LitKind::Integer | bridge::LitKind::Float | bridge::LitKind::ErrWithGuar => {
1426 f(&[symbol, suffix])
1427 }
1428 })
1429 }
1430
1431 #[unstable(feature = "proc_macro_value", issue = "136652")]
1433 pub fn str_value(&self) -> Result<String, ConversionErrorKind> {
1434 self.0.symbol.with(|symbol| match self.0.kind {
1435 bridge::LitKind::Str => {
1436 if symbol.contains('\\') {
1437 let mut buf = String::with_capacity(symbol.len());
1438 let mut error = None;
1439 unescape_unicode(
1443 symbol,
1444 Mode::Str,
1445 &mut #[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_mixed(symbol, Mode::CStr, &mut |_span, c| match c {
1475 Ok(MixedUnit::Char(c)) => {
1476 buf.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes())
1477 }
1478 Ok(MixedUnit::HighByte(b)) => buf.push(b),
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_unicode(symbol, Mode::ByteStr, &mut |_, c| match c {
1514 Ok(c) => buf.push(byte_from_char(c)),
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}