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