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")]
114#[non_exhaustive]
115#[derive(Debug)]
116pub struct LexError;
117
118#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
119impl fmt::Display for LexError {
120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121 f.write_str("cannot parse string into token stream")
122 }
123}
124
125#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
126impl error::Error for LexError {}
127
128#[stable(feature = "proc_macro_lib", since = "1.15.0")]
129impl !Send for LexError {}
130#[stable(feature = "proc_macro_lib", since = "1.15.0")]
131impl !Sync for LexError {}
132
133#[unstable(feature = "proc_macro_expand", issue = "90765")]
135#[non_exhaustive]
136#[derive(Debug)]
137pub struct ExpandError;
138
139#[unstable(feature = "proc_macro_expand", issue = "90765")]
140impl fmt::Display for ExpandError {
141 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142 f.write_str("macro expansion failed")
143 }
144}
145
146#[unstable(feature = "proc_macro_expand", issue = "90765")]
147impl error::Error for ExpandError {}
148
149#[unstable(feature = "proc_macro_expand", issue = "90765")]
150impl !Send for ExpandError {}
151
152#[unstable(feature = "proc_macro_expand", issue = "90765")]
153impl !Sync for ExpandError {}
154
155impl TokenStream {
156 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
158 pub fn new() -> TokenStream {
159 TokenStream(None)
160 }
161
162 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
164 pub fn is_empty(&self) -> bool {
165 self.0.as_ref().map(|h| BridgeMethods::ts_is_empty(h)).unwrap_or(true)
166 }
167
168 #[unstable(feature = "proc_macro_expand", issue = "90765")]
179 pub fn expand_expr(&self) -> Result<TokenStream, ExpandError> {
180 let stream = self.0.as_ref().ok_or(ExpandError)?;
181 match BridgeMethods::ts_expand_expr(stream) {
182 Ok(stream) => Ok(TokenStream(Some(stream))),
183 Err(_) => Err(ExpandError),
184 }
185 }
186}
187
188#[stable(feature = "proc_macro_lib", since = "1.15.0")]
196impl FromStr for TokenStream {
197 type Err = LexError;
198
199 fn from_str(src: &str) -> Result<TokenStream, LexError> {
200 Ok(TokenStream(Some(BridgeMethods::ts_from_str(src))))
201 }
202}
203
204#[stable(feature = "proc_macro_lib", since = "1.15.0")]
216impl fmt::Display for TokenStream {
217 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
218 match &self.0 {
219 Some(ts) => write!(f, "{}", BridgeMethods::ts_to_string(ts)),
220 None => Ok(()),
221 }
222 }
223}
224
225#[stable(feature = "proc_macro_lib", since = "1.15.0")]
227impl fmt::Debug for TokenStream {
228 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229 f.write_str("TokenStream ")?;
230 f.debug_list().entries(self.clone()).finish()
231 }
232}
233
234#[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
235impl Default for TokenStream {
236 fn default() -> Self {
237 TokenStream::new()
238 }
239}
240
241#[unstable(feature = "proc_macro_quote", issue = "54722")]
242pub use quote::{HasIterator, RepInterp, ThereIsNoIteratorInRepetition, ext, quote, quote_span};
243
244fn tree_to_bridge_tree(
245 tree: TokenTree,
246) -> bridge::TokenTree<bridge::client::TokenStream, bridge::client::Span, bridge::client::Symbol> {
247 match tree {
248 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
249 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
250 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
251 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
252 }
253}
254
255#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
257impl From<TokenTree> for TokenStream {
258 fn from(tree: TokenTree) -> TokenStream {
259 TokenStream(Some(BridgeMethods::ts_from_token_tree(tree_to_bridge_tree(tree))))
260 }
261}
262
263struct ConcatTreesHelper {
266 trees: Vec<
267 bridge::TokenTree<
268 bridge::client::TokenStream,
269 bridge::client::Span,
270 bridge::client::Symbol,
271 >,
272 >,
273}
274
275impl ConcatTreesHelper {
276 fn new(capacity: usize) -> Self {
277 ConcatTreesHelper { trees: Vec::with_capacity(capacity) }
278 }
279
280 fn push(&mut self, tree: TokenTree) {
281 self.trees.push(tree_to_bridge_tree(tree));
282 }
283
284 fn build(self) -> TokenStream {
285 if self.trees.is_empty() {
286 TokenStream(None)
287 } else {
288 TokenStream(Some(BridgeMethods::ts_concat_trees(None, self.trees)))
289 }
290 }
291
292 fn append_to(self, stream: &mut TokenStream) {
293 if self.trees.is_empty() {
294 return;
295 }
296 stream.0 = Some(BridgeMethods::ts_concat_trees(stream.0.take(), self.trees))
297 }
298}
299
300struct ConcatStreamsHelper {
303 streams: Vec<bridge::client::TokenStream>,
304}
305
306impl ConcatStreamsHelper {
307 fn new(capacity: usize) -> Self {
308 ConcatStreamsHelper { streams: Vec::with_capacity(capacity) }
309 }
310
311 fn push(&mut self, stream: TokenStream) {
312 if let Some(stream) = stream.0 {
313 self.streams.push(stream);
314 }
315 }
316
317 fn build(mut self) -> TokenStream {
318 if self.streams.len() <= 1 {
319 TokenStream(self.streams.pop())
320 } else {
321 TokenStream(Some(BridgeMethods::ts_concat_streams(None, self.streams)))
322 }
323 }
324
325 fn append_to(mut self, stream: &mut TokenStream) {
326 if self.streams.is_empty() {
327 return;
328 }
329 let base = stream.0.take();
330 if base.is_none() && self.streams.len() == 1 {
331 stream.0 = self.streams.pop();
332 } else {
333 stream.0 = Some(BridgeMethods::ts_concat_streams(base, self.streams));
334 }
335 }
336}
337
338#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
340impl FromIterator<TokenTree> for TokenStream {
341 fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
342 let iter = trees.into_iter();
343 let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
344 iter.for_each(|tree| builder.push(tree));
345 builder.build()
346 }
347}
348
349#[stable(feature = "proc_macro_lib", since = "1.15.0")]
352impl FromIterator<TokenStream> for TokenStream {
353 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
354 let iter = streams.into_iter();
355 let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
356 iter.for_each(|stream| builder.push(stream));
357 builder.build()
358 }
359}
360
361#[stable(feature = "token_stream_extend", since = "1.30.0")]
362impl Extend<TokenTree> for TokenStream {
363 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
364 let iter = trees.into_iter();
365 let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
366 iter.for_each(|tree| builder.push(tree));
367 builder.append_to(self);
368 }
369}
370
371#[stable(feature = "token_stream_extend", since = "1.30.0")]
372impl Extend<TokenStream> for TokenStream {
373 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
374 let iter = streams.into_iter();
375 let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
376 iter.for_each(|stream| builder.push(stream));
377 builder.append_to(self);
378 }
379}
380
381macro_rules! extend_items {
382 ($($item:ident)*) => {
383 $(
384 #[stable(feature = "token_stream_extend_ts_items", since = "1.92.0")]
385 impl Extend<$item> for TokenStream {
386 fn extend<T: IntoIterator<Item = $item>>(&mut self, iter: T) {
387 self.extend(iter.into_iter().map(TokenTree::$item));
388 }
389 }
390 )*
391 };
392}
393
394extend_items!(Group Literal Punct Ident);
395
396#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
398pub mod token_stream {
399 use crate::{BridgeMethods, Group, Ident, Literal, Punct, TokenStream, TokenTree, bridge};
400
401 #[derive(Clone)]
405 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
406 pub struct IntoIter(
407 std::vec::IntoIter<
408 bridge::TokenTree<
409 bridge::client::TokenStream,
410 bridge::client::Span,
411 bridge::client::Symbol,
412 >,
413 >,
414 );
415
416 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
417 impl Iterator for IntoIter {
418 type Item = TokenTree;
419
420 fn next(&mut self) -> Option<TokenTree> {
421 self.0.next().map(|tree| match tree {
422 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
423 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
424 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
425 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
426 })
427 }
428
429 fn size_hint(&self) -> (usize, Option<usize>) {
430 self.0.size_hint()
431 }
432
433 fn count(self) -> usize {
434 self.0.count()
435 }
436 }
437
438 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
439 impl IntoIterator for TokenStream {
440 type Item = TokenTree;
441 type IntoIter = IntoIter;
442
443 fn into_iter(self) -> IntoIter {
444 IntoIter(
445 self.0.map(|v| BridgeMethods::ts_into_trees(v)).unwrap_or_default().into_iter(),
446 )
447 }
448 }
449}
450
451#[unstable(feature = "proc_macro_quote", issue = "54722")]
458#[allow_internal_unstable(proc_macro_def_site, proc_macro_internals, proc_macro_totokens)]
459#[rustc_builtin_macro]
460pub macro quote($($t:tt)*) {
461 }
463
464#[unstable(feature = "proc_macro_internals", issue = "27812")]
465#[doc(hidden)]
466mod quote;
467
468#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
470#[derive(Copy, Clone)]
471pub struct Span(bridge::client::Span);
472
473#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
474impl !Send for Span {}
475#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
476impl !Sync for Span {}
477
478macro_rules! diagnostic_method {
479 ($name:ident, $level:expr) => {
480 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
483 pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
484 Diagnostic::spanned(self, $level, message)
485 }
486 };
487}
488
489impl Span {
490 #[unstable(feature = "proc_macro_def_site", issue = "54724")]
492 pub fn def_site() -> Span {
493 Span(bridge::client::Span::def_site())
494 }
495
496 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
501 pub fn call_site() -> Span {
502 Span(bridge::client::Span::call_site())
503 }
504
505 #[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
510 pub fn mixed_site() -> Span {
511 Span(bridge::client::Span::mixed_site())
512 }
513
514 #[unstable(feature = "proc_macro_span", issue = "54725")]
517 pub fn parent(&self) -> Option<Span> {
518 BridgeMethods::span_parent(self.0).map(Span)
519 }
520
521 #[unstable(feature = "proc_macro_span", issue = "54725")]
525 pub fn source(&self) -> Span {
526 Span(BridgeMethods::span_source(self.0))
527 }
528
529 #[unstable(feature = "proc_macro_span", issue = "54725")]
531 pub fn byte_range(&self) -> Range<usize> {
532 BridgeMethods::span_byte_range(self.0)
533 }
534
535 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
537 pub fn start(&self) -> Span {
538 Span(BridgeMethods::span_start(self.0))
539 }
540
541 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
543 pub fn end(&self) -> Span {
544 Span(BridgeMethods::span_end(self.0))
545 }
546
547 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
551 pub fn line(&self) -> usize {
552 BridgeMethods::span_line(self.0)
553 }
554
555 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
559 pub fn column(&self) -> usize {
560 BridgeMethods::span_column(self.0)
561 }
562
563 #[stable(feature = "proc_macro_span_file", since = "1.88.0")]
568 pub fn file(&self) -> String {
569 BridgeMethods::span_file(self.0)
570 }
571
572 #[stable(feature = "proc_macro_span_file", since = "1.88.0")]
578 pub fn local_file(&self) -> Option<PathBuf> {
579 BridgeMethods::span_local_file(self.0).map(PathBuf::from)
580 }
581
582 #[unstable(feature = "proc_macro_span", issue = "54725")]
586 pub fn join(&self, other: Span) -> Option<Span> {
587 BridgeMethods::span_join(self.0, other.0).map(Span)
588 }
589
590 #[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
593 pub fn resolved_at(&self, other: Span) -> Span {
594 Span(BridgeMethods::span_resolved_at(self.0, other.0))
595 }
596
597 #[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
600 pub fn located_at(&self, other: Span) -> Span {
601 other.resolved_at(*self)
602 }
603
604 #[unstable(feature = "proc_macro_span", issue = "54725")]
606 pub fn eq(&self, other: &Span) -> bool {
607 self.0 == other.0
608 }
609
610 #[stable(feature = "proc_macro_source_text", since = "1.66.0")]
618 pub fn source_text(&self) -> Option<String> {
619 BridgeMethods::span_source_text(self.0)
620 }
621
622 #[doc(hidden)]
624 #[unstable(feature = "proc_macro_internals", issue = "27812")]
625 pub fn save_span(&self) -> usize {
626 BridgeMethods::span_save_span(self.0)
627 }
628
629 #[doc(hidden)]
631 #[unstable(feature = "proc_macro_internals", issue = "27812")]
632 pub fn recover_proc_macro_span(id: usize) -> Span {
633 Span(BridgeMethods::span_recover_proc_macro_span(id))
634 }
635
636 diagnostic_method!(error, Level::Error);
637 diagnostic_method!(warning, Level::Warning);
638 diagnostic_method!(note, Level::Note);
639 diagnostic_method!(help, Level::Help);
640}
641
642#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
644impl fmt::Debug for Span {
645 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
646 self.0.fmt(f)
647 }
648}
649
650#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
652#[derive(Clone)]
653pub enum TokenTree {
654 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
656 Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
657 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
659 Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
660 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
662 Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
663 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
665 Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
666}
667
668#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
669impl !Send for TokenTree {}
670#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
671impl !Sync for TokenTree {}
672
673impl TokenTree {
674 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
677 pub fn span(&self) -> Span {
678 match *self {
679 TokenTree::Group(ref t) => t.span(),
680 TokenTree::Ident(ref t) => t.span(),
681 TokenTree::Punct(ref t) => t.span(),
682 TokenTree::Literal(ref t) => t.span(),
683 }
684 }
685
686 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
692 pub fn set_span(&mut self, span: Span) {
693 match *self {
694 TokenTree::Group(ref mut t) => t.set_span(span),
695 TokenTree::Ident(ref mut t) => t.set_span(span),
696 TokenTree::Punct(ref mut t) => t.set_span(span),
697 TokenTree::Literal(ref mut t) => t.set_span(span),
698 }
699 }
700}
701
702#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
704impl fmt::Debug for TokenTree {
705 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
706 match *self {
709 TokenTree::Group(ref tt) => tt.fmt(f),
710 TokenTree::Ident(ref tt) => tt.fmt(f),
711 TokenTree::Punct(ref tt) => tt.fmt(f),
712 TokenTree::Literal(ref tt) => tt.fmt(f),
713 }
714 }
715}
716
717#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
718impl From<Group> for TokenTree {
719 fn from(g: Group) -> TokenTree {
720 TokenTree::Group(g)
721 }
722}
723
724#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
725impl From<Ident> for TokenTree {
726 fn from(g: Ident) -> TokenTree {
727 TokenTree::Ident(g)
728 }
729}
730
731#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
732impl From<Punct> for TokenTree {
733 fn from(g: Punct) -> TokenTree {
734 TokenTree::Punct(g)
735 }
736}
737
738#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
739impl From<Literal> for TokenTree {
740 fn from(g: Literal) -> TokenTree {
741 TokenTree::Literal(g)
742 }
743}
744
745#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
757impl fmt::Display for TokenTree {
758 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
759 match self {
760 TokenTree::Group(t) => write!(f, "{t}"),
761 TokenTree::Ident(t) => write!(f, "{t}"),
762 TokenTree::Punct(t) => write!(f, "{t}"),
763 TokenTree::Literal(t) => write!(f, "{t}"),
764 }
765 }
766}
767
768#[derive(Clone)]
772#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
773pub struct Group(bridge::Group<bridge::client::TokenStream, bridge::client::Span>);
774
775#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
776impl !Send for Group {}
777#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
778impl !Sync for Group {}
779
780#[derive(Copy, Clone, Debug, PartialEq, Eq)]
782#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
783pub enum Delimiter {
784 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
786 Parenthesis,
787 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
789 Brace,
790 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
792 Bracket,
793 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
811 None,
812}
813
814impl Group {
815 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
821 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
822 Group(bridge::Group {
823 delimiter,
824 stream: stream.0,
825 span: bridge::DelimSpan::from_single(Span::call_site().0),
826 })
827 }
828
829 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
831 pub fn delimiter(&self) -> Delimiter {
832 self.0.delimiter
833 }
834
835 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
840 pub fn stream(&self) -> TokenStream {
841 TokenStream(self.0.stream.clone())
842 }
843
844 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
852 pub fn span(&self) -> Span {
853 Span(self.0.span.entire)
854 }
855
856 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
863 pub fn span_open(&self) -> Span {
864 Span(self.0.span.open)
865 }
866
867 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
874 pub fn span_close(&self) -> Span {
875 Span(self.0.span.close)
876 }
877
878 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
885 pub fn set_span(&mut self, span: Span) {
886 self.0.span = bridge::DelimSpan::from_single(span.0);
887 }
888}
889
890#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
894impl fmt::Display for Group {
895 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
896 write!(f, "{}", TokenStream::from(TokenTree::from(self.clone())))
897 }
898}
899
900#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
901impl fmt::Debug for Group {
902 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
903 f.debug_struct("Group")
904 .field("delimiter", &self.delimiter())
905 .field("stream", &self.stream())
906 .field("span", &self.span())
907 .finish()
908 }
909}
910
911#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
916#[derive(Clone)]
917pub struct Punct(bridge::Punct<bridge::client::Span>);
918
919#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
920impl !Send for Punct {}
921#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
922impl !Sync for Punct {}
923
924#[derive(Copy, Clone, Debug, PartialEq, Eq)]
927#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
928pub enum Spacing {
929 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
941 Joint,
942 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
949 Alone,
950}
951
952impl Punct {
953 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
960 pub fn new(ch: char, spacing: Spacing) -> Punct {
961 const LEGAL_CHARS: &[char] = &[
962 '=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
963 ':', '#', '$', '?', '\'',
964 ];
965 if !LEGAL_CHARS.contains(&ch) {
966 panic!("unsupported character `{:?}`", ch);
967 }
968 Punct(bridge::Punct {
969 ch: ch as u8,
970 joint: spacing == Spacing::Joint,
971 span: Span::call_site().0,
972 })
973 }
974
975 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
977 pub fn as_char(&self) -> char {
978 self.0.ch as char
979 }
980
981 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
985 pub fn spacing(&self) -> Spacing {
986 if self.0.joint { Spacing::Joint } else { Spacing::Alone }
987 }
988
989 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
991 pub fn span(&self) -> Span {
992 Span(self.0.span)
993 }
994
995 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
997 pub fn set_span(&mut self, span: Span) {
998 self.0.span = span.0;
999 }
1000}
1001
1002#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1005impl fmt::Display for Punct {
1006 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1007 write!(f, "{}", self.as_char())
1008 }
1009}
1010
1011#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1012impl fmt::Debug for Punct {
1013 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1014 f.debug_struct("Punct")
1015 .field("ch", &self.as_char())
1016 .field("spacing", &self.spacing())
1017 .field("span", &self.span())
1018 .finish()
1019 }
1020}
1021
1022#[stable(feature = "proc_macro_punct_eq", since = "1.50.0")]
1023impl PartialEq<char> for Punct {
1024 fn eq(&self, rhs: &char) -> bool {
1025 self.as_char() == *rhs
1026 }
1027}
1028
1029#[stable(feature = "proc_macro_punct_eq_flipped", since = "1.52.0")]
1030impl PartialEq<Punct> for char {
1031 fn eq(&self, rhs: &Punct) -> bool {
1032 *self == rhs.as_char()
1033 }
1034}
1035
1036#[derive(Clone)]
1038#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1039pub struct Ident(bridge::Ident<bridge::client::Span, bridge::client::Symbol>);
1040
1041impl Ident {
1042 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1066 pub fn new(string: &str, span: Span) -> Ident {
1067 Ident(bridge::Ident {
1068 sym: bridge::client::Symbol::new_ident(string, false),
1069 is_raw: false,
1070 span: span.0,
1071 })
1072 }
1073
1074 #[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
1079 pub fn new_raw(string: &str, span: Span) -> Ident {
1080 Ident(bridge::Ident {
1081 sym: bridge::client::Symbol::new_ident(string, true),
1082 is_raw: true,
1083 span: span.0,
1084 })
1085 }
1086
1087 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1090 pub fn span(&self) -> Span {
1091 Span(self.0.span)
1092 }
1093
1094 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1096 pub fn set_span(&mut self, span: Span) {
1097 self.0.span = span.0;
1098 }
1099}
1100
1101#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1104impl fmt::Display for Ident {
1105 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1106 if self.0.is_raw {
1107 f.write_str("r#")?;
1108 }
1109 fmt::Display::fmt(&self.0.sym, f)
1110 }
1111}
1112
1113#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1114impl fmt::Debug for Ident {
1115 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1116 f.debug_struct("Ident")
1117 .field("ident", &self.to_string())
1118 .field("span", &self.span())
1119 .finish()
1120 }
1121}
1122
1123#[derive(Clone)]
1128#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1129pub struct Literal(bridge::Literal<bridge::client::Span, bridge::client::Symbol>);
1130
1131macro_rules! suffixed_int_literals {
1132 ($($name:ident => $kind:ident,)*) => ($(
1133 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1145 pub fn $name(n: $kind) -> Literal {
1146 Literal(bridge::Literal {
1147 kind: bridge::LitKind::Integer,
1148 symbol: bridge::client::Symbol::new(&n.to_string()),
1149 suffix: Some(bridge::client::Symbol::new(stringify!($kind))),
1150 span: Span::call_site().0,
1151 })
1152 }
1153 )*)
1154}
1155
1156macro_rules! unsuffixed_int_literals {
1157 ($($name:ident => $kind:ident,)*) => ($(
1158 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1172 pub fn $name(n: $kind) -> Literal {
1173 Literal(bridge::Literal {
1174 kind: bridge::LitKind::Integer,
1175 symbol: bridge::client::Symbol::new(&n.to_string()),
1176 suffix: None,
1177 span: Span::call_site().0,
1178 })
1179 }
1180 )*)
1181}
1182
1183impl Literal {
1184 fn new(kind: bridge::LitKind, value: &str, suffix: Option<&str>) -> Self {
1185 Literal(bridge::Literal {
1186 kind,
1187 symbol: bridge::client::Symbol::new(value),
1188 suffix: suffix.map(bridge::client::Symbol::new),
1189 span: Span::call_site().0,
1190 })
1191 }
1192
1193 suffixed_int_literals! {
1194 u8_suffixed => u8,
1195 u16_suffixed => u16,
1196 u32_suffixed => u32,
1197 u64_suffixed => u64,
1198 u128_suffixed => u128,
1199 usize_suffixed => usize,
1200 i8_suffixed => i8,
1201 i16_suffixed => i16,
1202 i32_suffixed => i32,
1203 i64_suffixed => i64,
1204 i128_suffixed => i128,
1205 isize_suffixed => isize,
1206 }
1207
1208 unsuffixed_int_literals! {
1209 u8_unsuffixed => u8,
1210 u16_unsuffixed => u16,
1211 u32_unsuffixed => u32,
1212 u64_unsuffixed => u64,
1213 u128_unsuffixed => u128,
1214 usize_unsuffixed => usize,
1215 i8_unsuffixed => i8,
1216 i16_unsuffixed => i16,
1217 i32_unsuffixed => i32,
1218 i64_unsuffixed => i64,
1219 i128_unsuffixed => i128,
1220 isize_unsuffixed => isize,
1221 }
1222
1223 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1236 pub fn f32_unsuffixed(n: f32) -> Literal {
1237 if !n.is_finite() {
1238 panic!("Invalid float literal {n}");
1239 }
1240 let mut repr = n.to_string();
1241 if !repr.contains('.') {
1242 repr.push_str(".0");
1243 }
1244 Literal::new(bridge::LitKind::Float, &repr, None)
1245 }
1246
1247 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1261 pub fn f32_suffixed(n: f32) -> Literal {
1262 if !n.is_finite() {
1263 panic!("Invalid float literal {n}");
1264 }
1265 Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f32"))
1266 }
1267
1268 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1281 pub fn f64_unsuffixed(n: f64) -> Literal {
1282 if !n.is_finite() {
1283 panic!("Invalid float literal {n}");
1284 }
1285 let mut repr = n.to_string();
1286 if !repr.contains('.') {
1287 repr.push_str(".0");
1288 }
1289 Literal::new(bridge::LitKind::Float, &repr, None)
1290 }
1291
1292 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1306 pub fn f64_suffixed(n: f64) -> Literal {
1307 if !n.is_finite() {
1308 panic!("Invalid float literal {n}");
1309 }
1310 Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f64"))
1311 }
1312
1313 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1315 pub fn string(string: &str) -> Literal {
1316 let escape = EscapeOptions {
1317 escape_single_quote: false,
1318 escape_double_quote: true,
1319 escape_nonascii: false,
1320 };
1321 let repr = escape_bytes(string.as_bytes(), escape);
1322 Literal::new(bridge::LitKind::Str, &repr, None)
1323 }
1324
1325 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1327 pub fn character(ch: char) -> Literal {
1328 let escape = EscapeOptions {
1329 escape_single_quote: true,
1330 escape_double_quote: false,
1331 escape_nonascii: false,
1332 };
1333 let repr = escape_bytes(ch.encode_utf8(&mut [0u8; 4]).as_bytes(), escape);
1334 Literal::new(bridge::LitKind::Char, &repr, None)
1335 }
1336
1337 #[stable(feature = "proc_macro_byte_character", since = "1.79.0")]
1339 pub fn byte_character(byte: u8) -> Literal {
1340 let escape = EscapeOptions {
1341 escape_single_quote: true,
1342 escape_double_quote: false,
1343 escape_nonascii: true,
1344 };
1345 let repr = escape_bytes(&[byte], escape);
1346 Literal::new(bridge::LitKind::Byte, &repr, None)
1347 }
1348
1349 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1351 pub fn byte_string(bytes: &[u8]) -> Literal {
1352 let escape = EscapeOptions {
1353 escape_single_quote: false,
1354 escape_double_quote: true,
1355 escape_nonascii: true,
1356 };
1357 let repr = escape_bytes(bytes, escape);
1358 Literal::new(bridge::LitKind::ByteStr, &repr, None)
1359 }
1360
1361 #[stable(feature = "proc_macro_c_str_literals", since = "1.79.0")]
1363 pub fn c_string(string: &CStr) -> Literal {
1364 let escape = EscapeOptions {
1365 escape_single_quote: false,
1366 escape_double_quote: true,
1367 escape_nonascii: false,
1368 };
1369 let repr = escape_bytes(string.to_bytes(), escape);
1370 Literal::new(bridge::LitKind::CStr, &repr, None)
1371 }
1372
1373 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1375 pub fn span(&self) -> Span {
1376 Span(self.0.span)
1377 }
1378
1379 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1381 pub fn set_span(&mut self, span: Span) {
1382 self.0.span = span.0;
1383 }
1384
1385 #[unstable(feature = "proc_macro_span", issue = "54725")]
1397 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1398 BridgeMethods::span_subspan(
1399 self.0.span,
1400 range.start_bound().cloned(),
1401 range.end_bound().cloned(),
1402 )
1403 .map(Span)
1404 }
1405
1406 fn with_symbol_and_suffix<R>(&self, f: impl FnOnce(&str, &str) -> R) -> R {
1407 self.0.symbol.with(|symbol| match self.0.suffix {
1408 Some(suffix) => suffix.with(|suffix| f(symbol, suffix)),
1409 None => f(symbol, ""),
1410 })
1411 }
1412
1413 fn with_stringify_parts<R>(&self, f: impl FnOnce(&[&str]) -> R) -> R {
1418 fn get_hashes_str(num: u8) -> &'static str {
1422 const HASHES: &str = "\
1423 ################################################################\
1424 ################################################################\
1425 ################################################################\
1426 ################################################################\
1427 ";
1428 const _: () = assert!(HASHES.len() == 256);
1429 &HASHES[..num as usize]
1430 }
1431
1432 self.with_symbol_and_suffix(|symbol, suffix| match self.0.kind {
1433 bridge::LitKind::Byte => f(&["b'", symbol, "'", suffix]),
1434 bridge::LitKind::Char => f(&["'", symbol, "'", suffix]),
1435 bridge::LitKind::Str => f(&["\"", symbol, "\"", suffix]),
1436 bridge::LitKind::StrRaw(n) => {
1437 let hashes = get_hashes_str(n);
1438 f(&["r", hashes, "\"", symbol, "\"", hashes, suffix])
1439 }
1440 bridge::LitKind::ByteStr => f(&["b\"", symbol, "\"", suffix]),
1441 bridge::LitKind::ByteStrRaw(n) => {
1442 let hashes = get_hashes_str(n);
1443 f(&["br", hashes, "\"", symbol, "\"", hashes, suffix])
1444 }
1445 bridge::LitKind::CStr => f(&["c\"", symbol, "\"", suffix]),
1446 bridge::LitKind::CStrRaw(n) => {
1447 let hashes = get_hashes_str(n);
1448 f(&["cr", hashes, "\"", symbol, "\"", hashes, suffix])
1449 }
1450
1451 bridge::LitKind::Integer | bridge::LitKind::Float | bridge::LitKind::ErrWithGuar => {
1452 f(&[symbol, suffix])
1453 }
1454 })
1455 }
1456
1457 #[unstable(feature = "proc_macro_value", issue = "136652")]
1459 pub fn byte_character_value(&self) -> Result<u8, ConversionErrorKind> {
1460 self.0.symbol.with(|symbol| match self.0.kind {
1461 bridge::LitKind::Char => {
1462 unescape_byte(symbol).map_err(ConversionErrorKind::FailedToUnescape)
1463 }
1464 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1465 })
1466 }
1467
1468 #[unstable(feature = "proc_macro_value", issue = "136652")]
1470 pub fn character_value(&self) -> Result<char, ConversionErrorKind> {
1471 self.0.symbol.with(|symbol| match self.0.kind {
1472 bridge::LitKind::Char => {
1473 unescape_char(symbol).map_err(ConversionErrorKind::FailedToUnescape)
1474 }
1475 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1476 })
1477 }
1478
1479 #[unstable(feature = "proc_macro_value", issue = "136652")]
1481 pub fn str_value(&self) -> Result<String, ConversionErrorKind> {
1482 self.0.symbol.with(|symbol| match self.0.kind {
1483 bridge::LitKind::Str => {
1484 if symbol.contains('\\') {
1485 let mut buf = String::with_capacity(symbol.len());
1486 let mut error = None;
1487 unescape_str(
1491 symbol,
1492 #[inline(always)]
1493 |_, c| match c {
1494 Ok(c) => buf.push(c),
1495 Err(err) => {
1496 if err.is_fatal() {
1497 error = Some(ConversionErrorKind::FailedToUnescape(err));
1498 }
1499 }
1500 },
1501 );
1502 if let Some(error) = error { Err(error) } else { Ok(buf) }
1503 } else {
1504 Ok(symbol.to_string())
1505 }
1506 }
1507 bridge::LitKind::StrRaw(_) => Ok(symbol.to_string()),
1508 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1509 })
1510 }
1511
1512 #[unstable(feature = "proc_macro_value", issue = "136652")]
1515 pub fn cstr_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1516 self.0.symbol.with(|symbol| match self.0.kind {
1517 bridge::LitKind::CStr => {
1518 let mut error = None;
1519 let mut buf = Vec::with_capacity(symbol.len());
1520
1521 unescape_c_str(symbol, |_span, res| match res {
1522 Ok(MixedUnit::Char(c)) => {
1523 buf.extend_from_slice(c.get().encode_utf8(&mut [0; 4]).as_bytes())
1524 }
1525 Ok(MixedUnit::HighByte(b)) => buf.push(b.get()),
1526 Err(err) => {
1527 if err.is_fatal() {
1528 error = Some(ConversionErrorKind::FailedToUnescape(err));
1529 }
1530 }
1531 });
1532 if let Some(error) = error {
1533 Err(error)
1534 } else {
1535 buf.push(0);
1536 Ok(buf)
1537 }
1538 }
1539 bridge::LitKind::CStrRaw(_) => {
1540 let mut buf = symbol.to_owned().into_bytes();
1544 buf.push(0);
1545 Ok(buf)
1546 }
1547 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1548 })
1549 }
1550
1551 #[unstable(feature = "proc_macro_value", issue = "136652")]
1554 pub fn byte_str_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1555 self.0.symbol.with(|symbol| match self.0.kind {
1556 bridge::LitKind::ByteStr => {
1557 let mut buf = Vec::with_capacity(symbol.len());
1558 let mut error = None;
1559
1560 unescape_byte_str(symbol, |_, res| match res {
1561 Ok(b) => buf.push(b),
1562 Err(err) => {
1563 if err.is_fatal() {
1564 error = Some(ConversionErrorKind::FailedToUnescape(err));
1565 }
1566 }
1567 });
1568 if let Some(error) = error { Err(error) } else { Ok(buf) }
1569 }
1570 bridge::LitKind::ByteStrRaw(_) => {
1571 Ok(symbol.to_owned().into_bytes())
1574 }
1575 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1576 })
1577 }
1578}
1579
1580#[stable(feature = "proc_macro_literal_parse", since = "1.54.0")]
1591impl FromStr for Literal {
1592 type Err = LexError;
1593
1594 fn from_str(src: &str) -> Result<Self, LexError> {
1595 match BridgeMethods::literal_from_str(src) {
1596 Ok(literal) => Ok(Literal(literal)),
1597 Err(()) => Err(LexError),
1598 }
1599 }
1600}
1601
1602#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1605impl fmt::Display for Literal {
1606 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1607 self.with_stringify_parts(|parts| {
1608 for part in parts {
1609 fmt::Display::fmt(part, f)?;
1610 }
1611 Ok(())
1612 })
1613 }
1614}
1615
1616#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1617impl fmt::Debug for Literal {
1618 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1619 f.debug_struct("Literal")
1620 .field("kind", &format_args!("{:?}", self.0.kind))
1622 .field("symbol", &self.0.symbol)
1623 .field("suffix", &format_args!("{:?}", self.0.suffix))
1625 .field("span", &self.0.span)
1626 .finish()
1627 }
1628}
1629
1630#[unstable(
1631 feature = "proc_macro_tracked_path",
1632 issue = "99515",
1633 implied_by = "proc_macro_tracked_env"
1634)]
1635pub mod tracked {
1637 use std::env::{self, VarError};
1638 use std::ffi::OsStr;
1639 use std::path::Path;
1640
1641 use crate::BridgeMethods;
1642
1643 #[unstable(feature = "proc_macro_tracked_env", issue = "99515")]
1649 pub fn env_var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1650 let key: &str = key.as_ref();
1651 let value = BridgeMethods::injected_env_var(key).map_or_else(|| env::var(key), Ok);
1652 BridgeMethods::track_env_var(key, value.as_deref().ok());
1653 value
1654 }
1655
1656 #[unstable(feature = "proc_macro_tracked_path", issue = "99515")]
1660 pub fn path<P: AsRef<Path>>(path: P) {
1661 let path: &str = path.as_ref().to_str().unwrap();
1662 BridgeMethods::track_path(path);
1663 }
1664}