1#![stable(feature = "proc_macro_lib", since = "1.15.0")]
13#![deny(missing_docs)]
14#![doc(
15 html_playground_url = "https://play.rust-lang.org/",
16 issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/",
17 test(no_crate_inject, attr(deny(warnings))),
18 test(attr(allow(dead_code, deprecated, unused_variables, unused_mut)))
19)]
20#![doc(rust_logo)]
21#![feature(rustdoc_internals)]
22#![feature(staged_api)]
23#![feature(allow_internal_unstable)]
24#![feature(decl_macro)]
25#![feature(negative_impls)]
26#![feature(panic_can_unwind)]
27#![feature(restricted_std)]
28#![feature(rustc_attrs)]
29#![feature(extend_one)]
30#![feature(mem_conjure_zst)]
31#![recursion_limit = "256"]
32#![allow(internal_features)]
33#![deny(ffi_unwind_calls)]
34#![allow(rustc::internal)] #![warn(rustdoc::unescaped_backticks)]
36#![warn(unreachable_pub)]
37#![deny(unsafe_op_in_unsafe_fn)]
38
39#[unstable(feature = "proc_macro_internals", issue = "27812")]
40#[doc(hidden)]
41pub mod bridge;
42
43mod diagnostic;
44mod escape;
45mod to_tokens;
46
47use core::ops::BitOr;
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::{
59 MixedUnit, unescape_byte, unescape_byte_str, unescape_c_str, unescape_char, unescape_str,
60};
61#[unstable(feature = "proc_macro_totokens", issue = "130977")]
62pub use to_tokens::ToTokens;
63
64use crate::bridge::client::Methods as BridgeMethods;
65use crate::escape::{EscapeOptions, escape_bytes};
66
67#[unstable(feature = "proc_macro_value", issue = "136652")]
69#[derive(Debug, PartialEq, Eq)]
70pub enum ConversionErrorKind {
71 FailedToUnescape(EscapeError),
73 InvalidLiteralKind,
75}
76
77#[stable(feature = "proc_macro_is_available", since = "1.57.0")]
91pub fn is_available() -> bool {
92 bridge::client::is_available()
93}
94
95#[cfg_attr(feature = "rustc-dep-of-std", rustc_diagnostic_item = "TokenStream")]
103#[stable(feature = "proc_macro_lib", since = "1.15.0")]
104#[derive(Clone)]
105pub struct TokenStream(Option<bridge::client::TokenStream>);
106
107#[stable(feature = "proc_macro_lib", since = "1.15.0")]
108impl !Send for TokenStream {}
109#[stable(feature = "proc_macro_lib", since = "1.15.0")]
110impl !Sync for TokenStream {}
111
112#[stable(feature = "proc_macro_lib", since = "1.15.0")]
117#[non_exhaustive]
118#[derive(Debug)]
119pub struct LexError(String);
120
121#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
122impl fmt::Display for LexError {
123 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124 f.write_str(&self.0)
125 }
126}
127
128#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
129impl error::Error for LexError {}
130
131#[stable(feature = "proc_macro_lib", since = "1.15.0")]
132impl !Send for LexError {}
133#[stable(feature = "proc_macro_lib", since = "1.15.0")]
134impl !Sync for LexError {}
135
136#[unstable(feature = "proc_macro_expand", issue = "90765")]
138#[non_exhaustive]
139#[derive(Debug)]
140pub struct ExpandError;
141
142#[unstable(feature = "proc_macro_expand", issue = "90765")]
143impl fmt::Display for ExpandError {
144 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145 f.write_str("macro expansion failed")
146 }
147}
148
149#[unstable(feature = "proc_macro_expand", issue = "90765")]
150impl error::Error for ExpandError {}
151
152#[unstable(feature = "proc_macro_expand", issue = "90765")]
153impl !Send for ExpandError {}
154
155#[unstable(feature = "proc_macro_expand", issue = "90765")]
156impl !Sync for ExpandError {}
157
158impl TokenStream {
159 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
161 pub fn new() -> TokenStream {
162 TokenStream(None)
163 }
164
165 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
167 pub fn is_empty(&self) -> bool {
168 self.0.as_ref().map(|h| BridgeMethods::ts_is_empty(h)).unwrap_or(true)
169 }
170
171 #[unstable(feature = "proc_macro_expand", issue = "90765")]
182 pub fn expand_expr(&self) -> Result<TokenStream, ExpandError> {
183 let stream = self.0.as_ref().ok_or(ExpandError)?;
184 match BridgeMethods::ts_expand_expr(stream) {
185 Ok(stream) => Ok(TokenStream(Some(stream))),
186 Err(_) => Err(ExpandError),
187 }
188 }
189}
190
191#[stable(feature = "proc_macro_lib", since = "1.15.0")]
199impl FromStr for TokenStream {
200 type Err = LexError;
201
202 fn from_str(src: &str) -> Result<TokenStream, LexError> {
203 Ok(TokenStream(Some(BridgeMethods::ts_from_str(src).map_err(LexError)?)))
204 }
205}
206
207#[stable(feature = "proc_macro_lib", since = "1.15.0")]
219impl fmt::Display for TokenStream {
220 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
221 match &self.0 {
222 Some(ts) => write!(f, "{}", BridgeMethods::ts_to_string(ts)),
223 None => Ok(()),
224 }
225 }
226}
227
228#[stable(feature = "proc_macro_lib", since = "1.15.0")]
230impl fmt::Debug for TokenStream {
231 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
232 f.write_str("TokenStream ")?;
233 f.debug_list().entries(self.clone()).finish()
234 }
235}
236
237#[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
238impl Default for TokenStream {
239 fn default() -> Self {
240 TokenStream::new()
241 }
242}
243
244#[unstable(feature = "proc_macro_quote", issue = "54722")]
245pub use quote::{HasIterator, RepInterp, ThereIsNoIteratorInRepetition, ext, quote, quote_span};
246
247fn tree_to_bridge_tree(
248 tree: TokenTree,
249) -> bridge::TokenTree<bridge::client::TokenStream, bridge::client::Span, bridge::client::Symbol> {
250 match tree {
251 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
252 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
253 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
254 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
255 }
256}
257
258#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
260impl From<TokenTree> for TokenStream {
261 fn from(tree: TokenTree) -> TokenStream {
262 TokenStream(Some(BridgeMethods::ts_from_token_tree(tree_to_bridge_tree(tree))))
263 }
264}
265
266struct ConcatTreesHelper {
269 trees: Vec<
270 bridge::TokenTree<
271 bridge::client::TokenStream,
272 bridge::client::Span,
273 bridge::client::Symbol,
274 >,
275 >,
276}
277
278impl ConcatTreesHelper {
279 fn new(capacity: usize) -> Self {
280 ConcatTreesHelper { trees: Vec::with_capacity(capacity) }
281 }
282
283 fn push(&mut self, tree: TokenTree) {
284 self.trees.push(tree_to_bridge_tree(tree));
285 }
286
287 fn build(self) -> TokenStream {
288 if self.trees.is_empty() {
289 TokenStream(None)
290 } else {
291 TokenStream(Some(BridgeMethods::ts_concat_trees(None, self.trees)))
292 }
293 }
294
295 fn append_to(self, stream: &mut TokenStream) {
296 if self.trees.is_empty() {
297 return;
298 }
299 stream.0 = Some(BridgeMethods::ts_concat_trees(stream.0.take(), self.trees))
300 }
301}
302
303struct ConcatStreamsHelper {
306 streams: Vec<bridge::client::TokenStream>,
307}
308
309impl ConcatStreamsHelper {
310 fn new(capacity: usize) -> Self {
311 ConcatStreamsHelper { streams: Vec::with_capacity(capacity) }
312 }
313
314 fn push(&mut self, stream: TokenStream) {
315 if let Some(stream) = stream.0 {
316 self.streams.push(stream);
317 }
318 }
319
320 fn build(mut self) -> TokenStream {
321 if self.streams.len() <= 1 {
322 TokenStream(self.streams.pop())
323 } else {
324 TokenStream(Some(BridgeMethods::ts_concat_streams(None, self.streams)))
325 }
326 }
327
328 fn append_to(mut self, stream: &mut TokenStream) {
329 if self.streams.is_empty() {
330 return;
331 }
332 let base = stream.0.take();
333 if base.is_none() && self.streams.len() == 1 {
334 stream.0 = self.streams.pop();
335 } else {
336 stream.0 = Some(BridgeMethods::ts_concat_streams(base, self.streams));
337 }
338 }
339}
340
341#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
343impl FromIterator<TokenTree> for TokenStream {
344 fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
345 let iter = trees.into_iter();
346 let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
347 iter.for_each(|tree| builder.push(tree));
348 builder.build()
349 }
350}
351
352#[stable(feature = "proc_macro_lib", since = "1.15.0")]
355impl FromIterator<TokenStream> for TokenStream {
356 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
357 let iter = streams.into_iter();
358 let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
359 iter.for_each(|stream| builder.push(stream));
360 builder.build()
361 }
362}
363
364#[stable(feature = "token_stream_extend", since = "1.30.0")]
365impl Extend<TokenTree> for TokenStream {
366 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
367 let iter = trees.into_iter();
368 let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
369 iter.for_each(|tree| builder.push(tree));
370 builder.append_to(self);
371 }
372}
373
374#[stable(feature = "token_stream_extend", since = "1.30.0")]
375impl Extend<TokenStream> for TokenStream {
376 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
377 let iter = streams.into_iter();
378 let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
379 iter.for_each(|stream| builder.push(stream));
380 builder.append_to(self);
381 }
382}
383
384macro_rules! extend_items {
385 ($($item:ident)*) => {
386 $(
387 #[stable(feature = "token_stream_extend_ts_items", since = "1.92.0")]
388 impl Extend<$item> for TokenStream {
389 fn extend<T: IntoIterator<Item = $item>>(&mut self, iter: T) {
390 self.extend(iter.into_iter().map(TokenTree::$item));
391 }
392 }
393 )*
394 };
395}
396
397extend_items!(Group Literal Punct Ident);
398
399#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
401pub mod token_stream {
402 use crate::{BridgeMethods, Group, Ident, Literal, Punct, TokenStream, TokenTree, bridge};
403
404 #[derive(Clone)]
408 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
409 pub struct IntoIter(
410 std::vec::IntoIter<
411 bridge::TokenTree<
412 bridge::client::TokenStream,
413 bridge::client::Span,
414 bridge::client::Symbol,
415 >,
416 >,
417 );
418
419 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
420 impl Iterator for IntoIter {
421 type Item = TokenTree;
422
423 fn next(&mut self) -> Option<TokenTree> {
424 self.0.next().map(|tree| match tree {
425 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
426 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
427 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
428 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
429 })
430 }
431
432 fn size_hint(&self) -> (usize, Option<usize>) {
433 self.0.size_hint()
434 }
435
436 fn count(self) -> usize {
437 self.0.count()
438 }
439 }
440
441 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
442 impl IntoIterator for TokenStream {
443 type Item = TokenTree;
444 type IntoIter = IntoIter;
445
446 fn into_iter(self) -> IntoIter {
447 IntoIter(
448 self.0.map(|v| BridgeMethods::ts_into_trees(v)).unwrap_or_default().into_iter(),
449 )
450 }
451 }
452}
453
454#[unstable(feature = "proc_macro_quote", issue = "54722")]
461#[allow_internal_unstable(proc_macro_def_site, proc_macro_internals, proc_macro_totokens)]
462#[rustc_builtin_macro]
463pub macro quote($($t:tt)*) {
464 }
466
467#[unstable(feature = "proc_macro_internals", issue = "27812")]
468#[doc(hidden)]
469mod quote;
470
471#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
473#[derive(Copy, Clone)]
474pub struct Span(bridge::client::Span);
475
476#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
477impl !Send for Span {}
478#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
479impl !Sync for Span {}
480
481macro_rules! diagnostic_method {
482 ($name:ident, $level:expr) => {
483 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
486 pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
487 Diagnostic::spanned(self, $level, message)
488 }
489 };
490}
491
492impl Span {
493 #[unstable(feature = "proc_macro_def_site", issue = "54724")]
495 pub fn def_site() -> Span {
496 Span(bridge::client::Span::def_site())
497 }
498
499 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
504 pub fn call_site() -> Span {
505 Span(bridge::client::Span::call_site())
506 }
507
508 #[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
513 pub fn mixed_site() -> Span {
514 Span(bridge::client::Span::mixed_site())
515 }
516
517 #[unstable(feature = "proc_macro_span", issue = "54725")]
520 pub fn parent(&self) -> Option<Span> {
521 BridgeMethods::span_parent(self.0).map(Span)
522 }
523
524 #[unstable(feature = "proc_macro_span", issue = "54725")]
528 pub fn source(&self) -> Span {
529 Span(BridgeMethods::span_source(self.0))
530 }
531
532 #[unstable(feature = "proc_macro_span", issue = "54725")]
534 pub fn byte_range(&self) -> Range<usize> {
535 BridgeMethods::span_byte_range(self.0)
536 }
537
538 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
540 pub fn start(&self) -> Span {
541 Span(BridgeMethods::span_start(self.0))
542 }
543
544 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
546 pub fn end(&self) -> Span {
547 Span(BridgeMethods::span_end(self.0))
548 }
549
550 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
554 pub fn line(&self) -> usize {
555 BridgeMethods::span_line(self.0)
556 }
557
558 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
562 pub fn column(&self) -> usize {
563 BridgeMethods::span_column(self.0)
564 }
565
566 #[stable(feature = "proc_macro_span_file", since = "1.88.0")]
571 pub fn file(&self) -> String {
572 BridgeMethods::span_file(self.0)
573 }
574
575 #[stable(feature = "proc_macro_span_file", since = "1.88.0")]
581 pub fn local_file(&self) -> Option<PathBuf> {
582 BridgeMethods::span_local_file(self.0).map(PathBuf::from)
583 }
584
585 #[unstable(feature = "proc_macro_span", issue = "54725")]
589 pub fn join(&self, other: Span) -> Option<Span> {
590 BridgeMethods::span_join(self.0, other.0).map(Span)
591 }
592
593 #[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
596 pub fn resolved_at(&self, other: Span) -> Span {
597 Span(BridgeMethods::span_resolved_at(self.0, other.0))
598 }
599
600 #[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
603 pub fn located_at(&self, other: Span) -> Span {
604 other.resolved_at(*self)
605 }
606
607 #[unstable(feature = "proc_macro_span", issue = "54725")]
609 pub fn eq(&self, other: &Span) -> bool {
610 self.0 == other.0
611 }
612
613 #[stable(feature = "proc_macro_source_text", since = "1.66.0")]
621 pub fn source_text(&self) -> Option<String> {
622 BridgeMethods::span_source_text(self.0)
623 }
624
625 #[doc(hidden)]
627 #[unstable(feature = "proc_macro_internals", issue = "27812")]
628 pub fn save_span(&self) -> usize {
629 BridgeMethods::span_save_span(self.0)
630 }
631
632 #[doc(hidden)]
634 #[unstable(feature = "proc_macro_internals", issue = "27812")]
635 pub fn recover_proc_macro_span(id: usize) -> Span {
636 Span(BridgeMethods::span_recover_proc_macro_span(id))
637 }
638
639 diagnostic_method!(error, Level::Error);
640 diagnostic_method!(warning, Level::Warning);
641 diagnostic_method!(note, Level::Note);
642 diagnostic_method!(help, Level::Help);
643}
644
645#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
647impl fmt::Debug for Span {
648 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
649 self.0.fmt(f)
650 }
651}
652
653#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
655#[derive(Clone)]
656pub enum TokenTree {
657 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
659 Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
660 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
662 Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
663 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
665 Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
666 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
668 Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
669}
670
671#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
672impl !Send for TokenTree {}
673#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
674impl !Sync for TokenTree {}
675
676impl TokenTree {
677 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
680 pub fn span(&self) -> Span {
681 match *self {
682 TokenTree::Group(ref t) => t.span(),
683 TokenTree::Ident(ref t) => t.span(),
684 TokenTree::Punct(ref t) => t.span(),
685 TokenTree::Literal(ref t) => t.span(),
686 }
687 }
688
689 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
695 pub fn set_span(&mut self, span: Span) {
696 match *self {
697 TokenTree::Group(ref mut t) => t.set_span(span),
698 TokenTree::Ident(ref mut t) => t.set_span(span),
699 TokenTree::Punct(ref mut t) => t.set_span(span),
700 TokenTree::Literal(ref mut t) => t.set_span(span),
701 }
702 }
703}
704
705#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
707impl fmt::Debug for TokenTree {
708 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
709 match *self {
712 TokenTree::Group(ref tt) => tt.fmt(f),
713 TokenTree::Ident(ref tt) => tt.fmt(f),
714 TokenTree::Punct(ref tt) => tt.fmt(f),
715 TokenTree::Literal(ref tt) => tt.fmt(f),
716 }
717 }
718}
719
720#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
721impl From<Group> for TokenTree {
722 fn from(g: Group) -> TokenTree {
723 TokenTree::Group(g)
724 }
725}
726
727#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
728impl From<Ident> for TokenTree {
729 fn from(g: Ident) -> TokenTree {
730 TokenTree::Ident(g)
731 }
732}
733
734#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
735impl From<Punct> for TokenTree {
736 fn from(g: Punct) -> TokenTree {
737 TokenTree::Punct(g)
738 }
739}
740
741#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
742impl From<Literal> for TokenTree {
743 fn from(g: Literal) -> TokenTree {
744 TokenTree::Literal(g)
745 }
746}
747
748#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
760impl fmt::Display for TokenTree {
761 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
762 match self {
763 TokenTree::Group(t) => write!(f, "{t}"),
764 TokenTree::Ident(t) => write!(f, "{t}"),
765 TokenTree::Punct(t) => write!(f, "{t}"),
766 TokenTree::Literal(t) => write!(f, "{t}"),
767 }
768 }
769}
770
771#[derive(Clone)]
775#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
776pub struct Group(bridge::Group<bridge::client::TokenStream, bridge::client::Span>);
777
778#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
779impl !Send for Group {}
780#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
781impl !Sync for Group {}
782
783#[derive(Copy, Clone, Debug, PartialEq, Eq)]
785#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
786pub enum Delimiter {
787 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
789 Parenthesis,
790 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
792 Brace,
793 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
795 Bracket,
796 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
814 None,
815}
816
817impl Group {
818 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
824 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
825 Group(bridge::Group {
826 delimiter,
827 stream: stream.0,
828 span: bridge::DelimSpan::from_single(Span::call_site().0),
829 })
830 }
831
832 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
834 pub fn delimiter(&self) -> Delimiter {
835 self.0.delimiter
836 }
837
838 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
843 pub fn stream(&self) -> TokenStream {
844 TokenStream(self.0.stream.clone())
845 }
846
847 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
855 pub fn span(&self) -> Span {
856 Span(self.0.span.entire)
857 }
858
859 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
866 pub fn span_open(&self) -> Span {
867 Span(self.0.span.open)
868 }
869
870 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
877 pub fn span_close(&self) -> Span {
878 Span(self.0.span.close)
879 }
880
881 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
888 pub fn set_span(&mut self, span: Span) {
889 self.0.span = bridge::DelimSpan::from_single(span.0);
890 }
891}
892
893#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
897impl fmt::Display for Group {
898 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
899 write!(f, "{}", TokenStream::from(TokenTree::from(self.clone())))
900 }
901}
902
903#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
904impl fmt::Debug for Group {
905 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
906 f.debug_struct("Group")
907 .field("delimiter", &self.delimiter())
908 .field("stream", &self.stream())
909 .field("span", &self.span())
910 .finish()
911 }
912}
913
914#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
919#[derive(Clone)]
920pub struct Punct(bridge::Punct<bridge::client::Span>);
921
922#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
923impl !Send for Punct {}
924#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
925impl !Sync for Punct {}
926
927#[derive(Copy, Clone, Debug, PartialEq, Eq)]
930#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
931pub enum Spacing {
932 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
944 Joint,
945 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
952 Alone,
953}
954
955impl Punct {
956 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
963 pub fn new(ch: char, spacing: Spacing) -> Punct {
964 const LEGAL_CHARS: &[char] = &[
965 '=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
966 ':', '#', '$', '?', '\'',
967 ];
968 if !LEGAL_CHARS.contains(&ch) {
969 panic!("unsupported character `{:?}`", ch);
970 }
971 Punct(bridge::Punct {
972 ch: ch as u8,
973 joint: spacing == Spacing::Joint,
974 span: Span::call_site().0,
975 })
976 }
977
978 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
980 pub fn as_char(&self) -> char {
981 self.0.ch as char
982 }
983
984 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
988 pub fn spacing(&self) -> Spacing {
989 if self.0.joint { Spacing::Joint } else { Spacing::Alone }
990 }
991
992 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
994 pub fn span(&self) -> Span {
995 Span(self.0.span)
996 }
997
998 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1000 pub fn set_span(&mut self, span: Span) {
1001 self.0.span = span.0;
1002 }
1003}
1004
1005#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1008impl fmt::Display for Punct {
1009 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1010 write!(f, "{}", self.as_char())
1011 }
1012}
1013
1014#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1015impl fmt::Debug for Punct {
1016 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1017 f.debug_struct("Punct")
1018 .field("ch", &self.as_char())
1019 .field("spacing", &self.spacing())
1020 .field("span", &self.span())
1021 .finish()
1022 }
1023}
1024
1025#[stable(feature = "proc_macro_punct_eq", since = "1.50.0")]
1026impl PartialEq<char> for Punct {
1027 fn eq(&self, rhs: &char) -> bool {
1028 self.as_char() == *rhs
1029 }
1030}
1031
1032#[stable(feature = "proc_macro_punct_eq_flipped", since = "1.52.0")]
1033impl PartialEq<Punct> for char {
1034 fn eq(&self, rhs: &Punct) -> bool {
1035 *self == rhs.as_char()
1036 }
1037}
1038
1039#[derive(Clone)]
1041#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1042pub struct Ident(bridge::Ident<bridge::client::Span, bridge::client::Symbol>);
1043
1044impl Ident {
1045 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1069 pub fn new(string: &str, span: Span) -> Ident {
1070 Ident(bridge::Ident {
1071 sym: bridge::client::Symbol::new_ident(string, false),
1072 is_raw: false,
1073 span: span.0,
1074 })
1075 }
1076
1077 #[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
1082 pub fn new_raw(string: &str, span: Span) -> Ident {
1083 Ident(bridge::Ident {
1084 sym: bridge::client::Symbol::new_ident(string, true),
1085 is_raw: true,
1086 span: span.0,
1087 })
1088 }
1089
1090 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1093 pub fn span(&self) -> Span {
1094 Span(self.0.span)
1095 }
1096
1097 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1099 pub fn set_span(&mut self, span: Span) {
1100 self.0.span = span.0;
1101 }
1102}
1103
1104#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1107impl fmt::Display for Ident {
1108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1109 if self.0.is_raw {
1110 f.write_str("r#")?;
1111 }
1112 fmt::Display::fmt(&self.0.sym, f)
1113 }
1114}
1115
1116#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1117impl fmt::Debug for Ident {
1118 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1119 f.debug_struct("Ident")
1120 .field("ident", &self.to_string())
1121 .field("span", &self.span())
1122 .finish()
1123 }
1124}
1125
1126#[derive(Clone)]
1131#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1132pub struct Literal(bridge::Literal<bridge::client::Span, bridge::client::Symbol>);
1133
1134macro_rules! suffixed_int_literals {
1135 ($($name:ident => $kind:ident,)*) => ($(
1136 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1148 pub fn $name(n: $kind) -> Literal {
1149 Literal(bridge::Literal {
1150 kind: bridge::LitKind::Integer,
1151 symbol: bridge::client::Symbol::new(&n.to_string()),
1152 suffix: Some(bridge::client::Symbol::new(stringify!($kind))),
1153 span: Span::call_site().0,
1154 })
1155 }
1156 )*)
1157}
1158
1159macro_rules! unsuffixed_int_literals {
1160 ($($name:ident => $kind:ident,)*) => ($(
1161 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1175 pub fn $name(n: $kind) -> Literal {
1176 Literal(bridge::Literal {
1177 kind: bridge::LitKind::Integer,
1178 symbol: bridge::client::Symbol::new(&n.to_string()),
1179 suffix: None,
1180 span: Span::call_site().0,
1181 })
1182 }
1183 )*)
1184}
1185
1186impl Literal {
1187 fn new(kind: bridge::LitKind, value: &str, suffix: Option<&str>) -> Self {
1188 Literal(bridge::Literal {
1189 kind,
1190 symbol: bridge::client::Symbol::new(value),
1191 suffix: suffix.map(bridge::client::Symbol::new),
1192 span: Span::call_site().0,
1193 })
1194 }
1195
1196 suffixed_int_literals! {
1197 u8_suffixed => u8,
1198 u16_suffixed => u16,
1199 u32_suffixed => u32,
1200 u64_suffixed => u64,
1201 u128_suffixed => u128,
1202 usize_suffixed => usize,
1203 i8_suffixed => i8,
1204 i16_suffixed => i16,
1205 i32_suffixed => i32,
1206 i64_suffixed => i64,
1207 i128_suffixed => i128,
1208 isize_suffixed => isize,
1209 }
1210
1211 unsuffixed_int_literals! {
1212 u8_unsuffixed => u8,
1213 u16_unsuffixed => u16,
1214 u32_unsuffixed => u32,
1215 u64_unsuffixed => u64,
1216 u128_unsuffixed => u128,
1217 usize_unsuffixed => usize,
1218 i8_unsuffixed => i8,
1219 i16_unsuffixed => i16,
1220 i32_unsuffixed => i32,
1221 i64_unsuffixed => i64,
1222 i128_unsuffixed => i128,
1223 isize_unsuffixed => isize,
1224 }
1225
1226 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1239 pub fn f32_unsuffixed(n: f32) -> Literal {
1240 if !n.is_finite() {
1241 panic!("Invalid float literal {n}");
1242 }
1243 let mut repr = n.to_string();
1244 if !repr.contains('.') {
1245 repr.push_str(".0");
1246 }
1247 Literal::new(bridge::LitKind::Float, &repr, None)
1248 }
1249
1250 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1264 pub fn f32_suffixed(n: f32) -> Literal {
1265 if !n.is_finite() {
1266 panic!("Invalid float literal {n}");
1267 }
1268 Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f32"))
1269 }
1270
1271 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1284 pub fn f64_unsuffixed(n: f64) -> Literal {
1285 if !n.is_finite() {
1286 panic!("Invalid float literal {n}");
1287 }
1288 let mut repr = n.to_string();
1289 if !repr.contains('.') {
1290 repr.push_str(".0");
1291 }
1292 Literal::new(bridge::LitKind::Float, &repr, None)
1293 }
1294
1295 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1309 pub fn f64_suffixed(n: f64) -> Literal {
1310 if !n.is_finite() {
1311 panic!("Invalid float literal {n}");
1312 }
1313 Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f64"))
1314 }
1315
1316 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1318 pub fn string(string: &str) -> Literal {
1319 let escape = EscapeOptions {
1320 escape_single_quote: false,
1321 escape_double_quote: true,
1322 escape_nonascii: false,
1323 };
1324 let repr = escape_bytes(string.as_bytes(), escape);
1325 Literal::new(bridge::LitKind::Str, &repr, None)
1326 }
1327
1328 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1330 pub fn character(ch: char) -> Literal {
1331 let escape = EscapeOptions {
1332 escape_single_quote: true,
1333 escape_double_quote: false,
1334 escape_nonascii: false,
1335 };
1336 let repr = escape_bytes(ch.encode_utf8(&mut [0u8; 4]).as_bytes(), escape);
1337 Literal::new(bridge::LitKind::Char, &repr, None)
1338 }
1339
1340 #[stable(feature = "proc_macro_byte_character", since = "1.79.0")]
1342 pub fn byte_character(byte: u8) -> Literal {
1343 let escape = EscapeOptions {
1344 escape_single_quote: true,
1345 escape_double_quote: false,
1346 escape_nonascii: true,
1347 };
1348 let repr = escape_bytes(&[byte], escape);
1349 Literal::new(bridge::LitKind::Byte, &repr, None)
1350 }
1351
1352 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1354 pub fn byte_string(bytes: &[u8]) -> Literal {
1355 let escape = EscapeOptions {
1356 escape_single_quote: false,
1357 escape_double_quote: true,
1358 escape_nonascii: true,
1359 };
1360 let repr = escape_bytes(bytes, escape);
1361 Literal::new(bridge::LitKind::ByteStr, &repr, None)
1362 }
1363
1364 #[stable(feature = "proc_macro_c_str_literals", since = "1.79.0")]
1366 pub fn c_string(string: &CStr) -> Literal {
1367 let escape = EscapeOptions {
1368 escape_single_quote: false,
1369 escape_double_quote: true,
1370 escape_nonascii: false,
1371 };
1372 let repr = escape_bytes(string.to_bytes(), escape);
1373 Literal::new(bridge::LitKind::CStr, &repr, None)
1374 }
1375
1376 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1378 pub fn span(&self) -> Span {
1379 Span(self.0.span)
1380 }
1381
1382 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1384 pub fn set_span(&mut self, span: Span) {
1385 self.0.span = span.0;
1386 }
1387
1388 #[unstable(feature = "proc_macro_span", issue = "54725")]
1400 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1401 BridgeMethods::span_subspan(
1402 self.0.span,
1403 range.start_bound().cloned(),
1404 range.end_bound().cloned(),
1405 )
1406 .map(Span)
1407 }
1408
1409 fn with_symbol_and_suffix<R>(&self, f: impl FnOnce(&str, &str) -> R) -> R {
1410 self.0.symbol.with(|symbol| match self.0.suffix {
1411 Some(suffix) => suffix.with(|suffix| f(symbol, suffix)),
1412 None => f(symbol, ""),
1413 })
1414 }
1415
1416 fn with_stringify_parts<R>(&self, f: impl FnOnce(&[&str]) -> R) -> R {
1421 fn get_hashes_str(num: u8) -> &'static str {
1425 const HASHES: &str = "\
1426 ################################################################\
1427 ################################################################\
1428 ################################################################\
1429 ################################################################\
1430 ";
1431 const _: () = assert!(HASHES.len() == 256);
1432 &HASHES[..num as usize]
1433 }
1434
1435 self.with_symbol_and_suffix(|symbol, suffix| match self.0.kind {
1436 bridge::LitKind::Byte => f(&["b'", symbol, "'", suffix]),
1437 bridge::LitKind::Char => f(&["'", symbol, "'", suffix]),
1438 bridge::LitKind::Str => f(&["\"", symbol, "\"", suffix]),
1439 bridge::LitKind::StrRaw(n) => {
1440 let hashes = get_hashes_str(n);
1441 f(&["r", hashes, "\"", symbol, "\"", hashes, suffix])
1442 }
1443 bridge::LitKind::ByteStr => f(&["b\"", symbol, "\"", suffix]),
1444 bridge::LitKind::ByteStrRaw(n) => {
1445 let hashes = get_hashes_str(n);
1446 f(&["br", hashes, "\"", symbol, "\"", hashes, suffix])
1447 }
1448 bridge::LitKind::CStr => f(&["c\"", symbol, "\"", suffix]),
1449 bridge::LitKind::CStrRaw(n) => {
1450 let hashes = get_hashes_str(n);
1451 f(&["cr", hashes, "\"", symbol, "\"", hashes, suffix])
1452 }
1453
1454 bridge::LitKind::Integer | bridge::LitKind::Float | bridge::LitKind::ErrWithGuar => {
1455 f(&[symbol, suffix])
1456 }
1457 })
1458 }
1459
1460 #[unstable(feature = "proc_macro_value", issue = "136652")]
1462 pub fn byte_character_value(&self) -> Result<u8, ConversionErrorKind> {
1463 self.0.symbol.with(|symbol| match self.0.kind {
1464 bridge::LitKind::Char => {
1465 unescape_byte(symbol).map_err(ConversionErrorKind::FailedToUnescape)
1466 }
1467 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1468 })
1469 }
1470
1471 #[unstable(feature = "proc_macro_value", issue = "136652")]
1473 pub fn character_value(&self) -> Result<char, ConversionErrorKind> {
1474 self.0.symbol.with(|symbol| match self.0.kind {
1475 bridge::LitKind::Char => {
1476 unescape_char(symbol).map_err(ConversionErrorKind::FailedToUnescape)
1477 }
1478 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1479 })
1480 }
1481
1482 #[unstable(feature = "proc_macro_value", issue = "136652")]
1484 pub fn str_value(&self) -> Result<String, ConversionErrorKind> {
1485 self.0.symbol.with(|symbol| match self.0.kind {
1486 bridge::LitKind::Str => {
1487 if symbol.contains('\\') {
1488 let mut buf = String::with_capacity(symbol.len());
1489 let mut error = None;
1490 unescape_str(
1494 symbol,
1495 #[inline(always)]
1496 |_, c| match c {
1497 Ok(c) => buf.push(c),
1498 Err(err) => {
1499 if err.is_fatal() {
1500 error = Some(ConversionErrorKind::FailedToUnescape(err));
1501 }
1502 }
1503 },
1504 );
1505 if let Some(error) = error { Err(error) } else { Ok(buf) }
1506 } else {
1507 Ok(symbol.to_string())
1508 }
1509 }
1510 bridge::LitKind::StrRaw(_) => Ok(symbol.to_string()),
1511 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1512 })
1513 }
1514
1515 #[unstable(feature = "proc_macro_value", issue = "136652")]
1518 pub fn cstr_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1519 self.0.symbol.with(|symbol| match self.0.kind {
1520 bridge::LitKind::CStr => {
1521 let mut error = None;
1522 let mut buf = Vec::with_capacity(symbol.len());
1523
1524 unescape_c_str(symbol, |_span, res| match res {
1525 Ok(MixedUnit::Char(c)) => {
1526 buf.extend_from_slice(c.get().encode_utf8(&mut [0; 4]).as_bytes())
1527 }
1528 Ok(MixedUnit::HighByte(b)) => buf.push(b.get()),
1529 Err(err) => {
1530 if err.is_fatal() {
1531 error = Some(ConversionErrorKind::FailedToUnescape(err));
1532 }
1533 }
1534 });
1535 if let Some(error) = error {
1536 Err(error)
1537 } else {
1538 buf.push(0);
1539 Ok(buf)
1540 }
1541 }
1542 bridge::LitKind::CStrRaw(_) => {
1543 let mut buf = symbol.to_owned().into_bytes();
1547 buf.push(0);
1548 Ok(buf)
1549 }
1550 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1551 })
1552 }
1553
1554 #[unstable(feature = "proc_macro_value", issue = "136652")]
1557 pub fn byte_str_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1558 self.0.symbol.with(|symbol| match self.0.kind {
1559 bridge::LitKind::ByteStr => {
1560 let mut buf = Vec::with_capacity(symbol.len());
1561 let mut error = None;
1562
1563 unescape_byte_str(symbol, |_, res| match res {
1564 Ok(b) => buf.push(b),
1565 Err(err) => {
1566 if err.is_fatal() {
1567 error = Some(ConversionErrorKind::FailedToUnescape(err));
1568 }
1569 }
1570 });
1571 if let Some(error) = error { Err(error) } else { Ok(buf) }
1572 }
1573 bridge::LitKind::ByteStrRaw(_) => {
1574 Ok(symbol.to_owned().into_bytes())
1577 }
1578 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1579 })
1580 }
1581}
1582
1583#[stable(feature = "proc_macro_literal_parse", since = "1.54.0")]
1594impl FromStr for Literal {
1595 type Err = LexError;
1596
1597 fn from_str(src: &str) -> Result<Self, LexError> {
1598 match BridgeMethods::literal_from_str(src) {
1599 Ok(literal) => Ok(Literal(literal)),
1600 Err(msg) => Err(LexError(msg)),
1601 }
1602 }
1603}
1604
1605#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1608impl fmt::Display for Literal {
1609 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1610 self.with_stringify_parts(|parts| {
1611 for part in parts {
1612 fmt::Display::fmt(part, f)?;
1613 }
1614 Ok(())
1615 })
1616 }
1617}
1618
1619#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1620impl fmt::Debug for Literal {
1621 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1622 f.debug_struct("Literal")
1623 .field("kind", &format_args!("{:?}", self.0.kind))
1625 .field("symbol", &self.0.symbol)
1626 .field("suffix", &format_args!("{:?}", self.0.suffix))
1628 .field("span", &self.0.span)
1629 .finish()
1630 }
1631}
1632
1633#[unstable(
1634 feature = "proc_macro_tracked_path",
1635 issue = "99515",
1636 implied_by = "proc_macro_tracked_env"
1637)]
1638pub mod tracked {
1640 use std::env::{self, VarError};
1641 use std::ffi::OsStr;
1642 use std::path::Path;
1643
1644 use crate::BridgeMethods;
1645
1646 #[unstable(feature = "proc_macro_tracked_env", issue = "99515")]
1652 pub fn env_var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1653 let key: &str = key.as_ref();
1654 let value = BridgeMethods::injected_env_var(key).map_or_else(|| env::var(key), Ok);
1655 BridgeMethods::track_env_var(key, value.as_deref().ok());
1656 value
1657 }
1658
1659 #[unstable(feature = "proc_macro_tracked_path", issue = "99515")]
1663 pub fn path<P: AsRef<Path>>(path: P) {
1664 let path: &str = path.as_ref().to_str().unwrap();
1665 BridgeMethods::track_path(path);
1666 }
1667}