1#![stable(feature = "proc_macro_lib", since = "1.15.0")]
13#![deny(missing_docs)]
14#![doc(
15 html_playground_url = "https://play.rust-lang.org/",
16 issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/",
17 test(no_crate_inject, attr(deny(warnings))),
18 test(attr(allow(dead_code, deprecated, unused_variables, unused_mut)))
19)]
20#![doc(rust_logo)]
21#![feature(rustdoc_internals)]
22#![feature(staged_api)]
23#![feature(allow_internal_unstable)]
24#![feature(decl_macro)]
25#![feature(negative_impls)]
26#![feature(panic_can_unwind)]
27#![feature(restricted_std)]
28#![feature(rustc_attrs)]
29#![feature(extend_one)]
30#![recursion_limit = "256"]
31#![allow(internal_features)]
32#![deny(ffi_unwind_calls)]
33#![allow(rustc::internal)] #![warn(rustdoc::unescaped_backticks)]
35#![warn(unreachable_pub)]
36#![deny(unsafe_op_in_unsafe_fn)]
37
38#[unstable(feature = "proc_macro_internals", issue = "27812")]
39#[doc(hidden)]
40pub mod bridge;
41
42mod diagnostic;
43mod escape;
44mod to_tokens;
45
46use core::ops::BitOr;
47use std::ffi::CStr;
48use std::ops::{Range, RangeBounds};
49use std::path::PathBuf;
50use std::str::FromStr;
51use std::{error, fmt};
52
53#[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
54pub use diagnostic::{Diagnostic, Level, MultiSpan};
55#[unstable(feature = "proc_macro_value", issue = "136652")]
56pub use rustc_literal_escaper::EscapeError;
57use rustc_literal_escaper::{MixedUnit, unescape_byte_str, unescape_c_str, unescape_str};
58#[unstable(feature = "proc_macro_totokens", issue = "130977")]
59pub use to_tokens::ToTokens;
60
61use crate::escape::{EscapeOptions, escape_bytes};
62
63#[unstable(feature = "proc_macro_value", issue = "136652")]
65#[derive(Debug, PartialEq, Eq)]
66pub enum ConversionErrorKind {
67 FailedToUnescape(EscapeError),
69 InvalidLiteralKind,
71}
72
73#[stable(feature = "proc_macro_is_available", since = "1.57.0")]
87pub fn is_available() -> bool {
88 bridge::client::is_available()
89}
90
91#[cfg_attr(feature = "rustc-dep-of-std", rustc_diagnostic_item = "TokenStream")]
99#[stable(feature = "proc_macro_lib", since = "1.15.0")]
100#[derive(Clone)]
101pub struct TokenStream(Option<bridge::client::TokenStream>);
102
103#[stable(feature = "proc_macro_lib", since = "1.15.0")]
104impl !Send for TokenStream {}
105#[stable(feature = "proc_macro_lib", since = "1.15.0")]
106impl !Sync for TokenStream {}
107
108#[stable(feature = "proc_macro_lib", since = "1.15.0")]
110#[non_exhaustive]
111#[derive(Debug)]
112pub struct LexError;
113
114#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
115impl fmt::Display for LexError {
116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117 f.write_str("cannot parse string into token stream")
118 }
119}
120
121#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
122impl error::Error for LexError {}
123
124#[stable(feature = "proc_macro_lib", since = "1.15.0")]
125impl !Send for LexError {}
126#[stable(feature = "proc_macro_lib", since = "1.15.0")]
127impl !Sync for LexError {}
128
129#[unstable(feature = "proc_macro_expand", issue = "90765")]
131#[non_exhaustive]
132#[derive(Debug)]
133pub struct ExpandError;
134
135#[unstable(feature = "proc_macro_expand", issue = "90765")]
136impl fmt::Display for ExpandError {
137 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138 f.write_str("macro expansion failed")
139 }
140}
141
142#[unstable(feature = "proc_macro_expand", issue = "90765")]
143impl error::Error for ExpandError {}
144
145#[unstable(feature = "proc_macro_expand", issue = "90765")]
146impl !Send for ExpandError {}
147
148#[unstable(feature = "proc_macro_expand", issue = "90765")]
149impl !Sync for ExpandError {}
150
151impl TokenStream {
152 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
154 pub fn new() -> TokenStream {
155 TokenStream(None)
156 }
157
158 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
160 pub fn is_empty(&self) -> bool {
161 self.0.as_ref().map(|h| h.is_empty()).unwrap_or(true)
162 }
163
164 #[unstable(feature = "proc_macro_expand", issue = "90765")]
175 pub fn expand_expr(&self) -> Result<TokenStream, ExpandError> {
176 let stream = self.0.as_ref().ok_or(ExpandError)?;
177 match bridge::client::TokenStream::expand_expr(stream) {
178 Ok(stream) => Ok(TokenStream(Some(stream))),
179 Err(_) => Err(ExpandError),
180 }
181 }
182}
183
184#[stable(feature = "proc_macro_lib", since = "1.15.0")]
192impl FromStr for TokenStream {
193 type Err = LexError;
194
195 fn from_str(src: &str) -> Result<TokenStream, LexError> {
196 Ok(TokenStream(Some(bridge::client::TokenStream::from_str(src))))
197 }
198}
199
200#[stable(feature = "proc_macro_lib", since = "1.15.0")]
212impl fmt::Display for TokenStream {
213 #[allow(clippy::recursive_format_impl)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
215 match &self.0 {
216 Some(ts) => write!(f, "{}", ts.to_string()),
217 None => Ok(()),
218 }
219 }
220}
221
222#[stable(feature = "proc_macro_lib", since = "1.15.0")]
224impl fmt::Debug for TokenStream {
225 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
226 f.write_str("TokenStream ")?;
227 f.debug_list().entries(self.clone()).finish()
228 }
229}
230
231#[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
232impl Default for TokenStream {
233 fn default() -> Self {
234 TokenStream::new()
235 }
236}
237
238#[unstable(feature = "proc_macro_quote", issue = "54722")]
239pub use quote::{HasIterator, RepInterp, ThereIsNoIteratorInRepetition, ext, quote, quote_span};
240
241fn tree_to_bridge_tree(
242 tree: TokenTree,
243) -> bridge::TokenTree<bridge::client::TokenStream, bridge::client::Span, bridge::client::Symbol> {
244 match tree {
245 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
246 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
247 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
248 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
249 }
250}
251
252#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
254impl From<TokenTree> for TokenStream {
255 fn from(tree: TokenTree) -> TokenStream {
256 TokenStream(Some(bridge::client::TokenStream::from_token_tree(tree_to_bridge_tree(tree))))
257 }
258}
259
260struct ConcatTreesHelper {
263 trees: Vec<
264 bridge::TokenTree<
265 bridge::client::TokenStream,
266 bridge::client::Span,
267 bridge::client::Symbol,
268 >,
269 >,
270}
271
272impl ConcatTreesHelper {
273 fn new(capacity: usize) -> Self {
274 ConcatTreesHelper { trees: Vec::with_capacity(capacity) }
275 }
276
277 fn push(&mut self, tree: TokenTree) {
278 self.trees.push(tree_to_bridge_tree(tree));
279 }
280
281 fn build(self) -> TokenStream {
282 if self.trees.is_empty() {
283 TokenStream(None)
284 } else {
285 TokenStream(Some(bridge::client::TokenStream::concat_trees(None, self.trees)))
286 }
287 }
288
289 fn append_to(self, stream: &mut TokenStream) {
290 if self.trees.is_empty() {
291 return;
292 }
293 stream.0 = Some(bridge::client::TokenStream::concat_trees(stream.0.take(), self.trees))
294 }
295}
296
297struct ConcatStreamsHelper {
300 streams: Vec<bridge::client::TokenStream>,
301}
302
303impl ConcatStreamsHelper {
304 fn new(capacity: usize) -> Self {
305 ConcatStreamsHelper { streams: Vec::with_capacity(capacity) }
306 }
307
308 fn push(&mut self, stream: TokenStream) {
309 if let Some(stream) = stream.0 {
310 self.streams.push(stream);
311 }
312 }
313
314 fn build(mut self) -> TokenStream {
315 if self.streams.len() <= 1 {
316 TokenStream(self.streams.pop())
317 } else {
318 TokenStream(Some(bridge::client::TokenStream::concat_streams(None, self.streams)))
319 }
320 }
321
322 fn append_to(mut self, stream: &mut TokenStream) {
323 if self.streams.is_empty() {
324 return;
325 }
326 let base = stream.0.take();
327 if base.is_none() && self.streams.len() == 1 {
328 stream.0 = self.streams.pop();
329 } else {
330 stream.0 = Some(bridge::client::TokenStream::concat_streams(base, self.streams));
331 }
332 }
333}
334
335#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
337impl FromIterator<TokenTree> for TokenStream {
338 fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
339 let iter = trees.into_iter();
340 let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
341 iter.for_each(|tree| builder.push(tree));
342 builder.build()
343 }
344}
345
346#[stable(feature = "proc_macro_lib", since = "1.15.0")]
349impl FromIterator<TokenStream> for TokenStream {
350 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
351 let iter = streams.into_iter();
352 let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
353 iter.for_each(|stream| builder.push(stream));
354 builder.build()
355 }
356}
357
358#[stable(feature = "token_stream_extend", since = "1.30.0")]
359impl Extend<TokenTree> for TokenStream {
360 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
361 let iter = trees.into_iter();
362 let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
363 iter.for_each(|tree| builder.push(tree));
364 builder.append_to(self);
365 }
366}
367
368#[stable(feature = "token_stream_extend", since = "1.30.0")]
369impl Extend<TokenStream> for TokenStream {
370 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
371 let iter = streams.into_iter();
372 let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
373 iter.for_each(|stream| builder.push(stream));
374 builder.append_to(self);
375 }
376}
377
378macro_rules! extend_items {
379 ($($item:ident)*) => {
380 $(
381 #[stable(feature = "token_stream_extend_tt_items", since = "1.92.0")]
382 impl Extend<$item> for TokenStream {
383 fn extend<T: IntoIterator<Item = $item>>(&mut self, iter: T) {
384 self.extend(iter.into_iter().map(TokenTree::$item));
385 }
386 }
387 )*
388 };
389}
390
391extend_items!(Group Literal Punct Ident);
392
393#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
395pub mod token_stream {
396 use crate::{Group, Ident, Literal, Punct, TokenStream, TokenTree, bridge};
397
398 #[derive(Clone)]
402 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
403 pub struct IntoIter(
404 std::vec::IntoIter<
405 bridge::TokenTree<
406 bridge::client::TokenStream,
407 bridge::client::Span,
408 bridge::client::Symbol,
409 >,
410 >,
411 );
412
413 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
414 impl Iterator for IntoIter {
415 type Item = TokenTree;
416
417 fn next(&mut self) -> Option<TokenTree> {
418 self.0.next().map(|tree| match tree {
419 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
420 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
421 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
422 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
423 })
424 }
425
426 fn size_hint(&self) -> (usize, Option<usize>) {
427 self.0.size_hint()
428 }
429
430 fn count(self) -> usize {
431 self.0.count()
432 }
433 }
434
435 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
436 impl IntoIterator for TokenStream {
437 type Item = TokenTree;
438 type IntoIter = IntoIter;
439
440 fn into_iter(self) -> IntoIter {
441 IntoIter(self.0.map(|v| v.into_trees()).unwrap_or_default().into_iter())
442 }
443 }
444}
445
446#[unstable(feature = "proc_macro_quote", issue = "54722")]
453#[allow_internal_unstable(proc_macro_def_site, proc_macro_internals, proc_macro_totokens)]
454#[rustc_builtin_macro]
455pub macro quote($($t:tt)*) {
456 }
458
459#[unstable(feature = "proc_macro_internals", issue = "27812")]
460#[doc(hidden)]
461mod quote;
462
463#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
465#[derive(Copy, Clone)]
466pub struct Span(bridge::client::Span);
467
468#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
469impl !Send for Span {}
470#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
471impl !Sync for Span {}
472
473macro_rules! diagnostic_method {
474 ($name:ident, $level:expr) => {
475 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
478 pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
479 Diagnostic::spanned(self, $level, message)
480 }
481 };
482}
483
484impl Span {
485 #[unstable(feature = "proc_macro_def_site", issue = "54724")]
487 pub fn def_site() -> Span {
488 Span(bridge::client::Span::def_site())
489 }
490
491 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
496 pub fn call_site() -> Span {
497 Span(bridge::client::Span::call_site())
498 }
499
500 #[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
505 pub fn mixed_site() -> Span {
506 Span(bridge::client::Span::mixed_site())
507 }
508
509 #[unstable(feature = "proc_macro_span", issue = "54725")]
512 pub fn parent(&self) -> Option<Span> {
513 self.0.parent().map(Span)
514 }
515
516 #[unstable(feature = "proc_macro_span", issue = "54725")]
520 pub fn source(&self) -> Span {
521 Span(self.0.source())
522 }
523
524 #[unstable(feature = "proc_macro_span", issue = "54725")]
526 pub fn byte_range(&self) -> Range<usize> {
527 self.0.byte_range()
528 }
529
530 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
532 pub fn start(&self) -> Span {
533 Span(self.0.start())
534 }
535
536 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
538 pub fn end(&self) -> Span {
539 Span(self.0.end())
540 }
541
542 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
546 pub fn line(&self) -> usize {
547 self.0.line()
548 }
549
550 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
554 pub fn column(&self) -> usize {
555 self.0.column()
556 }
557
558 #[stable(feature = "proc_macro_span_file", since = "1.88.0")]
563 pub fn file(&self) -> String {
564 self.0.file()
565 }
566
567 #[stable(feature = "proc_macro_span_file", since = "1.88.0")]
573 pub fn local_file(&self) -> Option<PathBuf> {
574 self.0.local_file().map(|s| PathBuf::from(s))
575 }
576
577 #[unstable(feature = "proc_macro_span", issue = "54725")]
581 pub fn join(&self, other: Span) -> Option<Span> {
582 self.0.join(other.0).map(Span)
583 }
584
585 #[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
588 pub fn resolved_at(&self, other: Span) -> Span {
589 Span(self.0.resolved_at(other.0))
590 }
591
592 #[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
595 pub fn located_at(&self, other: Span) -> Span {
596 other.resolved_at(*self)
597 }
598
599 #[unstable(feature = "proc_macro_span", issue = "54725")]
601 pub fn eq(&self, other: &Span) -> bool {
602 self.0 == other.0
603 }
604
605 #[stable(feature = "proc_macro_source_text", since = "1.66.0")]
613 pub fn source_text(&self) -> Option<String> {
614 self.0.source_text()
615 }
616
617 #[doc(hidden)]
619 #[unstable(feature = "proc_macro_internals", issue = "27812")]
620 pub fn save_span(&self) -> usize {
621 self.0.save_span()
622 }
623
624 #[doc(hidden)]
626 #[unstable(feature = "proc_macro_internals", issue = "27812")]
627 pub fn recover_proc_macro_span(id: usize) -> Span {
628 Span(bridge::client::Span::recover_proc_macro_span(id))
629 }
630
631 diagnostic_method!(error, Level::Error);
632 diagnostic_method!(warning, Level::Warning);
633 diagnostic_method!(note, Level::Note);
634 diagnostic_method!(help, Level::Help);
635}
636
637#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
639impl fmt::Debug for Span {
640 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
641 self.0.fmt(f)
642 }
643}
644
645#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
647#[derive(Clone)]
648pub enum TokenTree {
649 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
651 Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
652 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
654 Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
655 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
657 Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
658 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
660 Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
661}
662
663#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
664impl !Send for TokenTree {}
665#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
666impl !Sync for TokenTree {}
667
668impl TokenTree {
669 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
672 pub fn span(&self) -> Span {
673 match *self {
674 TokenTree::Group(ref t) => t.span(),
675 TokenTree::Ident(ref t) => t.span(),
676 TokenTree::Punct(ref t) => t.span(),
677 TokenTree::Literal(ref t) => t.span(),
678 }
679 }
680
681 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
687 pub fn set_span(&mut self, span: Span) {
688 match *self {
689 TokenTree::Group(ref mut t) => t.set_span(span),
690 TokenTree::Ident(ref mut t) => t.set_span(span),
691 TokenTree::Punct(ref mut t) => t.set_span(span),
692 TokenTree::Literal(ref mut t) => t.set_span(span),
693 }
694 }
695}
696
697#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
699impl fmt::Debug for TokenTree {
700 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
701 match *self {
704 TokenTree::Group(ref tt) => tt.fmt(f),
705 TokenTree::Ident(ref tt) => tt.fmt(f),
706 TokenTree::Punct(ref tt) => tt.fmt(f),
707 TokenTree::Literal(ref tt) => tt.fmt(f),
708 }
709 }
710}
711
712#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
713impl From<Group> for TokenTree {
714 fn from(g: Group) -> TokenTree {
715 TokenTree::Group(g)
716 }
717}
718
719#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
720impl From<Ident> for TokenTree {
721 fn from(g: Ident) -> TokenTree {
722 TokenTree::Ident(g)
723 }
724}
725
726#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
727impl From<Punct> for TokenTree {
728 fn from(g: Punct) -> TokenTree {
729 TokenTree::Punct(g)
730 }
731}
732
733#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
734impl From<Literal> for TokenTree {
735 fn from(g: Literal) -> TokenTree {
736 TokenTree::Literal(g)
737 }
738}
739
740#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
752impl fmt::Display for TokenTree {
753 #[allow(clippy::recursive_format_impl)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
755 match self {
756 TokenTree::Group(t) => write!(f, "{t}"),
757 TokenTree::Ident(t) => write!(f, "{t}"),
758 TokenTree::Punct(t) => write!(f, "{t}"),
759 TokenTree::Literal(t) => write!(f, "{t}"),
760 }
761 }
762}
763
764#[derive(Clone)]
768#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
769pub struct Group(bridge::Group<bridge::client::TokenStream, bridge::client::Span>);
770
771#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
772impl !Send for Group {}
773#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
774impl !Sync for Group {}
775
776#[derive(Copy, Clone, Debug, PartialEq, Eq)]
778#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
779pub enum Delimiter {
780 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
782 Parenthesis,
783 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
785 Brace,
786 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
788 Bracket,
789 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
807 None,
808}
809
810impl Group {
811 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
817 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
818 Group(bridge::Group {
819 delimiter,
820 stream: stream.0,
821 span: bridge::DelimSpan::from_single(Span::call_site().0),
822 })
823 }
824
825 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
827 pub fn delimiter(&self) -> Delimiter {
828 self.0.delimiter
829 }
830
831 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
836 pub fn stream(&self) -> TokenStream {
837 TokenStream(self.0.stream.clone())
838 }
839
840 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
848 pub fn span(&self) -> Span {
849 Span(self.0.span.entire)
850 }
851
852 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
859 pub fn span_open(&self) -> Span {
860 Span(self.0.span.open)
861 }
862
863 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
870 pub fn span_close(&self) -> Span {
871 Span(self.0.span.close)
872 }
873
874 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
881 pub fn set_span(&mut self, span: Span) {
882 self.0.span = bridge::DelimSpan::from_single(span.0);
883 }
884}
885
886#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
890impl fmt::Display for Group {
891 #[allow(clippy::recursive_format_impl)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
893 write!(f, "{}", TokenStream::from(TokenTree::from(self.clone())))
894 }
895}
896
897#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
898impl fmt::Debug for Group {
899 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
900 f.debug_struct("Group")
901 .field("delimiter", &self.delimiter())
902 .field("stream", &self.stream())
903 .field("span", &self.span())
904 .finish()
905 }
906}
907
908#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
913#[derive(Clone)]
914pub struct Punct(bridge::Punct<bridge::client::Span>);
915
916#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
917impl !Send for Punct {}
918#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
919impl !Sync for Punct {}
920
921#[derive(Copy, Clone, Debug, PartialEq, Eq)]
924#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
925pub enum Spacing {
926 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
938 Joint,
939 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
946 Alone,
947}
948
949impl Punct {
950 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
957 pub fn new(ch: char, spacing: Spacing) -> Punct {
958 const LEGAL_CHARS: &[char] = &[
959 '=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
960 ':', '#', '$', '?', '\'',
961 ];
962 if !LEGAL_CHARS.contains(&ch) {
963 panic!("unsupported character `{:?}`", ch);
964 }
965 Punct(bridge::Punct {
966 ch: ch as u8,
967 joint: spacing == Spacing::Joint,
968 span: Span::call_site().0,
969 })
970 }
971
972 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
974 pub fn as_char(&self) -> char {
975 self.0.ch as char
976 }
977
978 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
982 pub fn spacing(&self) -> Spacing {
983 if self.0.joint { Spacing::Joint } else { Spacing::Alone }
984 }
985
986 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
988 pub fn span(&self) -> Span {
989 Span(self.0.span)
990 }
991
992 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
994 pub fn set_span(&mut self, span: Span) {
995 self.0.span = span.0;
996 }
997}
998
999#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1002impl fmt::Display for Punct {
1003 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1004 write!(f, "{}", self.as_char())
1005 }
1006}
1007
1008#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1009impl fmt::Debug for Punct {
1010 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1011 f.debug_struct("Punct")
1012 .field("ch", &self.as_char())
1013 .field("spacing", &self.spacing())
1014 .field("span", &self.span())
1015 .finish()
1016 }
1017}
1018
1019#[stable(feature = "proc_macro_punct_eq", since = "1.50.0")]
1020impl PartialEq<char> for Punct {
1021 fn eq(&self, rhs: &char) -> bool {
1022 self.as_char() == *rhs
1023 }
1024}
1025
1026#[stable(feature = "proc_macro_punct_eq_flipped", since = "1.52.0")]
1027impl PartialEq<Punct> for char {
1028 fn eq(&self, rhs: &Punct) -> bool {
1029 *self == rhs.as_char()
1030 }
1031}
1032
1033#[derive(Clone)]
1035#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1036pub struct Ident(bridge::Ident<bridge::client::Span, bridge::client::Symbol>);
1037
1038impl Ident {
1039 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1059 pub fn new(string: &str, span: Span) -> Ident {
1060 Ident(bridge::Ident {
1061 sym: bridge::client::Symbol::new_ident(string, false),
1062 is_raw: false,
1063 span: span.0,
1064 })
1065 }
1066
1067 #[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
1072 pub fn new_raw(string: &str, span: Span) -> Ident {
1073 Ident(bridge::Ident {
1074 sym: bridge::client::Symbol::new_ident(string, true),
1075 is_raw: true,
1076 span: span.0,
1077 })
1078 }
1079
1080 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1083 pub fn span(&self) -> Span {
1084 Span(self.0.span)
1085 }
1086
1087 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1089 pub fn set_span(&mut self, span: Span) {
1090 self.0.span = span.0;
1091 }
1092}
1093
1094#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1097impl fmt::Display for Ident {
1098 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1099 if self.0.is_raw {
1100 f.write_str("r#")?;
1101 }
1102 fmt::Display::fmt(&self.0.sym, f)
1103 }
1104}
1105
1106#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1107impl fmt::Debug for Ident {
1108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1109 f.debug_struct("Ident")
1110 .field("ident", &self.to_string())
1111 .field("span", &self.span())
1112 .finish()
1113 }
1114}
1115
1116#[derive(Clone)]
1121#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1122pub struct Literal(bridge::Literal<bridge::client::Span, bridge::client::Symbol>);
1123
1124macro_rules! suffixed_int_literals {
1125 ($($name:ident => $kind:ident,)*) => ($(
1126 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1138 pub fn $name(n: $kind) -> Literal {
1139 Literal(bridge::Literal {
1140 kind: bridge::LitKind::Integer,
1141 symbol: bridge::client::Symbol::new(&n.to_string()),
1142 suffix: Some(bridge::client::Symbol::new(stringify!($kind))),
1143 span: Span::call_site().0,
1144 })
1145 }
1146 )*)
1147}
1148
1149macro_rules! unsuffixed_int_literals {
1150 ($($name:ident => $kind:ident,)*) => ($(
1151 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1165 pub fn $name(n: $kind) -> Literal {
1166 Literal(bridge::Literal {
1167 kind: bridge::LitKind::Integer,
1168 symbol: bridge::client::Symbol::new(&n.to_string()),
1169 suffix: None,
1170 span: Span::call_site().0,
1171 })
1172 }
1173 )*)
1174}
1175
1176impl Literal {
1177 fn new(kind: bridge::LitKind, value: &str, suffix: Option<&str>) -> Self {
1178 Literal(bridge::Literal {
1179 kind,
1180 symbol: bridge::client::Symbol::new(value),
1181 suffix: suffix.map(bridge::client::Symbol::new),
1182 span: Span::call_site().0,
1183 })
1184 }
1185
1186 suffixed_int_literals! {
1187 u8_suffixed => u8,
1188 u16_suffixed => u16,
1189 u32_suffixed => u32,
1190 u64_suffixed => u64,
1191 u128_suffixed => u128,
1192 usize_suffixed => usize,
1193 i8_suffixed => i8,
1194 i16_suffixed => i16,
1195 i32_suffixed => i32,
1196 i64_suffixed => i64,
1197 i128_suffixed => i128,
1198 isize_suffixed => isize,
1199 }
1200
1201 unsuffixed_int_literals! {
1202 u8_unsuffixed => u8,
1203 u16_unsuffixed => u16,
1204 u32_unsuffixed => u32,
1205 u64_unsuffixed => u64,
1206 u128_unsuffixed => u128,
1207 usize_unsuffixed => usize,
1208 i8_unsuffixed => i8,
1209 i16_unsuffixed => i16,
1210 i32_unsuffixed => i32,
1211 i64_unsuffixed => i64,
1212 i128_unsuffixed => i128,
1213 isize_unsuffixed => isize,
1214 }
1215
1216 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1229 pub fn f32_unsuffixed(n: f32) -> Literal {
1230 if !n.is_finite() {
1231 panic!("Invalid float literal {n}");
1232 }
1233 let mut repr = n.to_string();
1234 if !repr.contains('.') {
1235 repr.push_str(".0");
1236 }
1237 Literal::new(bridge::LitKind::Float, &repr, None)
1238 }
1239
1240 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1254 pub fn f32_suffixed(n: f32) -> Literal {
1255 if !n.is_finite() {
1256 panic!("Invalid float literal {n}");
1257 }
1258 Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f32"))
1259 }
1260
1261 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1274 pub fn f64_unsuffixed(n: f64) -> Literal {
1275 if !n.is_finite() {
1276 panic!("Invalid float literal {n}");
1277 }
1278 let mut repr = n.to_string();
1279 if !repr.contains('.') {
1280 repr.push_str(".0");
1281 }
1282 Literal::new(bridge::LitKind::Float, &repr, None)
1283 }
1284
1285 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1299 pub fn f64_suffixed(n: f64) -> Literal {
1300 if !n.is_finite() {
1301 panic!("Invalid float literal {n}");
1302 }
1303 Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f64"))
1304 }
1305
1306 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1308 pub fn string(string: &str) -> Literal {
1309 let escape = EscapeOptions {
1310 escape_single_quote: false,
1311 escape_double_quote: true,
1312 escape_nonascii: false,
1313 };
1314 let repr = escape_bytes(string.as_bytes(), escape);
1315 Literal::new(bridge::LitKind::Str, &repr, None)
1316 }
1317
1318 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1320 pub fn character(ch: char) -> Literal {
1321 let escape = EscapeOptions {
1322 escape_single_quote: true,
1323 escape_double_quote: false,
1324 escape_nonascii: false,
1325 };
1326 let repr = escape_bytes(ch.encode_utf8(&mut [0u8; 4]).as_bytes(), escape);
1327 Literal::new(bridge::LitKind::Char, &repr, None)
1328 }
1329
1330 #[stable(feature = "proc_macro_byte_character", since = "1.79.0")]
1332 pub fn byte_character(byte: u8) -> Literal {
1333 let escape = EscapeOptions {
1334 escape_single_quote: true,
1335 escape_double_quote: false,
1336 escape_nonascii: true,
1337 };
1338 let repr = escape_bytes(&[byte], escape);
1339 Literal::new(bridge::LitKind::Byte, &repr, None)
1340 }
1341
1342 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1344 pub fn byte_string(bytes: &[u8]) -> Literal {
1345 let escape = EscapeOptions {
1346 escape_single_quote: false,
1347 escape_double_quote: true,
1348 escape_nonascii: true,
1349 };
1350 let repr = escape_bytes(bytes, escape);
1351 Literal::new(bridge::LitKind::ByteStr, &repr, None)
1352 }
1353
1354 #[stable(feature = "proc_macro_c_str_literals", since = "1.79.0")]
1356 pub fn c_string(string: &CStr) -> Literal {
1357 let escape = EscapeOptions {
1358 escape_single_quote: false,
1359 escape_double_quote: true,
1360 escape_nonascii: false,
1361 };
1362 let repr = escape_bytes(string.to_bytes(), escape);
1363 Literal::new(bridge::LitKind::CStr, &repr, None)
1364 }
1365
1366 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1368 pub fn span(&self) -> Span {
1369 Span(self.0.span)
1370 }
1371
1372 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1374 pub fn set_span(&mut self, span: Span) {
1375 self.0.span = span.0;
1376 }
1377
1378 #[unstable(feature = "proc_macro_span", issue = "54725")]
1390 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1391 self.0.span.subspan(range.start_bound().cloned(), range.end_bound().cloned()).map(Span)
1392 }
1393
1394 fn with_symbol_and_suffix<R>(&self, f: impl FnOnce(&str, &str) -> R) -> R {
1395 self.0.symbol.with(|symbol| match self.0.suffix {
1396 Some(suffix) => suffix.with(|suffix| f(symbol, suffix)),
1397 None => f(symbol, ""),
1398 })
1399 }
1400
1401 fn with_stringify_parts<R>(&self, f: impl FnOnce(&[&str]) -> R) -> R {
1406 fn get_hashes_str(num: u8) -> &'static str {
1410 const HASHES: &str = "\
1411 ################################################################\
1412 ################################################################\
1413 ################################################################\
1414 ################################################################\
1415 ";
1416 const _: () = assert!(HASHES.len() == 256);
1417 &HASHES[..num as usize]
1418 }
1419
1420 self.with_symbol_and_suffix(|symbol, suffix| match self.0.kind {
1421 bridge::LitKind::Byte => f(&["b'", symbol, "'", suffix]),
1422 bridge::LitKind::Char => f(&["'", symbol, "'", suffix]),
1423 bridge::LitKind::Str => f(&["\"", symbol, "\"", suffix]),
1424 bridge::LitKind::StrRaw(n) => {
1425 let hashes = get_hashes_str(n);
1426 f(&["r", hashes, "\"", symbol, "\"", hashes, suffix])
1427 }
1428 bridge::LitKind::ByteStr => f(&["b\"", symbol, "\"", suffix]),
1429 bridge::LitKind::ByteStrRaw(n) => {
1430 let hashes = get_hashes_str(n);
1431 f(&["br", hashes, "\"", symbol, "\"", hashes, suffix])
1432 }
1433 bridge::LitKind::CStr => f(&["c\"", symbol, "\"", suffix]),
1434 bridge::LitKind::CStrRaw(n) => {
1435 let hashes = get_hashes_str(n);
1436 f(&["cr", hashes, "\"", symbol, "\"", hashes, suffix])
1437 }
1438
1439 bridge::LitKind::Integer | bridge::LitKind::Float | bridge::LitKind::ErrWithGuar => {
1440 f(&[symbol, suffix])
1441 }
1442 })
1443 }
1444
1445 #[unstable(feature = "proc_macro_value", issue = "136652")]
1447 pub fn str_value(&self) -> Result<String, ConversionErrorKind> {
1448 self.0.symbol.with(|symbol| match self.0.kind {
1449 bridge::LitKind::Str => {
1450 if symbol.contains('\\') {
1451 let mut buf = String::with_capacity(symbol.len());
1452 let mut error = None;
1453 unescape_str(
1457 symbol,
1458 #[inline(always)]
1459 |_, c| match c {
1460 Ok(c) => buf.push(c),
1461 Err(err) => {
1462 if err.is_fatal() {
1463 error = Some(ConversionErrorKind::FailedToUnescape(err));
1464 }
1465 }
1466 },
1467 );
1468 if let Some(error) = error { Err(error) } else { Ok(buf) }
1469 } else {
1470 Ok(symbol.to_string())
1471 }
1472 }
1473 bridge::LitKind::StrRaw(_) => Ok(symbol.to_string()),
1474 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1475 })
1476 }
1477
1478 #[unstable(feature = "proc_macro_value", issue = "136652")]
1481 pub fn cstr_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1482 self.0.symbol.with(|symbol| match self.0.kind {
1483 bridge::LitKind::CStr => {
1484 let mut error = None;
1485 let mut buf = Vec::with_capacity(symbol.len());
1486
1487 unescape_c_str(symbol, |_span, res| match res {
1488 Ok(MixedUnit::Char(c)) => {
1489 buf.extend_from_slice(c.get().encode_utf8(&mut [0; 4]).as_bytes())
1490 }
1491 Ok(MixedUnit::HighByte(b)) => buf.push(b.get()),
1492 Err(err) => {
1493 if err.is_fatal() {
1494 error = Some(ConversionErrorKind::FailedToUnescape(err));
1495 }
1496 }
1497 });
1498 if let Some(error) = error {
1499 Err(error)
1500 } else {
1501 buf.push(0);
1502 Ok(buf)
1503 }
1504 }
1505 bridge::LitKind::CStrRaw(_) => {
1506 let mut buf = symbol.to_owned().into_bytes();
1510 buf.push(0);
1511 Ok(buf)
1512 }
1513 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1514 })
1515 }
1516
1517 #[unstable(feature = "proc_macro_value", issue = "136652")]
1520 pub fn byte_str_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1521 self.0.symbol.with(|symbol| match self.0.kind {
1522 bridge::LitKind::ByteStr => {
1523 let mut buf = Vec::with_capacity(symbol.len());
1524 let mut error = None;
1525
1526 unescape_byte_str(symbol, |_, res| match res {
1527 Ok(b) => buf.push(b),
1528 Err(err) => {
1529 if err.is_fatal() {
1530 error = Some(ConversionErrorKind::FailedToUnescape(err));
1531 }
1532 }
1533 });
1534 if let Some(error) = error { Err(error) } else { Ok(buf) }
1535 }
1536 bridge::LitKind::ByteStrRaw(_) => {
1537 Ok(symbol.to_owned().into_bytes())
1540 }
1541 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1542 })
1543 }
1544}
1545
1546#[stable(feature = "proc_macro_literal_parse", since = "1.54.0")]
1557impl FromStr for Literal {
1558 type Err = LexError;
1559
1560 fn from_str(src: &str) -> Result<Self, LexError> {
1561 match bridge::client::FreeFunctions::literal_from_str(src) {
1562 Ok(literal) => Ok(Literal(literal)),
1563 Err(()) => Err(LexError),
1564 }
1565 }
1566}
1567
1568#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1571impl fmt::Display for Literal {
1572 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1573 self.with_stringify_parts(|parts| {
1574 for part in parts {
1575 fmt::Display::fmt(part, f)?;
1576 }
1577 Ok(())
1578 })
1579 }
1580}
1581
1582#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1583impl fmt::Debug for Literal {
1584 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1585 f.debug_struct("Literal")
1586 .field("kind", &format_args!("{:?}", self.0.kind))
1588 .field("symbol", &self.0.symbol)
1589 .field("suffix", &format_args!("{:?}", self.0.suffix))
1591 .field("span", &self.0.span)
1592 .finish()
1593 }
1594}
1595
1596#[unstable(
1597 feature = "proc_macro_tracked_path",
1598 issue = "99515",
1599 implied_by = "proc_macro_tracked_env"
1600)]
1601pub mod tracked {
1603
1604 use std::env::{self, VarError};
1605 use std::ffi::OsStr;
1606 use std::path::Path;
1607
1608 #[unstable(feature = "proc_macro_tracked_env", issue = "99515")]
1614 pub fn env_var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1615 let key: &str = key.as_ref();
1616 let value = crate::bridge::client::FreeFunctions::injected_env_var(key)
1617 .map_or_else(|| env::var(key), Ok);
1618 crate::bridge::client::FreeFunctions::track_env_var(key, value.as_deref().ok());
1619 value
1620 }
1621
1622 #[unstable(feature = "proc_macro_tracked_path", issue = "99515")]
1626 pub fn path<P: AsRef<Path>>(path: P) {
1627 let path: &str = path.as_ref().to_str().unwrap();
1628 crate::bridge::client::FreeFunctions::track_path(path);
1629 }
1630}