]> git.lizzy.rs Git - rust.git/blob - src/librustc_expand/base.rs
Fix missed same-sized member clash in ClashingExternDeclarations.
[rust.git] / src / librustc_expand / base.rs
1 use crate::expand::{self, AstFragment, Invocation};
2 use crate::module::DirectoryOwnership;
3
4 use rustc_ast::ast::{self, Attribute, NodeId, PatKind};
5 use rustc_ast::mut_visit::{self, MutVisitor};
6 use rustc_ast::ptr::P;
7 use rustc_ast::token;
8 use rustc_ast::tokenstream::{self, TokenStream};
9 use rustc_ast::visit::{AssocCtxt, Visitor};
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};
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             }]
404         })
405     };
406 }
407
408 /// The result of a macro expansion. The return values of the various
409 /// methods are spliced into the AST at the callsite of the macro.
410 pub trait MacResult {
411     /// Creates an expression.
412     fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
413         None
414     }
415     /// Creates zero or more items.
416     fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
417         None
418     }
419
420     /// Creates zero or more impl items.
421     fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
422         None
423     }
424
425     /// Creates zero or more trait items.
426     fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
427         None
428     }
429
430     /// Creates zero or more items in an `extern {}` block
431     fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
432         None
433     }
434
435     /// Creates a pattern.
436     fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
437         None
438     }
439
440     /// Creates zero or more statements.
441     ///
442     /// By default this attempts to create an expression statement,
443     /// returning None if that fails.
444     fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
445         make_stmts_default!(self)
446     }
447
448     fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
449         None
450     }
451
452     fn make_arms(self: Box<Self>) -> Option<SmallVec<[ast::Arm; 1]>> {
453         None
454     }
455
456     fn make_fields(self: Box<Self>) -> Option<SmallVec<[ast::Field; 1]>> {
457         None
458     }
459
460     fn make_field_patterns(self: Box<Self>) -> Option<SmallVec<[ast::FieldPat; 1]>> {
461         None
462     }
463
464     fn make_generic_params(self: Box<Self>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
465         None
466     }
467
468     fn make_params(self: Box<Self>) -> Option<SmallVec<[ast::Param; 1]>> {
469         None
470     }
471
472     fn make_struct_fields(self: Box<Self>) -> Option<SmallVec<[ast::StructField; 1]>> {
473         None
474     }
475
476     fn make_variants(self: Box<Self>) -> Option<SmallVec<[ast::Variant; 1]>> {
477         None
478     }
479 }
480
481 macro_rules! make_MacEager {
482     ( $( $fld:ident: $t:ty, )* ) => {
483         /// `MacResult` implementation for the common case where you've already
484         /// built each form of AST that you might return.
485         #[derive(Default)]
486         pub struct MacEager {
487             $(
488                 pub $fld: Option<$t>,
489             )*
490         }
491
492         impl MacEager {
493             $(
494                 pub fn $fld(v: $t) -> Box<dyn MacResult> {
495                     Box::new(MacEager {
496                         $fld: Some(v),
497                         ..Default::default()
498                     })
499                 }
500             )*
501         }
502     }
503 }
504
505 make_MacEager! {
506     expr: P<ast::Expr>,
507     pat: P<ast::Pat>,
508     items: SmallVec<[P<ast::Item>; 1]>,
509     impl_items: SmallVec<[P<ast::AssocItem>; 1]>,
510     trait_items: SmallVec<[P<ast::AssocItem>; 1]>,
511     foreign_items: SmallVec<[P<ast::ForeignItem>; 1]>,
512     stmts: SmallVec<[ast::Stmt; 1]>,
513     ty: P<ast::Ty>,
514 }
515
516 impl MacResult for MacEager {
517     fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
518         self.expr
519     }
520
521     fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
522         self.items
523     }
524
525     fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
526         self.impl_items
527     }
528
529     fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
530         self.trait_items
531     }
532
533     fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
534         self.foreign_items
535     }
536
537     fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
538         match self.stmts.as_ref().map_or(0, |s| s.len()) {
539             0 => make_stmts_default!(self),
540             _ => self.stmts,
541         }
542     }
543
544     fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
545         if let Some(p) = self.pat {
546             return Some(p);
547         }
548         if let Some(e) = self.expr {
549             if let ast::ExprKind::Lit(_) = e.kind {
550                 return Some(P(ast::Pat {
551                     id: ast::DUMMY_NODE_ID,
552                     span: e.span,
553                     kind: PatKind::Lit(e),
554                 }));
555             }
556         }
557         None
558     }
559
560     fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
561         self.ty
562     }
563 }
564
565 /// Fill-in macro expansion result, to allow compilation to continue
566 /// after hitting errors.
567 #[derive(Copy, Clone)]
568 pub struct DummyResult {
569     is_error: bool,
570     span: Span,
571 }
572
573 impl DummyResult {
574     /// Creates a default MacResult that can be anything.
575     ///
576     /// Use this as a return value after hitting any errors and
577     /// calling `span_err`.
578     pub fn any(span: Span) -> Box<dyn MacResult + 'static> {
579         Box::new(DummyResult { is_error: true, span })
580     }
581
582     /// Same as `any`, but must be a valid fragment, not error.
583     pub fn any_valid(span: Span) -> Box<dyn MacResult + 'static> {
584         Box::new(DummyResult { is_error: false, span })
585     }
586
587     /// A plain dummy expression.
588     pub fn raw_expr(sp: Span, is_error: bool) -> P<ast::Expr> {
589         P(ast::Expr {
590             id: ast::DUMMY_NODE_ID,
591             kind: if is_error { ast::ExprKind::Err } else { ast::ExprKind::Tup(Vec::new()) },
592             span: sp,
593             attrs: ast::AttrVec::new(),
594             tokens: None,
595         })
596     }
597
598     /// A plain dummy pattern.
599     pub fn raw_pat(sp: Span) -> ast::Pat {
600         ast::Pat { id: ast::DUMMY_NODE_ID, kind: PatKind::Wild, span: sp }
601     }
602
603     /// A plain dummy type.
604     pub fn raw_ty(sp: Span, is_error: bool) -> P<ast::Ty> {
605         P(ast::Ty {
606             id: ast::DUMMY_NODE_ID,
607             kind: if is_error { ast::TyKind::Err } else { ast::TyKind::Tup(Vec::new()) },
608             span: sp,
609         })
610     }
611 }
612
613 impl MacResult for DummyResult {
614     fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
615         Some(DummyResult::raw_expr(self.span, self.is_error))
616     }
617
618     fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
619         Some(P(DummyResult::raw_pat(self.span)))
620     }
621
622     fn make_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
623         Some(SmallVec::new())
624     }
625
626     fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
627         Some(SmallVec::new())
628     }
629
630     fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
631         Some(SmallVec::new())
632     }
633
634     fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[P<ast::ForeignItem>; 1]>> {
635         Some(SmallVec::new())
636     }
637
638     fn make_stmts(self: Box<DummyResult>) -> Option<SmallVec<[ast::Stmt; 1]>> {
639         Some(smallvec![ast::Stmt {
640             id: ast::DUMMY_NODE_ID,
641             kind: ast::StmtKind::Expr(DummyResult::raw_expr(self.span, self.is_error)),
642             span: self.span,
643         }])
644     }
645
646     fn make_ty(self: Box<DummyResult>) -> Option<P<ast::Ty>> {
647         Some(DummyResult::raw_ty(self.span, self.is_error))
648     }
649
650     fn make_arms(self: Box<DummyResult>) -> Option<SmallVec<[ast::Arm; 1]>> {
651         Some(SmallVec::new())
652     }
653
654     fn make_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::Field; 1]>> {
655         Some(SmallVec::new())
656     }
657
658     fn make_field_patterns(self: Box<DummyResult>) -> Option<SmallVec<[ast::FieldPat; 1]>> {
659         Some(SmallVec::new())
660     }
661
662     fn make_generic_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::GenericParam; 1]>> {
663         Some(SmallVec::new())
664     }
665
666     fn make_params(self: Box<DummyResult>) -> Option<SmallVec<[ast::Param; 1]>> {
667         Some(SmallVec::new())
668     }
669
670     fn make_struct_fields(self: Box<DummyResult>) -> Option<SmallVec<[ast::StructField; 1]>> {
671         Some(SmallVec::new())
672     }
673
674     fn make_variants(self: Box<DummyResult>) -> Option<SmallVec<[ast::Variant; 1]>> {
675         Some(SmallVec::new())
676     }
677 }
678
679 /// A syntax extension kind.
680 pub enum SyntaxExtensionKind {
681     /// A token-based function-like macro.
682     Bang(
683         /// An expander with signature TokenStream -> TokenStream.
684         Box<dyn ProcMacro + sync::Sync + sync::Send>,
685     ),
686
687     /// An AST-based function-like macro.
688     LegacyBang(
689         /// An expander with signature TokenStream -> AST.
690         Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
691     ),
692
693     /// A token-based attribute macro.
694     Attr(
695         /// An expander with signature (TokenStream, TokenStream) -> TokenStream.
696         /// The first TokenSteam is the attribute itself, the second is the annotated item.
697         /// The produced TokenSteam replaces the input TokenSteam.
698         Box<dyn AttrProcMacro + sync::Sync + sync::Send>,
699     ),
700
701     /// An AST-based attribute macro.
702     LegacyAttr(
703         /// An expander with signature (AST, AST) -> AST.
704         /// The first AST fragment is the attribute itself, the second is the annotated item.
705         /// The produced AST fragment replaces the input AST fragment.
706         Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
707     ),
708
709     /// A trivial attribute "macro" that does nothing,
710     /// only keeps the attribute and marks it as inert,
711     /// thus making it ineligible for further expansion.
712     NonMacroAttr {
713         /// Suppresses the `unused_attributes` lint for this attribute.
714         mark_used: bool,
715     },
716
717     /// A token-based derive macro.
718     Derive(
719         /// An expander with signature TokenStream -> TokenStream (not yet).
720         /// The produced TokenSteam is appended to the input TokenSteam.
721         Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
722     ),
723
724     /// An AST-based derive macro.
725     LegacyDerive(
726         /// An expander with signature AST -> AST.
727         /// The produced AST fragment is appended to the input AST fragment.
728         Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
729     ),
730 }
731
732 /// A struct representing a macro definition in "lowered" form ready for expansion.
733 pub struct SyntaxExtension {
734     /// A syntax extension kind.
735     pub kind: SyntaxExtensionKind,
736     /// Span of the macro definition.
737     pub span: Span,
738     /// List of unstable features that are treated as stable inside this macro.
739     pub allow_internal_unstable: Option<Lrc<[Symbol]>>,
740     /// Suppresses the `unsafe_code` lint for code produced by this macro.
741     pub allow_internal_unsafe: bool,
742     /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`) for this macro.
743     pub local_inner_macros: bool,
744     /// The macro's stability info.
745     pub stability: Option<Stability>,
746     /// The macro's deprecation info.
747     pub deprecation: Option<Deprecation>,
748     /// Names of helper attributes registered by this macro.
749     pub helper_attrs: Vec<Symbol>,
750     /// Edition of the crate in which this macro is defined.
751     pub edition: Edition,
752     /// Built-in macros have a couple of special properties like availability
753     /// in `#[no_implicit_prelude]` modules, so we have to keep this flag.
754     pub is_builtin: bool,
755     /// We have to identify macros providing a `Copy` impl early for compatibility reasons.
756     pub is_derive_copy: bool,
757 }
758
759 impl SyntaxExtension {
760     /// Returns which kind of macro calls this syntax extension.
761     pub fn macro_kind(&self) -> MacroKind {
762         match self.kind {
763             SyntaxExtensionKind::Bang(..) | SyntaxExtensionKind::LegacyBang(..) => MacroKind::Bang,
764             SyntaxExtensionKind::Attr(..)
765             | SyntaxExtensionKind::LegacyAttr(..)
766             | SyntaxExtensionKind::NonMacroAttr { .. } => MacroKind::Attr,
767             SyntaxExtensionKind::Derive(..) | SyntaxExtensionKind::LegacyDerive(..) => {
768                 MacroKind::Derive
769             }
770         }
771     }
772
773     /// Constructs a syntax extension with default properties.
774     pub fn default(kind: SyntaxExtensionKind, edition: Edition) -> SyntaxExtension {
775         SyntaxExtension {
776             span: DUMMY_SP,
777             allow_internal_unstable: None,
778             allow_internal_unsafe: false,
779             local_inner_macros: false,
780             stability: None,
781             deprecation: None,
782             helper_attrs: Vec::new(),
783             edition,
784             is_builtin: false,
785             is_derive_copy: false,
786             kind,
787         }
788     }
789
790     /// Constructs a syntax extension with the given properties
791     /// and other properties converted from attributes.
792     pub fn new(
793         sess: &ParseSess,
794         kind: SyntaxExtensionKind,
795         span: Span,
796         helper_attrs: Vec<Symbol>,
797         edition: Edition,
798         name: Symbol,
799         attrs: &[ast::Attribute],
800     ) -> SyntaxExtension {
801         let allow_internal_unstable = attr::allow_internal_unstable(&attrs, &sess.span_diagnostic)
802             .map(|features| features.collect::<Vec<Symbol>>().into());
803
804         let mut local_inner_macros = false;
805         if let Some(macro_export) = attr::find_by_name(attrs, sym::macro_export) {
806             if let Some(l) = macro_export.meta_item_list() {
807                 local_inner_macros = attr::list_contains_name(&l, sym::local_inner_macros);
808             }
809         }
810
811         let is_builtin = attr::contains_name(attrs, sym::rustc_builtin_macro);
812         let (stability, const_stability) = attr::find_stability(&sess, attrs, span);
813         if const_stability.is_some() {
814             sess.span_diagnostic.span_err(span, "macros cannot have const stability attributes");
815         }
816
817         SyntaxExtension {
818             kind,
819             span,
820             allow_internal_unstable,
821             allow_internal_unsafe: attr::contains_name(attrs, sym::allow_internal_unsafe),
822             local_inner_macros,
823             stability,
824             deprecation: attr::find_deprecation(&sess, attrs, span),
825             helper_attrs,
826             edition,
827             is_builtin,
828             is_derive_copy: is_builtin && name == sym::Copy,
829         }
830     }
831
832     pub fn dummy_bang(edition: Edition) -> SyntaxExtension {
833         fn expander<'cx>(
834             _: &'cx mut ExtCtxt<'_>,
835             span: Span,
836             _: TokenStream,
837         ) -> Box<dyn MacResult + 'cx> {
838             DummyResult::any(span)
839         }
840         SyntaxExtension::default(SyntaxExtensionKind::LegacyBang(Box::new(expander)), edition)
841     }
842
843     pub fn dummy_derive(edition: Edition) -> SyntaxExtension {
844         fn expander(
845             _: &mut ExtCtxt<'_>,
846             _: Span,
847             _: &ast::MetaItem,
848             _: Annotatable,
849         ) -> Vec<Annotatable> {
850             Vec::new()
851         }
852         SyntaxExtension::default(SyntaxExtensionKind::Derive(Box::new(expander)), edition)
853     }
854
855     pub fn non_macro_attr(mark_used: bool, edition: Edition) -> SyntaxExtension {
856         SyntaxExtension::default(SyntaxExtensionKind::NonMacroAttr { mark_used }, edition)
857     }
858
859     pub fn expn_data(
860         &self,
861         parent: ExpnId,
862         call_site: Span,
863         descr: Symbol,
864         macro_def_id: Option<DefId>,
865     ) -> ExpnData {
866         ExpnData {
867             kind: ExpnKind::Macro(self.macro_kind(), descr),
868             parent,
869             call_site,
870             def_site: self.span,
871             allow_internal_unstable: self.allow_internal_unstable.clone(),
872             allow_internal_unsafe: self.allow_internal_unsafe,
873             local_inner_macros: self.local_inner_macros,
874             edition: self.edition,
875             macro_def_id,
876             krate: LOCAL_CRATE,
877             orig_id: None,
878         }
879     }
880 }
881
882 /// Result of resolving a macro invocation.
883 pub enum InvocationRes {
884     Single(Lrc<SyntaxExtension>),
885     DeriveContainer(Vec<Lrc<SyntaxExtension>>),
886 }
887
888 /// Error type that denotes indeterminacy.
889 pub struct Indeterminate;
890
891 pub trait ResolverExpand {
892     fn next_node_id(&mut self) -> NodeId;
893
894     fn resolve_dollar_crates(&mut self);
895     fn visit_ast_fragment_with_placeholders(&mut self, expn_id: ExpnId, fragment: &AstFragment);
896     fn register_builtin_macro(&mut self, ident: Ident, ext: SyntaxExtension);
897
898     fn expansion_for_ast_pass(
899         &mut self,
900         call_site: Span,
901         pass: AstPass,
902         features: &[Symbol],
903         parent_module_id: Option<NodeId>,
904     ) -> ExpnId;
905
906     fn resolve_imports(&mut self);
907
908     fn resolve_macro_invocation(
909         &mut self,
910         invoc: &Invocation,
911         eager_expansion_root: ExpnId,
912         force: bool,
913     ) -> Result<InvocationRes, Indeterminate>;
914
915     fn check_unused_macros(&mut self);
916
917     /// Some parent node that is close enough to the given macro call.
918     fn lint_node_id(&mut self, expn_id: ExpnId) -> NodeId;
919
920     fn has_derive_copy(&self, expn_id: ExpnId) -> bool;
921     fn add_derive_copy(&mut self, expn_id: ExpnId);
922     fn cfg_accessible(&mut self, expn_id: ExpnId, path: &ast::Path) -> Result<bool, Indeterminate>;
923 }
924
925 #[derive(Clone)]
926 pub struct ModuleData {
927     pub mod_path: Vec<Ident>,
928     pub directory: PathBuf,
929 }
930
931 #[derive(Clone)]
932 pub struct ExpansionData {
933     pub id: ExpnId,
934     pub depth: usize,
935     pub module: Rc<ModuleData>,
936     pub directory_ownership: DirectoryOwnership,
937     pub prior_type_ascription: Option<(Span, bool)>,
938 }
939
940 /// One of these is made during expansion and incrementally updated as we go;
941 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
942 /// -> expn_data` of their expansion context stored into their span.
943 pub struct ExtCtxt<'a> {
944     pub parse_sess: &'a ParseSess,
945     pub ecfg: expand::ExpansionConfig<'a>,
946     pub reduced_recursion_limit: Option<Limit>,
947     pub root_path: PathBuf,
948     pub resolver: &'a mut dyn ResolverExpand,
949     pub current_expansion: ExpansionData,
950     pub expansions: FxHashMap<Span, Vec<String>>,
951     /// Called directly after having parsed an external `mod foo;` in expansion.
952     pub(super) extern_mod_loaded: Option<&'a dyn Fn(&ast::Crate)>,
953 }
954
955 impl<'a> ExtCtxt<'a> {
956     pub fn new(
957         parse_sess: &'a ParseSess,
958         ecfg: expand::ExpansionConfig<'a>,
959         resolver: &'a mut dyn ResolverExpand,
960         extern_mod_loaded: Option<&'a dyn Fn(&ast::Crate)>,
961     ) -> ExtCtxt<'a> {
962         ExtCtxt {
963             parse_sess,
964             ecfg,
965             reduced_recursion_limit: None,
966             resolver,
967             extern_mod_loaded,
968             root_path: PathBuf::new(),
969             current_expansion: ExpansionData {
970                 id: ExpnId::root(),
971                 depth: 0,
972                 module: Rc::new(ModuleData { mod_path: Vec::new(), directory: PathBuf::new() }),
973                 directory_ownership: DirectoryOwnership::Owned { relative: None },
974                 prior_type_ascription: None,
975             },
976             expansions: FxHashMap::default(),
977         }
978     }
979
980     /// Returns a `Folder` for deeply expanding all macros in an AST node.
981     pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
982         expand::MacroExpander::new(self, false)
983     }
984
985     /// Returns a `Folder` that deeply expands all macros and assigns all `NodeId`s in an AST node.
986     /// Once `NodeId`s are assigned, the node may not be expanded, removed, or otherwise modified.
987     pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
988         expand::MacroExpander::new(self, true)
989     }
990     pub fn new_parser_from_tts(&self, stream: TokenStream) -> parser::Parser<'a> {
991         rustc_parse::stream_to_parser(self.parse_sess, stream, MACRO_ARGUMENTS)
992     }
993     pub fn source_map(&self) -> &'a SourceMap {
994         self.parse_sess.source_map()
995     }
996     pub fn parse_sess(&self) -> &'a ParseSess {
997         self.parse_sess
998     }
999     pub fn call_site(&self) -> Span {
1000         self.current_expansion.id.expn_data().call_site
1001     }
1002
1003     /// Equivalent of `Span::def_site` from the proc macro API,
1004     /// except that the location is taken from the span passed as an argument.
1005     pub fn with_def_site_ctxt(&self, span: Span) -> Span {
1006         span.with_def_site_ctxt(self.current_expansion.id)
1007     }
1008
1009     /// Equivalent of `Span::call_site` from the proc macro API,
1010     /// except that the location is taken from the span passed as an argument.
1011     pub fn with_call_site_ctxt(&self, span: Span) -> Span {
1012         span.with_call_site_ctxt(self.current_expansion.id)
1013     }
1014
1015     /// Equivalent of `Span::mixed_site` from the proc macro API,
1016     /// except that the location is taken from the span passed as an argument.
1017     pub fn with_mixed_site_ctxt(&self, span: Span) -> Span {
1018         span.with_mixed_site_ctxt(self.current_expansion.id)
1019     }
1020
1021     /// Returns span for the macro which originally caused the current expansion to happen.
1022     ///
1023     /// Stops backtracing at include! boundary.
1024     pub fn expansion_cause(&self) -> Option<Span> {
1025         self.current_expansion.id.expansion_cause()
1026     }
1027
1028     pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'a> {
1029         self.parse_sess.span_diagnostic.struct_span_err(sp, msg)
1030     }
1031
1032     /// Emit `msg` attached to `sp`, without immediately stopping
1033     /// compilation.
1034     ///
1035     /// Compilation will be stopped in the near future (at the end of
1036     /// the macro expansion phase).
1037     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1038         self.parse_sess.span_diagnostic.span_err(sp, msg);
1039     }
1040     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
1041         self.parse_sess.span_diagnostic.span_warn(sp, msg);
1042     }
1043     pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
1044         self.parse_sess.span_diagnostic.span_bug(sp, msg);
1045     }
1046     pub fn trace_macros_diag(&mut self) {
1047         for (sp, notes) in self.expansions.iter() {
1048             let mut db = self.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
1049             for note in notes {
1050                 db.note(note);
1051             }
1052             db.emit();
1053         }
1054         // Fixme: does this result in errors?
1055         self.expansions.clear();
1056     }
1057     pub fn bug(&self, msg: &str) -> ! {
1058         self.parse_sess.span_diagnostic.bug(msg);
1059     }
1060     pub fn trace_macros(&self) -> bool {
1061         self.ecfg.trace_mac
1062     }
1063     pub fn set_trace_macros(&mut self, x: bool) {
1064         self.ecfg.trace_mac = x
1065     }
1066     pub fn std_path(&self, components: &[Symbol]) -> Vec<Ident> {
1067         let def_site = self.with_def_site_ctxt(DUMMY_SP);
1068         iter::once(Ident::new(kw::DollarCrate, def_site))
1069             .chain(components.iter().map(|&s| Ident::with_dummy_span(s)))
1070             .collect()
1071     }
1072     pub fn name_of(&self, st: &str) -> Symbol {
1073         Symbol::intern(st)
1074     }
1075
1076     pub fn check_unused_macros(&mut self) {
1077         self.resolver.check_unused_macros();
1078     }
1079
1080     /// Resolves a path mentioned inside Rust code.
1081     ///
1082     /// This unifies the logic used for resolving `include_X!`, and `#[doc(include)]` file paths.
1083     ///
1084     /// Returns an absolute path to the file that `path` refers to.
1085     pub fn resolve_path(
1086         &self,
1087         path: impl Into<PathBuf>,
1088         span: Span,
1089     ) -> Result<PathBuf, DiagnosticBuilder<'a>> {
1090         let path = path.into();
1091
1092         // Relative paths are resolved relative to the file in which they are found
1093         // after macro expansion (that is, they are unhygienic).
1094         if !path.is_absolute() {
1095             let callsite = span.source_callsite();
1096             let mut result = match self.source_map().span_to_unmapped_path(callsite) {
1097                 FileName::Real(name) => name.into_local_path(),
1098                 FileName::DocTest(path, _) => path,
1099                 other => {
1100                     return Err(self.struct_span_err(
1101                         span,
1102                         &format!("cannot resolve relative path in non-file source `{}`", other),
1103                     ));
1104                 }
1105             };
1106             result.pop();
1107             result.push(path);
1108             Ok(result)
1109         } else {
1110             Ok(path)
1111         }
1112     }
1113 }
1114
1115 /// Extracts a string literal from the macro expanded version of `expr`,
1116 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
1117 /// compilation on error, merely emits a non-fatal error and returns `None`.
1118 pub fn expr_to_spanned_string<'a>(
1119     cx: &'a mut ExtCtxt<'_>,
1120     expr: P<ast::Expr>,
1121     err_msg: &str,
1122 ) -> Result<(Symbol, ast::StrStyle, Span), Option<DiagnosticBuilder<'a>>> {
1123     // Perform eager expansion on the expression.
1124     // We want to be able to handle e.g., `concat!("foo", "bar")`.
1125     let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1126
1127     Err(match expr.kind {
1128         ast::ExprKind::Lit(ref l) => match l.kind {
1129             ast::LitKind::Str(s, style) => return Ok((s, style, expr.span)),
1130             ast::LitKind::Err(_) => None,
1131             _ => Some(cx.struct_span_err(l.span, err_msg)),
1132         },
1133         ast::ExprKind::Err => None,
1134         _ => Some(cx.struct_span_err(expr.span, err_msg)),
1135     })
1136 }
1137
1138 pub fn expr_to_string(
1139     cx: &mut ExtCtxt<'_>,
1140     expr: P<ast::Expr>,
1141     err_msg: &str,
1142 ) -> Option<(Symbol, ast::StrStyle)> {
1143     expr_to_spanned_string(cx, expr, err_msg)
1144         .map_err(|err| {
1145             err.map(|mut err| {
1146                 err.emit();
1147             })
1148         })
1149         .ok()
1150         .map(|(symbol, style, _)| (symbol, style))
1151 }
1152
1153 /// Non-fatally assert that `tts` is empty. Note that this function
1154 /// returns even when `tts` is non-empty, macros that *need* to stop
1155 /// compilation should call
1156 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
1157 /// done as rarely as possible).
1158 pub fn check_zero_tts(cx: &ExtCtxt<'_>, sp: Span, tts: TokenStream, name: &str) {
1159     if !tts.is_empty() {
1160         cx.span_err(sp, &format!("{} takes no arguments", name));
1161     }
1162 }
1163
1164 /// Parse an expression. On error, emit it, advancing to `Eof`, and return `None`.
1165 pub fn parse_expr(p: &mut parser::Parser<'_>) -> Option<P<ast::Expr>> {
1166     match p.parse_expr() {
1167         Ok(e) => return Some(e),
1168         Err(mut err) => err.emit(),
1169     }
1170     while p.token != token::Eof {
1171         p.bump();
1172     }
1173     None
1174 }
1175
1176 /// Interpreting `tts` as a comma-separated sequence of expressions,
1177 /// expect exactly one string literal, or emit an error and return `None`.
1178 pub fn get_single_str_from_tts(
1179     cx: &mut ExtCtxt<'_>,
1180     sp: Span,
1181     tts: TokenStream,
1182     name: &str,
1183 ) -> Option<String> {
1184     let mut p = cx.new_parser_from_tts(tts);
1185     if p.token == token::Eof {
1186         cx.span_err(sp, &format!("{} takes 1 argument", name));
1187         return None;
1188     }
1189     let ret = parse_expr(&mut p)?;
1190     let _ = p.eat(&token::Comma);
1191
1192     if p.token != token::Eof {
1193         cx.span_err(sp, &format!("{} takes 1 argument", name));
1194     }
1195     expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| s.to_string())
1196 }
1197
1198 /// Extracts comma-separated expressions from `tts`.
1199 /// On error, emit it, and return `None`.
1200 pub fn get_exprs_from_tts(
1201     cx: &mut ExtCtxt<'_>,
1202     sp: Span,
1203     tts: TokenStream,
1204 ) -> Option<Vec<P<ast::Expr>>> {
1205     let mut p = cx.new_parser_from_tts(tts);
1206     let mut es = Vec::new();
1207     while p.token != token::Eof {
1208         let expr = parse_expr(&mut p)?;
1209
1210         // Perform eager expansion on the expression.
1211         // We want to be able to handle e.g., `concat!("foo", "bar")`.
1212         let expr = cx.expander().fully_expand_fragment(AstFragment::Expr(expr)).make_expr();
1213
1214         es.push(expr);
1215         if p.eat(&token::Comma) {
1216             continue;
1217         }
1218         if p.token != token::Eof {
1219             cx.span_err(sp, "expected token: `,`");
1220             return None;
1221         }
1222     }
1223     Some(es)
1224 }