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