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