]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_expand/src/base.rs
Rollup merge of #103084 - inquisitivecrystal:control-flow, r=scottmcm
[rust.git] / compiler / rustc_expand / src / base.rs
1 use crate::expand::{self, AstFragment, Invocation};
2 use crate::module::DirOwnership;
3
4 use rustc_ast::attr::MarkedAttrs;
5 use rustc_ast::ptr::P;
6 use rustc_ast::token::{self, Nonterminal};
7 use rustc_ast::tokenstream::TokenStream;
8 use rustc_ast::visit::{AssocCtxt, Visitor};
9 use rustc_ast::{self as ast, AttrVec, Attribute, HasAttrs, Item, NodeId, PatKind};
10 use rustc_attr::{self as attr, Deprecation, Stability};
11 use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
12 use rustc_data_structures::sync::{self, Lrc};
13 use rustc_errors::{
14     Applicability, DiagnosticBuilder, ErrorGuaranteed, IntoDiagnostic, MultiSpan, PResult,
15 };
16 use rustc_lint_defs::builtin::PROC_MACRO_BACK_COMPAT;
17 use rustc_lint_defs::{BufferedEarlyLint, BuiltinLintDiagnostics};
18 use rustc_parse::{self, parser, MACRO_ARGUMENTS};
19 use rustc_session::{parse::ParseSess, Limit, Session};
20 use rustc_span::def_id::{CrateNum, DefId, LocalDefId};
21 use rustc_span::edition::Edition;
22 use rustc_span::hygiene::{AstPass, ExpnData, ExpnKind, LocalExpnId};
23 use rustc_span::source_map::SourceMap;
24 use rustc_span::symbol::{kw, sym, Ident, Symbol};
25 use rustc_span::{BytePos, FileName, RealFileName, Span, DUMMY_SP};
26 use smallvec::{smallvec, SmallVec};
27
28 use std::default::Default;
29 use std::iter;
30 use std::path::PathBuf;
31 use std::rc::Rc;
32
33 pub(crate) use rustc_span::hygiene::MacroKind;
34
35 // When adding new variants, make sure to
36 // adjust the `visit_*` / `flat_map_*` calls in `InvocationCollector`
37 // to use `assign_id!`
38 #[derive(Debug, Clone)]
39 pub enum Annotatable {
40     Item(P<ast::Item>),
41     TraitItem(P<ast::AssocItem>),
42     ImplItem(P<ast::AssocItem>),
43     ForeignItem(P<ast::ForeignItem>),
44     Stmt(P<ast::Stmt>),
45     Expr(P<ast::Expr>),
46     Arm(ast::Arm),
47     ExprField(ast::ExprField),
48     PatField(ast::PatField),
49     GenericParam(ast::GenericParam),
50     Param(ast::Param),
51     FieldDef(ast::FieldDef),
52     Variant(ast::Variant),
53     Crate(ast::Crate),
54 }
55
56 impl Annotatable {
57     pub fn span(&self) -> Span {
58         match *self {
59             Annotatable::Item(ref item) => item.span,
60             Annotatable::TraitItem(ref trait_item) => trait_item.span,
61             Annotatable::ImplItem(ref impl_item) => impl_item.span,
62             Annotatable::ForeignItem(ref foreign_item) => foreign_item.span,
63             Annotatable::Stmt(ref stmt) => stmt.span,
64             Annotatable::Expr(ref expr) => expr.span,
65             Annotatable::Arm(ref arm) => arm.span,
66             Annotatable::ExprField(ref field) => field.span,
67             Annotatable::PatField(ref fp) => fp.pat.span,
68             Annotatable::GenericParam(ref gp) => gp.ident.span,
69             Annotatable::Param(ref p) => p.span,
70             Annotatable::FieldDef(ref sf) => sf.span,
71             Annotatable::Variant(ref v) => v.span,
72             Annotatable::Crate(ref c) => c.spans.inner_span,
73         }
74     }
75
76     pub fn visit_attrs(&mut self, f: impl FnOnce(&mut AttrVec)) {
77         match self {
78             Annotatable::Item(item) => item.visit_attrs(f),
79             Annotatable::TraitItem(trait_item) => trait_item.visit_attrs(f),
80             Annotatable::ImplItem(impl_item) => impl_item.visit_attrs(f),
81             Annotatable::ForeignItem(foreign_item) => foreign_item.visit_attrs(f),
82             Annotatable::Stmt(stmt) => stmt.visit_attrs(f),
83             Annotatable::Expr(expr) => expr.visit_attrs(f),
84             Annotatable::Arm(arm) => arm.visit_attrs(f),
85             Annotatable::ExprField(field) => field.visit_attrs(f),
86             Annotatable::PatField(fp) => fp.visit_attrs(f),
87             Annotatable::GenericParam(gp) => gp.visit_attrs(f),
88             Annotatable::Param(p) => p.visit_attrs(f),
89             Annotatable::FieldDef(sf) => sf.visit_attrs(f),
90             Annotatable::Variant(v) => v.visit_attrs(f),
91             Annotatable::Crate(c) => c.visit_attrs(f),
92         }
93     }
94
95     pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
96         match self {
97             Annotatable::Item(item) => visitor.visit_item(item),
98             Annotatable::TraitItem(item) => visitor.visit_assoc_item(item, AssocCtxt::Trait),
99             Annotatable::ImplItem(item) => visitor.visit_assoc_item(item, AssocCtxt::Impl),
100             Annotatable::ForeignItem(foreign_item) => visitor.visit_foreign_item(foreign_item),
101             Annotatable::Stmt(stmt) => visitor.visit_stmt(stmt),
102             Annotatable::Expr(expr) => visitor.visit_expr(expr),
103             Annotatable::Arm(arm) => visitor.visit_arm(arm),
104             Annotatable::ExprField(field) => visitor.visit_expr_field(field),
105             Annotatable::PatField(fp) => visitor.visit_pat_field(fp),
106             Annotatable::GenericParam(gp) => visitor.visit_generic_param(gp),
107             Annotatable::Param(p) => visitor.visit_param(p),
108             Annotatable::FieldDef(sf) => visitor.visit_field_def(sf),
109             Annotatable::Variant(v) => visitor.visit_variant(v),
110             Annotatable::Crate(c) => visitor.visit_crate(c),
111         }
112     }
113
114     pub fn to_tokens(&self) -> TokenStream {
115         match self {
116             Annotatable::Item(node) => TokenStream::from_ast(node),
117             Annotatable::TraitItem(node) | Annotatable::ImplItem(node) => {
118                 TokenStream::from_ast(node)
119             }
120             Annotatable::ForeignItem(node) => TokenStream::from_ast(node),
121             Annotatable::Stmt(node) => {
122                 assert!(!matches!(node.kind, ast::StmtKind::Empty));
123                 TokenStream::from_ast(node)
124             }
125             Annotatable::Expr(node) => TokenStream::from_ast(node),
126             Annotatable::Arm(..)
127             | Annotatable::ExprField(..)
128             | Annotatable::PatField(..)
129             | Annotatable::GenericParam(..)
130             | Annotatable::Param(..)
131             | Annotatable::FieldDef(..)
132             | Annotatable::Variant(..)
133             | Annotatable::Crate(..) => panic!("unexpected annotatable"),
134         }
135     }
136
137     pub fn expect_item(self) -> P<ast::Item> {
138         match self {
139             Annotatable::Item(i) => i,
140             _ => panic!("expected Item"),
141         }
142     }
143
144     pub fn expect_trait_item(self) -> P<ast::AssocItem> {
145         match self {
146             Annotatable::TraitItem(i) => i,
147             _ => panic!("expected Item"),
148         }
149     }
150
151     pub fn expect_impl_item(self) -> P<ast::AssocItem> {
152         match self {
153             Annotatable::ImplItem(i) => i,
154             _ => panic!("expected Item"),
155         }
156     }
157
158     pub fn expect_foreign_item(self) -> P<ast::ForeignItem> {
159         match self {
160             Annotatable::ForeignItem(i) => i,
161             _ => panic!("expected foreign item"),
162         }
163     }
164
165     pub fn expect_stmt(self) -> ast::Stmt {
166         match self {
167             Annotatable::Stmt(stmt) => stmt.into_inner(),
168             _ => panic!("expected statement"),
169         }
170     }
171
172     pub fn expect_expr(self) -> P<ast::Expr> {
173         match self {
174             Annotatable::Expr(expr) => expr,
175             _ => panic!("expected expression"),
176         }
177     }
178
179     pub fn expect_arm(self) -> ast::Arm {
180         match self {
181             Annotatable::Arm(arm) => arm,
182             _ => panic!("expected match arm"),
183         }
184     }
185
186     pub fn expect_expr_field(self) -> ast::ExprField {
187         match self {
188             Annotatable::ExprField(field) => field,
189             _ => panic!("expected field"),
190         }
191     }
192
193     pub fn expect_pat_field(self) -> ast::PatField {
194         match self {
195             Annotatable::PatField(fp) => fp,
196             _ => panic!("expected field pattern"),
197         }
198     }
199
200     pub fn expect_generic_param(self) -> ast::GenericParam {
201         match self {
202             Annotatable::GenericParam(gp) => gp,
203             _ => panic!("expected generic parameter"),
204         }
205     }
206
207     pub fn expect_param(self) -> ast::Param {
208         match self {
209             Annotatable::Param(param) => param,
210             _ => panic!("expected parameter"),
211         }
212     }
213
214     pub fn expect_field_def(self) -> ast::FieldDef {
215         match self {
216             Annotatable::FieldDef(sf) => sf,
217             _ => panic!("expected struct field"),
218         }
219     }
220
221     pub fn expect_variant(self) -> ast::Variant {
222         match self {
223             Annotatable::Variant(v) => v,
224             _ => panic!("expected variant"),
225         }
226     }
227
228     pub fn expect_crate(self) -> ast::Crate {
229         match self {
230             Annotatable::Crate(krate) => krate,
231             _ => panic!("expected krate"),
232         }
233     }
234 }
235
236 /// Result of an expansion that may need to be retried.
237 /// Consider using this for non-`MultiItemModifier` expanders as well.
238 pub enum ExpandResult<T, U> {
239     /// Expansion produced a result (possibly dummy).
240     Ready(T),
241     /// Expansion could not produce a result and needs to be retried.
242     Retry(U),
243 }
244
245 // `meta_item` is the attribute, and `item` is the item being modified.
246 pub trait MultiItemModifier {
247     fn expand(
248         &self,
249         ecx: &mut ExtCtxt<'_>,
250         span: Span,
251         meta_item: &ast::MetaItem,
252         item: Annotatable,
253     ) -> ExpandResult<Vec<Annotatable>, Annotatable>;
254 }
255
256 impl<F> MultiItemModifier for F
257 where
258     F: Fn(&mut ExtCtxt<'_>, Span, &ast::MetaItem, Annotatable) -> Vec<Annotatable>,
259 {
260     fn expand(
261         &self,
262         ecx: &mut ExtCtxt<'_>,
263         span: Span,
264         meta_item: &ast::MetaItem,
265         item: Annotatable,
266     ) -> ExpandResult<Vec<Annotatable>, Annotatable> {
267         ExpandResult::Ready(self(ecx, span, meta_item, item))
268     }
269 }
270
271 pub trait BangProcMacro {
272     fn expand<'cx>(
273         &self,
274         ecx: &'cx mut ExtCtxt<'_>,
275         span: Span,
276         ts: TokenStream,
277     ) -> Result<TokenStream, ErrorGuaranteed>;
278 }
279
280 impl<F> BangProcMacro for F
281 where
282     F: Fn(TokenStream) -> TokenStream,
283 {
284     fn expand<'cx>(
285         &self,
286         _ecx: &'cx mut ExtCtxt<'_>,
287         _span: Span,
288         ts: TokenStream,
289     ) -> Result<TokenStream, ErrorGuaranteed> {
290         // FIXME setup implicit context in TLS before calling self.
291         Ok(self(ts))
292     }
293 }
294
295 pub trait AttrProcMacro {
296     fn expand<'cx>(
297         &self,
298         ecx: &'cx mut ExtCtxt<'_>,
299         span: Span,
300         annotation: TokenStream,
301         annotated: TokenStream,
302     ) -> Result<TokenStream, ErrorGuaranteed>;
303 }
304
305 impl<F> AttrProcMacro for F
306 where
307     F: Fn(TokenStream, TokenStream) -> TokenStream,
308 {
309     fn expand<'cx>(
310         &self,
311         _ecx: &'cx mut ExtCtxt<'_>,
312         _span: Span,
313         annotation: TokenStream,
314         annotated: TokenStream,
315     ) -> Result<TokenStream, ErrorGuaranteed> {
316         // FIXME setup implicit context in TLS before calling self.
317         Ok(self(annotation, annotated))
318     }
319 }
320
321 /// Represents a thing that maps token trees to Macro Results
322 pub trait TTMacroExpander {
323     fn expand<'cx>(
324         &self,
325         ecx: &'cx mut ExtCtxt<'_>,
326         span: Span,
327         input: TokenStream,
328     ) -> Box<dyn MacResult + 'cx>;
329 }
330
331 pub type MacroExpanderFn =
332     for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>;
333
334 impl<F> TTMacroExpander for F
335 where
336     F: for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, TokenStream) -> Box<dyn MacResult + 'cx>,
337 {
338     fn expand<'cx>(
339         &self,
340         ecx: &'cx mut ExtCtxt<'_>,
341         span: Span,
342         input: TokenStream,
343     ) -> Box<dyn MacResult + 'cx> {
344         self(ecx, span, input)
345     }
346 }
347
348 // Use a macro because forwarding to a simple function has type system issues
349 macro_rules! make_stmts_default {
350     ($me:expr) => {
351         $me.make_expr().map(|e| {
352             smallvec![ast::Stmt {
353                 id: ast::DUMMY_NODE_ID,
354                 span: e.span,
355                 kind: ast::StmtKind::Expr(e),
356             }]
357         })
358     };
359 }
360
361 /// The result of a macro expansion. The return values of the various
362 /// methods are spliced into the AST at the callsite of the macro.
363 pub trait MacResult {
364     /// Creates an expression.
365     fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
366         None
367     }
368
369     /// Creates zero or more items.
370     fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
371         None
372     }
373
374     /// Creates zero or more impl items.
375     fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
376         None
377     }
378
379     /// Creates zero or more trait items.
380     fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
381         None
382     }
383
384     /// Creates zero or more items in an `extern {}` block
385     fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
386         None
387     }
388
389     /// Creates a pattern.
390     fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
391         None
392     }
393
394     /// Creates zero or more statements.
395     ///
396     /// By default this attempts to create an expression statement,
397     /// returning None if that fails.
398     fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
399         make_stmts_default!(self)
400     }
401
402     fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
403         None
404     }
405
406     fn make_arms(self: Box<Self>) -> Option<SmallVec<[ast::Arm; 1]>> {
407         None
408     }
409
410     fn make_expr_fields(self: Box<Self>) -> Option<SmallVec<[ast::ExprField; 1]>> {
411         None
412     }
413
414     fn make_pat_fields(self: Box<Self>) -> Option<SmallVec<[ast::PatField; 1]>> {
415         None
416     }
417
418     fn make_generic_params(self: Box<Self>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
419         None
420     }
421
422     fn make_params(self: Box<Self>) -> Option<SmallVec<[ast::Param; 1]>> {
423         None
424     }
425
426     fn make_field_defs(self: Box<Self>) -> Option<SmallVec<[ast::FieldDef; 1]>> {
427         None
428     }
429
430     fn make_variants(self: Box<Self>) -> Option<SmallVec<[ast::Variant; 1]>> {
431         None
432     }
433
434     fn make_crate(self: Box<Self>) -> Option<ast::Crate> {
435         // Fn-like macros cannot produce a crate.
436         unreachable!()
437     }
438 }
439
440 macro_rules! make_MacEager {
441     ( $( $fld:ident: $t:ty, )* ) => {
442         /// `MacResult` implementation for the common case where you've already
443         /// built each form of AST that you might return.
444         #[derive(Default)]
445         pub struct MacEager {
446             $(
447                 pub $fld: Option<$t>,
448             )*
449         }
450
451         impl MacEager {
452             $(
453                 pub fn $fld(v: $t) -> Box<dyn MacResult> {
454                     Box::new(MacEager {
455                         $fld: Some(v),
456                         ..Default::default()
457                     })
458                 }
459             )*
460         }
461     }
462 }
463
464 make_MacEager! {
465     expr: P<ast::Expr>,
466     pat: P<ast::Pat>,
467     items: SmallVec<[P<ast::Item>; 1]>,
468     impl_items: SmallVec<[P<ast::AssocItem>; 1]>,
469     trait_items: SmallVec<[P<ast::AssocItem>; 1]>,
470     foreign_items: SmallVec<[P<ast::ForeignItem>; 1]>,
471     stmts: SmallVec<[ast::Stmt; 1]>,
472     ty: P<ast::Ty>,
473 }
474
475 impl MacResult for MacEager {
476     fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
477         self.expr
478     }
479
480     fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
481         self.items
482     }
483
484     fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
485         self.impl_items
486     }
487
488     fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
489         self.trait_items
490     }
491
492     fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
493         self.foreign_items
494     }
495
496     fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
497         match self.stmts.as_ref().map_or(0, |s| s.len()) {
498             0 => make_stmts_default!(self),
499             _ => self.stmts,
500         }
501     }
502
503     fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
504         if let Some(p) = self.pat {
505             return Some(p);
506         }
507         if let Some(e) = self.expr {
508             if let ast::ExprKind::Lit(_) = e.kind {
509                 return Some(P(ast::Pat {
510                     id: ast::DUMMY_NODE_ID,
511                     span: e.span,
512                     kind: PatKind::Lit(e),
513                     tokens: None,
514                 }));
515             }
516         }
517         None
518     }
519
520     fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
521         self.ty
522     }
523 }
524
525 /// Fill-in macro expansion result, to allow compilation to continue
526 /// after hitting errors.
527 #[derive(Copy, Clone)]
528 pub struct DummyResult {
529     is_error: bool,
530     span: Span,
531 }
532
533 impl DummyResult {
534     /// Creates a default MacResult that can be anything.
535     ///
536     /// Use this as a return value after hitting any errors and
537     /// calling `span_err`.
538     pub fn any(span: Span) -> Box<dyn MacResult + 'static> {
539         Box::new(DummyResult { is_error: true, span })
540     }
541
542     /// Same as `any`, but must be a valid fragment, not error.
543     pub fn any_valid(span: Span) -> Box<dyn MacResult + 'static> {
544         Box::new(DummyResult { is_error: false, span })
545     }
546
547     /// A plain dummy expression.
548     pub fn raw_expr(sp: Span, is_error: bool) -> P<ast::Expr> {
549         P(ast::Expr {
550             id: ast::DUMMY_NODE_ID,
551             kind: if is_error { ast::ExprKind::Err } else { ast::ExprKind::Tup(Vec::new()) },
552             span: sp,
553             attrs: ast::AttrVec::new(),
554             tokens: None,
555         })
556     }
557
558     /// A plain dummy pattern.
559     pub fn raw_pat(sp: Span) -> ast::Pat {
560         ast::Pat { id: ast::DUMMY_NODE_ID, kind: PatKind::Wild, span: sp, tokens: None }
561     }
562
563     /// A plain dummy type.
564     pub fn raw_ty(sp: Span, is_error: bool) -> P<ast::Ty> {
565         P(ast::Ty {
566             id: ast::DUMMY_NODE_ID,
567             kind: if is_error { ast::TyKind::Err } else { ast::TyKind::Tup(Vec::new()) },
568             span: sp,
569             tokens: None,
570         })
571     }
572 }
573
574 impl MacResult for DummyResult {
575     fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
576         Some(DummyResult::raw_expr(self.span, self.is_error))
577     }
578
579     fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
580         Some(P(DummyResult::raw_pat(self.span)))
581     }
582
583     fn make_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
584         Some(SmallVec::new())
585     }
586
587     fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
588         Some(SmallVec::new())
589     }
590
591     fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
592         Some(SmallVec::new())
593     }
594
595     fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
596         Some(SmallVec::new())
597     }
598
599     fn make_stmts(self: Box<DummyResult>) -> Option<SmallVec<[ast::Stmt; 1]>> {
600         Some(smallvec![ast::Stmt {
601             id: ast::DUMMY_NODE_ID,
602             kind: ast::StmtKind::Expr(DummyResult::raw_expr(self.span, self.is_error)),
603             span: self.span,
604         }])
605     }
606
607     fn make_ty(self: Box<DummyResult>) -> Option<P<ast::Ty>> {
608         Some(DummyResult::raw_ty(self.span, self.is_error))
609     }
610
611     fn make_arms(self: Box<DummyResult>) -> Option<SmallVec<[ast::Arm; 1]>> {
612         Some(SmallVec::new())
613     }
614
615     fn make_expr_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::ExprField; 1]>> {
616         Some(SmallVec::new())
617     }
618
619     fn make_pat_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::PatField; 1]>> {
620         Some(SmallVec::new())
621     }
622
623     fn make_generic_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
624         Some(SmallVec::new())
625     }
626
627     fn make_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::Param; 1]>> {
628         Some(SmallVec::new())
629     }
630
631     fn make_field_defs(self: Box<DummyResult>) -> Option<SmallVec<[ast::FieldDef; 1]>> {
632         Some(SmallVec::new())
633     }
634
635     fn make_variants(self: Box<DummyResult>) -> Option<SmallVec<[ast::Variant; 1]>> {
636         Some(SmallVec::new())
637     }
638 }
639
640 /// A syntax extension kind.
641 pub enum SyntaxExtensionKind {
642     /// A token-based function-like macro.
643     Bang(
644         /// An expander with signature TokenStream -> TokenStream.
645         Box<dyn BangProcMacro + sync::Sync + sync::Send>,
646     ),
647
648     /// An AST-based function-like macro.
649     LegacyBang(
650         /// An expander with signature TokenStream -> AST.
651         Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
652     ),
653
654     /// A token-based attribute macro.
655     Attr(
656         /// An expander with signature (TokenStream, TokenStream) -> TokenStream.
657         /// The first TokenSteam is the attribute itself, the second is the annotated item.
658         /// The produced TokenSteam replaces the input TokenSteam.
659         Box<dyn AttrProcMacro + sync::Sync + sync::Send>,
660     ),
661
662     /// An AST-based attribute macro.
663     LegacyAttr(
664         /// An expander with signature (AST, AST) -> AST.
665         /// The first AST fragment is the attribute itself, the second is the annotated item.
666         /// The produced AST fragment replaces the input AST fragment.
667         Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
668     ),
669
670     /// A trivial attribute "macro" that does nothing,
671     /// only keeps the attribute and marks it as inert,
672     /// thus making it ineligible for further expansion.
673     NonMacroAttr,
674
675     /// A token-based derive macro.
676     Derive(
677         /// An expander with signature TokenStream -> TokenStream (not yet).
678         /// The produced TokenSteam is appended to the input TokenSteam.
679         Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
680     ),
681
682     /// An AST-based derive macro.
683     LegacyDerive(
684         /// An expander with signature AST -> AST.
685         /// The produced AST fragment is appended to the input AST fragment.
686         Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
687     ),
688 }
689
690 /// A struct representing a macro definition in "lowered" form ready for expansion.
691 pub struct SyntaxExtension {
692     /// A syntax extension kind.
693     pub kind: SyntaxExtensionKind,
694     /// Span of the macro definition.
695     pub span: Span,
696     /// List of unstable features that are treated as stable inside this macro.
697     pub allow_internal_unstable: Option<Lrc<[Symbol]>>,
698     /// The macro's stability info.
699     pub stability: Option<Stability>,
700     /// The macro's deprecation info.
701     pub deprecation: Option<Deprecation>,
702     /// Names of helper attributes registered by this macro.
703     pub helper_attrs: Vec<Symbol>,
704     /// Edition of the crate in which this macro is defined.
705     pub edition: Edition,
706     /// Built-in macros have a couple of special properties like availability
707     /// in `#[no_implicit_prelude]` modules, so we have to keep this flag.
708     pub builtin_name: Option<Symbol>,
709     /// Suppresses the `unsafe_code` lint for code produced by this macro.
710     pub allow_internal_unsafe: bool,
711     /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`) for this macro.
712     pub local_inner_macros: bool,
713     /// Should debuginfo for the macro be collapsed to the outermost expansion site (in other
714     /// words, was the macro definition annotated with `#[collapse_debuginfo]`)?
715     pub collapse_debuginfo: bool,
716 }
717
718 impl SyntaxExtension {
719     /// Returns which kind of macro calls this syntax extension.
720     pub fn macro_kind(&self) -> MacroKind {
721         match self.kind {
722             SyntaxExtensionKind::Bang(..) | SyntaxExtensionKind::LegacyBang(..) => MacroKind::Bang,
723             SyntaxExtensionKind::Attr(..)
724             | SyntaxExtensionKind::LegacyAttr(..)
725             | SyntaxExtensionKind::NonMacroAttr => MacroKind::Attr,
726             SyntaxExtensionKind::Derive(..) | SyntaxExtensionKind::LegacyDerive(..) => {
727                 MacroKind::Derive
728             }
729         }
730     }
731
732     /// Constructs a syntax extension with default properties.
733     pub fn default(kind: SyntaxExtensionKind, edition: Edition) -> SyntaxExtension {
734         SyntaxExtension {
735             span: DUMMY_SP,
736             allow_internal_unstable: None,
737             stability: None,
738             deprecation: None,
739             helper_attrs: Vec::new(),
740             edition,
741             builtin_name: None,
742             kind,
743             allow_internal_unsafe: false,
744             local_inner_macros: false,
745             collapse_debuginfo: false,
746         }
747     }
748
749     /// Constructs a syntax extension with the given properties
750     /// and other properties converted from attributes.
751     pub fn new(
752         sess: &Session,
753         kind: SyntaxExtensionKind,
754         span: Span,
755         helper_attrs: Vec<Symbol>,
756         edition: Edition,
757         name: Symbol,
758         attrs: &[ast::Attribute],
759     ) -> SyntaxExtension {
760         let allow_internal_unstable =
761             attr::allow_internal_unstable(sess, &attrs).collect::<Vec<Symbol>>();
762
763         let allow_internal_unsafe = sess.contains_name(attrs, sym::allow_internal_unsafe);
764         let local_inner_macros = sess
765             .find_by_name(attrs, sym::macro_export)
766             .and_then(|macro_export| macro_export.meta_item_list())
767             .map_or(false, |l| attr::list_contains_name(&l, sym::local_inner_macros));
768         let collapse_debuginfo = sess.contains_name(attrs, sym::collapse_debuginfo);
769         tracing::debug!(?local_inner_macros, ?collapse_debuginfo, ?allow_internal_unsafe);
770
771         let (builtin_name, helper_attrs) = sess
772             .find_by_name(attrs, sym::rustc_builtin_macro)
773             .map(|attr| {
774                 // Override `helper_attrs` passed above if it's a built-in macro,
775                 // marking `proc_macro_derive` macros as built-in is not a realistic use case.
776                 parse_macro_name_and_helper_attrs(sess.diagnostic(), attr, "built-in").map_or_else(
777                     || (Some(name), Vec::new()),
778                     |(name, helper_attrs)| (Some(name), helper_attrs),
779                 )
780             })
781             .unwrap_or_else(|| (None, helper_attrs));
782         let (stability, const_stability, body_stability) = attr::find_stability(&sess, attrs, span);
783         if let Some((_, sp)) = const_stability {
784             sess.parse_sess
785                 .span_diagnostic
786                 .struct_span_err(sp, "macros cannot have const stability attributes")
787                 .span_label(sp, "invalid const stability attribute")
788                 .span_label(
789                     sess.source_map().guess_head_span(span),
790                     "const stability attribute affects this macro",
791                 )
792                 .emit();
793         }
794         if let Some((_, sp)) = body_stability {
795             sess.parse_sess
796                 .span_diagnostic
797                 .struct_span_err(sp, "macros cannot have body stability attributes")
798                 .span_label(sp, "invalid body stability attribute")
799                 .span_label(
800                     sess.source_map().guess_head_span(span),
801                     "body stability attribute affects this macro",
802                 )
803                 .emit();
804         }
805
806         SyntaxExtension {
807             kind,
808             span,
809             allow_internal_unstable: (!allow_internal_unstable.is_empty())
810                 .then(|| allow_internal_unstable.into()),
811             stability: stability.map(|(s, _)| s),
812             deprecation: attr::find_deprecation(&sess, attrs).map(|(d, _)| d),
813             helper_attrs,
814             edition,
815             builtin_name,
816             allow_internal_unsafe,
817             local_inner_macros,
818             collapse_debuginfo,
819         }
820     }
821
822     pub fn dummy_bang(edition: Edition) -> SyntaxExtension {
823         fn expander<'cx>(
824             _: &'cx mut ExtCtxt<'_>,
825             span: Span,
826             _: TokenStream,
827         ) -> Box<dyn MacResult + 'cx> {
828             DummyResult::any(span)
829         }
830         SyntaxExtension::default(SyntaxExtensionKind::LegacyBang(Box::new(expander)), edition)
831     }
832
833     pub fn dummy_derive(edition: Edition) -> SyntaxExtension {
834         fn expander(
835             _: &mut ExtCtxt<'_>,
836             _: Span,
837             _: &ast::MetaItem,
838             _: Annotatable,
839         ) -> Vec<Annotatable> {
840             Vec::new()
841         }
842         SyntaxExtension::default(SyntaxExtensionKind::Derive(Box::new(expander)), edition)
843     }
844
845     pub fn non_macro_attr(edition: Edition) -> SyntaxExtension {
846         SyntaxExtension::default(SyntaxExtensionKind::NonMacroAttr, edition)
847     }
848
849     pub fn expn_data(
850         &self,
851         parent: LocalExpnId,
852         call_site: Span,
853         descr: Symbol,
854         macro_def_id: Option<DefId>,
855         parent_module: Option<DefId>,
856     ) -> ExpnData {
857         ExpnData::new(
858             ExpnKind::Macro(self.macro_kind(), descr),
859             parent.to_expn_id(),
860             call_site,
861             self.span,
862             self.allow_internal_unstable.clone(),
863             self.edition,
864             macro_def_id,
865             parent_module,
866             self.allow_internal_unsafe,
867             self.local_inner_macros,
868             self.collapse_debuginfo,
869         )
870     }
871 }
872
873 /// Error type that denotes indeterminacy.
874 pub struct Indeterminate;
875
876 pub type DeriveResolutions = Vec<(ast::Path, Annotatable, Option<Lrc<SyntaxExtension>>)>;
877
878 pub trait ResolverExpand {
879     fn next_node_id(&mut self) -> NodeId;
880     fn invocation_parent(&self, id: LocalExpnId) -> LocalDefId;
881
882     fn resolve_dollar_crates(&mut self);
883     fn visit_ast_fragment_with_placeholders(
884         &mut self,
885         expn_id: LocalExpnId,
886         fragment: &AstFragment,
887     );
888     fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind);
889
890     fn expansion_for_ast_pass(
891         &mut self,
892         call_site: Span,
893         pass: AstPass,
894         features: &[Symbol],
895         parent_module_id: Option<NodeId>,
896     ) -> LocalExpnId;
897
898     fn resolve_imports(&mut self);
899
900     fn resolve_macro_invocation(
901         &mut self,
902         invoc: &Invocation,
903         eager_expansion_root: LocalExpnId,
904         force: bool,
905     ) -> Result<Lrc<SyntaxExtension>, Indeterminate>;
906
907     fn record_macro_rule_usage(&mut self, mac_id: NodeId, rule_index: usize);
908
909     fn check_unused_macros(&mut self);
910
911     // Resolver interfaces for specific built-in macros.
912     /// Does `#[derive(...)]` attribute with the given `ExpnId` have built-in `Copy` inside it?
913     fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool;
914     /// Resolve paths inside the `#[derive(...)]` attribute with the given `ExpnId`.
915     fn resolve_derives(
916         &mut self,
917         expn_id: LocalExpnId,
918         force: bool,
919         derive_paths: &dyn Fn() -> DeriveResolutions,
920     ) -> Result<(), Indeterminate>;
921     /// Take resolutions for paths inside the `#[derive(...)]` attribute with the given `ExpnId`
922     /// back from resolver.
923     fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<DeriveResolutions>;
924     /// Path resolution logic for `#[cfg_accessible(path)]`.
925     fn cfg_accessible(
926         &mut self,
927         expn_id: LocalExpnId,
928         path: &ast::Path,
929     ) -> Result<bool, Indeterminate>;
930
931     /// Decodes the proc-macro quoted span in the specified crate, with the specified id.
932     /// No caching is performed.
933     fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span;
934
935     /// The order of items in the HIR is unrelated to the order of
936     /// items in the AST. However, we generate proc macro harnesses
937     /// based on the AST order, and later refer to these harnesses
938     /// from the HIR. This field keeps track of the order in which
939     /// we generated proc macros harnesses, so that we can map
940     /// HIR proc macros items back to their harness items.
941     fn declare_proc_macro(&mut self, id: NodeId);
942
943     /// Tools registered with `#![register_tool]` and used by tool attributes and lints.
944     fn registered_tools(&self) -> &FxHashSet<Ident>;
945 }
946
947 pub trait LintStoreExpand {
948     fn pre_expansion_lint(
949         &self,
950         sess: &Session,
951         registered_tools: &FxHashSet<Ident>,
952         node_id: NodeId,
953         attrs: &[Attribute],
954         items: &[P<Item>],
955         name: &str,
956     );
957 }
958
959 type LintStoreExpandDyn<'a> = Option<&'a (dyn LintStoreExpand + 'a)>;
960
961 #[derive(Clone, Default)]
962 pub struct ModuleData {
963     /// Path to the module starting from the crate name, like `my_crate::foo::bar`.
964     pub mod_path: Vec<Ident>,
965     /// Stack of paths to files loaded by out-of-line module items,
966     /// used to detect and report recursive module inclusions.
967     pub file_path_stack: Vec<PathBuf>,
968     /// Directory to search child module files in,
969     /// often (but not necessarily) the parent of the top file path on the `file_path_stack`.
970     pub dir_path: PathBuf,
971 }
972
973 impl ModuleData {
974     pub fn with_dir_path(&self, dir_path: PathBuf) -> ModuleData {
975         ModuleData {
976             mod_path: self.mod_path.clone(),
977             file_path_stack: self.file_path_stack.clone(),
978             dir_path,
979         }
980     }
981 }
982
983 #[derive(Clone)]
984 pub struct ExpansionData {
985     pub id: LocalExpnId,
986     pub depth: usize,
987     pub module: Rc<ModuleData>,
988     pub dir_ownership: DirOwnership,
989     pub prior_type_ascription: Option<(Span, bool)>,
990     /// Some parent node that is close to this macro call
991     pub lint_node_id: NodeId,
992     pub is_trailing_mac: bool,
993 }
994
995 /// One of these is made during expansion and incrementally updated as we go;
996 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
997 /// -> expn_data` of their expansion context stored into their span.
998 pub struct ExtCtxt<'a> {
999     pub sess: &'a Session,
1000     pub ecfg: expand::ExpansionConfig<'a>,
1001     pub reduced_recursion_limit: Option<Limit>,
1002     pub root_path: PathBuf,
1003     pub resolver: &'a mut dyn ResolverExpand,
1004     pub current_expansion: ExpansionData,
1005     /// Error recovery mode entered when expansion is stuck
1006     /// (or during eager expansion, but that's a hack).
1007     pub force_mode: bool,
1008     pub expansions: FxIndexMap<Span, Vec<String>>,
1009     /// Used for running pre-expansion lints on freshly loaded modules.
1010     pub(super) lint_store: LintStoreExpandDyn<'a>,
1011     /// Used for storing lints generated during expansion, like `NAMED_ARGUMENTS_USED_POSITIONALLY`
1012     pub buffered_early_lint: Vec<BufferedEarlyLint>,
1013     /// When we 'expand' an inert attribute, we leave it
1014     /// in the AST, but insert it here so that we know
1015     /// not to expand it again.
1016     pub(super) expanded_inert_attrs: MarkedAttrs,
1017 }
1018
1019 impl<'a> ExtCtxt<'a> {
1020     pub fn new(
1021         sess: &'a Session,
1022         ecfg: expand::ExpansionConfig<'a>,
1023         resolver: &'a mut dyn ResolverExpand,
1024         lint_store: LintStoreExpandDyn<'a>,
1025     ) -> ExtCtxt<'a> {
1026         ExtCtxt {
1027             sess,
1028             ecfg,
1029             reduced_recursion_limit: None,
1030             resolver,
1031             lint_store,
1032             root_path: PathBuf::new(),
1033             current_expansion: ExpansionData {
1034                 id: LocalExpnId::ROOT,
1035                 depth: 0,
1036                 module: Default::default(),
1037                 dir_ownership: DirOwnership::Owned { relative: None },
1038                 prior_type_ascription: None,
1039                 lint_node_id: ast::CRATE_NODE_ID,
1040                 is_trailing_mac: false,
1041             },
1042             force_mode: false,
1043             expansions: FxIndexMap::default(),
1044             expanded_inert_attrs: MarkedAttrs::new(),
1045             buffered_early_lint: vec![],
1046         }
1047     }
1048
1049     /// Returns a `Folder` for deeply expanding all macros in an AST node.
1050     pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
1051         expand::MacroExpander::new(self, false)
1052     }
1053
1054     /// Returns a `Folder` that deeply expands all macros and assigns all `NodeId`s in an AST node.
1055     /// Once `NodeId`s are assigned, the node may not be expanded, removed, or otherwise modified.
1056     pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
1057         expand::MacroExpander::new(self, true)
1058     }
1059     pub fn new_parser_from_tts(&self, stream: TokenStream) -> parser::Parser<'a> {
1060         rustc_parse::stream_to_parser(&self.sess.parse_sess, stream, MACRO_ARGUMENTS)
1061     }
1062     pub fn source_map(&self) -> &'a SourceMap {
1063         self.sess.parse_sess.source_map()
1064     }
1065     pub fn parse_sess(&self) -> &'a ParseSess {
1066         &self.sess.parse_sess
1067     }
1068     pub fn call_site(&self) -> Span {
1069         self.current_expansion.id.expn_data().call_site
1070     }
1071
1072     /// Returns the current expansion kind's description.
1073     pub(crate) fn expansion_descr(&self) -> String {
1074         let expn_data = self.current_expansion.id.expn_data();
1075         expn_data.kind.descr()
1076     }
1077
1078     /// Equivalent of `Span::def_site` from the proc macro API,
1079     /// except that the location is taken from the span passed as an argument.
1080     pub fn with_def_site_ctxt(&self, span: Span) -> Span {
1081         span.with_def_site_ctxt(self.current_expansion.id.to_expn_id())
1082     }
1083
1084     /// Equivalent of `Span::call_site` from the proc macro API,
1085     /// except that the location is taken from the span passed as an argument.
1086     pub fn with_call_site_ctxt(&self, span: Span) -> Span {
1087         span.with_call_site_ctxt(self.current_expansion.id.to_expn_id())
1088     }
1089
1090     /// Equivalent of `Span::mixed_site` from the proc macro API,
1091     /// except that the location is taken from the span passed as an argument.
1092     pub fn with_mixed_site_ctxt(&self, span: Span) -> Span {
1093         span.with_mixed_site_ctxt(self.current_expansion.id.to_expn_id())
1094     }
1095
1096     /// Returns span for the macro which originally caused the current expansion to happen.
1097     ///
1098     /// Stops backtracing at include! boundary.
1099     pub fn expansion_cause(&self) -> Option<Span> {
1100         self.current_expansion.id.expansion_cause()
1101     }
1102
1103     #[rustc_lint_diagnostics]
1104     pub fn struct_span_err<S: Into<MultiSpan>>(
1105         &self,
1106         sp: S,
1107         msg: &str,
1108     ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
1109         self.sess.parse_sess.span_diagnostic.struct_span_err(sp, msg)
1110     }
1111
1112     pub fn create_err(
1113         &self,
1114         err: impl IntoDiagnostic<'a>,
1115     ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
1116         self.sess.create_err(err)
1117     }
1118
1119     pub fn emit_err(&self, err: impl IntoDiagnostic<'a>) -> ErrorGuaranteed {
1120         self.sess.emit_err(err)
1121     }
1122
1123     /// Emit `msg` attached to `sp`, without immediately stopping
1124     /// compilation.
1125     ///
1126     /// Compilation will be stopped in the near future (at the end of
1127     /// the macro expansion phase).
1128     #[rustc_lint_diagnostics]
1129     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1130         self.sess.parse_sess.span_diagnostic.span_err(sp, msg);
1131     }
1132     #[rustc_lint_diagnostics]
1133     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1134         self.sess.parse_sess.span_diagnostic.span_warn(sp, msg);
1135     }
1136     pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
1137         self.sess.parse_sess.span_diagnostic.span_bug(sp, msg);
1138     }
1139     pub fn trace_macros_diag(&mut self) {
1140         for (sp, notes) in self.expansions.iter() {
1141             let mut db = self.sess.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
1142             for note in notes {
1143                 db.note(note);
1144             }
1145             db.emit();
1146         }
1147         // Fixme: does this result in errors?
1148         self.expansions.clear();
1149     }
1150     pub fn bug(&self, msg: &str) -> ! {
1151         self.sess.parse_sess.span_diagnostic.bug(msg);
1152     }
1153     pub fn trace_macros(&self) -> bool {
1154         self.ecfg.trace_mac
1155     }
1156     pub fn set_trace_macros(&mut self, x: bool) {
1157         self.ecfg.trace_mac = x
1158     }
1159     pub fn std_path(&self, components: &[Symbol]) -> Vec<Ident> {
1160         let def_site = self.with_def_site_ctxt(DUMMY_SP);
1161         iter::once(Ident::new(kw::DollarCrate, def_site))
1162             .chain(components.iter().map(|&s| Ident::with_dummy_span(s)))
1163             .collect()
1164     }
1165     pub fn def_site_path(&self, components: &[Symbol]) -> Vec<Ident> {
1166         let def_site = self.with_def_site_ctxt(DUMMY_SP);
1167         components.iter().map(|&s| Ident::new(s, def_site)).collect()
1168     }
1169
1170     pub fn check_unused_macros(&mut self) {
1171         self.resolver.check_unused_macros();
1172     }
1173 }
1174
1175 /// Resolves a `path` mentioned inside Rust code, returning an absolute path.
1176 ///
1177 /// This unifies the logic used for resolving `include_X!`.
1178 pub fn resolve_path(
1179     parse_sess: &ParseSess,
1180     path: impl Into<PathBuf>,
1181     span: Span,
1182 ) -> PResult<'_, PathBuf> {
1183     let path = path.into();
1184
1185     // Relative paths are resolved relative to the file in which they are found
1186     // after macro expansion (that is, they are unhygienic).
1187     if !path.is_absolute() {
1188         let callsite = span.source_callsite();
1189         let mut result = match parse_sess.source_map().span_to_filename(callsite) {
1190             FileName::Real(name) => name
1191                 .into_local_path()
1192                 .expect("attempting to resolve a file path in an external file"),
1193             FileName::DocTest(path, _) => path,
1194             other => {
1195                 return Err(parse_sess.span_diagnostic.struct_span_err(
1196                     span,
1197                     &format!(
1198                         "cannot resolve relative path in non-file source `{}`",
1199                         parse_sess.source_map().filename_for_diagnostics(&other)
1200                     ),
1201                 ));
1202             }
1203         };
1204         result.pop();
1205         result.push(path);
1206         Ok(result)
1207     } else {
1208         Ok(path)
1209     }
1210 }
1211
1212 /// Extracts a string literal from the macro expanded version of `expr`,
1213 /// returning a diagnostic error of `err_msg` if `expr` is not a string literal.
1214 /// The returned bool indicates whether an applicable suggestion has already been
1215 /// added to the diagnostic to avoid emitting multiple suggestions. `Err(None)`
1216 /// indicates that an ast error was encountered.
1217 pub fn expr_to_spanned_string<'a>(
1218     cx: &'a mut ExtCtxt<'_>,
1219     expr: P<ast::Expr>,
1220     err_msg: &str,
1221 ) -> Result<(Symbol, ast::StrStyle, Span), Option<(DiagnosticBuilder<'a, ErrorGuaranteed>, bool)>> {
1222     // Perform eager expansion on the expression.
1223     // We want to be able to handle e.g., `concat!("foo", "bar")`.
1224     let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1225
1226     Err(match expr.kind {
1227         ast::ExprKind::Lit(ref l) => match l.kind {
1228             ast::LitKind::Str(s, style) => return Ok((s, style, expr.span)),
1229             ast::LitKind::ByteStr(_) => {
1230                 let mut err = cx.struct_span_err(l.span, err_msg);
1231                 let span = expr.span.shrink_to_lo();
1232                 err.span_suggestion(
1233                     span.with_hi(span.lo() + BytePos(1)),
1234                     "consider removing the leading `b`",
1235                     "",
1236                     Applicability::MaybeIncorrect,
1237                 );
1238                 Some((err, true))
1239             }
1240             ast::LitKind::Err => None,
1241             _ => Some((cx.struct_span_err(l.span, err_msg), false)),
1242         },
1243         ast::ExprKind::Err => None,
1244         _ => Some((cx.struct_span_err(expr.span, err_msg), false)),
1245     })
1246 }
1247
1248 /// Extracts a string literal from the macro expanded version of `expr`,
1249 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
1250 /// compilation on error, merely emits a non-fatal error and returns `None`.
1251 pub fn expr_to_string(
1252     cx: &mut ExtCtxt<'_>,
1253     expr: P<ast::Expr>,
1254     err_msg: &str,
1255 ) -> Option<(Symbol, ast::StrStyle)> {
1256     expr_to_spanned_string(cx, expr, err_msg)
1257         .map_err(|err| {
1258             err.map(|(mut err, _)| {
1259                 err.emit();
1260             })
1261         })
1262         .ok()
1263         .map(|(symbol, style, _)| (symbol, style))
1264 }
1265
1266 /// Non-fatally assert that `tts` is empty. Note that this function
1267 /// returns even when `tts` is non-empty, macros that *need* to stop
1268 /// compilation should call
1269 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
1270 /// done as rarely as possible).
1271 pub fn check_zero_tts(cx: &ExtCtxt<'_>, sp: Span, tts: TokenStream, name: &str) {
1272     if !tts.is_empty() {
1273         cx.span_err(sp, &format!("{} takes no arguments", name));
1274     }
1275 }
1276
1277 /// Parse an expression. On error, emit it, advancing to `Eof`, and return `None`.
1278 pub fn parse_expr(p: &mut parser::Parser<'_>) -> Option<P<ast::Expr>> {
1279     match p.parse_expr() {
1280         Ok(e) => return Some(e),
1281         Err(mut err) => {
1282             err.emit();
1283         }
1284     }
1285     while p.token != token::Eof {
1286         p.bump();
1287     }
1288     None
1289 }
1290
1291 /// Interpreting `tts` as a comma-separated sequence of expressions,
1292 /// expect exactly one string literal, or emit an error and return `None`.
1293 pub fn get_single_str_from_tts(
1294     cx: &mut ExtCtxt<'_>,
1295     sp: Span,
1296     tts: TokenStream,
1297     name: &str,
1298 ) -> Option<Symbol> {
1299     let mut p = cx.new_parser_from_tts(tts);
1300     if p.token == token::Eof {
1301         cx.span_err(sp, &format!("{} takes 1 argument", name));
1302         return None;
1303     }
1304     let ret = parse_expr(&mut p)?;
1305     let _ = p.eat(&token::Comma);
1306
1307     if p.token != token::Eof {
1308         cx.span_err(sp, &format!("{} takes 1 argument", name));
1309     }
1310     expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| s)
1311 }
1312
1313 /// Extracts comma-separated expressions from `tts`.
1314 /// On error, emit it, and return `None`.
1315 pub fn get_exprs_from_tts(
1316     cx: &mut ExtCtxt<'_>,
1317     sp: Span,
1318     tts: TokenStream,
1319 ) -> Option<Vec<P<ast::Expr>>> {
1320     let mut p = cx.new_parser_from_tts(tts);
1321     let mut es = Vec::new();
1322     while p.token != token::Eof {
1323         let expr = parse_expr(&mut p)?;
1324
1325         // Perform eager expansion on the expression.
1326         // We want to be able to handle e.g., `concat!("foo", "bar")`.
1327         let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1328
1329         es.push(expr);
1330         if p.eat(&token::Comma) {
1331             continue;
1332         }
1333         if p.token != token::Eof {
1334             cx.span_err(sp, "expected token: `,`");
1335             return None;
1336         }
1337     }
1338     Some(es)
1339 }
1340
1341 pub fn parse_macro_name_and_helper_attrs(
1342     diag: &rustc_errors::Handler,
1343     attr: &Attribute,
1344     descr: &str,
1345 ) -> Option<(Symbol, Vec<Symbol>)> {
1346     // Once we've located the `#[proc_macro_derive]` attribute, verify
1347     // that it's of the form `#[proc_macro_derive(Foo)]` or
1348     // `#[proc_macro_derive(Foo, attributes(A, ..))]`
1349     let list = attr.meta_item_list()?;
1350     if list.len() != 1 && list.len() != 2 {
1351         diag.span_err(attr.span, "attribute must have either one or two arguments");
1352         return None;
1353     }
1354     let Some(trait_attr) = list[0].meta_item() else {
1355         diag.span_err(list[0].span(), "not a meta item");
1356         return None;
1357     };
1358     let trait_ident = match trait_attr.ident() {
1359         Some(trait_ident) if trait_attr.is_word() => trait_ident,
1360         _ => {
1361             diag.span_err(trait_attr.span, "must only be one word");
1362             return None;
1363         }
1364     };
1365
1366     if !trait_ident.name.can_be_raw() {
1367         diag.span_err(
1368             trait_attr.span,
1369             &format!("`{}` cannot be a name of {} macro", trait_ident, descr),
1370         );
1371     }
1372
1373     let attributes_attr = list.get(1);
1374     let proc_attrs: Vec<_> = if let Some(attr) = attributes_attr {
1375         if !attr.has_name(sym::attributes) {
1376             diag.span_err(attr.span(), "second argument must be `attributes`");
1377         }
1378         attr.meta_item_list()
1379             .unwrap_or_else(|| {
1380                 diag.span_err(attr.span(), "attribute must be of form: `attributes(foo, bar)`");
1381                 &[]
1382             })
1383             .iter()
1384             .filter_map(|attr| {
1385                 let Some(attr) = attr.meta_item() else {
1386                     diag.span_err(attr.span(), "not a meta item");
1387                     return None;
1388                 };
1389
1390                 let ident = match attr.ident() {
1391                     Some(ident) if attr.is_word() => ident,
1392                     _ => {
1393                         diag.span_err(attr.span, "must only be one word");
1394                         return None;
1395                     }
1396                 };
1397                 if !ident.name.can_be_raw() {
1398                     diag.span_err(
1399                         attr.span,
1400                         &format!("`{}` cannot be a name of derive helper attribute", ident),
1401                     );
1402                 }
1403
1404                 Some(ident.name)
1405             })
1406             .collect()
1407     } else {
1408         Vec::new()
1409     };
1410
1411     Some((trait_ident.name, proc_attrs))
1412 }
1413
1414 /// This nonterminal looks like some specific enums from
1415 /// `proc-macro-hack` and `procedural-masquerade` crates.
1416 /// We need to maintain some special pretty-printing behavior for them due to incorrect
1417 /// asserts in old versions of those crates and their wide use in the ecosystem.
1418 /// See issue #73345 for more details.
1419 /// FIXME(#73933): Remove this eventually.
1420 fn pretty_printing_compatibility_hack(item: &Item, sess: &ParseSess) -> bool {
1421     let name = item.ident.name;
1422     if name == sym::ProceduralMasqueradeDummyType {
1423         if let ast::ItemKind::Enum(enum_def, _) = &item.kind {
1424             if let [variant] = &*enum_def.variants {
1425                 if variant.ident.name == sym::Input {
1426                     let filename = sess.source_map().span_to_filename(item.ident.span);
1427                     if let FileName::Real(RealFileName::LocalPath(path)) = filename {
1428                         if let Some(c) = path
1429                             .components()
1430                             .flat_map(|c| c.as_os_str().to_str())
1431                             .find(|c| c.starts_with("rental") || c.starts_with("allsorts-rental"))
1432                         {
1433                             let crate_matches = if c.starts_with("allsorts-rental") {
1434                                 true
1435                             } else {
1436                                 let mut version = c.trim_start_matches("rental-").split(".");
1437                                 version.next() == Some("0")
1438                                     && version.next() == Some("5")
1439                                     && version
1440                                         .next()
1441                                         .and_then(|c| c.parse::<u32>().ok())
1442                                         .map_or(false, |v| v < 6)
1443                             };
1444
1445                             if crate_matches {
1446                                 sess.buffer_lint_with_diagnostic(
1447                                         &PROC_MACRO_BACK_COMPAT,
1448                                         item.ident.span,
1449                                         ast::CRATE_NODE_ID,
1450                                         "using an old version of `rental`",
1451                                         BuiltinLintDiagnostics::ProcMacroBackCompat(
1452                                         "older versions of the `rental` crate will stop compiling in future versions of Rust; \
1453                                         please update to `rental` v0.5.6, or switch to one of the `rental` alternatives".to_string()
1454                                         )
1455                                     );
1456                                 return true;
1457                             }
1458                         }
1459                     }
1460                 }
1461             }
1462         }
1463     }
1464     false
1465 }
1466
1467 pub(crate) fn ann_pretty_printing_compatibility_hack(ann: &Annotatable, sess: &ParseSess) -> bool {
1468     let item = match ann {
1469         Annotatable::Item(item) => item,
1470         Annotatable::Stmt(stmt) => match &stmt.kind {
1471             ast::StmtKind::Item(item) => item,
1472             _ => return false,
1473         },
1474         _ => return false,
1475     };
1476     pretty_printing_compatibility_hack(item, sess)
1477 }
1478
1479 pub(crate) fn nt_pretty_printing_compatibility_hack(nt: &Nonterminal, sess: &ParseSess) -> bool {
1480     let item = match nt {
1481         Nonterminal::NtItem(item) => item,
1482         Nonterminal::NtStmt(stmt) => match &stmt.kind {
1483             ast::StmtKind::Item(item) => item,
1484             _ => return false,
1485         },
1486         _ => return false,
1487     };
1488     pretty_printing_compatibility_hack(item, sess)
1489 }