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