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