]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/base.rs
4b5b9ff7bbeeee5b9febe53a99f84b9c7184ca29
[rust.git] / src / libsyntax / ext / base.rs
1 pub use SyntaxExtension::*;
2
3 use crate::ast::{self, Attribute, Name, PatKind, MetaItem};
4 use crate::attr::HasAttrs;
5 use crate::source_map::{SourceMap, Spanned, respan};
6 use crate::edition::Edition;
7 use crate::ext::expand::{self, AstFragment, Invocation};
8 use crate::ext::hygiene::{Mark, SyntaxContext, Transparency};
9 use crate::mut_visit::{self, MutVisitor};
10 use crate::parse::{self, parser, DirectoryOwnership};
11 use crate::parse::token;
12 use crate::ptr::P;
13 use crate::symbol::{kw, sym, Ident, Symbol};
14 use crate::{ThinVec, MACRO_ARGUMENTS};
15 use crate::tokenstream::{self, TokenStream};
16
17 use errors::{DiagnosticBuilder, DiagnosticId};
18 use smallvec::{smallvec, SmallVec};
19 use syntax_pos::{Span, MultiSpan, DUMMY_SP};
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
29 #[derive(Debug,Clone)]
30 pub enum Annotatable {
31     Item(P<ast::Item>),
32     TraitItem(P<ast::TraitItem>),
33     ImplItem(P<ast::ImplItem>),
34     ForeignItem(P<ast::ForeignItem>),
35     Stmt(P<ast::Stmt>),
36     Expr(P<ast::Expr>),
37 }
38
39 impl HasAttrs for Annotatable {
40     fn attrs(&self) -> &[Attribute] {
41         match *self {
42             Annotatable::Item(ref item) => &item.attrs,
43             Annotatable::TraitItem(ref trait_item) => &trait_item.attrs,
44             Annotatable::ImplItem(ref impl_item) => &impl_item.attrs,
45             Annotatable::ForeignItem(ref foreign_item) => &foreign_item.attrs,
46             Annotatable::Stmt(ref stmt) => stmt.attrs(),
47             Annotatable::Expr(ref expr) => &expr.attrs,
48         }
49     }
50
51     fn visit_attrs<F: FnOnce(&mut Vec<Attribute>)>(&mut self, f: F) {
52         match self {
53             Annotatable::Item(item) => item.visit_attrs(f),
54             Annotatable::TraitItem(trait_item) => trait_item.visit_attrs(f),
55             Annotatable::ImplItem(impl_item) => impl_item.visit_attrs(f),
56             Annotatable::ForeignItem(foreign_item) => foreign_item.visit_attrs(f),
57             Annotatable::Stmt(stmt) => stmt.visit_attrs(f),
58             Annotatable::Expr(expr) => expr.visit_attrs(f),
59         }
60     }
61 }
62
63 impl Annotatable {
64     pub fn span(&self) -> Span {
65         match *self {
66             Annotatable::Item(ref item) => item.span,
67             Annotatable::TraitItem(ref trait_item) => trait_item.span,
68             Annotatable::ImplItem(ref impl_item) => impl_item.span,
69             Annotatable::ForeignItem(ref foreign_item) => foreign_item.span,
70             Annotatable::Stmt(ref stmt) => stmt.span,
71             Annotatable::Expr(ref expr) => expr.span,
72         }
73     }
74
75     pub fn expect_item(self) -> P<ast::Item> {
76         match self {
77             Annotatable::Item(i) => i,
78             _ => panic!("expected Item")
79         }
80     }
81
82     pub fn map_item_or<F, G>(self, mut f: F, mut or: G) -> Annotatable
83         where F: FnMut(P<ast::Item>) -> P<ast::Item>,
84               G: FnMut(Annotatable) -> Annotatable
85     {
86         match self {
87             Annotatable::Item(i) => Annotatable::Item(f(i)),
88             _ => or(self)
89         }
90     }
91
92     pub fn expect_trait_item(self) -> ast::TraitItem {
93         match self {
94             Annotatable::TraitItem(i) => i.into_inner(),
95             _ => panic!("expected Item")
96         }
97     }
98
99     pub fn expect_impl_item(self) -> ast::ImplItem {
100         match self {
101             Annotatable::ImplItem(i) => i.into_inner(),
102             _ => panic!("expected Item")
103         }
104     }
105
106     pub fn expect_foreign_item(self) -> ast::ForeignItem {
107         match self {
108             Annotatable::ForeignItem(i) => i.into_inner(),
109             _ => panic!("expected foreign item")
110         }
111     }
112
113     pub fn expect_stmt(self) -> ast::Stmt {
114         match self {
115             Annotatable::Stmt(stmt) => stmt.into_inner(),
116             _ => panic!("expected statement"),
117         }
118     }
119
120     pub fn expect_expr(self) -> P<ast::Expr> {
121         match self {
122             Annotatable::Expr(expr) => expr,
123             _ => panic!("expected expression"),
124         }
125     }
126
127     pub fn derive_allowed(&self) -> bool {
128         match *self {
129             Annotatable::Item(ref item) => match item.node {
130                 ast::ItemKind::Struct(..) |
131                 ast::ItemKind::Enum(..) |
132                 ast::ItemKind::Union(..) => true,
133                 _ => false,
134             },
135             _ => false,
136         }
137     }
138 }
139
140 // A more flexible ItemDecorator.
141 pub trait MultiItemDecorator {
142     fn expand(&self,
143               ecx: &mut ExtCtxt<'_>,
144               sp: Span,
145               meta_item: &ast::MetaItem,
146               item: &Annotatable,
147               push: &mut dyn FnMut(Annotatable));
148 }
149
150 impl<F> MultiItemDecorator for F
151     where F : Fn(&mut ExtCtxt<'_>, Span, &ast::MetaItem, &Annotatable, &mut dyn FnMut(Annotatable))
152 {
153     fn expand(&self,
154               ecx: &mut ExtCtxt<'_>,
155               sp: Span,
156               meta_item: &ast::MetaItem,
157               item: &Annotatable,
158               push: &mut dyn FnMut(Annotatable)) {
159         (*self)(ecx, sp, meta_item, item, push)
160     }
161 }
162
163 // `meta_item` is the annotation, and `item` is the item being modified.
164 // FIXME Decorators should follow the same pattern too.
165 pub trait MultiItemModifier {
166     fn expand(&self,
167               ecx: &mut ExtCtxt<'_>,
168               span: Span,
169               meta_item: &ast::MetaItem,
170               item: Annotatable)
171               -> Vec<Annotatable>;
172 }
173
174 impl<F, T> MultiItemModifier for F
175     where F: Fn(&mut ExtCtxt<'_>, Span, &ast::MetaItem, Annotatable) -> T,
176           T: Into<Vec<Annotatable>>,
177 {
178     fn expand(&self,
179               ecx: &mut ExtCtxt<'_>,
180               span: Span,
181               meta_item: &ast::MetaItem,
182               item: Annotatable)
183               -> Vec<Annotatable> {
184         (*self)(ecx, span, meta_item, item).into()
185     }
186 }
187
188 impl Into<Vec<Annotatable>> for Annotatable {
189     fn into(self) -> Vec<Annotatable> {
190         vec![self]
191     }
192 }
193
194 pub trait ProcMacro {
195     fn expand<'cx>(&self,
196                    ecx: &'cx mut ExtCtxt<'_>,
197                    span: Span,
198                    ts: TokenStream)
199                    -> TokenStream;
200 }
201
202 impl<F> ProcMacro for F
203     where F: Fn(TokenStream) -> TokenStream
204 {
205     fn expand<'cx>(&self,
206                    _ecx: &'cx mut ExtCtxt<'_>,
207                    _span: Span,
208                    ts: TokenStream)
209                    -> TokenStream {
210         // FIXME setup implicit context in TLS before calling self.
211         (*self)(ts)
212     }
213 }
214
215 pub trait AttrProcMacro {
216     fn expand<'cx>(&self,
217                    ecx: &'cx mut ExtCtxt<'_>,
218                    span: Span,
219                    annotation: TokenStream,
220                    annotated: TokenStream)
221                    -> TokenStream;
222 }
223
224 impl<F> AttrProcMacro for F
225     where F: Fn(TokenStream, TokenStream) -> TokenStream
226 {
227     fn expand<'cx>(&self,
228                    _ecx: &'cx mut ExtCtxt<'_>,
229                    _span: Span,
230                    annotation: TokenStream,
231                    annotated: TokenStream)
232                    -> TokenStream {
233         // FIXME setup implicit context in TLS before calling self.
234         (*self)(annotation, annotated)
235     }
236 }
237
238 /// Represents a thing that maps token trees to Macro Results
239 pub trait TTMacroExpander {
240     fn expand<'cx>(
241         &self,
242         ecx: &'cx mut ExtCtxt<'_>,
243         span: Span,
244         input: TokenStream,
245         def_span: Option<Span>,
246     ) -> Box<dyn MacResult+'cx>;
247 }
248
249 pub type MacroExpanderFn =
250     for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, &[tokenstream::TokenTree])
251                 -> Box<dyn MacResult+'cx>;
252
253 impl<F> TTMacroExpander for F
254     where F: for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, &[tokenstream::TokenTree])
255     -> Box<dyn MacResult+'cx>
256 {
257     fn expand<'cx>(
258         &self,
259         ecx: &'cx mut ExtCtxt<'_>,
260         span: Span,
261         input: TokenStream,
262         _def_span: Option<Span>,
263     ) -> Box<dyn MacResult+'cx> {
264         struct AvoidInterpolatedIdents;
265
266         impl MutVisitor for AvoidInterpolatedIdents {
267             fn visit_tt(&mut self, tt: &mut tokenstream::TokenTree) {
268                 if let tokenstream::TokenTree::Token(_, token::Interpolated(nt)) = tt {
269                     if let token::NtIdent(ident, is_raw) = **nt {
270                         *tt = tokenstream::TokenTree::Token(ident.span,
271                                                             token::Ident(ident, is_raw));
272                     }
273                 }
274                 mut_visit::noop_visit_tt(tt, self)
275             }
276
277             fn visit_mac(&mut self, mac: &mut ast::Mac) {
278                 mut_visit::noop_visit_mac(mac, self)
279             }
280         }
281
282         let input: Vec<_> =
283             input.trees().map(|mut tt| { AvoidInterpolatedIdents.visit_tt(&mut tt); tt }).collect();
284         (*self)(ecx, span, &input)
285     }
286 }
287
288 pub trait IdentMacroExpander {
289     fn expand<'cx>(&self,
290                    cx: &'cx mut ExtCtxt<'_>,
291                    sp: Span,
292                    ident: ast::Ident,
293                    token_tree: Vec<tokenstream::TokenTree>)
294                    -> Box<dyn MacResult+'cx>;
295 }
296
297 pub type IdentMacroExpanderFn =
298     for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, ast::Ident, Vec<tokenstream::TokenTree>)
299                 -> Box<dyn MacResult+'cx>;
300
301 impl<F> IdentMacroExpander for F
302     where F : for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, ast::Ident,
303                           Vec<tokenstream::TokenTree>) -> Box<dyn MacResult+'cx>
304 {
305     fn expand<'cx>(&self,
306                    cx: &'cx mut ExtCtxt<'_>,
307                    sp: Span,
308                    ident: ast::Ident,
309                    token_tree: Vec<tokenstream::TokenTree>)
310                    -> Box<dyn MacResult+'cx>
311     {
312         (*self)(cx, sp, ident, token_tree)
313     }
314 }
315
316 // Use a macro because forwarding to a simple function has type system issues
317 macro_rules! make_stmts_default {
318     ($me:expr) => {
319         $me.make_expr().map(|e| smallvec![ast::Stmt {
320             id: ast::DUMMY_NODE_ID,
321             span: e.span,
322             node: ast::StmtKind::Expr(e),
323         }])
324     }
325 }
326
327 /// The result of a macro expansion. The return values of the various
328 /// methods are spliced into the AST at the callsite of the macro.
329 pub trait MacResult {
330     /// Creates an expression.
331     fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
332         None
333     }
334     /// Creates zero or more items.
335     fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
336         None
337     }
338
339     /// Creates zero or more impl items.
340     fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[ast::ImplItem; 1]>> {
341         None
342     }
343
344     /// Creates zero or more trait items.
345     fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[ast::TraitItem; 1]>> {
346         None
347     }
348
349     /// Creates zero or more items in an `extern {}` block
350     fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> { None }
351
352     /// Creates a pattern.
353     fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
354         None
355     }
356
357     /// Creates zero or more statements.
358     ///
359     /// By default this attempts to create an expression statement,
360     /// returning None if that fails.
361     fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
362         make_stmts_default!(self)
363     }
364
365     fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
366         None
367     }
368 }
369
370 macro_rules! make_MacEager {
371     ( $( $fld:ident: $t:ty, )* ) => {
372         /// `MacResult` implementation for the common case where you've already
373         /// built each form of AST that you might return.
374         #[derive(Default)]
375         pub struct MacEager {
376             $(
377                 pub $fld: Option<$t>,
378             )*
379         }
380
381         impl MacEager {
382             $(
383                 pub fn $fld(v: $t) -> Box<dyn MacResult> {
384                     Box::new(MacEager {
385                         $fld: Some(v),
386                         ..Default::default()
387                     })
388                 }
389             )*
390         }
391     }
392 }
393
394 make_MacEager! {
395     expr: P<ast::Expr>,
396     pat: P<ast::Pat>,
397     items: SmallVec<[P<ast::Item>; 1]>,
398     impl_items: SmallVec<[ast::ImplItem; 1]>,
399     trait_items: SmallVec<[ast::TraitItem; 1]>,
400     foreign_items: SmallVec<[ast::ForeignItem; 1]>,
401     stmts: SmallVec<[ast::Stmt; 1]>,
402     ty: P<ast::Ty>,
403 }
404
405 impl MacResult for MacEager {
406     fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
407         self.expr
408     }
409
410     fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
411         self.items
412     }
413
414     fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[ast::ImplItem; 1]>> {
415         self.impl_items
416     }
417
418     fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[ast::TraitItem; 1]>> {
419         self.trait_items
420     }
421
422     fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> {
423         self.foreign_items
424     }
425
426     fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
427         match self.stmts.as_ref().map_or(0, |s| s.len()) {
428             0 => make_stmts_default!(self),
429             _ => self.stmts,
430         }
431     }
432
433     fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
434         if let Some(p) = self.pat {
435             return Some(p);
436         }
437         if let Some(e) = self.expr {
438             if let ast::ExprKind::Lit(_) = e.node {
439                 return Some(P(ast::Pat {
440                     id: ast::DUMMY_NODE_ID,
441                     span: e.span,
442                     node: PatKind::Lit(e),
443                 }));
444             }
445         }
446         None
447     }
448
449     fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
450         self.ty
451     }
452 }
453
454 /// Fill-in macro expansion result, to allow compilation to continue
455 /// after hitting errors.
456 #[derive(Copy, Clone)]
457 pub struct DummyResult {
458     expr_only: bool,
459     is_error: bool,
460     span: Span,
461 }
462
463 impl DummyResult {
464     /// Creates a default MacResult that can be anything.
465     ///
466     /// Use this as a return value after hitting any errors and
467     /// calling `span_err`.
468     pub fn any(span: Span) -> Box<dyn MacResult+'static> {
469         Box::new(DummyResult { expr_only: false, is_error: true, span })
470     }
471
472     /// Same as `any`, but must be a valid fragment, not error.
473     pub fn any_valid(span: Span) -> Box<dyn MacResult+'static> {
474         Box::new(DummyResult { expr_only: false, is_error: false, span })
475     }
476
477     /// Creates a default MacResult that can only be an expression.
478     ///
479     /// Use this for macros that must expand to an expression, so even
480     /// if an error is encountered internally, the user will receive
481     /// an error that they also used it in the wrong place.
482     pub fn expr(span: Span) -> Box<dyn MacResult+'static> {
483         Box::new(DummyResult { expr_only: true, is_error: true, span })
484     }
485
486     /// A plain dummy expression.
487     pub fn raw_expr(sp: Span, is_error: bool) -> P<ast::Expr> {
488         P(ast::Expr {
489             id: ast::DUMMY_NODE_ID,
490             node: if is_error { ast::ExprKind::Err } else { ast::ExprKind::Tup(Vec::new()) },
491             span: sp,
492             attrs: ThinVec::new(),
493         })
494     }
495
496     /// A plain dummy pattern.
497     pub fn raw_pat(sp: Span) -> ast::Pat {
498         ast::Pat {
499             id: ast::DUMMY_NODE_ID,
500             node: PatKind::Wild,
501             span: sp,
502         }
503     }
504
505     /// A plain dummy type.
506     pub fn raw_ty(sp: Span, is_error: bool) -> P<ast::Ty> {
507         P(ast::Ty {
508             id: ast::DUMMY_NODE_ID,
509             node: if is_error { ast::TyKind::Err } else { ast::TyKind::Tup(Vec::new()) },
510             span: sp
511         })
512     }
513 }
514
515 impl MacResult for DummyResult {
516     fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
517         Some(DummyResult::raw_expr(self.span, self.is_error))
518     }
519
520     fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
521         Some(P(DummyResult::raw_pat(self.span)))
522     }
523
524     fn make_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
525         // this code needs a comment... why not always just return the Some() ?
526         if self.expr_only {
527             None
528         } else {
529             Some(SmallVec::new())
530         }
531     }
532
533     fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[ast::ImplItem; 1]>> {
534         if self.expr_only {
535             None
536         } else {
537             Some(SmallVec::new())
538         }
539     }
540
541     fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[ast::TraitItem; 1]>> {
542         if self.expr_only {
543             None
544         } else {
545             Some(SmallVec::new())
546         }
547     }
548
549     fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> {
550         if self.expr_only {
551             None
552         } else {
553             Some(SmallVec::new())
554         }
555     }
556
557     fn make_stmts(self: Box<DummyResult>) -> Option<SmallVec<[ast::Stmt; 1]>> {
558         Some(smallvec![ast::Stmt {
559             id: ast::DUMMY_NODE_ID,
560             node: ast::StmtKind::Expr(DummyResult::raw_expr(self.span, self.is_error)),
561             span: self.span,
562         }])
563     }
564
565     fn make_ty(self: Box<DummyResult>) -> Option<P<ast::Ty>> {
566         Some(DummyResult::raw_ty(self.span, self.is_error))
567     }
568 }
569
570 pub type BuiltinDeriveFn =
571     for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, &MetaItem, &Annotatable, &mut dyn FnMut(Annotatable));
572
573 /// Represents different kinds of macro invocations that can be resolved.
574 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
575 pub enum MacroKind {
576     /// A bang macro - foo!()
577     Bang,
578     /// An attribute macro - #[foo]
579     Attr,
580     /// A derive attribute macro - #[derive(Foo)]
581     Derive,
582     /// A view of a procedural macro from the same crate that defines it.
583     ProcMacroStub,
584 }
585
586 impl MacroKind {
587     pub fn descr(self) -> &'static str {
588         match self {
589             MacroKind::Bang => "macro",
590             MacroKind::Attr => "attribute macro",
591             MacroKind::Derive => "derive macro",
592             MacroKind::ProcMacroStub => "crate-local procedural macro",
593         }
594     }
595
596     pub fn article(self) -> &'static str {
597         match self {
598             MacroKind::Attr => "an",
599             _ => "a",
600         }
601     }
602 }
603
604 /// An enum representing the different kinds of syntax extensions.
605 pub enum SyntaxExtension {
606     /// A trivial "extension" that does nothing, only keeps the attribute and marks it as known.
607     NonMacroAttr { mark_used: bool },
608
609     /// A syntax extension that is attached to an item and creates new items
610     /// based upon it.
611     ///
612     /// `#[derive(...)]` is a `MultiItemDecorator`.
613     ///
614     /// Prefer ProcMacro or MultiModifier since they are more flexible.
615     MultiDecorator(Box<dyn MultiItemDecorator + sync::Sync + sync::Send>),
616
617     /// A syntax extension that is attached to an item and modifies it
618     /// in-place. Also allows decoration, i.e., creating new items.
619     MultiModifier(Box<dyn MultiItemModifier + sync::Sync + sync::Send>),
620
621     /// A function-like procedural macro. TokenStream -> TokenStream.
622     ProcMacro {
623         expander: Box<dyn ProcMacro + sync::Sync + sync::Send>,
624         /// Whitelist of unstable features that are treated as stable inside this macro
625         allow_internal_unstable: Option<Lrc<[Symbol]>>,
626         edition: Edition,
627     },
628
629     /// An attribute-like procedural macro. TokenStream, TokenStream -> TokenStream.
630     /// The first TokenSteam is the attribute, the second is the annotated item.
631     /// Allows modification of the input items and adding new items, similar to
632     /// MultiModifier, but uses TokenStreams, rather than AST nodes.
633     AttrProcMacro(Box<dyn AttrProcMacro + sync::Sync + sync::Send>, Edition),
634
635     /// A normal, function-like syntax extension.
636     ///
637     /// `bytes!` is a `NormalTT`.
638     NormalTT {
639         expander: Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
640         def_info: Option<(ast::NodeId, Span)>,
641         /// Whether the contents of the macro can
642         /// directly use `#[unstable]` things.
643         ///
644         /// Only allows things that require a feature gate in the given whitelist
645         allow_internal_unstable: Option<Lrc<[Symbol]>>,
646         /// Whether the contents of the macro can use `unsafe`
647         /// without triggering the `unsafe_code` lint.
648         allow_internal_unsafe: bool,
649         /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`)
650         /// for a given macro.
651         local_inner_macros: bool,
652         /// The macro's feature name if it is unstable, and the stability feature
653         unstable_feature: Option<(Symbol, u32)>,
654         /// Edition of the crate in which the macro is defined
655         edition: Edition,
656     },
657
658     /// A function-like syntax extension that has an extra ident before
659     /// the block.
660     IdentTT {
661         expander: Box<dyn IdentMacroExpander + sync::Sync + sync::Send>,
662         span: Option<Span>,
663         allow_internal_unstable: Option<Lrc<[Symbol]>>,
664     },
665
666     /// An attribute-like procedural macro. TokenStream -> TokenStream.
667     /// The input is the annotated item.
668     /// Allows generating code to implement a Trait for a given struct
669     /// or enum item.
670     ProcMacroDerive(Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
671                     Vec<Symbol> /* inert attribute names */, Edition),
672
673     /// An attribute-like procedural macro that derives a builtin trait.
674     BuiltinDerive(BuiltinDeriveFn),
675
676     /// A declarative macro, e.g., `macro m() {}`.
677     DeclMacro {
678         expander: Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
679         def_info: Option<(ast::NodeId, Span)>,
680         is_transparent: bool,
681         edition: Edition,
682     }
683 }
684
685 impl SyntaxExtension {
686     /// Returns which kind of macro calls this syntax extension.
687     pub fn kind(&self) -> MacroKind {
688         match *self {
689             SyntaxExtension::DeclMacro { .. } |
690             SyntaxExtension::NormalTT { .. } |
691             SyntaxExtension::IdentTT { .. } |
692             SyntaxExtension::ProcMacro { .. } =>
693                 MacroKind::Bang,
694             SyntaxExtension::NonMacroAttr { .. } |
695             SyntaxExtension::MultiDecorator(..) |
696             SyntaxExtension::MultiModifier(..) |
697             SyntaxExtension::AttrProcMacro(..) =>
698                 MacroKind::Attr,
699             SyntaxExtension::ProcMacroDerive(..) |
700             SyntaxExtension::BuiltinDerive(..) =>
701                 MacroKind::Derive,
702         }
703     }
704
705     pub fn default_transparency(&self) -> Transparency {
706         match *self {
707             SyntaxExtension::ProcMacro { .. } |
708             SyntaxExtension::AttrProcMacro(..) |
709             SyntaxExtension::ProcMacroDerive(..) |
710             SyntaxExtension::DeclMacro { is_transparent: false, .. } => Transparency::Opaque,
711             SyntaxExtension::DeclMacro { is_transparent: true, .. } => Transparency::Transparent,
712             _ => Transparency::SemiTransparent,
713         }
714     }
715
716     pub fn edition(&self, default_edition: Edition) -> Edition {
717         match *self {
718             SyntaxExtension::NormalTT { edition, .. } |
719             SyntaxExtension::DeclMacro { edition, .. } |
720             SyntaxExtension::ProcMacro { edition, .. } |
721             SyntaxExtension::AttrProcMacro(.., edition) |
722             SyntaxExtension::ProcMacroDerive(.., edition) => edition,
723             // Unstable legacy stuff
724             SyntaxExtension::NonMacroAttr { .. } |
725             SyntaxExtension::IdentTT { .. } |
726             SyntaxExtension::MultiDecorator(..) |
727             SyntaxExtension::MultiModifier(..) |
728             SyntaxExtension::BuiltinDerive(..) => default_edition,
729         }
730     }
731 }
732
733 pub type NamedSyntaxExtension = (Name, SyntaxExtension);
734
735 pub trait Resolver {
736     fn next_node_id(&mut self) -> ast::NodeId;
737
738     fn get_module_scope(&mut self, id: ast::NodeId) -> Mark;
739
740     fn resolve_dollar_crates(&mut self, fragment: &AstFragment);
741     fn visit_ast_fragment_with_placeholders(&mut self, mark: Mark, fragment: &AstFragment,
742                                             derives: &[Mark]);
743     fn add_builtin(&mut self, ident: ast::Ident, ext: Lrc<SyntaxExtension>);
744
745     fn resolve_imports(&mut self);
746
747     fn resolve_macro_invocation(&mut self, invoc: &Invocation, invoc_id: Mark, force: bool)
748                                 -> Result<Option<Lrc<SyntaxExtension>>, Determinacy>;
749     fn resolve_macro_path(&mut self, path: &ast::Path, kind: MacroKind, invoc_id: Mark,
750                           derives_in_scope: Vec<ast::Path>, force: bool)
751                           -> Result<Lrc<SyntaxExtension>, Determinacy>;
752
753     fn check_unused_macros(&self);
754 }
755
756 #[derive(Copy, Clone, PartialEq, Debug)]
757 pub enum Determinacy {
758     Determined,
759     Undetermined,
760 }
761
762 impl Determinacy {
763     pub fn determined(determined: bool) -> Determinacy {
764         if determined { Determinacy::Determined } else { Determinacy::Undetermined }
765     }
766 }
767
768 pub struct DummyResolver;
769
770 impl Resolver for DummyResolver {
771     fn next_node_id(&mut self) -> ast::NodeId { ast::DUMMY_NODE_ID }
772
773     fn get_module_scope(&mut self, _id: ast::NodeId) -> Mark { Mark::root() }
774
775     fn resolve_dollar_crates(&mut self, _fragment: &AstFragment) {}
776     fn visit_ast_fragment_with_placeholders(&mut self, _invoc: Mark, _fragment: &AstFragment,
777                                             _derives: &[Mark]) {}
778     fn add_builtin(&mut self, _ident: ast::Ident, _ext: Lrc<SyntaxExtension>) {}
779
780     fn resolve_imports(&mut self) {}
781     fn resolve_macro_invocation(&mut self, _invoc: &Invocation, _invoc_id: Mark, _force: bool)
782                                 -> Result<Option<Lrc<SyntaxExtension>>, Determinacy> {
783         Err(Determinacy::Determined)
784     }
785     fn resolve_macro_path(&mut self, _path: &ast::Path, _kind: MacroKind, _invoc_id: Mark,
786                           _derives_in_scope: Vec<ast::Path>, _force: bool)
787                           -> Result<Lrc<SyntaxExtension>, Determinacy> {
788         Err(Determinacy::Determined)
789     }
790     fn check_unused_macros(&self) {}
791 }
792
793 #[derive(Clone)]
794 pub struct ModuleData {
795     pub mod_path: Vec<ast::Ident>,
796     pub directory: PathBuf,
797 }
798
799 #[derive(Clone)]
800 pub struct ExpansionData {
801     pub mark: Mark,
802     pub depth: usize,
803     pub module: Rc<ModuleData>,
804     pub directory_ownership: DirectoryOwnership,
805     pub crate_span: Option<Span>,
806 }
807
808 /// One of these is made during expansion and incrementally updated as we go;
809 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
810 /// -> expn_info` of their expansion context stored into their span.
811 pub struct ExtCtxt<'a> {
812     pub parse_sess: &'a parse::ParseSess,
813     pub ecfg: expand::ExpansionConfig<'a>,
814     pub root_path: PathBuf,
815     pub resolver: &'a mut dyn Resolver,
816     pub current_expansion: ExpansionData,
817     pub expansions: FxHashMap<Span, Vec<String>>,
818 }
819
820 impl<'a> ExtCtxt<'a> {
821     pub fn new(parse_sess: &'a parse::ParseSess,
822                ecfg: expand::ExpansionConfig<'a>,
823                resolver: &'a mut dyn Resolver)
824                -> ExtCtxt<'a> {
825         ExtCtxt {
826             parse_sess,
827             ecfg,
828             root_path: PathBuf::new(),
829             resolver,
830             current_expansion: ExpansionData {
831                 mark: Mark::root(),
832                 depth: 0,
833                 module: Rc::new(ModuleData { mod_path: Vec::new(), directory: PathBuf::new() }),
834                 directory_ownership: DirectoryOwnership::Owned { relative: None },
835                 crate_span: None,
836             },
837             expansions: FxHashMap::default(),
838         }
839     }
840
841     /// Returns a `Folder` for deeply expanding all macros in an AST node.
842     pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
843         expand::MacroExpander::new(self, false)
844     }
845
846     /// Returns a `Folder` that deeply expands all macros and assigns all `NodeId`s in an AST node.
847     /// Once `NodeId`s are assigned, the node may not be expanded, removed, or otherwise modified.
848     pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
849         expand::MacroExpander::new(self, true)
850     }
851
852     pub fn new_parser_from_tts(&self, tts: &[tokenstream::TokenTree]) -> parser::Parser<'a> {
853         parse::stream_to_parser(self.parse_sess, tts.iter().cloned().collect(), MACRO_ARGUMENTS)
854     }
855     pub fn source_map(&self) -> &'a SourceMap { self.parse_sess.source_map() }
856     pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
857     pub fn cfg(&self) -> &ast::CrateConfig { &self.parse_sess.config }
858     pub fn call_site(&self) -> Span {
859         match self.current_expansion.mark.expn_info() {
860             Some(expn_info) => expn_info.call_site,
861             None => DUMMY_SP,
862         }
863     }
864     pub fn backtrace(&self) -> SyntaxContext {
865         SyntaxContext::empty().apply_mark(self.current_expansion.mark)
866     }
867
868     /// Returns span for the macro which originally caused the current expansion to happen.
869     ///
870     /// Stops backtracing at include! boundary.
871     pub fn expansion_cause(&self) -> Option<Span> {
872         let mut ctxt = self.backtrace();
873         let mut last_macro = None;
874         loop {
875             if ctxt.outer_expn_info().map_or(None, |info| {
876                 if info.format.name() == sym::include {
877                     // Stop going up the backtrace once include! is encountered
878                     return None;
879                 }
880                 ctxt = info.call_site.ctxt();
881                 last_macro = Some(info.call_site);
882                 Some(())
883             }).is_none() {
884                 break
885             }
886         }
887         last_macro
888     }
889
890     pub fn struct_span_warn<S: Into<MultiSpan>>(&self,
891                                                 sp: S,
892                                                 msg: &str)
893                                                 -> DiagnosticBuilder<'a> {
894         self.parse_sess.span_diagnostic.struct_span_warn(sp, msg)
895     }
896     pub fn struct_span_err<S: Into<MultiSpan>>(&self,
897                                                sp: S,
898                                                msg: &str)
899                                                -> DiagnosticBuilder<'a> {
900         self.parse_sess.span_diagnostic.struct_span_err(sp, msg)
901     }
902     pub fn struct_span_fatal<S: Into<MultiSpan>>(&self,
903                                                  sp: S,
904                                                  msg: &str)
905                                                  -> DiagnosticBuilder<'a> {
906         self.parse_sess.span_diagnostic.struct_span_fatal(sp, msg)
907     }
908
909     /// Emit `msg` attached to `sp`, and stop compilation immediately.
910     ///
911     /// `span_err` should be strongly preferred where-ever possible:
912     /// this should *only* be used when:
913     ///
914     /// - continuing has a high risk of flow-on errors (e.g., errors in
915     ///   declaring a macro would cause all uses of that macro to
916     ///   complain about "undefined macro"), or
917     /// - there is literally nothing else that can be done (however,
918     ///   in most cases one can construct a dummy expression/item to
919     ///   substitute; we never hit resolve/type-checking so the dummy
920     ///   value doesn't have to match anything)
921     pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
922         self.parse_sess.span_diagnostic.span_fatal(sp, msg).raise();
923     }
924
925     /// Emit `msg` attached to `sp`, without immediately stopping
926     /// compilation.
927     ///
928     /// Compilation will be stopped in the near future (at the end of
929     /// the macro expansion phase).
930     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
931         self.parse_sess.span_diagnostic.span_err(sp, msg);
932     }
933     pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
934         self.parse_sess.span_diagnostic.span_err_with_code(sp, msg, code);
935     }
936     pub fn mut_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str)
937                         -> DiagnosticBuilder<'a> {
938         self.parse_sess.span_diagnostic.mut_span_err(sp, msg)
939     }
940     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
941         self.parse_sess.span_diagnostic.span_warn(sp, msg);
942     }
943     pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
944         self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
945     }
946     pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
947         self.parse_sess.span_diagnostic.span_bug(sp, msg);
948     }
949     pub fn trace_macros_diag(&mut self) {
950         for (sp, notes) in self.expansions.iter() {
951             let mut db = self.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
952             for note in notes {
953                 db.note(note);
954             }
955             db.emit();
956         }
957         // Fixme: does this result in errors?
958         self.expansions.clear();
959     }
960     pub fn bug(&self, msg: &str) -> ! {
961         self.parse_sess.span_diagnostic.bug(msg);
962     }
963     pub fn trace_macros(&self) -> bool {
964         self.ecfg.trace_mac
965     }
966     pub fn set_trace_macros(&mut self, x: bool) {
967         self.ecfg.trace_mac = x
968     }
969     pub fn ident_of(&self, st: &str) -> ast::Ident {
970         ast::Ident::from_str(st)
971     }
972     pub fn std_path(&self, components: &[Symbol]) -> Vec<ast::Ident> {
973         let def_site = DUMMY_SP.apply_mark(self.current_expansion.mark);
974         iter::once(Ident::new(kw::DollarCrate, def_site))
975             .chain(components.iter().map(|&s| Ident::with_empty_ctxt(s)))
976             .collect()
977     }
978     pub fn name_of(&self, st: &str) -> ast::Name {
979         Symbol::intern(st)
980     }
981
982     pub fn check_unused_macros(&self) {
983         self.resolver.check_unused_macros();
984     }
985 }
986
987 /// Extracts a string literal from the macro expanded version of `expr`,
988 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
989 /// compilation on error, merely emits a non-fatal error and returns `None`.
990 pub fn expr_to_spanned_string<'a>(
991     cx: &'a mut ExtCtxt<'_>,
992     mut expr: P<ast::Expr>,
993     err_msg: &str,
994 ) -> Result<Spanned<(Symbol, ast::StrStyle)>, Option<DiagnosticBuilder<'a>>> {
995     // Update `expr.span`'s ctxt now in case expr is an `include!` macro invocation.
996     expr.span = expr.span.apply_mark(cx.current_expansion.mark);
997
998     // we want to be able to handle e.g., `concat!("foo", "bar")`
999     cx.expander().visit_expr(&mut expr);
1000     Err(match expr.node {
1001         ast::ExprKind::Lit(ref l) => match l.node {
1002             ast::LitKind::Str(s, style) => return Ok(respan(expr.span, (s, style))),
1003             ast::LitKind::Err(_) => None,
1004             _ => Some(cx.struct_span_err(l.span, err_msg))
1005         },
1006         ast::ExprKind::Err => None,
1007         _ => Some(cx.struct_span_err(expr.span, err_msg))
1008     })
1009 }
1010
1011 pub fn expr_to_string(cx: &mut ExtCtxt<'_>, expr: P<ast::Expr>, err_msg: &str)
1012                       -> Option<(Symbol, ast::StrStyle)> {
1013     expr_to_spanned_string(cx, expr, err_msg)
1014         .map_err(|err| err.map(|mut err| err.emit()))
1015         .ok()
1016         .map(|s| s.node)
1017 }
1018
1019 /// Non-fatally assert that `tts` is empty. Note that this function
1020 /// returns even when `tts` is non-empty, macros that *need* to stop
1021 /// compilation should call
1022 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
1023 /// done as rarely as possible).
1024 pub fn check_zero_tts(cx: &ExtCtxt<'_>,
1025                       sp: Span,
1026                       tts: &[tokenstream::TokenTree],
1027                       name: &str) {
1028     if !tts.is_empty() {
1029         cx.span_err(sp, &format!("{} takes no arguments", name));
1030     }
1031 }
1032
1033 /// Interpreting `tts` as a comma-separated sequence of expressions,
1034 /// expect exactly one string literal, or emit an error and return `None`.
1035 pub fn get_single_str_from_tts(cx: &mut ExtCtxt<'_>,
1036                                sp: Span,
1037                                tts: &[tokenstream::TokenTree],
1038                                name: &str)
1039                                -> Option<String> {
1040     let mut p = cx.new_parser_from_tts(tts);
1041     if p.token == token::Eof {
1042         cx.span_err(sp, &format!("{} takes 1 argument", name));
1043         return None
1044     }
1045     let ret = panictry!(p.parse_expr());
1046     let _ = p.eat(&token::Comma);
1047
1048     if p.token != token::Eof {
1049         cx.span_err(sp, &format!("{} takes 1 argument", name));
1050     }
1051     expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
1052         s.to_string()
1053     })
1054 }
1055
1056 /// Extracts comma-separated expressions from `tts`. If there is a
1057 /// parsing error, emit a non-fatal error and return `None`.
1058 pub fn get_exprs_from_tts(cx: &mut ExtCtxt<'_>,
1059                           sp: Span,
1060                           tts: &[tokenstream::TokenTree]) -> Option<Vec<P<ast::Expr>>> {
1061     let mut p = cx.new_parser_from_tts(tts);
1062     let mut es = Vec::new();
1063     while p.token != token::Eof {
1064         let mut expr = panictry!(p.parse_expr());
1065         cx.expander().visit_expr(&mut expr);
1066         es.push(expr);
1067         if p.eat(&token::Comma) {
1068             continue;
1069         }
1070         if p.token != token::Eof {
1071             cx.span_err(sp, "expected token: `,`");
1072             return None;
1073         }
1074     }
1075     Some(es)
1076 }