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