]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/base.rs
libsyntax: Remove `Mark` into `ExpnId`
[rust.git] / src / libsyntax / ext / base.rs
1 use crate::ast::{self, Attribute, Name, PatKind};
2 use crate::attr::{HasAttrs, Stability, Deprecation};
3 use crate::source_map::{SourceMap, Spanned, respan};
4 use crate::edition::Edition;
5 use crate::ext::expand::{self, AstFragment, Invocation};
6 use crate::ext::hygiene::{ExpnId, SyntaxContext, Transparency};
7 use crate::mut_visit::{self, MutVisitor};
8 use crate::parse::{self, parser, 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, TokenTree};
14
15 use errors::{DiagnosticBuilder, DiagnosticId};
16 use smallvec::{smallvec, SmallVec};
17 use syntax_pos::{Span, MultiSpan, DUMMY_SP};
18 use syntax_pos::hygiene::{ExpnInfo, ExpnKind};
19
20 use rustc_data_structures::fx::FxHashMap;
21 use rustc_data_structures::sync::{self, Lrc};
22 use std::iter;
23 use std::path::PathBuf;
24 use std::rc::Rc;
25 use std::default::Default;
26
27 pub use syntax_pos::hygiene::MacroKind;
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 // `meta_item` is the annotation, and `item` is the item being modified.
141 // FIXME Decorators should follow the same pattern too.
142 pub trait MultiItemModifier {
143     fn expand(&self,
144               ecx: &mut ExtCtxt<'_>,
145               span: Span,
146               meta_item: &ast::MetaItem,
147               item: Annotatable)
148               -> Vec<Annotatable>;
149 }
150
151 impl<F, T> MultiItemModifier for F
152     where F: Fn(&mut ExtCtxt<'_>, Span, &ast::MetaItem, Annotatable) -> T,
153           T: Into<Vec<Annotatable>>,
154 {
155     fn expand(&self,
156               ecx: &mut ExtCtxt<'_>,
157               span: Span,
158               meta_item: &ast::MetaItem,
159               item: Annotatable)
160               -> Vec<Annotatable> {
161         (*self)(ecx, span, meta_item, item).into()
162     }
163 }
164
165 impl Into<Vec<Annotatable>> for Annotatable {
166     fn into(self) -> Vec<Annotatable> {
167         vec![self]
168     }
169 }
170
171 pub trait ProcMacro {
172     fn expand<'cx>(&self,
173                    ecx: &'cx mut ExtCtxt<'_>,
174                    span: Span,
175                    ts: TokenStream)
176                    -> TokenStream;
177 }
178
179 impl<F> ProcMacro for F
180     where F: Fn(TokenStream) -> TokenStream
181 {
182     fn expand<'cx>(&self,
183                    _ecx: &'cx mut ExtCtxt<'_>,
184                    _span: Span,
185                    ts: TokenStream)
186                    -> TokenStream {
187         // FIXME setup implicit context in TLS before calling self.
188         (*self)(ts)
189     }
190 }
191
192 pub trait AttrProcMacro {
193     fn expand<'cx>(&self,
194                    ecx: &'cx mut ExtCtxt<'_>,
195                    span: Span,
196                    annotation: TokenStream,
197                    annotated: TokenStream)
198                    -> TokenStream;
199 }
200
201 impl<F> AttrProcMacro for F
202     where F: Fn(TokenStream, TokenStream) -> TokenStream
203 {
204     fn expand<'cx>(&self,
205                    _ecx: &'cx mut ExtCtxt<'_>,
206                    _span: Span,
207                    annotation: TokenStream,
208                    annotated: TokenStream)
209                    -> TokenStream {
210         // FIXME setup implicit context in TLS before calling self.
211         (*self)(annotation, annotated)
212     }
213 }
214
215 /// Represents a thing that maps token trees to Macro Results
216 pub trait TTMacroExpander {
217     fn expand<'cx>(
218         &self,
219         ecx: &'cx mut ExtCtxt<'_>,
220         span: Span,
221         input: TokenStream,
222     ) -> Box<dyn MacResult+'cx>;
223 }
224
225 pub type MacroExpanderFn =
226     for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, &[tokenstream::TokenTree])
227                 -> Box<dyn MacResult+'cx>;
228
229 impl<F> TTMacroExpander for F
230     where F: for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, &[tokenstream::TokenTree])
231     -> Box<dyn MacResult+'cx>
232 {
233     fn expand<'cx>(
234         &self,
235         ecx: &'cx mut ExtCtxt<'_>,
236         span: Span,
237         input: TokenStream,
238     ) -> Box<dyn MacResult+'cx> {
239         struct AvoidInterpolatedIdents;
240
241         impl MutVisitor for AvoidInterpolatedIdents {
242             fn visit_tt(&mut self, tt: &mut tokenstream::TokenTree) {
243                 if let tokenstream::TokenTree::Token(token) = tt {
244                     if let token::Interpolated(nt) = &token.kind {
245                         if let token::NtIdent(ident, is_raw) = **nt {
246                             *tt = tokenstream::TokenTree::token(
247                                 token::Ident(ident.name, is_raw), ident.span
248                             );
249                         }
250                     }
251                 }
252                 mut_visit::noop_visit_tt(tt, self)
253             }
254
255             fn visit_mac(&mut self, mac: &mut ast::Mac) {
256                 mut_visit::noop_visit_mac(mac, self)
257             }
258         }
259
260         let input: Vec<_> =
261             input.trees().map(|mut tt| { AvoidInterpolatedIdents.visit_tt(&mut tt); tt }).collect();
262         (*self)(ecx, span, &input)
263     }
264 }
265
266 // Use a macro because forwarding to a simple function has type system issues
267 macro_rules! make_stmts_default {
268     ($me:expr) => {
269         $me.make_expr().map(|e| smallvec![ast::Stmt {
270             id: ast::DUMMY_NODE_ID,
271             span: e.span,
272             node: ast::StmtKind::Expr(e),
273         }])
274     }
275 }
276
277 /// The result of a macro expansion. The return values of the various
278 /// methods are spliced into the AST at the callsite of the macro.
279 pub trait MacResult {
280     /// Creates an expression.
281     fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
282         None
283     }
284     /// Creates zero or more items.
285     fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
286         None
287     }
288
289     /// Creates zero or more impl items.
290     fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[ast::ImplItem; 1]>> {
291         None
292     }
293
294     /// Creates zero or more trait items.
295     fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[ast::TraitItem; 1]>> {
296         None
297     }
298
299     /// Creates zero or more items in an `extern {}` block
300     fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> { None }
301
302     /// Creates a pattern.
303     fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
304         None
305     }
306
307     /// Creates zero or more statements.
308     ///
309     /// By default this attempts to create an expression statement,
310     /// returning None if that fails.
311     fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
312         make_stmts_default!(self)
313     }
314
315     fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
316         None
317     }
318 }
319
320 macro_rules! make_MacEager {
321     ( $( $fld:ident: $t:ty, )* ) => {
322         /// `MacResult` implementation for the common case where you've already
323         /// built each form of AST that you might return.
324         #[derive(Default)]
325         pub struct MacEager {
326             $(
327                 pub $fld: Option<$t>,
328             )*
329         }
330
331         impl MacEager {
332             $(
333                 pub fn $fld(v: $t) -> Box<dyn MacResult> {
334                     Box::new(MacEager {
335                         $fld: Some(v),
336                         ..Default::default()
337                     })
338                 }
339             )*
340         }
341     }
342 }
343
344 make_MacEager! {
345     expr: P<ast::Expr>,
346     pat: P<ast::Pat>,
347     items: SmallVec<[P<ast::Item>; 1]>,
348     impl_items: SmallVec<[ast::ImplItem; 1]>,
349     trait_items: SmallVec<[ast::TraitItem; 1]>,
350     foreign_items: SmallVec<[ast::ForeignItem; 1]>,
351     stmts: SmallVec<[ast::Stmt; 1]>,
352     ty: P<ast::Ty>,
353 }
354
355 impl MacResult for MacEager {
356     fn make_expr(self: Box<Self>) -> Option<P<ast::Expr>> {
357         self.expr
358     }
359
360     fn make_items(self: Box<Self>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
361         self.items
362     }
363
364     fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[ast::ImplItem; 1]>> {
365         self.impl_items
366     }
367
368     fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[ast::TraitItem; 1]>> {
369         self.trait_items
370     }
371
372     fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> {
373         self.foreign_items
374     }
375
376     fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
377         match self.stmts.as_ref().map_or(0, |s| s.len()) {
378             0 => make_stmts_default!(self),
379             _ => self.stmts,
380         }
381     }
382
383     fn make_pat(self: Box<Self>) -> Option<P<ast::Pat>> {
384         if let Some(p) = self.pat {
385             return Some(p);
386         }
387         if let Some(e) = self.expr {
388             if let ast::ExprKind::Lit(_) = e.node {
389                 return Some(P(ast::Pat {
390                     id: ast::DUMMY_NODE_ID,
391                     span: e.span,
392                     node: PatKind::Lit(e),
393                 }));
394             }
395         }
396         None
397     }
398
399     fn make_ty(self: Box<Self>) -> Option<P<ast::Ty>> {
400         self.ty
401     }
402 }
403
404 /// Fill-in macro expansion result, to allow compilation to continue
405 /// after hitting errors.
406 #[derive(Copy, Clone)]
407 pub struct DummyResult {
408     expr_only: bool,
409     is_error: bool,
410     span: Span,
411 }
412
413 impl DummyResult {
414     /// Creates a default MacResult that can be anything.
415     ///
416     /// Use this as a return value after hitting any errors and
417     /// calling `span_err`.
418     pub fn any(span: Span) -> Box<dyn MacResult+'static> {
419         Box::new(DummyResult { expr_only: false, is_error: true, span })
420     }
421
422     /// Same as `any`, but must be a valid fragment, not error.
423     pub fn any_valid(span: Span) -> Box<dyn MacResult+'static> {
424         Box::new(DummyResult { expr_only: false, is_error: false, span })
425     }
426
427     /// Creates a default MacResult that can only be an expression.
428     ///
429     /// Use this for macros that must expand to an expression, so even
430     /// if an error is encountered internally, the user will receive
431     /// an error that they also used it in the wrong place.
432     pub fn expr(span: Span) -> Box<dyn MacResult+'static> {
433         Box::new(DummyResult { expr_only: true, is_error: true, span })
434     }
435
436     /// A plain dummy expression.
437     pub fn raw_expr(sp: Span, is_error: bool) -> P<ast::Expr> {
438         P(ast::Expr {
439             id: ast::DUMMY_NODE_ID,
440             node: if is_error { ast::ExprKind::Err } else { ast::ExprKind::Tup(Vec::new()) },
441             span: sp,
442             attrs: ThinVec::new(),
443         })
444     }
445
446     /// A plain dummy pattern.
447     pub fn raw_pat(sp: Span) -> ast::Pat {
448         ast::Pat {
449             id: ast::DUMMY_NODE_ID,
450             node: PatKind::Wild,
451             span: sp,
452         }
453     }
454
455     /// A plain dummy type.
456     pub fn raw_ty(sp: Span, is_error: bool) -> P<ast::Ty> {
457         P(ast::Ty {
458             id: ast::DUMMY_NODE_ID,
459             node: if is_error { ast::TyKind::Err } else { ast::TyKind::Tup(Vec::new()) },
460             span: sp
461         })
462     }
463 }
464
465 impl MacResult for DummyResult {
466     fn make_expr(self: Box<DummyResult>) -> Option<P<ast::Expr>> {
467         Some(DummyResult::raw_expr(self.span, self.is_error))
468     }
469
470     fn make_pat(self: Box<DummyResult>) -> Option<P<ast::Pat>> {
471         Some(P(DummyResult::raw_pat(self.span)))
472     }
473
474     fn make_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
475         // this code needs a comment... why not always just return the Some() ?
476         if self.expr_only {
477             None
478         } else {
479             Some(SmallVec::new())
480         }
481     }
482
483     fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[ast::ImplItem; 1]>> {
484         if self.expr_only {
485             None
486         } else {
487             Some(SmallVec::new())
488         }
489     }
490
491     fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[ast::TraitItem; 1]>> {
492         if self.expr_only {
493             None
494         } else {
495             Some(SmallVec::new())
496         }
497     }
498
499     fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> {
500         if self.expr_only {
501             None
502         } else {
503             Some(SmallVec::new())
504         }
505     }
506
507     fn make_stmts(self: Box<DummyResult>) -> Option<SmallVec<[ast::Stmt; 1]>> {
508         Some(smallvec![ast::Stmt {
509             id: ast::DUMMY_NODE_ID,
510             node: ast::StmtKind::Expr(DummyResult::raw_expr(self.span, self.is_error)),
511             span: self.span,
512         }])
513     }
514
515     fn make_ty(self: Box<DummyResult>) -> Option<P<ast::Ty>> {
516         Some(DummyResult::raw_ty(self.span, self.is_error))
517     }
518 }
519
520 /// A syntax extension kind.
521 pub enum SyntaxExtensionKind {
522     /// A token-based function-like macro.
523     Bang(
524         /// An expander with signature TokenStream -> TokenStream.
525         Box<dyn ProcMacro + sync::Sync + sync::Send>,
526     ),
527
528     /// An AST-based function-like macro.
529     LegacyBang(
530         /// An expander with signature TokenStream -> AST.
531         Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
532     ),
533
534     /// A token-based attribute macro.
535     Attr(
536         /// An expander with signature (TokenStream, TokenStream) -> TokenStream.
537         /// The first TokenSteam is the attribute itself, the second is the annotated item.
538         /// The produced TokenSteam replaces the input TokenSteam.
539         Box<dyn AttrProcMacro + sync::Sync + sync::Send>,
540     ),
541
542     /// An AST-based attribute macro.
543     LegacyAttr(
544         /// An expander with signature (AST, AST) -> AST.
545         /// The first AST fragment is the attribute itself, the second is the annotated item.
546         /// The produced AST fragment replaces the input AST fragment.
547         Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
548     ),
549
550     /// A trivial attribute "macro" that does nothing,
551     /// only keeps the attribute and marks it as inert,
552     /// thus making it ineligible for further expansion.
553     NonMacroAttr {
554         /// Suppresses the `unused_attributes` lint for this attribute.
555         mark_used: bool,
556     },
557
558     /// A token-based derive macro.
559     Derive(
560         /// An expander with signature TokenStream -> TokenStream (not yet).
561         /// The produced TokenSteam is appended to the input TokenSteam.
562         Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
563     ),
564
565     /// An AST-based derive macro.
566     LegacyDerive(
567         /// An expander with signature AST -> AST.
568         /// The produced AST fragment is appended to the input AST fragment.
569         Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
570     ),
571 }
572
573 /// A struct representing a macro definition in "lowered" form ready for expansion.
574 pub struct SyntaxExtension {
575     /// A syntax extension kind.
576     pub kind: SyntaxExtensionKind,
577     /// Span of the macro definition.
578     pub span: Span,
579     /// Hygienic properties of spans produced by this macro by default.
580     pub default_transparency: Transparency,
581     /// Whitelist of unstable features that are treated as stable inside this macro.
582     pub allow_internal_unstable: Option<Lrc<[Symbol]>>,
583     /// Suppresses the `unsafe_code` lint for code produced by this macro.
584     pub allow_internal_unsafe: bool,
585     /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`) for this macro.
586     pub local_inner_macros: bool,
587     /// The macro's stability info.
588     pub stability: Option<Stability>,
589     /// The macro's deprecation info.
590     pub deprecation: Option<Deprecation>,
591     /// Names of helper attributes registered by this macro.
592     pub helper_attrs: Vec<Symbol>,
593     /// Edition of the crate in which this macro is defined.
594     pub edition: Edition,
595 }
596
597 impl SyntaxExtensionKind {
598     /// When a syntax extension is constructed,
599     /// its transparency can often be inferred from its kind.
600     fn default_transparency(&self) -> Transparency {
601         match self {
602             SyntaxExtensionKind::Bang(..) |
603             SyntaxExtensionKind::Attr(..) |
604             SyntaxExtensionKind::Derive(..) |
605             SyntaxExtensionKind::NonMacroAttr { .. } => Transparency::Opaque,
606             SyntaxExtensionKind::LegacyBang(..) |
607             SyntaxExtensionKind::LegacyAttr(..) |
608             SyntaxExtensionKind::LegacyDerive(..) => Transparency::SemiTransparent,
609         }
610     }
611 }
612
613 impl SyntaxExtension {
614     /// Returns which kind of macro calls this syntax extension.
615     pub fn macro_kind(&self) -> MacroKind {
616         match self.kind {
617             SyntaxExtensionKind::Bang(..) |
618             SyntaxExtensionKind::LegacyBang(..) => MacroKind::Bang,
619             SyntaxExtensionKind::Attr(..) |
620             SyntaxExtensionKind::LegacyAttr(..) |
621             SyntaxExtensionKind::NonMacroAttr { .. } => MacroKind::Attr,
622             SyntaxExtensionKind::Derive(..) |
623             SyntaxExtensionKind::LegacyDerive(..) => MacroKind::Derive,
624         }
625     }
626
627     /// Constructs a syntax extension with default properties.
628     pub fn default(kind: SyntaxExtensionKind, edition: Edition) -> SyntaxExtension {
629         SyntaxExtension {
630             span: DUMMY_SP,
631             default_transparency: kind.default_transparency(),
632             allow_internal_unstable: None,
633             allow_internal_unsafe: false,
634             local_inner_macros: false,
635             stability: None,
636             deprecation: None,
637             helper_attrs: Vec::new(),
638             edition,
639             kind,
640         }
641     }
642
643     pub fn dummy_bang(edition: Edition) -> SyntaxExtension {
644         fn expander<'cx>(_: &'cx mut ExtCtxt<'_>, span: Span, _: &[TokenTree])
645                          -> Box<dyn MacResult + 'cx> {
646             DummyResult::any(span)
647         }
648         SyntaxExtension::default(SyntaxExtensionKind::LegacyBang(Box::new(expander)), edition)
649     }
650
651     pub fn dummy_derive(edition: Edition) -> SyntaxExtension {
652         fn expander(_: &mut ExtCtxt<'_>, _: Span, _: &ast::MetaItem, _: Annotatable)
653                     -> Vec<Annotatable> {
654             Vec::new()
655         }
656         SyntaxExtension::default(SyntaxExtensionKind::Derive(Box::new(expander)), edition)
657     }
658
659     pub fn non_macro_attr(mark_used: bool, edition: Edition) -> SyntaxExtension {
660         SyntaxExtension::default(SyntaxExtensionKind::NonMacroAttr { mark_used }, edition)
661     }
662
663     pub fn expn_info(&self, call_site: Span, descr: Symbol) -> ExpnInfo {
664         ExpnInfo {
665             call_site,
666             kind: ExpnKind::Macro(self.macro_kind(), descr),
667             def_site: self.span,
668             default_transparency: self.default_transparency,
669             allow_internal_unstable: self.allow_internal_unstable.clone(),
670             allow_internal_unsafe: self.allow_internal_unsafe,
671             local_inner_macros: self.local_inner_macros,
672             edition: self.edition,
673         }
674     }
675 }
676
677 pub type NamedSyntaxExtension = (Name, SyntaxExtension);
678
679 /// Error type that denotes indeterminacy.
680 pub struct Indeterminate;
681
682 pub trait Resolver {
683     fn next_node_id(&mut self) -> ast::NodeId;
684
685     fn get_module_scope(&mut self, id: ast::NodeId) -> ExpnId;
686
687     fn resolve_dollar_crates(&mut self);
688     fn visit_ast_fragment_with_placeholders(&mut self, mark: ExpnId, fragment: &AstFragment,
689                                             derives: &[ExpnId]);
690     fn add_builtin(&mut self, ident: ast::Ident, ext: Lrc<SyntaxExtension>);
691
692     fn resolve_imports(&mut self);
693
694     fn resolve_macro_invocation(&mut self, invoc: &Invocation, invoc_id: ExpnId, force: bool)
695                                 -> Result<Option<Lrc<SyntaxExtension>>, Indeterminate>;
696
697     fn check_unused_macros(&self);
698 }
699
700 #[derive(Clone)]
701 pub struct ModuleData {
702     pub mod_path: Vec<ast::Ident>,
703     pub directory: PathBuf,
704 }
705
706 #[derive(Clone)]
707 pub struct ExpansionData {
708     pub mark: ExpnId,
709     pub depth: usize,
710     pub module: Rc<ModuleData>,
711     pub directory_ownership: DirectoryOwnership,
712 }
713
714 /// One of these is made during expansion and incrementally updated as we go;
715 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
716 /// -> expn_info` of their expansion context stored into their span.
717 pub struct ExtCtxt<'a> {
718     pub parse_sess: &'a parse::ParseSess,
719     pub ecfg: expand::ExpansionConfig<'a>,
720     pub root_path: PathBuf,
721     pub resolver: &'a mut dyn Resolver,
722     pub current_expansion: ExpansionData,
723     pub expansions: FxHashMap<Span, Vec<String>>,
724     pub allow_derive_markers: Lrc<[Symbol]>,
725 }
726
727 impl<'a> ExtCtxt<'a> {
728     pub fn new(parse_sess: &'a parse::ParseSess,
729                ecfg: expand::ExpansionConfig<'a>,
730                resolver: &'a mut dyn Resolver)
731                -> ExtCtxt<'a> {
732         ExtCtxt {
733             parse_sess,
734             ecfg,
735             root_path: PathBuf::new(),
736             resolver,
737             current_expansion: ExpansionData {
738                 mark: ExpnId::root(),
739                 depth: 0,
740                 module: Rc::new(ModuleData { mod_path: Vec::new(), directory: PathBuf::new() }),
741                 directory_ownership: DirectoryOwnership::Owned { relative: None },
742             },
743             expansions: FxHashMap::default(),
744             allow_derive_markers: [sym::rustc_attrs, sym::structural_match][..].into(),
745         }
746     }
747
748     /// Returns a `Folder` for deeply expanding all macros in an AST node.
749     pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
750         expand::MacroExpander::new(self, false)
751     }
752
753     /// Returns a `Folder` that deeply expands all macros and assigns all `NodeId`s in an AST node.
754     /// Once `NodeId`s are assigned, the node may not be expanded, removed, or otherwise modified.
755     pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
756         expand::MacroExpander::new(self, true)
757     }
758
759     pub fn new_parser_from_tts(&self, tts: &[tokenstream::TokenTree]) -> parser::Parser<'a> {
760         parse::stream_to_parser(self.parse_sess, tts.iter().cloned().collect(), MACRO_ARGUMENTS)
761     }
762     pub fn source_map(&self) -> &'a SourceMap { self.parse_sess.source_map() }
763     pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
764     pub fn cfg(&self) -> &ast::CrateConfig { &self.parse_sess.config }
765     pub fn call_site(&self) -> Span {
766         match self.current_expansion.mark.expn_info() {
767             Some(expn_info) => expn_info.call_site,
768             None => DUMMY_SP,
769         }
770     }
771     pub fn backtrace(&self) -> SyntaxContext {
772         SyntaxContext::empty().apply_mark(self.current_expansion.mark)
773     }
774
775     /// Returns span for the macro which originally caused the current expansion to happen.
776     ///
777     /// Stops backtracing at include! boundary.
778     pub fn expansion_cause(&self) -> Option<Span> {
779         let mut ctxt = self.backtrace();
780         let mut last_macro = None;
781         loop {
782             if ctxt.outer_expn_info().map_or(None, |info| {
783                 if info.kind.descr() == sym::include {
784                     // Stop going up the backtrace once include! is encountered
785                     return None;
786                 }
787                 ctxt = info.call_site.ctxt();
788                 last_macro = Some(info.call_site);
789                 Some(())
790             }).is_none() {
791                 break
792             }
793         }
794         last_macro
795     }
796
797     pub fn struct_span_warn<S: Into<MultiSpan>>(&self,
798                                                 sp: S,
799                                                 msg: &str)
800                                                 -> DiagnosticBuilder<'a> {
801         self.parse_sess.span_diagnostic.struct_span_warn(sp, msg)
802     }
803     pub fn struct_span_err<S: Into<MultiSpan>>(&self,
804                                                sp: S,
805                                                msg: &str)
806                                                -> DiagnosticBuilder<'a> {
807         self.parse_sess.span_diagnostic.struct_span_err(sp, msg)
808     }
809     pub fn struct_span_fatal<S: Into<MultiSpan>>(&self,
810                                                  sp: S,
811                                                  msg: &str)
812                                                  -> DiagnosticBuilder<'a> {
813         self.parse_sess.span_diagnostic.struct_span_fatal(sp, msg)
814     }
815
816     /// Emit `msg` attached to `sp`, and stop compilation immediately.
817     ///
818     /// `span_err` should be strongly preferred where-ever possible:
819     /// this should *only* be used when:
820     ///
821     /// - continuing has a high risk of flow-on errors (e.g., errors in
822     ///   declaring a macro would cause all uses of that macro to
823     ///   complain about "undefined macro"), or
824     /// - there is literally nothing else that can be done (however,
825     ///   in most cases one can construct a dummy expression/item to
826     ///   substitute; we never hit resolve/type-checking so the dummy
827     ///   value doesn't have to match anything)
828     pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
829         self.parse_sess.span_diagnostic.span_fatal(sp, msg).raise();
830     }
831
832     /// Emit `msg` attached to `sp`, without immediately stopping
833     /// compilation.
834     ///
835     /// Compilation will be stopped in the near future (at the end of
836     /// the macro expansion phase).
837     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
838         self.parse_sess.span_diagnostic.span_err(sp, msg);
839     }
840     pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
841         self.parse_sess.span_diagnostic.span_err_with_code(sp, msg, code);
842     }
843     pub fn mut_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str)
844                         -> DiagnosticBuilder<'a> {
845         self.parse_sess.span_diagnostic.mut_span_err(sp, msg)
846     }
847     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
848         self.parse_sess.span_diagnostic.span_warn(sp, msg);
849     }
850     pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
851         self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
852     }
853     pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
854         self.parse_sess.span_diagnostic.span_bug(sp, msg);
855     }
856     pub fn trace_macros_diag(&mut self) {
857         for (sp, notes) in self.expansions.iter() {
858             let mut db = self.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
859             for note in notes {
860                 db.note(note);
861             }
862             db.emit();
863         }
864         // Fixme: does this result in errors?
865         self.expansions.clear();
866     }
867     pub fn bug(&self, msg: &str) -> ! {
868         self.parse_sess.span_diagnostic.bug(msg);
869     }
870     pub fn trace_macros(&self) -> bool {
871         self.ecfg.trace_mac
872     }
873     pub fn set_trace_macros(&mut self, x: bool) {
874         self.ecfg.trace_mac = x
875     }
876     pub fn ident_of(&self, st: &str) -> ast::Ident {
877         ast::Ident::from_str(st)
878     }
879     pub fn std_path(&self, components: &[Symbol]) -> Vec<ast::Ident> {
880         let def_site = DUMMY_SP.apply_mark(self.current_expansion.mark);
881         iter::once(Ident::new(kw::DollarCrate, def_site))
882             .chain(components.iter().map(|&s| Ident::with_empty_ctxt(s)))
883             .collect()
884     }
885     pub fn name_of(&self, st: &str) -> ast::Name {
886         Symbol::intern(st)
887     }
888
889     pub fn check_unused_macros(&self) {
890         self.resolver.check_unused_macros();
891     }
892 }
893
894 /// Extracts a string literal from the macro expanded version of `expr`,
895 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
896 /// compilation on error, merely emits a non-fatal error and returns `None`.
897 pub fn expr_to_spanned_string<'a>(
898     cx: &'a mut ExtCtxt<'_>,
899     mut expr: P<ast::Expr>,
900     err_msg: &str,
901 ) -> Result<Spanned<(Symbol, ast::StrStyle)>, Option<DiagnosticBuilder<'a>>> {
902     // Update `expr.span`'s ctxt now in case expr is an `include!` macro invocation.
903     expr.span = expr.span.apply_mark(cx.current_expansion.mark);
904
905     // we want to be able to handle e.g., `concat!("foo", "bar")`
906     cx.expander().visit_expr(&mut expr);
907     Err(match expr.node {
908         ast::ExprKind::Lit(ref l) => match l.node {
909             ast::LitKind::Str(s, style) => return Ok(respan(expr.span, (s, style))),
910             ast::LitKind::Err(_) => None,
911             _ => Some(cx.struct_span_err(l.span, err_msg))
912         },
913         ast::ExprKind::Err => None,
914         _ => Some(cx.struct_span_err(expr.span, err_msg))
915     })
916 }
917
918 pub fn expr_to_string(cx: &mut ExtCtxt<'_>, expr: P<ast::Expr>, err_msg: &str)
919                       -> Option<(Symbol, ast::StrStyle)> {
920     expr_to_spanned_string(cx, expr, err_msg)
921         .map_err(|err| err.map(|mut err| err.emit()))
922         .ok()
923         .map(|s| s.node)
924 }
925
926 /// Non-fatally assert that `tts` is empty. Note that this function
927 /// returns even when `tts` is non-empty, macros that *need* to stop
928 /// compilation should call
929 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
930 /// done as rarely as possible).
931 pub fn check_zero_tts(cx: &ExtCtxt<'_>,
932                       sp: Span,
933                       tts: &[tokenstream::TokenTree],
934                       name: &str) {
935     if !tts.is_empty() {
936         cx.span_err(sp, &format!("{} takes no arguments", name));
937     }
938 }
939
940 /// Interpreting `tts` as a comma-separated sequence of expressions,
941 /// expect exactly one string literal, or emit an error and return `None`.
942 pub fn get_single_str_from_tts(cx: &mut ExtCtxt<'_>,
943                                sp: Span,
944                                tts: &[tokenstream::TokenTree],
945                                name: &str)
946                                -> Option<String> {
947     let mut p = cx.new_parser_from_tts(tts);
948     if p.token == token::Eof {
949         cx.span_err(sp, &format!("{} takes 1 argument", name));
950         return None
951     }
952     let ret = panictry!(p.parse_expr());
953     let _ = p.eat(&token::Comma);
954
955     if p.token != token::Eof {
956         cx.span_err(sp, &format!("{} takes 1 argument", name));
957     }
958     expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
959         s.to_string()
960     })
961 }
962
963 /// Extracts comma-separated expressions from `tts`. If there is a
964 /// parsing error, emit a non-fatal error and return `None`.
965 pub fn get_exprs_from_tts(cx: &mut ExtCtxt<'_>,
966                           sp: Span,
967                           tts: &[tokenstream::TokenTree]) -> Option<Vec<P<ast::Expr>>> {
968     let mut p = cx.new_parser_from_tts(tts);
969     let mut es = Vec::new();
970     while p.token != token::Eof {
971         let mut expr = panictry!(p.parse_expr());
972         cx.expander().visit_expr(&mut expr);
973         es.push(expr);
974         if p.eat(&token::Comma) {
975             continue;
976         }
977         if p.token != token::Eof {
978             cx.span_err(sp, "expected token: `,`");
979             return None;
980         }
981     }
982     Some(es)
983 }