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::bridge::client::Methods as BridgeMethods;
62use crate::escape::{EscapeOptions, escape_bytes};
63
64#[unstable(feature = "proc_macro_value", issue = "136652")]
66#[derive(Debug, PartialEq, Eq)]
67pub enum ConversionErrorKind {
68 FailedToUnescape(EscapeError),
70 InvalidLiteralKind,
72}
73
74#[stable(feature = "proc_macro_is_available", since = "1.57.0")]
88pub fn is_available() -> bool {
89 bridge::client::is_available()
90}
91
92#[cfg_attr(feature = "rustc-dep-of-std", rustc_diagnostic_item = "TokenStream")]
100#[stable(feature = "proc_macro_lib", since = "1.15.0")]
101#[derive(Clone)]
102pub struct TokenStream(Option<bridge::client::TokenStream>);
103
104#[stable(feature = "proc_macro_lib", since = "1.15.0")]
105impl !Send for TokenStream {}
106#[stable(feature = "proc_macro_lib", since = "1.15.0")]
107impl !Sync for TokenStream {}
108
109#[stable(feature = "proc_macro_lib", since = "1.15.0")]
111#[non_exhaustive]
112#[derive(Debug)]
113pub struct LexError;
114
115#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
116impl fmt::Display for LexError {
117 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118 f.write_str("cannot parse string into token stream")
119 }
120}
121
122#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
123impl error::Error for LexError {}
124
125#[stable(feature = "proc_macro_lib", since = "1.15.0")]
126impl !Send for LexError {}
127#[stable(feature = "proc_macro_lib", since = "1.15.0")]
128impl !Sync for LexError {}
129
130#[unstable(feature = "proc_macro_expand", issue = "90765")]
132#[non_exhaustive]
133#[derive(Debug)]
134pub struct ExpandError;
135
136#[unstable(feature = "proc_macro_expand", issue = "90765")]
137impl fmt::Display for ExpandError {
138 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139 f.write_str("macro expansion failed")
140 }
141}
142
143#[unstable(feature = "proc_macro_expand", issue = "90765")]
144impl error::Error for ExpandError {}
145
146#[unstable(feature = "proc_macro_expand", issue = "90765")]
147impl !Send for ExpandError {}
148
149#[unstable(feature = "proc_macro_expand", issue = "90765")]
150impl !Sync for ExpandError {}
151
152impl TokenStream {
153 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
155 pub fn new() -> TokenStream {
156 TokenStream(None)
157 }
158
159 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
161 pub fn is_empty(&self) -> bool {
162 self.0.as_ref().map(|h| BridgeMethods::ts_is_empty(h)).unwrap_or(true)
163 }
164
165 #[unstable(feature = "proc_macro_expand", issue = "90765")]
176 pub fn expand_expr(&self) -> Result<TokenStream, ExpandError> {
177 let stream = self.0.as_ref().ok_or(ExpandError)?;
178 match BridgeMethods::ts_expand_expr(stream) {
179 Ok(stream) => Ok(TokenStream(Some(stream))),
180 Err(_) => Err(ExpandError),
181 }
182 }
183}
184
185#[stable(feature = "proc_macro_lib", since = "1.15.0")]
193impl FromStr for TokenStream {
194 type Err = LexError;
195
196 fn from_str(src: &str) -> Result<TokenStream, LexError> {
197 Ok(TokenStream(Some(BridgeMethods::ts_from_str(src))))
198 }
199}
200
201#[stable(feature = "proc_macro_lib", since = "1.15.0")]
213impl fmt::Display for TokenStream {
214 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
215 match &self.0 {
216 Some(ts) => write!(f, "{}", BridgeMethods::ts_to_string(ts)),
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(BridgeMethods::ts_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(BridgeMethods::ts_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(BridgeMethods::ts_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(BridgeMethods::ts_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(BridgeMethods::ts_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_ts_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::{BridgeMethods, 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(
442 self.0.map(|v| BridgeMethods::ts_into_trees(v)).unwrap_or_default().into_iter(),
443 )
444 }
445 }
446}
447
448#[unstable(feature = "proc_macro_quote", issue = "54722")]
455#[allow_internal_unstable(proc_macro_def_site, proc_macro_internals, proc_macro_totokens)]
456#[rustc_builtin_macro]
457pub macro quote($($t:tt)*) {
458 }
460
461#[unstable(feature = "proc_macro_internals", issue = "27812")]
462#[doc(hidden)]
463mod quote;
464
465#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
467#[derive(Copy, Clone)]
468pub struct Span(bridge::client::Span);
469
470#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
471impl !Send for Span {}
472#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
473impl !Sync for Span {}
474
475macro_rules! diagnostic_method {
476 ($name:ident, $level:expr) => {
477 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
480 pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
481 Diagnostic::spanned(self, $level, message)
482 }
483 };
484}
485
486impl Span {
487 #[unstable(feature = "proc_macro_def_site", issue = "54724")]
489 pub fn def_site() -> Span {
490 Span(bridge::client::Span::def_site())
491 }
492
493 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
498 pub fn call_site() -> Span {
499 Span(bridge::client::Span::call_site())
500 }
501
502 #[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
507 pub fn mixed_site() -> Span {
508 Span(bridge::client::Span::mixed_site())
509 }
510
511 #[unstable(feature = "proc_macro_span", issue = "54725")]
514 pub fn parent(&self) -> Option<Span> {
515 BridgeMethods::span_parent(self.0).map(Span)
516 }
517
518 #[unstable(feature = "proc_macro_span", issue = "54725")]
522 pub fn source(&self) -> Span {
523 Span(BridgeMethods::span_source(self.0))
524 }
525
526 #[unstable(feature = "proc_macro_span", issue = "54725")]
528 pub fn byte_range(&self) -> Range<usize> {
529 BridgeMethods::span_byte_range(self.0)
530 }
531
532 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
534 pub fn start(&self) -> Span {
535 Span(BridgeMethods::span_start(self.0))
536 }
537
538 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
540 pub fn end(&self) -> Span {
541 Span(BridgeMethods::span_end(self.0))
542 }
543
544 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
548 pub fn line(&self) -> usize {
549 BridgeMethods::span_line(self.0)
550 }
551
552 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
556 pub fn column(&self) -> usize {
557 BridgeMethods::span_column(self.0)
558 }
559
560 #[stable(feature = "proc_macro_span_file", since = "1.88.0")]
565 pub fn file(&self) -> String {
566 BridgeMethods::span_file(self.0)
567 }
568
569 #[stable(feature = "proc_macro_span_file", since = "1.88.0")]
575 pub fn local_file(&self) -> Option<PathBuf> {
576 BridgeMethods::span_local_file(self.0).map(PathBuf::from)
577 }
578
579 #[unstable(feature = "proc_macro_span", issue = "54725")]
583 pub fn join(&self, other: Span) -> Option<Span> {
584 BridgeMethods::span_join(self.0, other.0).map(Span)
585 }
586
587 #[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
590 pub fn resolved_at(&self, other: Span) -> Span {
591 Span(BridgeMethods::span_resolved_at(self.0, other.0))
592 }
593
594 #[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
597 pub fn located_at(&self, other: Span) -> Span {
598 other.resolved_at(*self)
599 }
600
601 #[unstable(feature = "proc_macro_span", issue = "54725")]
603 pub fn eq(&self, other: &Span) -> bool {
604 self.0 == other.0
605 }
606
607 #[stable(feature = "proc_macro_source_text", since = "1.66.0")]
615 pub fn source_text(&self) -> Option<String> {
616 BridgeMethods::span_source_text(self.0)
617 }
618
619 #[doc(hidden)]
621 #[unstable(feature = "proc_macro_internals", issue = "27812")]
622 pub fn save_span(&self) -> usize {
623 BridgeMethods::span_save_span(self.0)
624 }
625
626 #[doc(hidden)]
628 #[unstable(feature = "proc_macro_internals", issue = "27812")]
629 pub fn recover_proc_macro_span(id: usize) -> Span {
630 Span(BridgeMethods::span_recover_proc_macro_span(id))
631 }
632
633 diagnostic_method!(error, Level::Error);
634 diagnostic_method!(warning, Level::Warning);
635 diagnostic_method!(note, Level::Note);
636 diagnostic_method!(help, Level::Help);
637}
638
639#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
641impl fmt::Debug for Span {
642 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
643 self.0.fmt(f)
644 }
645}
646
647#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
649#[derive(Clone)]
650pub enum TokenTree {
651 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
653 Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
654 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
656 Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
657 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
659 Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
660 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
662 Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
663}
664
665#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
666impl !Send for TokenTree {}
667#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
668impl !Sync for TokenTree {}
669
670impl TokenTree {
671 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
674 pub fn span(&self) -> Span {
675 match *self {
676 TokenTree::Group(ref t) => t.span(),
677 TokenTree::Ident(ref t) => t.span(),
678 TokenTree::Punct(ref t) => t.span(),
679 TokenTree::Literal(ref t) => t.span(),
680 }
681 }
682
683 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
689 pub fn set_span(&mut self, span: Span) {
690 match *self {
691 TokenTree::Group(ref mut t) => t.set_span(span),
692 TokenTree::Ident(ref mut t) => t.set_span(span),
693 TokenTree::Punct(ref mut t) => t.set_span(span),
694 TokenTree::Literal(ref mut t) => t.set_span(span),
695 }
696 }
697}
698
699#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
701impl fmt::Debug for TokenTree {
702 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
703 match *self {
706 TokenTree::Group(ref tt) => tt.fmt(f),
707 TokenTree::Ident(ref tt) => tt.fmt(f),
708 TokenTree::Punct(ref tt) => tt.fmt(f),
709 TokenTree::Literal(ref tt) => tt.fmt(f),
710 }
711 }
712}
713
714#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
715impl From<Group> for TokenTree {
716 fn from(g: Group) -> TokenTree {
717 TokenTree::Group(g)
718 }
719}
720
721#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
722impl From<Ident> for TokenTree {
723 fn from(g: Ident) -> TokenTree {
724 TokenTree::Ident(g)
725 }
726}
727
728#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
729impl From<Punct> for TokenTree {
730 fn from(g: Punct) -> TokenTree {
731 TokenTree::Punct(g)
732 }
733}
734
735#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
736impl From<Literal> for TokenTree {
737 fn from(g: Literal) -> TokenTree {
738 TokenTree::Literal(g)
739 }
740}
741
742#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
754impl fmt::Display for TokenTree {
755 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
756 match self {
757 TokenTree::Group(t) => write!(f, "{t}"),
758 TokenTree::Ident(t) => write!(f, "{t}"),
759 TokenTree::Punct(t) => write!(f, "{t}"),
760 TokenTree::Literal(t) => write!(f, "{t}"),
761 }
762 }
763}
764
765#[derive(Clone)]
769#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
770pub struct Group(bridge::Group<bridge::client::TokenStream, bridge::client::Span>);
771
772#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
773impl !Send for Group {}
774#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
775impl !Sync for Group {}
776
777#[derive(Copy, Clone, Debug, PartialEq, Eq)]
779#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
780pub enum Delimiter {
781 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
783 Parenthesis,
784 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
786 Brace,
787 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
789 Bracket,
790 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
808 None,
809}
810
811impl Group {
812 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
818 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
819 Group(bridge::Group {
820 delimiter,
821 stream: stream.0,
822 span: bridge::DelimSpan::from_single(Span::call_site().0),
823 })
824 }
825
826 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
828 pub fn delimiter(&self) -> Delimiter {
829 self.0.delimiter
830 }
831
832 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
837 pub fn stream(&self) -> TokenStream {
838 TokenStream(self.0.stream.clone())
839 }
840
841 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
849 pub fn span(&self) -> Span {
850 Span(self.0.span.entire)
851 }
852
853 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
860 pub fn span_open(&self) -> Span {
861 Span(self.0.span.open)
862 }
863
864 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
871 pub fn span_close(&self) -> Span {
872 Span(self.0.span.close)
873 }
874
875 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
882 pub fn set_span(&mut self, span: Span) {
883 self.0.span = bridge::DelimSpan::from_single(span.0);
884 }
885}
886
887#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
891impl fmt::Display for Group {
892 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")]
1063 pub fn new(string: &str, span: Span) -> Ident {
1064 Ident(bridge::Ident {
1065 sym: bridge::client::Symbol::new_ident(string, false),
1066 is_raw: false,
1067 span: span.0,
1068 })
1069 }
1070
1071 #[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
1076 pub fn new_raw(string: &str, span: Span) -> Ident {
1077 Ident(bridge::Ident {
1078 sym: bridge::client::Symbol::new_ident(string, true),
1079 is_raw: true,
1080 span: span.0,
1081 })
1082 }
1083
1084 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1087 pub fn span(&self) -> Span {
1088 Span(self.0.span)
1089 }
1090
1091 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1093 pub fn set_span(&mut self, span: Span) {
1094 self.0.span = span.0;
1095 }
1096}
1097
1098#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1101impl fmt::Display for Ident {
1102 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1103 if self.0.is_raw {
1104 f.write_str("r#")?;
1105 }
1106 fmt::Display::fmt(&self.0.sym, f)
1107 }
1108}
1109
1110#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1111impl fmt::Debug for Ident {
1112 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1113 f.debug_struct("Ident")
1114 .field("ident", &self.to_string())
1115 .field("span", &self.span())
1116 .finish()
1117 }
1118}
1119
1120#[derive(Clone)]
1125#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1126pub struct Literal(bridge::Literal<bridge::client::Span, bridge::client::Symbol>);
1127
1128macro_rules! suffixed_int_literals {
1129 ($($name:ident => $kind:ident,)*) => ($(
1130 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1142 pub fn $name(n: $kind) -> Literal {
1143 Literal(bridge::Literal {
1144 kind: bridge::LitKind::Integer,
1145 symbol: bridge::client::Symbol::new(&n.to_string()),
1146 suffix: Some(bridge::client::Symbol::new(stringify!($kind))),
1147 span: Span::call_site().0,
1148 })
1149 }
1150 )*)
1151}
1152
1153macro_rules! unsuffixed_int_literals {
1154 ($($name:ident => $kind:ident,)*) => ($(
1155 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1169 pub fn $name(n: $kind) -> Literal {
1170 Literal(bridge::Literal {
1171 kind: bridge::LitKind::Integer,
1172 symbol: bridge::client::Symbol::new(&n.to_string()),
1173 suffix: None,
1174 span: Span::call_site().0,
1175 })
1176 }
1177 )*)
1178}
1179
1180impl Literal {
1181 fn new(kind: bridge::LitKind, value: &str, suffix: Option<&str>) -> Self {
1182 Literal(bridge::Literal {
1183 kind,
1184 symbol: bridge::client::Symbol::new(value),
1185 suffix: suffix.map(bridge::client::Symbol::new),
1186 span: Span::call_site().0,
1187 })
1188 }
1189
1190 suffixed_int_literals! {
1191 u8_suffixed => u8,
1192 u16_suffixed => u16,
1193 u32_suffixed => u32,
1194 u64_suffixed => u64,
1195 u128_suffixed => u128,
1196 usize_suffixed => usize,
1197 i8_suffixed => i8,
1198 i16_suffixed => i16,
1199 i32_suffixed => i32,
1200 i64_suffixed => i64,
1201 i128_suffixed => i128,
1202 isize_suffixed => isize,
1203 }
1204
1205 unsuffixed_int_literals! {
1206 u8_unsuffixed => u8,
1207 u16_unsuffixed => u16,
1208 u32_unsuffixed => u32,
1209 u64_unsuffixed => u64,
1210 u128_unsuffixed => u128,
1211 usize_unsuffixed => usize,
1212 i8_unsuffixed => i8,
1213 i16_unsuffixed => i16,
1214 i32_unsuffixed => i32,
1215 i64_unsuffixed => i64,
1216 i128_unsuffixed => i128,
1217 isize_unsuffixed => isize,
1218 }
1219
1220 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1233 pub fn f32_unsuffixed(n: f32) -> Literal {
1234 if !n.is_finite() {
1235 panic!("Invalid float literal {n}");
1236 }
1237 let mut repr = n.to_string();
1238 if !repr.contains('.') {
1239 repr.push_str(".0");
1240 }
1241 Literal::new(bridge::LitKind::Float, &repr, None)
1242 }
1243
1244 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1258 pub fn f32_suffixed(n: f32) -> Literal {
1259 if !n.is_finite() {
1260 panic!("Invalid float literal {n}");
1261 }
1262 Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f32"))
1263 }
1264
1265 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1278 pub fn f64_unsuffixed(n: f64) -> Literal {
1279 if !n.is_finite() {
1280 panic!("Invalid float literal {n}");
1281 }
1282 let mut repr = n.to_string();
1283 if !repr.contains('.') {
1284 repr.push_str(".0");
1285 }
1286 Literal::new(bridge::LitKind::Float, &repr, None)
1287 }
1288
1289 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1303 pub fn f64_suffixed(n: f64) -> Literal {
1304 if !n.is_finite() {
1305 panic!("Invalid float literal {n}");
1306 }
1307 Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f64"))
1308 }
1309
1310 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1312 pub fn string(string: &str) -> Literal {
1313 let escape = EscapeOptions {
1314 escape_single_quote: false,
1315 escape_double_quote: true,
1316 escape_nonascii: false,
1317 };
1318 let repr = escape_bytes(string.as_bytes(), escape);
1319 Literal::new(bridge::LitKind::Str, &repr, None)
1320 }
1321
1322 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1324 pub fn character(ch: char) -> Literal {
1325 let escape = EscapeOptions {
1326 escape_single_quote: true,
1327 escape_double_quote: false,
1328 escape_nonascii: false,
1329 };
1330 let repr = escape_bytes(ch.encode_utf8(&mut [0u8; 4]).as_bytes(), escape);
1331 Literal::new(bridge::LitKind::Char, &repr, None)
1332 }
1333
1334 #[stable(feature = "proc_macro_byte_character", since = "1.79.0")]
1336 pub fn byte_character(byte: u8) -> Literal {
1337 let escape = EscapeOptions {
1338 escape_single_quote: true,
1339 escape_double_quote: false,
1340 escape_nonascii: true,
1341 };
1342 let repr = escape_bytes(&[byte], escape);
1343 Literal::new(bridge::LitKind::Byte, &repr, None)
1344 }
1345
1346 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1348 pub fn byte_string(bytes: &[u8]) -> Literal {
1349 let escape = EscapeOptions {
1350 escape_single_quote: false,
1351 escape_double_quote: true,
1352 escape_nonascii: true,
1353 };
1354 let repr = escape_bytes(bytes, escape);
1355 Literal::new(bridge::LitKind::ByteStr, &repr, None)
1356 }
1357
1358 #[stable(feature = "proc_macro_c_str_literals", since = "1.79.0")]
1360 pub fn c_string(string: &CStr) -> Literal {
1361 let escape = EscapeOptions {
1362 escape_single_quote: false,
1363 escape_double_quote: true,
1364 escape_nonascii: false,
1365 };
1366 let repr = escape_bytes(string.to_bytes(), escape);
1367 Literal::new(bridge::LitKind::CStr, &repr, None)
1368 }
1369
1370 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1372 pub fn span(&self) -> Span {
1373 Span(self.0.span)
1374 }
1375
1376 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1378 pub fn set_span(&mut self, span: Span) {
1379 self.0.span = span.0;
1380 }
1381
1382 #[unstable(feature = "proc_macro_span", issue = "54725")]
1394 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1395 BridgeMethods::span_subspan(
1396 self.0.span,
1397 range.start_bound().cloned(),
1398 range.end_bound().cloned(),
1399 )
1400 .map(Span)
1401 }
1402
1403 fn with_symbol_and_suffix<R>(&self, f: impl FnOnce(&str, &str) -> R) -> R {
1404 self.0.symbol.with(|symbol| match self.0.suffix {
1405 Some(suffix) => suffix.with(|suffix| f(symbol, suffix)),
1406 None => f(symbol, ""),
1407 })
1408 }
1409
1410 fn with_stringify_parts<R>(&self, f: impl FnOnce(&[&str]) -> R) -> R {
1415 fn get_hashes_str(num: u8) -> &'static str {
1419 const HASHES: &str = "\
1420 ################################################################\
1421 ################################################################\
1422 ################################################################\
1423 ################################################################\
1424 ";
1425 const _: () = assert!(HASHES.len() == 256);
1426 &HASHES[..num as usize]
1427 }
1428
1429 self.with_symbol_and_suffix(|symbol, suffix| match self.0.kind {
1430 bridge::LitKind::Byte => f(&["b'", symbol, "'", suffix]),
1431 bridge::LitKind::Char => f(&["'", symbol, "'", suffix]),
1432 bridge::LitKind::Str => f(&["\"", symbol, "\"", suffix]),
1433 bridge::LitKind::StrRaw(n) => {
1434 let hashes = get_hashes_str(n);
1435 f(&["r", hashes, "\"", symbol, "\"", hashes, suffix])
1436 }
1437 bridge::LitKind::ByteStr => f(&["b\"", symbol, "\"", suffix]),
1438 bridge::LitKind::ByteStrRaw(n) => {
1439 let hashes = get_hashes_str(n);
1440 f(&["br", hashes, "\"", symbol, "\"", hashes, suffix])
1441 }
1442 bridge::LitKind::CStr => f(&["c\"", symbol, "\"", suffix]),
1443 bridge::LitKind::CStrRaw(n) => {
1444 let hashes = get_hashes_str(n);
1445 f(&["cr", hashes, "\"", symbol, "\"", hashes, suffix])
1446 }
1447
1448 bridge::LitKind::Integer | bridge::LitKind::Float | bridge::LitKind::ErrWithGuar => {
1449 f(&[symbol, suffix])
1450 }
1451 })
1452 }
1453
1454 #[unstable(feature = "proc_macro_value", issue = "136652")]
1456 pub fn str_value(&self) -> Result<String, ConversionErrorKind> {
1457 self.0.symbol.with(|symbol| match self.0.kind {
1458 bridge::LitKind::Str => {
1459 if symbol.contains('\\') {
1460 let mut buf = String::with_capacity(symbol.len());
1461 let mut error = None;
1462 unescape_str(
1466 symbol,
1467 #[inline(always)]
1468 |_, c| match c {
1469 Ok(c) => buf.push(c),
1470 Err(err) => {
1471 if err.is_fatal() {
1472 error = Some(ConversionErrorKind::FailedToUnescape(err));
1473 }
1474 }
1475 },
1476 );
1477 if let Some(error) = error { Err(error) } else { Ok(buf) }
1478 } else {
1479 Ok(symbol.to_string())
1480 }
1481 }
1482 bridge::LitKind::StrRaw(_) => Ok(symbol.to_string()),
1483 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1484 })
1485 }
1486
1487 #[unstable(feature = "proc_macro_value", issue = "136652")]
1490 pub fn cstr_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1491 self.0.symbol.with(|symbol| match self.0.kind {
1492 bridge::LitKind::CStr => {
1493 let mut error = None;
1494 let mut buf = Vec::with_capacity(symbol.len());
1495
1496 unescape_c_str(symbol, |_span, res| match res {
1497 Ok(MixedUnit::Char(c)) => {
1498 buf.extend_from_slice(c.get().encode_utf8(&mut [0; 4]).as_bytes())
1499 }
1500 Ok(MixedUnit::HighByte(b)) => buf.push(b.get()),
1501 Err(err) => {
1502 if err.is_fatal() {
1503 error = Some(ConversionErrorKind::FailedToUnescape(err));
1504 }
1505 }
1506 });
1507 if let Some(error) = error {
1508 Err(error)
1509 } else {
1510 buf.push(0);
1511 Ok(buf)
1512 }
1513 }
1514 bridge::LitKind::CStrRaw(_) => {
1515 let mut buf = symbol.to_owned().into_bytes();
1519 buf.push(0);
1520 Ok(buf)
1521 }
1522 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1523 })
1524 }
1525
1526 #[unstable(feature = "proc_macro_value", issue = "136652")]
1529 pub fn byte_str_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1530 self.0.symbol.with(|symbol| match self.0.kind {
1531 bridge::LitKind::ByteStr => {
1532 let mut buf = Vec::with_capacity(symbol.len());
1533 let mut error = None;
1534
1535 unescape_byte_str(symbol, |_, res| match res {
1536 Ok(b) => buf.push(b),
1537 Err(err) => {
1538 if err.is_fatal() {
1539 error = Some(ConversionErrorKind::FailedToUnescape(err));
1540 }
1541 }
1542 });
1543 if let Some(error) = error { Err(error) } else { Ok(buf) }
1544 }
1545 bridge::LitKind::ByteStrRaw(_) => {
1546 Ok(symbol.to_owned().into_bytes())
1549 }
1550 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1551 })
1552 }
1553}
1554
1555#[stable(feature = "proc_macro_literal_parse", since = "1.54.0")]
1566impl FromStr for Literal {
1567 type Err = LexError;
1568
1569 fn from_str(src: &str) -> Result<Self, LexError> {
1570 match BridgeMethods::literal_from_str(src) {
1571 Ok(literal) => Ok(Literal(literal)),
1572 Err(()) => Err(LexError),
1573 }
1574 }
1575}
1576
1577#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1580impl fmt::Display for Literal {
1581 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1582 self.with_stringify_parts(|parts| {
1583 for part in parts {
1584 fmt::Display::fmt(part, f)?;
1585 }
1586 Ok(())
1587 })
1588 }
1589}
1590
1591#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1592impl fmt::Debug for Literal {
1593 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1594 f.debug_struct("Literal")
1595 .field("kind", &format_args!("{:?}", self.0.kind))
1597 .field("symbol", &self.0.symbol)
1598 .field("suffix", &format_args!("{:?}", self.0.suffix))
1600 .field("span", &self.0.span)
1601 .finish()
1602 }
1603}
1604
1605#[unstable(
1606 feature = "proc_macro_tracked_path",
1607 issue = "99515",
1608 implied_by = "proc_macro_tracked_env"
1609)]
1610pub mod tracked {
1612 use std::env::{self, VarError};
1613 use std::ffi::OsStr;
1614 use std::path::Path;
1615
1616 use crate::BridgeMethods;
1617
1618 #[unstable(feature = "proc_macro_tracked_env", issue = "99515")]
1624 pub fn env_var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1625 let key: &str = key.as_ref();
1626 let value = BridgeMethods::injected_env_var(key).map_or_else(|| env::var(key), Ok);
1627 BridgeMethods::track_env_var(key, value.as_deref().ok());
1628 value
1629 }
1630
1631 #[unstable(feature = "proc_macro_tracked_path", issue = "99515")]
1635 pub fn path<P: AsRef<Path>>(path: P) {
1636 let path: &str = path.as_ref().to_str().unwrap();
1637 BridgeMethods::track_path(path);
1638 }
1639}