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