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(maybe_uninit_write_slice)]
26#![feature(negative_impls)]
27#![feature(panic_can_unwind)]
28#![feature(restricted_std)]
29#![feature(rustc_attrs)]
30#![feature(extend_one)]
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::{MixedUnit, unescape_byte_str, unescape_c_str, unescape_str};
59#[unstable(feature = "proc_macro_totokens", issue = "130977")]
60pub use to_tokens::ToTokens;
61
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| h.is_empty()).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 bridge::client::TokenStream::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(bridge::client::TokenStream::from_str(src))))
198 }
199}
200
201#[stable(feature = "proc_macro_lib", since = "1.15.0")]
213impl fmt::Display for TokenStream {
214 #[allow(clippy::recursive_format_impl)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216 match &self.0 {
217 Some(ts) => write!(f, "{}", ts.to_string()),
218 None => Ok(()),
219 }
220 }
221}
222
223#[stable(feature = "proc_macro_lib", since = "1.15.0")]
225impl fmt::Debug for TokenStream {
226 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
227 f.write_str("TokenStream ")?;
228 f.debug_list().entries(self.clone()).finish()
229 }
230}
231
232#[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
233impl Default for TokenStream {
234 fn default() -> Self {
235 TokenStream::new()
236 }
237}
238
239#[unstable(feature = "proc_macro_quote", issue = "54722")]
240pub use quote::{HasIterator, RepInterp, ThereIsNoIteratorInRepetition, ext, quote, quote_span};
241
242fn tree_to_bridge_tree(
243 tree: TokenTree,
244) -> bridge::TokenTree<bridge::client::TokenStream, bridge::client::Span, bridge::client::Symbol> {
245 match tree {
246 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
247 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
248 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
249 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
250 }
251}
252
253#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
255impl From<TokenTree> for TokenStream {
256 fn from(tree: TokenTree) -> TokenStream {
257 TokenStream(Some(bridge::client::TokenStream::from_token_tree(tree_to_bridge_tree(tree))))
258 }
259}
260
261struct ConcatTreesHelper {
264 trees: Vec<
265 bridge::TokenTree<
266 bridge::client::TokenStream,
267 bridge::client::Span,
268 bridge::client::Symbol,
269 >,
270 >,
271}
272
273impl ConcatTreesHelper {
274 fn new(capacity: usize) -> Self {
275 ConcatTreesHelper { trees: Vec::with_capacity(capacity) }
276 }
277
278 fn push(&mut self, tree: TokenTree) {
279 self.trees.push(tree_to_bridge_tree(tree));
280 }
281
282 fn build(self) -> TokenStream {
283 if self.trees.is_empty() {
284 TokenStream(None)
285 } else {
286 TokenStream(Some(bridge::client::TokenStream::concat_trees(None, self.trees)))
287 }
288 }
289
290 fn append_to(self, stream: &mut TokenStream) {
291 if self.trees.is_empty() {
292 return;
293 }
294 stream.0 = Some(bridge::client::TokenStream::concat_trees(stream.0.take(), self.trees))
295 }
296}
297
298struct ConcatStreamsHelper {
301 streams: Vec<bridge::client::TokenStream>,
302}
303
304impl ConcatStreamsHelper {
305 fn new(capacity: usize) -> Self {
306 ConcatStreamsHelper { streams: Vec::with_capacity(capacity) }
307 }
308
309 fn push(&mut self, stream: TokenStream) {
310 if let Some(stream) = stream.0 {
311 self.streams.push(stream);
312 }
313 }
314
315 fn build(mut self) -> TokenStream {
316 if self.streams.len() <= 1 {
317 TokenStream(self.streams.pop())
318 } else {
319 TokenStream(Some(bridge::client::TokenStream::concat_streams(None, self.streams)))
320 }
321 }
322
323 fn append_to(mut self, stream: &mut TokenStream) {
324 if self.streams.is_empty() {
325 return;
326 }
327 let base = stream.0.take();
328 if base.is_none() && self.streams.len() == 1 {
329 stream.0 = self.streams.pop();
330 } else {
331 stream.0 = Some(bridge::client::TokenStream::concat_streams(base, self.streams));
332 }
333 }
334}
335
336#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
338impl FromIterator<TokenTree> for TokenStream {
339 fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
340 let iter = trees.into_iter();
341 let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
342 iter.for_each(|tree| builder.push(tree));
343 builder.build()
344 }
345}
346
347#[stable(feature = "proc_macro_lib", since = "1.15.0")]
350impl FromIterator<TokenStream> for TokenStream {
351 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
352 let iter = streams.into_iter();
353 let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
354 iter.for_each(|stream| builder.push(stream));
355 builder.build()
356 }
357}
358
359#[stable(feature = "token_stream_extend", since = "1.30.0")]
360impl Extend<TokenTree> for TokenStream {
361 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
362 let iter = trees.into_iter();
363 let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
364 iter.for_each(|tree| builder.push(tree));
365 builder.append_to(self);
366 }
367}
368
369#[stable(feature = "token_stream_extend", since = "1.30.0")]
370impl Extend<TokenStream> for TokenStream {
371 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
372 let iter = streams.into_iter();
373 let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
374 iter.for_each(|stream| builder.push(stream));
375 builder.append_to(self);
376 }
377}
378
379macro_rules! extend_items {
380 ($($item:ident)*) => {
381 $(
382 #[stable(feature = "token_stream_extend_tt_items", since = "CURRENT_RUSTC_VERSION")]
383 impl Extend<$item> for TokenStream {
384 fn extend<T: IntoIterator<Item = $item>>(&mut self, iter: T) {
385 self.extend(iter.into_iter().map(TokenTree::$item));
386 }
387 }
388 )*
389 };
390}
391
392extend_items!(Group Literal Punct Ident);
393
394#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
396pub mod token_stream {
397 use crate::{Group, Ident, Literal, Punct, TokenStream, TokenTree, bridge};
398
399 #[derive(Clone)]
403 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
404 pub struct IntoIter(
405 std::vec::IntoIter<
406 bridge::TokenTree<
407 bridge::client::TokenStream,
408 bridge::client::Span,
409 bridge::client::Symbol,
410 >,
411 >,
412 );
413
414 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
415 impl Iterator for IntoIter {
416 type Item = TokenTree;
417
418 fn next(&mut self) -> Option<TokenTree> {
419 self.0.next().map(|tree| match tree {
420 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
421 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
422 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
423 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
424 })
425 }
426
427 fn size_hint(&self) -> (usize, Option<usize>) {
428 self.0.size_hint()
429 }
430
431 fn count(self) -> usize {
432 self.0.count()
433 }
434 }
435
436 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
437 impl IntoIterator for TokenStream {
438 type Item = TokenTree;
439 type IntoIter = IntoIter;
440
441 fn into_iter(self) -> IntoIter {
442 IntoIter(self.0.map(|v| v.into_trees()).unwrap_or_default().into_iter())
443 }
444 }
445}
446
447#[unstable(feature = "proc_macro_quote", issue = "54722")]
454#[allow_internal_unstable(proc_macro_def_site, proc_macro_internals, proc_macro_totokens)]
455#[rustc_builtin_macro]
456pub macro quote($($t:tt)*) {
457 }
459
460#[unstable(feature = "proc_macro_internals", issue = "27812")]
461#[doc(hidden)]
462mod quote;
463
464#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
466#[derive(Copy, Clone)]
467pub struct Span(bridge::client::Span);
468
469#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
470impl !Send for Span {}
471#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
472impl !Sync for Span {}
473
474macro_rules! diagnostic_method {
475 ($name:ident, $level:expr) => {
476 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
479 pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
480 Diagnostic::spanned(self, $level, message)
481 }
482 };
483}
484
485impl Span {
486 #[unstable(feature = "proc_macro_def_site", issue = "54724")]
488 pub fn def_site() -> Span {
489 Span(bridge::client::Span::def_site())
490 }
491
492 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
497 pub fn call_site() -> Span {
498 Span(bridge::client::Span::call_site())
499 }
500
501 #[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
506 pub fn mixed_site() -> Span {
507 Span(bridge::client::Span::mixed_site())
508 }
509
510 #[unstable(feature = "proc_macro_span", issue = "54725")]
513 pub fn parent(&self) -> Option<Span> {
514 self.0.parent().map(Span)
515 }
516
517 #[unstable(feature = "proc_macro_span", issue = "54725")]
521 pub fn source(&self) -> Span {
522 Span(self.0.source())
523 }
524
525 #[unstable(feature = "proc_macro_span", issue = "54725")]
527 pub fn byte_range(&self) -> Range<usize> {
528 self.0.byte_range()
529 }
530
531 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
533 pub fn start(&self) -> Span {
534 Span(self.0.start())
535 }
536
537 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
539 pub fn end(&self) -> Span {
540 Span(self.0.end())
541 }
542
543 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
547 pub fn line(&self) -> usize {
548 self.0.line()
549 }
550
551 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
555 pub fn column(&self) -> usize {
556 self.0.column()
557 }
558
559 #[stable(feature = "proc_macro_span_file", since = "1.88.0")]
564 pub fn file(&self) -> String {
565 self.0.file()
566 }
567
568 #[stable(feature = "proc_macro_span_file", since = "1.88.0")]
574 pub fn local_file(&self) -> Option<PathBuf> {
575 self.0.local_file().map(|s| PathBuf::from(s))
576 }
577
578 #[unstable(feature = "proc_macro_span", issue = "54725")]
582 pub fn join(&self, other: Span) -> Option<Span> {
583 self.0.join(other.0).map(Span)
584 }
585
586 #[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
589 pub fn resolved_at(&self, other: Span) -> Span {
590 Span(self.0.resolved_at(other.0))
591 }
592
593 #[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
596 pub fn located_at(&self, other: Span) -> Span {
597 other.resolved_at(*self)
598 }
599
600 #[unstable(feature = "proc_macro_span", issue = "54725")]
602 pub fn eq(&self, other: &Span) -> bool {
603 self.0 == other.0
604 }
605
606 #[stable(feature = "proc_macro_source_text", since = "1.66.0")]
614 pub fn source_text(&self) -> Option<String> {
615 self.0.source_text()
616 }
617
618 #[doc(hidden)]
620 #[unstable(feature = "proc_macro_internals", issue = "27812")]
621 pub fn save_span(&self) -> usize {
622 self.0.save_span()
623 }
624
625 #[doc(hidden)]
627 #[unstable(feature = "proc_macro_internals", issue = "27812")]
628 pub fn recover_proc_macro_span(id: usize) -> Span {
629 Span(bridge::client::Span::recover_proc_macro_span(id))
630 }
631
632 diagnostic_method!(error, Level::Error);
633 diagnostic_method!(warning, Level::Warning);
634 diagnostic_method!(note, Level::Note);
635 diagnostic_method!(help, Level::Help);
636}
637
638#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
640impl fmt::Debug for Span {
641 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
642 self.0.fmt(f)
643 }
644}
645
646#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
648#[derive(Clone)]
649pub enum TokenTree {
650 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
652 Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
653 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
655 Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
656 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
658 Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
659 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
661 Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
662}
663
664#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
665impl !Send for TokenTree {}
666#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
667impl !Sync for TokenTree {}
668
669impl TokenTree {
670 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
673 pub fn span(&self) -> Span {
674 match *self {
675 TokenTree::Group(ref t) => t.span(),
676 TokenTree::Ident(ref t) => t.span(),
677 TokenTree::Punct(ref t) => t.span(),
678 TokenTree::Literal(ref t) => t.span(),
679 }
680 }
681
682 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
688 pub fn set_span(&mut self, span: Span) {
689 match *self {
690 TokenTree::Group(ref mut t) => t.set_span(span),
691 TokenTree::Ident(ref mut t) => t.set_span(span),
692 TokenTree::Punct(ref mut t) => t.set_span(span),
693 TokenTree::Literal(ref mut t) => t.set_span(span),
694 }
695 }
696}
697
698#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
700impl fmt::Debug for TokenTree {
701 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
702 match *self {
705 TokenTree::Group(ref tt) => tt.fmt(f),
706 TokenTree::Ident(ref tt) => tt.fmt(f),
707 TokenTree::Punct(ref tt) => tt.fmt(f),
708 TokenTree::Literal(ref tt) => tt.fmt(f),
709 }
710 }
711}
712
713#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
714impl From<Group> for TokenTree {
715 fn from(g: Group) -> TokenTree {
716 TokenTree::Group(g)
717 }
718}
719
720#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
721impl From<Ident> for TokenTree {
722 fn from(g: Ident) -> TokenTree {
723 TokenTree::Ident(g)
724 }
725}
726
727#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
728impl From<Punct> for TokenTree {
729 fn from(g: Punct) -> TokenTree {
730 TokenTree::Punct(g)
731 }
732}
733
734#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
735impl From<Literal> for TokenTree {
736 fn from(g: Literal) -> TokenTree {
737 TokenTree::Literal(g)
738 }
739}
740
741#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
753impl fmt::Display for TokenTree {
754 #[allow(clippy::recursive_format_impl)] 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 #[allow(clippy::recursive_format_impl)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
894 write!(f, "{}", TokenStream::from(TokenTree::from(self.clone())))
895 }
896}
897
898#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
899impl fmt::Debug for Group {
900 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
901 f.debug_struct("Group")
902 .field("delimiter", &self.delimiter())
903 .field("stream", &self.stream())
904 .field("span", &self.span())
905 .finish()
906 }
907}
908
909#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
914#[derive(Clone)]
915pub struct Punct(bridge::Punct<bridge::client::Span>);
916
917#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
918impl !Send for Punct {}
919#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
920impl !Sync for Punct {}
921
922#[derive(Copy, Clone, Debug, PartialEq, Eq)]
925#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
926pub enum Spacing {
927 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
939 Joint,
940 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
947 Alone,
948}
949
950impl Punct {
951 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
958 pub fn new(ch: char, spacing: Spacing) -> Punct {
959 const LEGAL_CHARS: &[char] = &[
960 '=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
961 ':', '#', '$', '?', '\'',
962 ];
963 if !LEGAL_CHARS.contains(&ch) {
964 panic!("unsupported character `{:?}`", ch);
965 }
966 Punct(bridge::Punct {
967 ch: ch as u8,
968 joint: spacing == Spacing::Joint,
969 span: Span::call_site().0,
970 })
971 }
972
973 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
975 pub fn as_char(&self) -> char {
976 self.0.ch as char
977 }
978
979 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
983 pub fn spacing(&self) -> Spacing {
984 if self.0.joint { Spacing::Joint } else { Spacing::Alone }
985 }
986
987 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
989 pub fn span(&self) -> Span {
990 Span(self.0.span)
991 }
992
993 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
995 pub fn set_span(&mut self, span: Span) {
996 self.0.span = span.0;
997 }
998}
999
1000#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1003impl fmt::Display for Punct {
1004 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1005 write!(f, "{}", self.as_char())
1006 }
1007}
1008
1009#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1010impl fmt::Debug for Punct {
1011 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1012 f.debug_struct("Punct")
1013 .field("ch", &self.as_char())
1014 .field("spacing", &self.spacing())
1015 .field("span", &self.span())
1016 .finish()
1017 }
1018}
1019
1020#[stable(feature = "proc_macro_punct_eq", since = "1.50.0")]
1021impl PartialEq<char> for Punct {
1022 fn eq(&self, rhs: &char) -> bool {
1023 self.as_char() == *rhs
1024 }
1025}
1026
1027#[stable(feature = "proc_macro_punct_eq_flipped", since = "1.52.0")]
1028impl PartialEq<Punct> for char {
1029 fn eq(&self, rhs: &Punct) -> bool {
1030 *self == rhs.as_char()
1031 }
1032}
1033
1034#[derive(Clone)]
1036#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1037pub struct Ident(bridge::Ident<bridge::client::Span, bridge::client::Symbol>);
1038
1039impl Ident {
1040 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1060 pub fn new(string: &str, span: Span) -> Ident {
1061 Ident(bridge::Ident {
1062 sym: bridge::client::Symbol::new_ident(string, false),
1063 is_raw: false,
1064 span: span.0,
1065 })
1066 }
1067
1068 #[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
1073 pub fn new_raw(string: &str, span: Span) -> Ident {
1074 Ident(bridge::Ident {
1075 sym: bridge::client::Symbol::new_ident(string, true),
1076 is_raw: true,
1077 span: span.0,
1078 })
1079 }
1080
1081 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1084 pub fn span(&self) -> Span {
1085 Span(self.0.span)
1086 }
1087
1088 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1090 pub fn set_span(&mut self, span: Span) {
1091 self.0.span = span.0;
1092 }
1093}
1094
1095#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1098impl fmt::Display for Ident {
1099 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1100 if self.0.is_raw {
1101 f.write_str("r#")?;
1102 }
1103 fmt::Display::fmt(&self.0.sym, f)
1104 }
1105}
1106
1107#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1108impl fmt::Debug for Ident {
1109 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1110 f.debug_struct("Ident")
1111 .field("ident", &self.to_string())
1112 .field("span", &self.span())
1113 .finish()
1114 }
1115}
1116
1117#[derive(Clone)]
1122#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1123pub struct Literal(bridge::Literal<bridge::client::Span, bridge::client::Symbol>);
1124
1125macro_rules! suffixed_int_literals {
1126 ($($name:ident => $kind:ident,)*) => ($(
1127 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1139 pub fn $name(n: $kind) -> Literal {
1140 Literal(bridge::Literal {
1141 kind: bridge::LitKind::Integer,
1142 symbol: bridge::client::Symbol::new(&n.to_string()),
1143 suffix: Some(bridge::client::Symbol::new(stringify!($kind))),
1144 span: Span::call_site().0,
1145 })
1146 }
1147 )*)
1148}
1149
1150macro_rules! unsuffixed_int_literals {
1151 ($($name:ident => $kind:ident,)*) => ($(
1152 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1166 pub fn $name(n: $kind) -> Literal {
1167 Literal(bridge::Literal {
1168 kind: bridge::LitKind::Integer,
1169 symbol: bridge::client::Symbol::new(&n.to_string()),
1170 suffix: None,
1171 span: Span::call_site().0,
1172 })
1173 }
1174 )*)
1175}
1176
1177impl Literal {
1178 fn new(kind: bridge::LitKind, value: &str, suffix: Option<&str>) -> Self {
1179 Literal(bridge::Literal {
1180 kind,
1181 symbol: bridge::client::Symbol::new(value),
1182 suffix: suffix.map(bridge::client::Symbol::new),
1183 span: Span::call_site().0,
1184 })
1185 }
1186
1187 suffixed_int_literals! {
1188 u8_suffixed => u8,
1189 u16_suffixed => u16,
1190 u32_suffixed => u32,
1191 u64_suffixed => u64,
1192 u128_suffixed => u128,
1193 usize_suffixed => usize,
1194 i8_suffixed => i8,
1195 i16_suffixed => i16,
1196 i32_suffixed => i32,
1197 i64_suffixed => i64,
1198 i128_suffixed => i128,
1199 isize_suffixed => isize,
1200 }
1201
1202 unsuffixed_int_literals! {
1203 u8_unsuffixed => u8,
1204 u16_unsuffixed => u16,
1205 u32_unsuffixed => u32,
1206 u64_unsuffixed => u64,
1207 u128_unsuffixed => u128,
1208 usize_unsuffixed => usize,
1209 i8_unsuffixed => i8,
1210 i16_unsuffixed => i16,
1211 i32_unsuffixed => i32,
1212 i64_unsuffixed => i64,
1213 i128_unsuffixed => i128,
1214 isize_unsuffixed => isize,
1215 }
1216
1217 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1230 pub fn f32_unsuffixed(n: f32) -> Literal {
1231 if !n.is_finite() {
1232 panic!("Invalid float literal {n}");
1233 }
1234 let mut repr = n.to_string();
1235 if !repr.contains('.') {
1236 repr.push_str(".0");
1237 }
1238 Literal::new(bridge::LitKind::Float, &repr, None)
1239 }
1240
1241 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1255 pub fn f32_suffixed(n: f32) -> Literal {
1256 if !n.is_finite() {
1257 panic!("Invalid float literal {n}");
1258 }
1259 Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f32"))
1260 }
1261
1262 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1275 pub fn f64_unsuffixed(n: f64) -> Literal {
1276 if !n.is_finite() {
1277 panic!("Invalid float literal {n}");
1278 }
1279 let mut repr = n.to_string();
1280 if !repr.contains('.') {
1281 repr.push_str(".0");
1282 }
1283 Literal::new(bridge::LitKind::Float, &repr, None)
1284 }
1285
1286 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1300 pub fn f64_suffixed(n: f64) -> Literal {
1301 if !n.is_finite() {
1302 panic!("Invalid float literal {n}");
1303 }
1304 Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f64"))
1305 }
1306
1307 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1309 pub fn string(string: &str) -> Literal {
1310 let escape = EscapeOptions {
1311 escape_single_quote: false,
1312 escape_double_quote: true,
1313 escape_nonascii: false,
1314 };
1315 let repr = escape_bytes(string.as_bytes(), escape);
1316 Literal::new(bridge::LitKind::Str, &repr, None)
1317 }
1318
1319 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1321 pub fn character(ch: char) -> Literal {
1322 let escape = EscapeOptions {
1323 escape_single_quote: true,
1324 escape_double_quote: false,
1325 escape_nonascii: false,
1326 };
1327 let repr = escape_bytes(ch.encode_utf8(&mut [0u8; 4]).as_bytes(), escape);
1328 Literal::new(bridge::LitKind::Char, &repr, None)
1329 }
1330
1331 #[stable(feature = "proc_macro_byte_character", since = "1.79.0")]
1333 pub fn byte_character(byte: u8) -> Literal {
1334 let escape = EscapeOptions {
1335 escape_single_quote: true,
1336 escape_double_quote: false,
1337 escape_nonascii: true,
1338 };
1339 let repr = escape_bytes(&[byte], escape);
1340 Literal::new(bridge::LitKind::Byte, &repr, None)
1341 }
1342
1343 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1345 pub fn byte_string(bytes: &[u8]) -> Literal {
1346 let escape = EscapeOptions {
1347 escape_single_quote: false,
1348 escape_double_quote: true,
1349 escape_nonascii: true,
1350 };
1351 let repr = escape_bytes(bytes, escape);
1352 Literal::new(bridge::LitKind::ByteStr, &repr, None)
1353 }
1354
1355 #[stable(feature = "proc_macro_c_str_literals", since = "1.79.0")]
1357 pub fn c_string(string: &CStr) -> Literal {
1358 let escape = EscapeOptions {
1359 escape_single_quote: false,
1360 escape_double_quote: true,
1361 escape_nonascii: false,
1362 };
1363 let repr = escape_bytes(string.to_bytes(), escape);
1364 Literal::new(bridge::LitKind::CStr, &repr, None)
1365 }
1366
1367 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1369 pub fn span(&self) -> Span {
1370 Span(self.0.span)
1371 }
1372
1373 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1375 pub fn set_span(&mut self, span: Span) {
1376 self.0.span = span.0;
1377 }
1378
1379 #[unstable(feature = "proc_macro_span", issue = "54725")]
1391 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1392 self.0.span.subspan(range.start_bound().cloned(), range.end_bound().cloned()).map(Span)
1393 }
1394
1395 fn with_symbol_and_suffix<R>(&self, f: impl FnOnce(&str, &str) -> R) -> R {
1396 self.0.symbol.with(|symbol| match self.0.suffix {
1397 Some(suffix) => suffix.with(|suffix| f(symbol, suffix)),
1398 None => f(symbol, ""),
1399 })
1400 }
1401
1402 fn with_stringify_parts<R>(&self, f: impl FnOnce(&[&str]) -> R) -> R {
1407 fn get_hashes_str(num: u8) -> &'static str {
1411 const HASHES: &str = "\
1412 ################################################################\
1413 ################################################################\
1414 ################################################################\
1415 ################################################################\
1416 ";
1417 const _: () = assert!(HASHES.len() == 256);
1418 &HASHES[..num as usize]
1419 }
1420
1421 self.with_symbol_and_suffix(|symbol, suffix| match self.0.kind {
1422 bridge::LitKind::Byte => f(&["b'", symbol, "'", suffix]),
1423 bridge::LitKind::Char => f(&["'", symbol, "'", suffix]),
1424 bridge::LitKind::Str => f(&["\"", symbol, "\"", suffix]),
1425 bridge::LitKind::StrRaw(n) => {
1426 let hashes = get_hashes_str(n);
1427 f(&["r", hashes, "\"", symbol, "\"", hashes, suffix])
1428 }
1429 bridge::LitKind::ByteStr => f(&["b\"", symbol, "\"", suffix]),
1430 bridge::LitKind::ByteStrRaw(n) => {
1431 let hashes = get_hashes_str(n);
1432 f(&["br", hashes, "\"", symbol, "\"", hashes, suffix])
1433 }
1434 bridge::LitKind::CStr => f(&["c\"", symbol, "\"", suffix]),
1435 bridge::LitKind::CStrRaw(n) => {
1436 let hashes = get_hashes_str(n);
1437 f(&["cr", hashes, "\"", symbol, "\"", hashes, suffix])
1438 }
1439
1440 bridge::LitKind::Integer | bridge::LitKind::Float | bridge::LitKind::ErrWithGuar => {
1441 f(&[symbol, suffix])
1442 }
1443 })
1444 }
1445
1446 #[unstable(feature = "proc_macro_value", issue = "136652")]
1448 pub fn str_value(&self) -> Result<String, ConversionErrorKind> {
1449 self.0.symbol.with(|symbol| match self.0.kind {
1450 bridge::LitKind::Str => {
1451 if symbol.contains('\\') {
1452 let mut buf = String::with_capacity(symbol.len());
1453 let mut error = None;
1454 unescape_str(
1458 symbol,
1459 #[inline(always)]
1460 |_, c| match c {
1461 Ok(c) => buf.push(c),
1462 Err(err) => {
1463 if err.is_fatal() {
1464 error = Some(ConversionErrorKind::FailedToUnescape(err));
1465 }
1466 }
1467 },
1468 );
1469 if let Some(error) = error { Err(error) } else { Ok(buf) }
1470 } else {
1471 Ok(symbol.to_string())
1472 }
1473 }
1474 bridge::LitKind::StrRaw(_) => Ok(symbol.to_string()),
1475 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1476 })
1477 }
1478
1479 #[unstable(feature = "proc_macro_value", issue = "136652")]
1482 pub fn cstr_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1483 self.0.symbol.with(|symbol| match self.0.kind {
1484 bridge::LitKind::CStr => {
1485 let mut error = None;
1486 let mut buf = Vec::with_capacity(symbol.len());
1487
1488 unescape_c_str(symbol, |_span, res| match res {
1489 Ok(MixedUnit::Char(c)) => {
1490 buf.extend_from_slice(c.get().encode_utf8(&mut [0; 4]).as_bytes())
1491 }
1492 Ok(MixedUnit::HighByte(b)) => buf.push(b.get()),
1493 Err(err) => {
1494 if err.is_fatal() {
1495 error = Some(ConversionErrorKind::FailedToUnescape(err));
1496 }
1497 }
1498 });
1499 if let Some(error) = error {
1500 Err(error)
1501 } else {
1502 buf.push(0);
1503 Ok(buf)
1504 }
1505 }
1506 bridge::LitKind::CStrRaw(_) => {
1507 let mut buf = symbol.to_owned().into_bytes();
1511 buf.push(0);
1512 Ok(buf)
1513 }
1514 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1515 })
1516 }
1517
1518 #[unstable(feature = "proc_macro_value", issue = "136652")]
1521 pub fn byte_str_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1522 self.0.symbol.with(|symbol| match self.0.kind {
1523 bridge::LitKind::ByteStr => {
1524 let mut buf = Vec::with_capacity(symbol.len());
1525 let mut error = None;
1526
1527 unescape_byte_str(symbol, |_, res| match res {
1528 Ok(b) => buf.push(b),
1529 Err(err) => {
1530 if err.is_fatal() {
1531 error = Some(ConversionErrorKind::FailedToUnescape(err));
1532 }
1533 }
1534 });
1535 if let Some(error) = error { Err(error) } else { Ok(buf) }
1536 }
1537 bridge::LitKind::ByteStrRaw(_) => {
1538 Ok(symbol.to_owned().into_bytes())
1541 }
1542 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1543 })
1544 }
1545}
1546
1547#[stable(feature = "proc_macro_literal_parse", since = "1.54.0")]
1558impl FromStr for Literal {
1559 type Err = LexError;
1560
1561 fn from_str(src: &str) -> Result<Self, LexError> {
1562 match bridge::client::FreeFunctions::literal_from_str(src) {
1563 Ok(literal) => Ok(Literal(literal)),
1564 Err(()) => Err(LexError),
1565 }
1566 }
1567}
1568
1569#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1572impl fmt::Display for Literal {
1573 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1574 self.with_stringify_parts(|parts| {
1575 for part in parts {
1576 fmt::Display::fmt(part, f)?;
1577 }
1578 Ok(())
1579 })
1580 }
1581}
1582
1583#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1584impl fmt::Debug for Literal {
1585 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1586 f.debug_struct("Literal")
1587 .field("kind", &format_args!("{:?}", self.0.kind))
1589 .field("symbol", &self.0.symbol)
1590 .field("suffix", &format_args!("{:?}", self.0.suffix))
1592 .field("span", &self.0.span)
1593 .finish()
1594 }
1595}
1596
1597#[unstable(feature = "proc_macro_tracked_env", issue = "99515")]
1599pub mod tracked_env {
1600 use std::env::{self, VarError};
1601 use std::ffi::OsStr;
1602
1603 #[unstable(feature = "proc_macro_tracked_env", issue = "99515")]
1609 pub fn var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1610 let key: &str = key.as_ref();
1611 let value = crate::bridge::client::FreeFunctions::injected_env_var(key)
1612 .map_or_else(|| env::var(key), Ok);
1613 crate::bridge::client::FreeFunctions::track_env_var(key, value.as_deref().ok());
1614 value
1615 }
1616}
1617
1618#[unstable(feature = "track_path", issue = "99515")]
1620pub mod tracked_path {
1621
1622 #[unstable(feature = "track_path", issue = "99515")]
1626 pub fn path<P: AsRef<str>>(path: P) {
1627 let path: &str = path.as_ref();
1628 crate::bridge::client::FreeFunctions::track_path(path);
1629 }
1630}