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