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::escape::{EscapeOptions, escape_bytes};
62
63#[unstable(feature = "proc_macro_value", issue = "136652")]
65#[derive(Debug, PartialEq, Eq)]
66pub enum ConversionErrorKind {
67 FailedToUnescape(EscapeError),
69 InvalidLiteralKind,
71}
72
73#[stable(feature = "proc_macro_is_available", since = "1.57.0")]
87pub fn is_available() -> bool {
88 bridge::client::is_available()
89}
90
91#[cfg_attr(feature = "rustc-dep-of-std", rustc_diagnostic_item = "TokenStream")]
99#[stable(feature = "proc_macro_lib", since = "1.15.0")]
100#[derive(Clone)]
101pub struct TokenStream(Option<bridge::client::TokenStream>);
102
103#[stable(feature = "proc_macro_lib", since = "1.15.0")]
104impl !Send for TokenStream {}
105#[stable(feature = "proc_macro_lib", since = "1.15.0")]
106impl !Sync for TokenStream {}
107
108#[stable(feature = "proc_macro_lib", since = "1.15.0")]
110#[non_exhaustive]
111#[derive(Debug)]
112pub struct LexError;
113
114#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
115impl fmt::Display for LexError {
116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117 f.write_str("cannot parse string into token stream")
118 }
119}
120
121#[stable(feature = "proc_macro_lexerror_impls", since = "1.44.0")]
122impl error::Error for LexError {}
123
124#[stable(feature = "proc_macro_lib", since = "1.15.0")]
125impl !Send for LexError {}
126#[stable(feature = "proc_macro_lib", since = "1.15.0")]
127impl !Sync for LexError {}
128
129#[unstable(feature = "proc_macro_expand", issue = "90765")]
131#[non_exhaustive]
132#[derive(Debug)]
133pub struct ExpandError;
134
135#[unstable(feature = "proc_macro_expand", issue = "90765")]
136impl fmt::Display for ExpandError {
137 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138 f.write_str("macro expansion failed")
139 }
140}
141
142#[unstable(feature = "proc_macro_expand", issue = "90765")]
143impl error::Error for ExpandError {}
144
145#[unstable(feature = "proc_macro_expand", issue = "90765")]
146impl !Send for ExpandError {}
147
148#[unstable(feature = "proc_macro_expand", issue = "90765")]
149impl !Sync for ExpandError {}
150
151impl TokenStream {
152 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
154 pub fn new() -> TokenStream {
155 TokenStream(None)
156 }
157
158 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
160 pub fn is_empty(&self) -> bool {
161 self.0.as_ref().map(|h| h.is_empty()).unwrap_or(true)
162 }
163
164 #[unstable(feature = "proc_macro_expand", issue = "90765")]
175 pub fn expand_expr(&self) -> Result<TokenStream, ExpandError> {
176 let stream = self.0.as_ref().ok_or(ExpandError)?;
177 match bridge::client::TokenStream::expand_expr(stream) {
178 Ok(stream) => Ok(TokenStream(Some(stream))),
179 Err(_) => Err(ExpandError),
180 }
181 }
182}
183
184#[stable(feature = "proc_macro_lib", since = "1.15.0")]
192impl FromStr for TokenStream {
193 type Err = LexError;
194
195 fn from_str(src: &str) -> Result<TokenStream, LexError> {
196 Ok(TokenStream(Some(bridge::client::TokenStream::from_str(src))))
197 }
198}
199
200#[stable(feature = "proc_macro_lib", since = "1.15.0")]
212impl fmt::Display for TokenStream {
213 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
214 match &self.0 {
215 Some(ts) => write!(f, "{}", ts.to_string()),
216 None => Ok(()),
217 }
218 }
219}
220
221#[stable(feature = "proc_macro_lib", since = "1.15.0")]
223impl fmt::Debug for TokenStream {
224 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225 f.write_str("TokenStream ")?;
226 f.debug_list().entries(self.clone()).finish()
227 }
228}
229
230#[stable(feature = "proc_macro_token_stream_default", since = "1.45.0")]
231impl Default for TokenStream {
232 fn default() -> Self {
233 TokenStream::new()
234 }
235}
236
237#[unstable(feature = "proc_macro_quote", issue = "54722")]
238pub use quote::{HasIterator, RepInterp, ThereIsNoIteratorInRepetition, ext, quote, quote_span};
239
240fn tree_to_bridge_tree(
241 tree: TokenTree,
242) -> bridge::TokenTree<bridge::client::TokenStream, bridge::client::Span, bridge::client::Symbol> {
243 match tree {
244 TokenTree::Group(tt) => bridge::TokenTree::Group(tt.0),
245 TokenTree::Punct(tt) => bridge::TokenTree::Punct(tt.0),
246 TokenTree::Ident(tt) => bridge::TokenTree::Ident(tt.0),
247 TokenTree::Literal(tt) => bridge::TokenTree::Literal(tt.0),
248 }
249}
250
251#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
253impl From<TokenTree> for TokenStream {
254 fn from(tree: TokenTree) -> TokenStream {
255 TokenStream(Some(bridge::client::TokenStream::from_token_tree(tree_to_bridge_tree(tree))))
256 }
257}
258
259struct ConcatTreesHelper {
262 trees: Vec<
263 bridge::TokenTree<
264 bridge::client::TokenStream,
265 bridge::client::Span,
266 bridge::client::Symbol,
267 >,
268 >,
269}
270
271impl ConcatTreesHelper {
272 fn new(capacity: usize) -> Self {
273 ConcatTreesHelper { trees: Vec::with_capacity(capacity) }
274 }
275
276 fn push(&mut self, tree: TokenTree) {
277 self.trees.push(tree_to_bridge_tree(tree));
278 }
279
280 fn build(self) -> TokenStream {
281 if self.trees.is_empty() {
282 TokenStream(None)
283 } else {
284 TokenStream(Some(bridge::client::TokenStream::concat_trees(None, self.trees)))
285 }
286 }
287
288 fn append_to(self, stream: &mut TokenStream) {
289 if self.trees.is_empty() {
290 return;
291 }
292 stream.0 = Some(bridge::client::TokenStream::concat_trees(stream.0.take(), self.trees))
293 }
294}
295
296struct ConcatStreamsHelper {
299 streams: Vec<bridge::client::TokenStream>,
300}
301
302impl ConcatStreamsHelper {
303 fn new(capacity: usize) -> Self {
304 ConcatStreamsHelper { streams: Vec::with_capacity(capacity) }
305 }
306
307 fn push(&mut self, stream: TokenStream) {
308 if let Some(stream) = stream.0 {
309 self.streams.push(stream);
310 }
311 }
312
313 fn build(mut self) -> TokenStream {
314 if self.streams.len() <= 1 {
315 TokenStream(self.streams.pop())
316 } else {
317 TokenStream(Some(bridge::client::TokenStream::concat_streams(None, self.streams)))
318 }
319 }
320
321 fn append_to(mut self, stream: &mut TokenStream) {
322 if self.streams.is_empty() {
323 return;
324 }
325 let base = stream.0.take();
326 if base.is_none() && self.streams.len() == 1 {
327 stream.0 = self.streams.pop();
328 } else {
329 stream.0 = Some(bridge::client::TokenStream::concat_streams(base, self.streams));
330 }
331 }
332}
333
334#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
336impl FromIterator<TokenTree> for TokenStream {
337 fn from_iter<I: IntoIterator<Item = TokenTree>>(trees: I) -> Self {
338 let iter = trees.into_iter();
339 let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
340 iter.for_each(|tree| builder.push(tree));
341 builder.build()
342 }
343}
344
345#[stable(feature = "proc_macro_lib", since = "1.15.0")]
348impl FromIterator<TokenStream> for TokenStream {
349 fn from_iter<I: IntoIterator<Item = TokenStream>>(streams: I) -> Self {
350 let iter = streams.into_iter();
351 let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
352 iter.for_each(|stream| builder.push(stream));
353 builder.build()
354 }
355}
356
357#[stable(feature = "token_stream_extend", since = "1.30.0")]
358impl Extend<TokenTree> for TokenStream {
359 fn extend<I: IntoIterator<Item = TokenTree>>(&mut self, trees: I) {
360 let iter = trees.into_iter();
361 let mut builder = ConcatTreesHelper::new(iter.size_hint().0);
362 iter.for_each(|tree| builder.push(tree));
363 builder.append_to(self);
364 }
365}
366
367#[stable(feature = "token_stream_extend", since = "1.30.0")]
368impl Extend<TokenStream> for TokenStream {
369 fn extend<I: IntoIterator<Item = TokenStream>>(&mut self, streams: I) {
370 let iter = streams.into_iter();
371 let mut builder = ConcatStreamsHelper::new(iter.size_hint().0);
372 iter.for_each(|stream| builder.push(stream));
373 builder.append_to(self);
374 }
375}
376
377macro_rules! extend_items {
378 ($($item:ident)*) => {
379 $(
380 #[stable(feature = "token_stream_extend_tt_items", since = "1.92.0")]
381 impl Extend<$item> for TokenStream {
382 fn extend<T: IntoIterator<Item = $item>>(&mut self, iter: T) {
383 self.extend(iter.into_iter().map(TokenTree::$item));
384 }
385 }
386 )*
387 };
388}
389
390extend_items!(Group Literal Punct Ident);
391
392#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
394pub mod token_stream {
395 use crate::{Group, Ident, Literal, Punct, TokenStream, TokenTree, bridge};
396
397 #[derive(Clone)]
401 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
402 pub struct IntoIter(
403 std::vec::IntoIter<
404 bridge::TokenTree<
405 bridge::client::TokenStream,
406 bridge::client::Span,
407 bridge::client::Symbol,
408 >,
409 >,
410 );
411
412 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
413 impl Iterator for IntoIter {
414 type Item = TokenTree;
415
416 fn next(&mut self) -> Option<TokenTree> {
417 self.0.next().map(|tree| match tree {
418 bridge::TokenTree::Group(tt) => TokenTree::Group(Group(tt)),
419 bridge::TokenTree::Punct(tt) => TokenTree::Punct(Punct(tt)),
420 bridge::TokenTree::Ident(tt) => TokenTree::Ident(Ident(tt)),
421 bridge::TokenTree::Literal(tt) => TokenTree::Literal(Literal(tt)),
422 })
423 }
424
425 fn size_hint(&self) -> (usize, Option<usize>) {
426 self.0.size_hint()
427 }
428
429 fn count(self) -> usize {
430 self.0.count()
431 }
432 }
433
434 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
435 impl IntoIterator for TokenStream {
436 type Item = TokenTree;
437 type IntoIter = IntoIter;
438
439 fn into_iter(self) -> IntoIter {
440 IntoIter(self.0.map(|v| v.into_trees()).unwrap_or_default().into_iter())
441 }
442 }
443}
444
445#[unstable(feature = "proc_macro_quote", issue = "54722")]
452#[allow_internal_unstable(proc_macro_def_site, proc_macro_internals, proc_macro_totokens)]
453#[rustc_builtin_macro]
454pub macro quote($($t:tt)*) {
455 }
457
458#[unstable(feature = "proc_macro_internals", issue = "27812")]
459#[doc(hidden)]
460mod quote;
461
462#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
464#[derive(Copy, Clone)]
465pub struct Span(bridge::client::Span);
466
467#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
468impl !Send for Span {}
469#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
470impl !Sync for Span {}
471
472macro_rules! diagnostic_method {
473 ($name:ident, $level:expr) => {
474 #[unstable(feature = "proc_macro_diagnostic", issue = "54140")]
477 pub fn $name<T: Into<String>>(self, message: T) -> Diagnostic {
478 Diagnostic::spanned(self, $level, message)
479 }
480 };
481}
482
483impl Span {
484 #[unstable(feature = "proc_macro_def_site", issue = "54724")]
486 pub fn def_site() -> Span {
487 Span(bridge::client::Span::def_site())
488 }
489
490 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
495 pub fn call_site() -> Span {
496 Span(bridge::client::Span::call_site())
497 }
498
499 #[stable(feature = "proc_macro_mixed_site", since = "1.45.0")]
504 pub fn mixed_site() -> Span {
505 Span(bridge::client::Span::mixed_site())
506 }
507
508 #[unstable(feature = "proc_macro_span", issue = "54725")]
511 pub fn parent(&self) -> Option<Span> {
512 self.0.parent().map(Span)
513 }
514
515 #[unstable(feature = "proc_macro_span", issue = "54725")]
519 pub fn source(&self) -> Span {
520 Span(self.0.source())
521 }
522
523 #[unstable(feature = "proc_macro_span", issue = "54725")]
525 pub fn byte_range(&self) -> Range<usize> {
526 self.0.byte_range()
527 }
528
529 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
531 pub fn start(&self) -> Span {
532 Span(self.0.start())
533 }
534
535 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
537 pub fn end(&self) -> Span {
538 Span(self.0.end())
539 }
540
541 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
545 pub fn line(&self) -> usize {
546 self.0.line()
547 }
548
549 #[stable(feature = "proc_macro_span_location", since = "1.88.0")]
553 pub fn column(&self) -> usize {
554 self.0.column()
555 }
556
557 #[stable(feature = "proc_macro_span_file", since = "1.88.0")]
562 pub fn file(&self) -> String {
563 self.0.file()
564 }
565
566 #[stable(feature = "proc_macro_span_file", since = "1.88.0")]
572 pub fn local_file(&self) -> Option<PathBuf> {
573 self.0.local_file().map(PathBuf::from)
574 }
575
576 #[unstable(feature = "proc_macro_span", issue = "54725")]
580 pub fn join(&self, other: Span) -> Option<Span> {
581 self.0.join(other.0).map(Span)
582 }
583
584 #[stable(feature = "proc_macro_span_resolved_at", since = "1.45.0")]
587 pub fn resolved_at(&self, other: Span) -> Span {
588 Span(self.0.resolved_at(other.0))
589 }
590
591 #[stable(feature = "proc_macro_span_located_at", since = "1.45.0")]
594 pub fn located_at(&self, other: Span) -> Span {
595 other.resolved_at(*self)
596 }
597
598 #[unstable(feature = "proc_macro_span", issue = "54725")]
600 pub fn eq(&self, other: &Span) -> bool {
601 self.0 == other.0
602 }
603
604 #[stable(feature = "proc_macro_source_text", since = "1.66.0")]
612 pub fn source_text(&self) -> Option<String> {
613 self.0.source_text()
614 }
615
616 #[doc(hidden)]
618 #[unstable(feature = "proc_macro_internals", issue = "27812")]
619 pub fn save_span(&self) -> usize {
620 self.0.save_span()
621 }
622
623 #[doc(hidden)]
625 #[unstable(feature = "proc_macro_internals", issue = "27812")]
626 pub fn recover_proc_macro_span(id: usize) -> Span {
627 Span(bridge::client::Span::recover_proc_macro_span(id))
628 }
629
630 diagnostic_method!(error, Level::Error);
631 diagnostic_method!(warning, Level::Warning);
632 diagnostic_method!(note, Level::Note);
633 diagnostic_method!(help, Level::Help);
634}
635
636#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
638impl fmt::Debug for Span {
639 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
640 self.0.fmt(f)
641 }
642}
643
644#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
646#[derive(Clone)]
647pub enum TokenTree {
648 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
650 Group(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Group),
651 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
653 Ident(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Ident),
654 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
656 Punct(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Punct),
657 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
659 Literal(#[stable(feature = "proc_macro_lib2", since = "1.29.0")] Literal),
660}
661
662#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
663impl !Send for TokenTree {}
664#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
665impl !Sync for TokenTree {}
666
667impl TokenTree {
668 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
671 pub fn span(&self) -> Span {
672 match *self {
673 TokenTree::Group(ref t) => t.span(),
674 TokenTree::Ident(ref t) => t.span(),
675 TokenTree::Punct(ref t) => t.span(),
676 TokenTree::Literal(ref t) => t.span(),
677 }
678 }
679
680 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
686 pub fn set_span(&mut self, span: Span) {
687 match *self {
688 TokenTree::Group(ref mut t) => t.set_span(span),
689 TokenTree::Ident(ref mut t) => t.set_span(span),
690 TokenTree::Punct(ref mut t) => t.set_span(span),
691 TokenTree::Literal(ref mut t) => t.set_span(span),
692 }
693 }
694}
695
696#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
698impl fmt::Debug for TokenTree {
699 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
700 match *self {
703 TokenTree::Group(ref tt) => tt.fmt(f),
704 TokenTree::Ident(ref tt) => tt.fmt(f),
705 TokenTree::Punct(ref tt) => tt.fmt(f),
706 TokenTree::Literal(ref tt) => tt.fmt(f),
707 }
708 }
709}
710
711#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
712impl From<Group> for TokenTree {
713 fn from(g: Group) -> TokenTree {
714 TokenTree::Group(g)
715 }
716}
717
718#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
719impl From<Ident> for TokenTree {
720 fn from(g: Ident) -> TokenTree {
721 TokenTree::Ident(g)
722 }
723}
724
725#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
726impl From<Punct> for TokenTree {
727 fn from(g: Punct) -> TokenTree {
728 TokenTree::Punct(g)
729 }
730}
731
732#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
733impl From<Literal> for TokenTree {
734 fn from(g: Literal) -> TokenTree {
735 TokenTree::Literal(g)
736 }
737}
738
739#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
751impl fmt::Display for TokenTree {
752 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
753 match self {
754 TokenTree::Group(t) => write!(f, "{t}"),
755 TokenTree::Ident(t) => write!(f, "{t}"),
756 TokenTree::Punct(t) => write!(f, "{t}"),
757 TokenTree::Literal(t) => write!(f, "{t}"),
758 }
759 }
760}
761
762#[derive(Clone)]
766#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
767pub struct Group(bridge::Group<bridge::client::TokenStream, bridge::client::Span>);
768
769#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
770impl !Send for Group {}
771#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
772impl !Sync for Group {}
773
774#[derive(Copy, Clone, Debug, PartialEq, Eq)]
776#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
777pub enum Delimiter {
778 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
780 Parenthesis,
781 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
783 Brace,
784 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
786 Bracket,
787 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
805 None,
806}
807
808impl Group {
809 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
815 pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group {
816 Group(bridge::Group {
817 delimiter,
818 stream: stream.0,
819 span: bridge::DelimSpan::from_single(Span::call_site().0),
820 })
821 }
822
823 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
825 pub fn delimiter(&self) -> Delimiter {
826 self.0.delimiter
827 }
828
829 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
834 pub fn stream(&self) -> TokenStream {
835 TokenStream(self.0.stream.clone())
836 }
837
838 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
846 pub fn span(&self) -> Span {
847 Span(self.0.span.entire)
848 }
849
850 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
857 pub fn span_open(&self) -> Span {
858 Span(self.0.span.open)
859 }
860
861 #[stable(feature = "proc_macro_group_span", since = "1.55.0")]
868 pub fn span_close(&self) -> Span {
869 Span(self.0.span.close)
870 }
871
872 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
879 pub fn set_span(&mut self, span: Span) {
880 self.0.span = bridge::DelimSpan::from_single(span.0);
881 }
882}
883
884#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
888impl fmt::Display for Group {
889 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
890 write!(f, "{}", TokenStream::from(TokenTree::from(self.clone())))
891 }
892}
893
894#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
895impl fmt::Debug for Group {
896 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
897 f.debug_struct("Group")
898 .field("delimiter", &self.delimiter())
899 .field("stream", &self.stream())
900 .field("span", &self.span())
901 .finish()
902 }
903}
904
905#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
910#[derive(Clone)]
911pub struct Punct(bridge::Punct<bridge::client::Span>);
912
913#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
914impl !Send for Punct {}
915#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
916impl !Sync for Punct {}
917
918#[derive(Copy, Clone, Debug, PartialEq, Eq)]
921#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
922pub enum Spacing {
923 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
935 Joint,
936 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
943 Alone,
944}
945
946impl Punct {
947 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
954 pub fn new(ch: char, spacing: Spacing) -> Punct {
955 const LEGAL_CHARS: &[char] = &[
956 '=', '<', '>', '!', '~', '+', '-', '*', '/', '%', '^', '&', '|', '@', '.', ',', ';',
957 ':', '#', '$', '?', '\'',
958 ];
959 if !LEGAL_CHARS.contains(&ch) {
960 panic!("unsupported character `{:?}`", ch);
961 }
962 Punct(bridge::Punct {
963 ch: ch as u8,
964 joint: spacing == Spacing::Joint,
965 span: Span::call_site().0,
966 })
967 }
968
969 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
971 pub fn as_char(&self) -> char {
972 self.0.ch as char
973 }
974
975 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
979 pub fn spacing(&self) -> Spacing {
980 if self.0.joint { Spacing::Joint } else { Spacing::Alone }
981 }
982
983 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
985 pub fn span(&self) -> Span {
986 Span(self.0.span)
987 }
988
989 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
991 pub fn set_span(&mut self, span: Span) {
992 self.0.span = span.0;
993 }
994}
995
996#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
999impl fmt::Display for Punct {
1000 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1001 write!(f, "{}", self.as_char())
1002 }
1003}
1004
1005#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1006impl fmt::Debug for Punct {
1007 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1008 f.debug_struct("Punct")
1009 .field("ch", &self.as_char())
1010 .field("spacing", &self.spacing())
1011 .field("span", &self.span())
1012 .finish()
1013 }
1014}
1015
1016#[stable(feature = "proc_macro_punct_eq", since = "1.50.0")]
1017impl PartialEq<char> for Punct {
1018 fn eq(&self, rhs: &char) -> bool {
1019 self.as_char() == *rhs
1020 }
1021}
1022
1023#[stable(feature = "proc_macro_punct_eq_flipped", since = "1.52.0")]
1024impl PartialEq<Punct> for char {
1025 fn eq(&self, rhs: &Punct) -> bool {
1026 *self == rhs.as_char()
1027 }
1028}
1029
1030#[derive(Clone)]
1032#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1033pub struct Ident(bridge::Ident<bridge::client::Span, bridge::client::Symbol>);
1034
1035impl Ident {
1036 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1056 pub fn new(string: &str, span: Span) -> Ident {
1057 Ident(bridge::Ident {
1058 sym: bridge::client::Symbol::new_ident(string, false),
1059 is_raw: false,
1060 span: span.0,
1061 })
1062 }
1063
1064 #[stable(feature = "proc_macro_raw_ident", since = "1.47.0")]
1069 pub fn new_raw(string: &str, span: Span) -> Ident {
1070 Ident(bridge::Ident {
1071 sym: bridge::client::Symbol::new_ident(string, true),
1072 is_raw: true,
1073 span: span.0,
1074 })
1075 }
1076
1077 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1080 pub fn span(&self) -> Span {
1081 Span(self.0.span)
1082 }
1083
1084 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1086 pub fn set_span(&mut self, span: Span) {
1087 self.0.span = span.0;
1088 }
1089}
1090
1091#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1094impl fmt::Display for Ident {
1095 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1096 if self.0.is_raw {
1097 f.write_str("r#")?;
1098 }
1099 fmt::Display::fmt(&self.0.sym, f)
1100 }
1101}
1102
1103#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1104impl fmt::Debug for Ident {
1105 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1106 f.debug_struct("Ident")
1107 .field("ident", &self.to_string())
1108 .field("span", &self.span())
1109 .finish()
1110 }
1111}
1112
1113#[derive(Clone)]
1118#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1119pub struct Literal(bridge::Literal<bridge::client::Span, bridge::client::Symbol>);
1120
1121macro_rules! suffixed_int_literals {
1122 ($($name:ident => $kind:ident,)*) => ($(
1123 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1135 pub fn $name(n: $kind) -> Literal {
1136 Literal(bridge::Literal {
1137 kind: bridge::LitKind::Integer,
1138 symbol: bridge::client::Symbol::new(&n.to_string()),
1139 suffix: Some(bridge::client::Symbol::new(stringify!($kind))),
1140 span: Span::call_site().0,
1141 })
1142 }
1143 )*)
1144}
1145
1146macro_rules! unsuffixed_int_literals {
1147 ($($name:ident => $kind:ident,)*) => ($(
1148 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1162 pub fn $name(n: $kind) -> Literal {
1163 Literal(bridge::Literal {
1164 kind: bridge::LitKind::Integer,
1165 symbol: bridge::client::Symbol::new(&n.to_string()),
1166 suffix: None,
1167 span: Span::call_site().0,
1168 })
1169 }
1170 )*)
1171}
1172
1173impl Literal {
1174 fn new(kind: bridge::LitKind, value: &str, suffix: Option<&str>) -> Self {
1175 Literal(bridge::Literal {
1176 kind,
1177 symbol: bridge::client::Symbol::new(value),
1178 suffix: suffix.map(bridge::client::Symbol::new),
1179 span: Span::call_site().0,
1180 })
1181 }
1182
1183 suffixed_int_literals! {
1184 u8_suffixed => u8,
1185 u16_suffixed => u16,
1186 u32_suffixed => u32,
1187 u64_suffixed => u64,
1188 u128_suffixed => u128,
1189 usize_suffixed => usize,
1190 i8_suffixed => i8,
1191 i16_suffixed => i16,
1192 i32_suffixed => i32,
1193 i64_suffixed => i64,
1194 i128_suffixed => i128,
1195 isize_suffixed => isize,
1196 }
1197
1198 unsuffixed_int_literals! {
1199 u8_unsuffixed => u8,
1200 u16_unsuffixed => u16,
1201 u32_unsuffixed => u32,
1202 u64_unsuffixed => u64,
1203 u128_unsuffixed => u128,
1204 usize_unsuffixed => usize,
1205 i8_unsuffixed => i8,
1206 i16_unsuffixed => i16,
1207 i32_unsuffixed => i32,
1208 i64_unsuffixed => i64,
1209 i128_unsuffixed => i128,
1210 isize_unsuffixed => isize,
1211 }
1212
1213 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1226 pub fn f32_unsuffixed(n: f32) -> Literal {
1227 if !n.is_finite() {
1228 panic!("Invalid float literal {n}");
1229 }
1230 let mut repr = n.to_string();
1231 if !repr.contains('.') {
1232 repr.push_str(".0");
1233 }
1234 Literal::new(bridge::LitKind::Float, &repr, None)
1235 }
1236
1237 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1251 pub fn f32_suffixed(n: f32) -> Literal {
1252 if !n.is_finite() {
1253 panic!("Invalid float literal {n}");
1254 }
1255 Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f32"))
1256 }
1257
1258 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1271 pub fn f64_unsuffixed(n: f64) -> Literal {
1272 if !n.is_finite() {
1273 panic!("Invalid float literal {n}");
1274 }
1275 let mut repr = n.to_string();
1276 if !repr.contains('.') {
1277 repr.push_str(".0");
1278 }
1279 Literal::new(bridge::LitKind::Float, &repr, None)
1280 }
1281
1282 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1296 pub fn f64_suffixed(n: f64) -> Literal {
1297 if !n.is_finite() {
1298 panic!("Invalid float literal {n}");
1299 }
1300 Literal::new(bridge::LitKind::Float, &n.to_string(), Some("f64"))
1301 }
1302
1303 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1305 pub fn string(string: &str) -> Literal {
1306 let escape = EscapeOptions {
1307 escape_single_quote: false,
1308 escape_double_quote: true,
1309 escape_nonascii: false,
1310 };
1311 let repr = escape_bytes(string.as_bytes(), escape);
1312 Literal::new(bridge::LitKind::Str, &repr, None)
1313 }
1314
1315 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1317 pub fn character(ch: char) -> Literal {
1318 let escape = EscapeOptions {
1319 escape_single_quote: true,
1320 escape_double_quote: false,
1321 escape_nonascii: false,
1322 };
1323 let repr = escape_bytes(ch.encode_utf8(&mut [0u8; 4]).as_bytes(), escape);
1324 Literal::new(bridge::LitKind::Char, &repr, None)
1325 }
1326
1327 #[stable(feature = "proc_macro_byte_character", since = "1.79.0")]
1329 pub fn byte_character(byte: u8) -> Literal {
1330 let escape = EscapeOptions {
1331 escape_single_quote: true,
1332 escape_double_quote: false,
1333 escape_nonascii: true,
1334 };
1335 let repr = escape_bytes(&[byte], escape);
1336 Literal::new(bridge::LitKind::Byte, &repr, None)
1337 }
1338
1339 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1341 pub fn byte_string(bytes: &[u8]) -> Literal {
1342 let escape = EscapeOptions {
1343 escape_single_quote: false,
1344 escape_double_quote: true,
1345 escape_nonascii: true,
1346 };
1347 let repr = escape_bytes(bytes, escape);
1348 Literal::new(bridge::LitKind::ByteStr, &repr, None)
1349 }
1350
1351 #[stable(feature = "proc_macro_c_str_literals", since = "1.79.0")]
1353 pub fn c_string(string: &CStr) -> Literal {
1354 let escape = EscapeOptions {
1355 escape_single_quote: false,
1356 escape_double_quote: true,
1357 escape_nonascii: false,
1358 };
1359 let repr = escape_bytes(string.to_bytes(), escape);
1360 Literal::new(bridge::LitKind::CStr, &repr, None)
1361 }
1362
1363 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1365 pub fn span(&self) -> Span {
1366 Span(self.0.span)
1367 }
1368
1369 #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1371 pub fn set_span(&mut self, span: Span) {
1372 self.0.span = span.0;
1373 }
1374
1375 #[unstable(feature = "proc_macro_span", issue = "54725")]
1387 pub fn subspan<R: RangeBounds<usize>>(&self, range: R) -> Option<Span> {
1388 self.0.span.subspan(range.start_bound().cloned(), range.end_bound().cloned()).map(Span)
1389 }
1390
1391 fn with_symbol_and_suffix<R>(&self, f: impl FnOnce(&str, &str) -> R) -> R {
1392 self.0.symbol.with(|symbol| match self.0.suffix {
1393 Some(suffix) => suffix.with(|suffix| f(symbol, suffix)),
1394 None => f(symbol, ""),
1395 })
1396 }
1397
1398 fn with_stringify_parts<R>(&self, f: impl FnOnce(&[&str]) -> R) -> R {
1403 fn get_hashes_str(num: u8) -> &'static str {
1407 const HASHES: &str = "\
1408 ################################################################\
1409 ################################################################\
1410 ################################################################\
1411 ################################################################\
1412 ";
1413 const _: () = assert!(HASHES.len() == 256);
1414 &HASHES[..num as usize]
1415 }
1416
1417 self.with_symbol_and_suffix(|symbol, suffix| match self.0.kind {
1418 bridge::LitKind::Byte => f(&["b'", symbol, "'", suffix]),
1419 bridge::LitKind::Char => f(&["'", symbol, "'", suffix]),
1420 bridge::LitKind::Str => f(&["\"", symbol, "\"", suffix]),
1421 bridge::LitKind::StrRaw(n) => {
1422 let hashes = get_hashes_str(n);
1423 f(&["r", hashes, "\"", symbol, "\"", hashes, suffix])
1424 }
1425 bridge::LitKind::ByteStr => f(&["b\"", symbol, "\"", suffix]),
1426 bridge::LitKind::ByteStrRaw(n) => {
1427 let hashes = get_hashes_str(n);
1428 f(&["br", hashes, "\"", symbol, "\"", hashes, suffix])
1429 }
1430 bridge::LitKind::CStr => f(&["c\"", symbol, "\"", suffix]),
1431 bridge::LitKind::CStrRaw(n) => {
1432 let hashes = get_hashes_str(n);
1433 f(&["cr", hashes, "\"", symbol, "\"", hashes, suffix])
1434 }
1435
1436 bridge::LitKind::Integer | bridge::LitKind::Float | bridge::LitKind::ErrWithGuar => {
1437 f(&[symbol, suffix])
1438 }
1439 })
1440 }
1441
1442 #[unstable(feature = "proc_macro_value", issue = "136652")]
1444 pub fn str_value(&self) -> Result<String, ConversionErrorKind> {
1445 self.0.symbol.with(|symbol| match self.0.kind {
1446 bridge::LitKind::Str => {
1447 if symbol.contains('\\') {
1448 let mut buf = String::with_capacity(symbol.len());
1449 let mut error = None;
1450 unescape_str(
1454 symbol,
1455 #[inline(always)]
1456 |_, c| match c {
1457 Ok(c) => buf.push(c),
1458 Err(err) => {
1459 if err.is_fatal() {
1460 error = Some(ConversionErrorKind::FailedToUnescape(err));
1461 }
1462 }
1463 },
1464 );
1465 if let Some(error) = error { Err(error) } else { Ok(buf) }
1466 } else {
1467 Ok(symbol.to_string())
1468 }
1469 }
1470 bridge::LitKind::StrRaw(_) => Ok(symbol.to_string()),
1471 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1472 })
1473 }
1474
1475 #[unstable(feature = "proc_macro_value", issue = "136652")]
1478 pub fn cstr_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1479 self.0.symbol.with(|symbol| match self.0.kind {
1480 bridge::LitKind::CStr => {
1481 let mut error = None;
1482 let mut buf = Vec::with_capacity(symbol.len());
1483
1484 unescape_c_str(symbol, |_span, res| match res {
1485 Ok(MixedUnit::Char(c)) => {
1486 buf.extend_from_slice(c.get().encode_utf8(&mut [0; 4]).as_bytes())
1487 }
1488 Ok(MixedUnit::HighByte(b)) => buf.push(b.get()),
1489 Err(err) => {
1490 if err.is_fatal() {
1491 error = Some(ConversionErrorKind::FailedToUnescape(err));
1492 }
1493 }
1494 });
1495 if let Some(error) = error {
1496 Err(error)
1497 } else {
1498 buf.push(0);
1499 Ok(buf)
1500 }
1501 }
1502 bridge::LitKind::CStrRaw(_) => {
1503 let mut buf = symbol.to_owned().into_bytes();
1507 buf.push(0);
1508 Ok(buf)
1509 }
1510 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1511 })
1512 }
1513
1514 #[unstable(feature = "proc_macro_value", issue = "136652")]
1517 pub fn byte_str_value(&self) -> Result<Vec<u8>, ConversionErrorKind> {
1518 self.0.symbol.with(|symbol| match self.0.kind {
1519 bridge::LitKind::ByteStr => {
1520 let mut buf = Vec::with_capacity(symbol.len());
1521 let mut error = None;
1522
1523 unescape_byte_str(symbol, |_, res| match res {
1524 Ok(b) => buf.push(b),
1525 Err(err) => {
1526 if err.is_fatal() {
1527 error = Some(ConversionErrorKind::FailedToUnescape(err));
1528 }
1529 }
1530 });
1531 if let Some(error) = error { Err(error) } else { Ok(buf) }
1532 }
1533 bridge::LitKind::ByteStrRaw(_) => {
1534 Ok(symbol.to_owned().into_bytes())
1537 }
1538 _ => Err(ConversionErrorKind::InvalidLiteralKind),
1539 })
1540 }
1541}
1542
1543#[stable(feature = "proc_macro_literal_parse", since = "1.54.0")]
1554impl FromStr for Literal {
1555 type Err = LexError;
1556
1557 fn from_str(src: &str) -> Result<Self, LexError> {
1558 match bridge::client::FreeFunctions::literal_from_str(src) {
1559 Ok(literal) => Ok(Literal(literal)),
1560 Err(()) => Err(LexError),
1561 }
1562 }
1563}
1564
1565#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1568impl fmt::Display for Literal {
1569 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1570 self.with_stringify_parts(|parts| {
1571 for part in parts {
1572 fmt::Display::fmt(part, f)?;
1573 }
1574 Ok(())
1575 })
1576 }
1577}
1578
1579#[stable(feature = "proc_macro_lib2", since = "1.29.0")]
1580impl fmt::Debug for Literal {
1581 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1582 f.debug_struct("Literal")
1583 .field("kind", &format_args!("{:?}", self.0.kind))
1585 .field("symbol", &self.0.symbol)
1586 .field("suffix", &format_args!("{:?}", self.0.suffix))
1588 .field("span", &self.0.span)
1589 .finish()
1590 }
1591}
1592
1593#[unstable(
1594 feature = "proc_macro_tracked_path",
1595 issue = "99515",
1596 implied_by = "proc_macro_tracked_env"
1597)]
1598pub mod tracked {
1600
1601 use std::env::{self, VarError};
1602 use std::ffi::OsStr;
1603 use std::path::Path;
1604
1605 #[unstable(feature = "proc_macro_tracked_env", issue = "99515")]
1611 pub fn env_var<K: AsRef<OsStr> + AsRef<str>>(key: K) -> Result<String, VarError> {
1612 let key: &str = key.as_ref();
1613 let value = crate::bridge::client::FreeFunctions::injected_env_var(key)
1614 .map_or_else(|| env::var(key), Ok);
1615 crate::bridge::client::FreeFunctions::track_env_var(key, value.as_deref().ok());
1616 value
1617 }
1618
1619 #[unstable(feature = "proc_macro_tracked_path", issue = "99515")]
1623 pub fn path<P: AsRef<Path>>(path: P) {
1624 let path: &str = path.as_ref().to_str().unwrap();
1625 crate::bridge::client::FreeFunctions::track_path(path);
1626 }
1627}