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