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