]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/base.rs
Rollup merge of #63055 - Mark-Simulacrum:save-analysis-clean-2, r=Xanewok
[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::{FileName, 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     /// Built-in macros have a couple of special properties (meaning of `$crate`,
596     /// availability in `#[no_implicit_prelude]` modules), so we have to keep this flag.
597     pub is_builtin: bool,
598 }
599
600 impl SyntaxExtensionKind {
601     /// When a syntax extension is constructed,
602     /// its transparency can often be inferred from its kind.
603     fn default_transparency(&self) -> Transparency {
604         match self {
605             SyntaxExtensionKind::Bang(..) |
606             SyntaxExtensionKind::Attr(..) |
607             SyntaxExtensionKind::Derive(..) |
608             SyntaxExtensionKind::NonMacroAttr { .. } => Transparency::Opaque,
609             SyntaxExtensionKind::LegacyBang(..) |
610             SyntaxExtensionKind::LegacyAttr(..) |
611             SyntaxExtensionKind::LegacyDerive(..) => Transparency::SemiTransparent,
612         }
613     }
614 }
615
616 impl SyntaxExtension {
617     /// Returns which kind of macro calls this syntax extension.
618     pub fn macro_kind(&self) -> MacroKind {
619         match self.kind {
620             SyntaxExtensionKind::Bang(..) |
621             SyntaxExtensionKind::LegacyBang(..) => MacroKind::Bang,
622             SyntaxExtensionKind::Attr(..) |
623             SyntaxExtensionKind::LegacyAttr(..) |
624             SyntaxExtensionKind::NonMacroAttr { .. } => MacroKind::Attr,
625             SyntaxExtensionKind::Derive(..) |
626             SyntaxExtensionKind::LegacyDerive(..) => MacroKind::Derive,
627         }
628     }
629
630     /// Constructs a syntax extension with default properties.
631     pub fn default(kind: SyntaxExtensionKind, edition: Edition) -> SyntaxExtension {
632         SyntaxExtension {
633             span: DUMMY_SP,
634             default_transparency: kind.default_transparency(),
635             allow_internal_unstable: None,
636             allow_internal_unsafe: false,
637             local_inner_macros: false,
638             stability: None,
639             deprecation: None,
640             helper_attrs: Vec::new(),
641             edition,
642             is_builtin: false,
643             kind,
644         }
645     }
646
647     pub fn dummy_bang(edition: Edition) -> SyntaxExtension {
648         fn expander<'cx>(_: &'cx mut ExtCtxt<'_>, span: Span, _: &[TokenTree])
649                          -> Box<dyn MacResult + 'cx> {
650             DummyResult::any(span)
651         }
652         SyntaxExtension::default(SyntaxExtensionKind::LegacyBang(Box::new(expander)), edition)
653     }
654
655     pub fn dummy_derive(edition: Edition) -> SyntaxExtension {
656         fn expander(_: &mut ExtCtxt<'_>, _: Span, _: &ast::MetaItem, _: Annotatable)
657                     -> Vec<Annotatable> {
658             Vec::new()
659         }
660         SyntaxExtension::default(SyntaxExtensionKind::Derive(Box::new(expander)), edition)
661     }
662
663     pub fn non_macro_attr(mark_used: bool, edition: Edition) -> SyntaxExtension {
664         SyntaxExtension::default(SyntaxExtensionKind::NonMacroAttr { mark_used }, edition)
665     }
666
667     pub fn expn_info(&self, call_site: Span, descr: Symbol) -> ExpnInfo {
668         ExpnInfo {
669             call_site,
670             kind: ExpnKind::Macro(self.macro_kind(), descr),
671             def_site: self.span,
672             default_transparency: self.default_transparency,
673             allow_internal_unstable: self.allow_internal_unstable.clone(),
674             allow_internal_unsafe: self.allow_internal_unsafe,
675             local_inner_macros: self.local_inner_macros,
676             edition: self.edition,
677         }
678     }
679 }
680
681 pub type NamedSyntaxExtension = (Name, SyntaxExtension);
682
683 /// Error type that denotes indeterminacy.
684 pub struct Indeterminate;
685
686 pub trait Resolver {
687     fn next_node_id(&mut self) -> ast::NodeId;
688
689     fn get_module_scope(&mut self, id: ast::NodeId) -> ExpnId;
690
691     fn resolve_dollar_crates(&mut self);
692     fn visit_ast_fragment_with_placeholders(&mut self, expn_id: ExpnId, fragment: &AstFragment,
693                                             derives: &[ExpnId]);
694     fn register_builtin_macro(&mut self, ident: ast::Ident, ext: SyntaxExtension);
695
696     fn resolve_imports(&mut self);
697
698     fn resolve_macro_invocation(&mut self, invoc: &Invocation, invoc_id: ExpnId, force: bool)
699                                 -> Result<Option<Lrc<SyntaxExtension>>, Indeterminate>;
700
701     fn check_unused_macros(&self);
702 }
703
704 #[derive(Clone)]
705 pub struct ModuleData {
706     pub mod_path: Vec<ast::Ident>,
707     pub directory: PathBuf,
708 }
709
710 #[derive(Clone)]
711 pub struct ExpansionData {
712     pub id: ExpnId,
713     pub depth: usize,
714     pub module: Rc<ModuleData>,
715     pub directory_ownership: DirectoryOwnership,
716 }
717
718 /// One of these is made during expansion and incrementally updated as we go;
719 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
720 /// -> expn_info` of their expansion context stored into their span.
721 pub struct ExtCtxt<'a> {
722     pub parse_sess: &'a parse::ParseSess,
723     pub ecfg: expand::ExpansionConfig<'a>,
724     pub root_path: PathBuf,
725     pub resolver: &'a mut dyn Resolver,
726     pub current_expansion: ExpansionData,
727     pub expansions: FxHashMap<Span, Vec<String>>,
728     pub allow_derive_markers: Lrc<[Symbol]>,
729 }
730
731 impl<'a> ExtCtxt<'a> {
732     pub fn new(parse_sess: &'a parse::ParseSess,
733                ecfg: expand::ExpansionConfig<'a>,
734                resolver: &'a mut dyn Resolver)
735                -> ExtCtxt<'a> {
736         ExtCtxt {
737             parse_sess,
738             ecfg,
739             root_path: PathBuf::new(),
740             resolver,
741             current_expansion: ExpansionData {
742                 id: ExpnId::root(),
743                 depth: 0,
744                 module: Rc::new(ModuleData { mod_path: Vec::new(), directory: PathBuf::new() }),
745                 directory_ownership: DirectoryOwnership::Owned { relative: None },
746             },
747             expansions: FxHashMap::default(),
748             allow_derive_markers: [sym::rustc_attrs, sym::structural_match][..].into(),
749         }
750     }
751
752     /// Returns a `Folder` for deeply expanding all macros in an AST node.
753     pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
754         expand::MacroExpander::new(self, false)
755     }
756
757     /// Returns a `Folder` that deeply expands all macros and assigns all `NodeId`s in an AST node.
758     /// Once `NodeId`s are assigned, the node may not be expanded, removed, or otherwise modified.
759     pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
760         expand::MacroExpander::new(self, true)
761     }
762
763     pub fn new_parser_from_tts(&self, tts: &[tokenstream::TokenTree]) -> parser::Parser<'a> {
764         parse::stream_to_parser(self.parse_sess, tts.iter().cloned().collect(), MACRO_ARGUMENTS)
765     }
766     pub fn source_map(&self) -> &'a SourceMap { self.parse_sess.source_map() }
767     pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
768     pub fn cfg(&self) -> &ast::CrateConfig { &self.parse_sess.config }
769     pub fn call_site(&self) -> Span {
770         match self.current_expansion.id.expn_info() {
771             Some(expn_info) => expn_info.call_site,
772             None => DUMMY_SP,
773         }
774     }
775     pub fn backtrace(&self) -> SyntaxContext {
776         SyntaxContext::empty().apply_mark(self.current_expansion.id)
777     }
778
779     /// Returns span for the macro which originally caused the current expansion to happen.
780     ///
781     /// Stops backtracing at include! boundary.
782     pub fn expansion_cause(&self) -> Option<Span> {
783         let mut ctxt = self.backtrace();
784         let mut last_macro = None;
785         loop {
786             if ctxt.outer_expn_info().map_or(None, |info| {
787                 if info.kind.descr() == sym::include {
788                     // Stop going up the backtrace once include! is encountered
789                     return None;
790                 }
791                 ctxt = info.call_site.ctxt();
792                 last_macro = Some(info.call_site);
793                 Some(())
794             }).is_none() {
795                 break
796             }
797         }
798         last_macro
799     }
800
801     pub fn struct_span_warn<S: Into<MultiSpan>>(&self,
802                                                 sp: S,
803                                                 msg: &str)
804                                                 -> DiagnosticBuilder<'a> {
805         self.parse_sess.span_diagnostic.struct_span_warn(sp, msg)
806     }
807     pub fn struct_span_err<S: Into<MultiSpan>>(&self,
808                                                sp: S,
809                                                msg: &str)
810                                                -> DiagnosticBuilder<'a> {
811         self.parse_sess.span_diagnostic.struct_span_err(sp, msg)
812     }
813     pub fn struct_span_fatal<S: Into<MultiSpan>>(&self,
814                                                  sp: S,
815                                                  msg: &str)
816                                                  -> DiagnosticBuilder<'a> {
817         self.parse_sess.span_diagnostic.struct_span_fatal(sp, msg)
818     }
819
820     /// Emit `msg` attached to `sp`, and stop compilation immediately.
821     ///
822     /// `span_err` should be strongly preferred where-ever possible:
823     /// this should *only* be used when:
824     ///
825     /// - continuing has a high risk of flow-on errors (e.g., errors in
826     ///   declaring a macro would cause all uses of that macro to
827     ///   complain about "undefined macro"), or
828     /// - there is literally nothing else that can be done (however,
829     ///   in most cases one can construct a dummy expression/item to
830     ///   substitute; we never hit resolve/type-checking so the dummy
831     ///   value doesn't have to match anything)
832     pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
833         self.parse_sess.span_diagnostic.span_fatal(sp, msg).raise();
834     }
835
836     /// Emit `msg` attached to `sp`, without immediately stopping
837     /// compilation.
838     ///
839     /// Compilation will be stopped in the near future (at the end of
840     /// the macro expansion phase).
841     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
842         self.parse_sess.span_diagnostic.span_err(sp, msg);
843     }
844     pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
845         self.parse_sess.span_diagnostic.span_err_with_code(sp, msg, code);
846     }
847     pub fn mut_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str)
848                         -> DiagnosticBuilder<'a> {
849         self.parse_sess.span_diagnostic.mut_span_err(sp, msg)
850     }
851     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
852         self.parse_sess.span_diagnostic.span_warn(sp, msg);
853     }
854     pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
855         self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
856     }
857     pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
858         self.parse_sess.span_diagnostic.span_bug(sp, msg);
859     }
860     pub fn trace_macros_diag(&mut self) {
861         for (sp, notes) in self.expansions.iter() {
862             let mut db = self.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
863             for note in notes {
864                 db.note(note);
865             }
866             db.emit();
867         }
868         // Fixme: does this result in errors?
869         self.expansions.clear();
870     }
871     pub fn bug(&self, msg: &str) -> ! {
872         self.parse_sess.span_diagnostic.bug(msg);
873     }
874     pub fn trace_macros(&self) -> bool {
875         self.ecfg.trace_mac
876     }
877     pub fn set_trace_macros(&mut self, x: bool) {
878         self.ecfg.trace_mac = x
879     }
880     pub fn ident_of(&self, st: &str) -> ast::Ident {
881         ast::Ident::from_str(st)
882     }
883     pub fn std_path(&self, components: &[Symbol]) -> Vec<ast::Ident> {
884         let def_site = DUMMY_SP.apply_mark(self.current_expansion.id);
885         iter::once(Ident::new(kw::DollarCrate, def_site))
886             .chain(components.iter().map(|&s| Ident::with_empty_ctxt(s)))
887             .collect()
888     }
889     pub fn name_of(&self, st: &str) -> ast::Name {
890         Symbol::intern(st)
891     }
892
893     pub fn check_unused_macros(&self) {
894         self.resolver.check_unused_macros();
895     }
896
897     /// Resolve a path mentioned inside Rust code.
898     ///
899     /// This unifies the logic used for resolving `include_X!`, and `#[doc(include)]` file paths.
900     ///
901     /// Returns an absolute path to the file that `path` refers to.
902     pub fn resolve_path(&self, path: impl Into<PathBuf>, span: Span) -> PathBuf {
903         let path = path.into();
904
905         // Relative paths are resolved relative to the file in which they are found
906         // after macro expansion (that is, they are unhygienic).
907         if !path.is_absolute() {
908             let callsite = span.source_callsite();
909             let mut result = match self.source_map().span_to_unmapped_path(callsite) {
910                 FileName::Real(path) => path,
911                 FileName::DocTest(path, _) => path,
912                 other => panic!("cannot resolve relative path in non-file source `{}`", other),
913             };
914             result.pop();
915             result.push(path);
916             result
917         } else {
918             path
919         }
920     }
921 }
922
923 /// Extracts a string literal from the macro expanded version of `expr`,
924 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
925 /// compilation on error, merely emits a non-fatal error and returns `None`.
926 pub fn expr_to_spanned_string<'a>(
927     cx: &'a mut ExtCtxt<'_>,
928     mut expr: P<ast::Expr>,
929     err_msg: &str,
930 ) -> Result<Spanned<(Symbol, ast::StrStyle)>, Option<DiagnosticBuilder<'a>>> {
931     // Update `expr.span`'s ctxt now in case expr is an `include!` macro invocation.
932     expr.span = expr.span.apply_mark(cx.current_expansion.id);
933
934     // we want to be able to handle e.g., `concat!("foo", "bar")`
935     cx.expander().visit_expr(&mut expr);
936     Err(match expr.node {
937         ast::ExprKind::Lit(ref l) => match l.node {
938             ast::LitKind::Str(s, style) => return Ok(respan(expr.span, (s, style))),
939             ast::LitKind::Err(_) => None,
940             _ => Some(cx.struct_span_err(l.span, err_msg))
941         },
942         ast::ExprKind::Err => None,
943         _ => Some(cx.struct_span_err(expr.span, err_msg))
944     })
945 }
946
947 pub fn expr_to_string(cx: &mut ExtCtxt<'_>, expr: P<ast::Expr>, err_msg: &str)
948                       -> Option<(Symbol, ast::StrStyle)> {
949     expr_to_spanned_string(cx, expr, err_msg)
950         .map_err(|err| err.map(|mut err| err.emit()))
951         .ok()
952         .map(|s| s.node)
953 }
954
955 /// Non-fatally assert that `tts` is empty. Note that this function
956 /// returns even when `tts` is non-empty, macros that *need* to stop
957 /// compilation should call
958 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
959 /// done as rarely as possible).
960 pub fn check_zero_tts(cx: &ExtCtxt<'_>,
961                       sp: Span,
962                       tts: &[tokenstream::TokenTree],
963                       name: &str) {
964     if !tts.is_empty() {
965         cx.span_err(sp, &format!("{} takes no arguments", name));
966     }
967 }
968
969 /// Interpreting `tts` as a comma-separated sequence of expressions,
970 /// expect exactly one string literal, or emit an error and return `None`.
971 pub fn get_single_str_from_tts(cx: &mut ExtCtxt<'_>,
972                                sp: Span,
973                                tts: &[tokenstream::TokenTree],
974                                name: &str)
975                                -> Option<String> {
976     let mut p = cx.new_parser_from_tts(tts);
977     if p.token == token::Eof {
978         cx.span_err(sp, &format!("{} takes 1 argument", name));
979         return None
980     }
981     let ret = panictry!(p.parse_expr());
982     let _ = p.eat(&token::Comma);
983
984     if p.token != token::Eof {
985         cx.span_err(sp, &format!("{} takes 1 argument", name));
986     }
987     expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
988         s.to_string()
989     })
990 }
991
992 /// Extracts comma-separated expressions from `tts`. If there is a
993 /// parsing error, emit a non-fatal error and return `None`.
994 pub fn get_exprs_from_tts(cx: &mut ExtCtxt<'_>,
995                           sp: Span,
996                           tts: &[tokenstream::TokenTree]) -> Option<Vec<P<ast::Expr>>> {
997     let mut p = cx.new_parser_from_tts(tts);
998     let mut es = Vec::new();
999     while p.token != token::Eof {
1000         let mut expr = panictry!(p.parse_expr());
1001         cx.expander().visit_expr(&mut expr);
1002         es.push(expr);
1003         if p.eat(&token::Comma) {
1004             continue;
1005         }
1006         if p.token != token::Eof {
1007             cx.span_err(sp, "expected token: `,`");
1008             return None;
1009         }
1010     }
1011     Some(es)
1012 }