]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/base.rs
Rollup merge of #61705 - petrhosek:llvm-cflags, r=alexcrichton
[rust.git] / src / libsyntax / ext / base.rs
1 use crate::ast::{self, Attribute, Name, PatKind};
2 use crate::attr::HasAttrs;
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::{Mark, 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};
14
15 use errors::{DiagnosticBuilder, DiagnosticId};
16 use smallvec::{smallvec, SmallVec};
17 use syntax_pos::{Span, MultiSpan, DUMMY_SP};
18
19 use rustc_data_structures::fx::FxHashMap;
20 use rustc_data_structures::sync::{self, Lrc};
21 use std::iter;
22 use std::path::PathBuf;
23 use std::rc::Rc;
24 use std::default::Default;
25
26
27 #[derive(Debug,Clone)]
28 pub enum Annotatable {
29     Item(P<ast::Item>),
30     TraitItem(P<ast::TraitItem>),
31     ImplItem(P<ast::ImplItem>),
32     ForeignItem(P<ast::ForeignItem>),
33     Stmt(P<ast::Stmt>),
34     Expr(P<ast::Expr>),
35 }
36
37 impl HasAttrs for Annotatable {
38     fn attrs(&self) -> &[Attribute] {
39         match *self {
40             Annotatable::Item(ref item) => &item.attrs,
41             Annotatable::TraitItem(ref trait_item) => &trait_item.attrs,
42             Annotatable::ImplItem(ref impl_item) => &impl_item.attrs,
43             Annotatable::ForeignItem(ref foreign_item) => &foreign_item.attrs,
44             Annotatable::Stmt(ref stmt) => stmt.attrs(),
45             Annotatable::Expr(ref expr) => &expr.attrs,
46         }
47     }
48
49     fn visit_attrs<F: FnOnce(&mut Vec<Attribute>)>(&mut self, f: F) {
50         match self {
51             Annotatable::Item(item) => item.visit_attrs(f),
52             Annotatable::TraitItem(trait_item) => trait_item.visit_attrs(f),
53             Annotatable::ImplItem(impl_item) => impl_item.visit_attrs(f),
54             Annotatable::ForeignItem(foreign_item) => foreign_item.visit_attrs(f),
55             Annotatable::Stmt(stmt) => stmt.visit_attrs(f),
56             Annotatable::Expr(expr) => expr.visit_attrs(f),
57         }
58     }
59 }
60
61 impl Annotatable {
62     pub fn span(&self) -> Span {
63         match *self {
64             Annotatable::Item(ref item) => item.span,
65             Annotatable::TraitItem(ref trait_item) => trait_item.span,
66             Annotatable::ImplItem(ref impl_item) => impl_item.span,
67             Annotatable::ForeignItem(ref foreign_item) => foreign_item.span,
68             Annotatable::Stmt(ref stmt) => stmt.span,
69             Annotatable::Expr(ref expr) => expr.span,
70         }
71     }
72
73     pub fn expect_item(self) -> P<ast::Item> {
74         match self {
75             Annotatable::Item(i) => i,
76             _ => panic!("expected Item")
77         }
78     }
79
80     pub fn map_item_or<F, G>(self, mut f: F, mut or: G) -> Annotatable
81         where F: FnMut(P<ast::Item>) -> P<ast::Item>,
82               G: FnMut(Annotatable) -> Annotatable
83     {
84         match self {
85             Annotatable::Item(i) => Annotatable::Item(f(i)),
86             _ => or(self)
87         }
88     }
89
90     pub fn expect_trait_item(self) -> ast::TraitItem {
91         match self {
92             Annotatable::TraitItem(i) => i.into_inner(),
93             _ => panic!("expected Item")
94         }
95     }
96
97     pub fn expect_impl_item(self) -> ast::ImplItem {
98         match self {
99             Annotatable::ImplItem(i) => i.into_inner(),
100             _ => panic!("expected Item")
101         }
102     }
103
104     pub fn expect_foreign_item(self) -> ast::ForeignItem {
105         match self {
106             Annotatable::ForeignItem(i) => i.into_inner(),
107             _ => panic!("expected foreign item")
108         }
109     }
110
111     pub fn expect_stmt(self) -> ast::Stmt {
112         match self {
113             Annotatable::Stmt(stmt) => stmt.into_inner(),
114             _ => panic!("expected statement"),
115         }
116     }
117
118     pub fn expect_expr(self) -> P<ast::Expr> {
119         match self {
120             Annotatable::Expr(expr) => expr,
121             _ => panic!("expected expression"),
122         }
123     }
124
125     pub fn derive_allowed(&self) -> bool {
126         match *self {
127             Annotatable::Item(ref item) => match item.node {
128                 ast::ItemKind::Struct(..) |
129                 ast::ItemKind::Enum(..) |
130                 ast::ItemKind::Union(..) => true,
131                 _ => false,
132             },
133             _ => false,
134         }
135     }
136 }
137
138 // `meta_item` is the annotation, and `item` is the item being modified.
139 // FIXME Decorators should follow the same pattern too.
140 pub trait MultiItemModifier {
141     fn expand(&self,
142               ecx: &mut ExtCtxt<'_>,
143               span: Span,
144               meta_item: &ast::MetaItem,
145               item: Annotatable)
146               -> Vec<Annotatable>;
147 }
148
149 impl<F, T> MultiItemModifier for F
150     where F: Fn(&mut ExtCtxt<'_>, Span, &ast::MetaItem, Annotatable) -> T,
151           T: Into<Vec<Annotatable>>,
152 {
153     fn expand(&self,
154               ecx: &mut ExtCtxt<'_>,
155               span: Span,
156               meta_item: &ast::MetaItem,
157               item: Annotatable)
158               -> Vec<Annotatable> {
159         (*self)(ecx, span, meta_item, item).into()
160     }
161 }
162
163 impl Into<Vec<Annotatable>> for Annotatable {
164     fn into(self) -> Vec<Annotatable> {
165         vec![self]
166     }
167 }
168
169 pub trait ProcMacro {
170     fn expand<'cx>(&self,
171                    ecx: &'cx mut ExtCtxt<'_>,
172                    span: Span,
173                    ts: TokenStream)
174                    -> TokenStream;
175 }
176
177 impl<F> ProcMacro for F
178     where F: Fn(TokenStream) -> TokenStream
179 {
180     fn expand<'cx>(&self,
181                    _ecx: &'cx mut ExtCtxt<'_>,
182                    _span: Span,
183                    ts: TokenStream)
184                    -> TokenStream {
185         // FIXME setup implicit context in TLS before calling self.
186         (*self)(ts)
187     }
188 }
189
190 pub trait AttrProcMacro {
191     fn expand<'cx>(&self,
192                    ecx: &'cx mut ExtCtxt<'_>,
193                    span: Span,
194                    annotation: TokenStream,
195                    annotated: TokenStream)
196                    -> TokenStream;
197 }
198
199 impl<F> AttrProcMacro for F
200     where F: Fn(TokenStream, TokenStream) -> TokenStream
201 {
202     fn expand<'cx>(&self,
203                    _ecx: &'cx mut ExtCtxt<'_>,
204                    _span: Span,
205                    annotation: TokenStream,
206                    annotated: TokenStream)
207                    -> TokenStream {
208         // FIXME setup implicit context in TLS before calling self.
209         (*self)(annotation, annotated)
210     }
211 }
212
213 /// Represents a thing that maps token trees to Macro Results
214 pub trait TTMacroExpander {
215     fn expand<'cx>(
216         &self,
217         ecx: &'cx mut ExtCtxt<'_>,
218         span: Span,
219         input: TokenStream,
220         def_span: Option<Span>,
221     ) -> Box<dyn MacResult+'cx>;
222 }
223
224 pub type MacroExpanderFn =
225     for<'cx> fn(&'cx mut ExtCtxt<'_>, Span, &[tokenstream::TokenTree])
226                 -> Box<dyn MacResult+'cx>;
227
228 impl<F> TTMacroExpander for F
229     where F: for<'cx> Fn(&'cx mut ExtCtxt<'_>, Span, &[tokenstream::TokenTree])
230     -> Box<dyn MacResult+'cx>
231 {
232     fn expand<'cx>(
233         &self,
234         ecx: &'cx mut ExtCtxt<'_>,
235         span: Span,
236         input: TokenStream,
237         _def_span: Option<Span>,
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 /// Represents different kinds of macro invocations that can be resolved.
521 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
522 pub enum MacroKind {
523     /// A bang macro - foo!()
524     Bang,
525     /// An attribute macro - #[foo]
526     Attr,
527     /// A derive attribute macro - #[derive(Foo)]
528     Derive,
529     /// A view of a procedural macro from the same crate that defines it.
530     ProcMacroStub,
531 }
532
533 impl MacroKind {
534     pub fn descr(self) -> &'static str {
535         match self {
536             MacroKind::Bang => "macro",
537             MacroKind::Attr => "attribute macro",
538             MacroKind::Derive => "derive macro",
539             MacroKind::ProcMacroStub => "crate-local procedural macro",
540         }
541     }
542
543     pub fn article(self) -> &'static str {
544         match self {
545             MacroKind::Attr => "an",
546             _ => "a",
547         }
548     }
549 }
550
551 /// An enum representing the different kinds of syntax extensions.
552 pub enum SyntaxExtension {
553     /// A token-based function-like macro.
554     Bang {
555         /// An expander with signature TokenStream -> TokenStream.
556         expander: Box<dyn ProcMacro + sync::Sync + sync::Send>,
557         /// Whitelist of unstable features that are treated as stable inside this macro.
558         allow_internal_unstable: Option<Lrc<[Symbol]>>,
559         /// Edition of the crate in which this macro is defined.
560         edition: Edition,
561     },
562
563     /// An AST-based function-like macro.
564     LegacyBang {
565         /// An expander with signature TokenStream -> AST.
566         expander: Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
567         /// Some info about the macro's definition point.
568         def_info: Option<(ast::NodeId, Span)>,
569         /// Hygienic properties of identifiers produced by this macro.
570         transparency: Transparency,
571         /// Whitelist of unstable features that are treated as stable inside this macro.
572         allow_internal_unstable: Option<Lrc<[Symbol]>>,
573         /// Suppresses the `unsafe_code` lint for code produced by this macro.
574         allow_internal_unsafe: bool,
575         /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`) for this macro.
576         local_inner_macros: bool,
577         /// The macro's feature name and tracking issue number if it is unstable.
578         unstable_feature: Option<(Symbol, u32)>,
579         /// Edition of the crate in which this macro is defined.
580         edition: Edition,
581     },
582
583     /// A token-based attribute macro.
584     Attr(
585         /// An expander with signature (TokenStream, TokenStream) -> TokenStream.
586         /// The first TokenSteam is the attribute itself, the second is the annotated item.
587         /// The produced TokenSteam replaces the input TokenSteam.
588         Box<dyn AttrProcMacro + sync::Sync + sync::Send>,
589         /// Edition of the crate in which this macro is defined.
590         Edition,
591     ),
592
593     /// An AST-based attribute macro.
594     LegacyAttr(
595         /// An expander with signature (AST, AST) -> AST.
596         /// The first AST fragment is the attribute itself, the second is the annotated item.
597         /// The produced AST fragment replaces the input AST fragment.
598         Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
599     ),
600
601     /// A trivial attribute "macro" that does nothing,
602     /// only keeps the attribute and marks it as known.
603     NonMacroAttr {
604         /// Suppresses the `unused_attributes` lint for this attribute.
605         mark_used: bool,
606     },
607
608     /// A token-based derive macro.
609     Derive(
610         /// An expander with signature TokenStream -> TokenStream (not yet).
611         /// The produced TokenSteam is appended to the input TokenSteam.
612         Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
613         /// Names of helper attributes registered by this macro.
614         Vec<Symbol>,
615         /// Edition of the crate in which this macro is defined.
616         Edition,
617     ),
618
619     /// An AST-based derive macro.
620     LegacyDerive(
621         /// An expander with signature AST -> AST.
622         /// The produced AST fragment is appended to the input AST fragment.
623         Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
624     ),
625 }
626
627 impl SyntaxExtension {
628     /// Returns which kind of macro calls this syntax extension.
629     pub fn kind(&self) -> MacroKind {
630         match *self {
631             SyntaxExtension::Bang { .. } |
632             SyntaxExtension::LegacyBang { .. } => MacroKind::Bang,
633             SyntaxExtension::Attr(..) |
634             SyntaxExtension::LegacyAttr(..) |
635             SyntaxExtension::NonMacroAttr { .. } => MacroKind::Attr,
636             SyntaxExtension::Derive(..) |
637             SyntaxExtension::LegacyDerive(..) => MacroKind::Derive,
638         }
639     }
640
641     pub fn default_transparency(&self) -> Transparency {
642         match *self {
643             SyntaxExtension::LegacyBang { transparency, .. } => transparency,
644             SyntaxExtension::Bang { .. } |
645             SyntaxExtension::Attr(..) |
646             SyntaxExtension::Derive(..) |
647             SyntaxExtension::NonMacroAttr { .. } => Transparency::Opaque,
648             SyntaxExtension::LegacyAttr(..) |
649             SyntaxExtension::LegacyDerive(..) => Transparency::SemiTransparent,
650         }
651     }
652
653     pub fn edition(&self, default_edition: Edition) -> Edition {
654         match *self {
655             SyntaxExtension::Bang { edition, .. } |
656             SyntaxExtension::LegacyBang { edition, .. } |
657             SyntaxExtension::Attr(.., edition) |
658             SyntaxExtension::Derive(.., edition) => edition,
659             // Unstable legacy stuff
660             SyntaxExtension::NonMacroAttr { .. } |
661             SyntaxExtension::LegacyAttr(..) |
662             SyntaxExtension::LegacyDerive(..) => default_edition,
663         }
664     }
665 }
666
667 pub type NamedSyntaxExtension = (Name, SyntaxExtension);
668
669 pub trait Resolver {
670     fn next_node_id(&mut self) -> ast::NodeId;
671
672     fn get_module_scope(&mut self, id: ast::NodeId) -> Mark;
673
674     fn resolve_dollar_crates(&mut self, fragment: &AstFragment);
675     fn visit_ast_fragment_with_placeholders(&mut self, mark: Mark, fragment: &AstFragment,
676                                             derives: &[Mark]);
677     fn add_builtin(&mut self, ident: ast::Ident, ext: Lrc<SyntaxExtension>);
678
679     fn resolve_imports(&mut self);
680
681     fn resolve_macro_invocation(&mut self, invoc: &Invocation, invoc_id: Mark, force: bool)
682                                 -> Result<Option<Lrc<SyntaxExtension>>, Determinacy>;
683     fn resolve_macro_path(&mut self, path: &ast::Path, kind: MacroKind, invoc_id: Mark,
684                           derives_in_scope: Vec<ast::Path>, force: bool)
685                           -> Result<Lrc<SyntaxExtension>, Determinacy>;
686
687     fn check_unused_macros(&self);
688 }
689
690 #[derive(Copy, Clone, PartialEq, Debug)]
691 pub enum Determinacy {
692     Determined,
693     Undetermined,
694 }
695
696 impl Determinacy {
697     pub fn determined(determined: bool) -> Determinacy {
698         if determined { Determinacy::Determined } else { Determinacy::Undetermined }
699     }
700 }
701
702 pub struct DummyResolver;
703
704 impl Resolver for DummyResolver {
705     fn next_node_id(&mut self) -> ast::NodeId { ast::DUMMY_NODE_ID }
706
707     fn get_module_scope(&mut self, _id: ast::NodeId) -> Mark { Mark::root() }
708
709     fn resolve_dollar_crates(&mut self, _fragment: &AstFragment) {}
710     fn visit_ast_fragment_with_placeholders(&mut self, _invoc: Mark, _fragment: &AstFragment,
711                                             _derives: &[Mark]) {}
712     fn add_builtin(&mut self, _ident: ast::Ident, _ext: Lrc<SyntaxExtension>) {}
713
714     fn resolve_imports(&mut self) {}
715     fn resolve_macro_invocation(&mut self, _invoc: &Invocation, _invoc_id: Mark, _force: bool)
716                                 -> Result<Option<Lrc<SyntaxExtension>>, Determinacy> {
717         Err(Determinacy::Determined)
718     }
719     fn resolve_macro_path(&mut self, _path: &ast::Path, _kind: MacroKind, _invoc_id: Mark,
720                           _derives_in_scope: Vec<ast::Path>, _force: bool)
721                           -> Result<Lrc<SyntaxExtension>, Determinacy> {
722         Err(Determinacy::Determined)
723     }
724     fn check_unused_macros(&self) {}
725 }
726
727 #[derive(Clone)]
728 pub struct ModuleData {
729     pub mod_path: Vec<ast::Ident>,
730     pub directory: PathBuf,
731 }
732
733 #[derive(Clone)]
734 pub struct ExpansionData {
735     pub mark: Mark,
736     pub depth: usize,
737     pub module: Rc<ModuleData>,
738     pub directory_ownership: DirectoryOwnership,
739     pub crate_span: Option<Span>,
740 }
741
742 /// One of these is made during expansion and incrementally updated as we go;
743 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
744 /// -> expn_info` of their expansion context stored into their span.
745 pub struct ExtCtxt<'a> {
746     pub parse_sess: &'a parse::ParseSess,
747     pub ecfg: expand::ExpansionConfig<'a>,
748     pub root_path: PathBuf,
749     pub resolver: &'a mut dyn Resolver,
750     pub current_expansion: ExpansionData,
751     pub expansions: FxHashMap<Span, Vec<String>>,
752 }
753
754 impl<'a> ExtCtxt<'a> {
755     pub fn new(parse_sess: &'a parse::ParseSess,
756                ecfg: expand::ExpansionConfig<'a>,
757                resolver: &'a mut dyn Resolver)
758                -> ExtCtxt<'a> {
759         ExtCtxt {
760             parse_sess,
761             ecfg,
762             root_path: PathBuf::new(),
763             resolver,
764             current_expansion: ExpansionData {
765                 mark: Mark::root(),
766                 depth: 0,
767                 module: Rc::new(ModuleData { mod_path: Vec::new(), directory: PathBuf::new() }),
768                 directory_ownership: DirectoryOwnership::Owned { relative: None },
769                 crate_span: None,
770             },
771             expansions: FxHashMap::default(),
772         }
773     }
774
775     /// Returns a `Folder` for deeply expanding all macros in an AST node.
776     pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
777         expand::MacroExpander::new(self, false)
778     }
779
780     /// Returns a `Folder` that deeply expands all macros and assigns all `NodeId`s in an AST node.
781     /// Once `NodeId`s are assigned, the node may not be expanded, removed, or otherwise modified.
782     pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
783         expand::MacroExpander::new(self, true)
784     }
785
786     pub fn new_parser_from_tts(&self, tts: &[tokenstream::TokenTree]) -> parser::Parser<'a> {
787         parse::stream_to_parser(self.parse_sess, tts.iter().cloned().collect(), MACRO_ARGUMENTS)
788     }
789     pub fn source_map(&self) -> &'a SourceMap { self.parse_sess.source_map() }
790     pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
791     pub fn cfg(&self) -> &ast::CrateConfig { &self.parse_sess.config }
792     pub fn call_site(&self) -> Span {
793         match self.current_expansion.mark.expn_info() {
794             Some(expn_info) => expn_info.call_site,
795             None => DUMMY_SP,
796         }
797     }
798     pub fn backtrace(&self) -> SyntaxContext {
799         SyntaxContext::empty().apply_mark(self.current_expansion.mark)
800     }
801
802     /// Returns span for the macro which originally caused the current expansion to happen.
803     ///
804     /// Stops backtracing at include! boundary.
805     pub fn expansion_cause(&self) -> Option<Span> {
806         let mut ctxt = self.backtrace();
807         let mut last_macro = None;
808         loop {
809             if ctxt.outer_expn_info().map_or(None, |info| {
810                 if info.format.name() == sym::include {
811                     // Stop going up the backtrace once include! is encountered
812                     return None;
813                 }
814                 ctxt = info.call_site.ctxt();
815                 last_macro = Some(info.call_site);
816                 Some(())
817             }).is_none() {
818                 break
819             }
820         }
821         last_macro
822     }
823
824     pub fn struct_span_warn<S: Into<MultiSpan>>(&self,
825                                                 sp: S,
826                                                 msg: &str)
827                                                 -> DiagnosticBuilder<'a> {
828         self.parse_sess.span_diagnostic.struct_span_warn(sp, msg)
829     }
830     pub fn struct_span_err<S: Into<MultiSpan>>(&self,
831                                                sp: S,
832                                                msg: &str)
833                                                -> DiagnosticBuilder<'a> {
834         self.parse_sess.span_diagnostic.struct_span_err(sp, msg)
835     }
836     pub fn struct_span_fatal<S: Into<MultiSpan>>(&self,
837                                                  sp: S,
838                                                  msg: &str)
839                                                  -> DiagnosticBuilder<'a> {
840         self.parse_sess.span_diagnostic.struct_span_fatal(sp, msg)
841     }
842
843     /// Emit `msg` attached to `sp`, and stop compilation immediately.
844     ///
845     /// `span_err` should be strongly preferred where-ever possible:
846     /// this should *only* be used when:
847     ///
848     /// - continuing has a high risk of flow-on errors (e.g., errors in
849     ///   declaring a macro would cause all uses of that macro to
850     ///   complain about "undefined macro"), or
851     /// - there is literally nothing else that can be done (however,
852     ///   in most cases one can construct a dummy expression/item to
853     ///   substitute; we never hit resolve/type-checking so the dummy
854     ///   value doesn't have to match anything)
855     pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
856         self.parse_sess.span_diagnostic.span_fatal(sp, msg).raise();
857     }
858
859     /// Emit `msg` attached to `sp`, without immediately stopping
860     /// compilation.
861     ///
862     /// Compilation will be stopped in the near future (at the end of
863     /// the macro expansion phase).
864     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
865         self.parse_sess.span_diagnostic.span_err(sp, msg);
866     }
867     pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
868         self.parse_sess.span_diagnostic.span_err_with_code(sp, msg, code);
869     }
870     pub fn mut_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str)
871                         -> DiagnosticBuilder<'a> {
872         self.parse_sess.span_diagnostic.mut_span_err(sp, msg)
873     }
874     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
875         self.parse_sess.span_diagnostic.span_warn(sp, msg);
876     }
877     pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
878         self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
879     }
880     pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
881         self.parse_sess.span_diagnostic.span_bug(sp, msg);
882     }
883     pub fn trace_macros_diag(&mut self) {
884         for (sp, notes) in self.expansions.iter() {
885             let mut db = self.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
886             for note in notes {
887                 db.note(note);
888             }
889             db.emit();
890         }
891         // Fixme: does this result in errors?
892         self.expansions.clear();
893     }
894     pub fn bug(&self, msg: &str) -> ! {
895         self.parse_sess.span_diagnostic.bug(msg);
896     }
897     pub fn trace_macros(&self) -> bool {
898         self.ecfg.trace_mac
899     }
900     pub fn set_trace_macros(&mut self, x: bool) {
901         self.ecfg.trace_mac = x
902     }
903     pub fn ident_of(&self, st: &str) -> ast::Ident {
904         ast::Ident::from_str(st)
905     }
906     pub fn std_path(&self, components: &[Symbol]) -> Vec<ast::Ident> {
907         let def_site = DUMMY_SP.apply_mark(self.current_expansion.mark);
908         iter::once(Ident::new(kw::DollarCrate, def_site))
909             .chain(components.iter().map(|&s| Ident::with_empty_ctxt(s)))
910             .collect()
911     }
912     pub fn name_of(&self, st: &str) -> ast::Name {
913         Symbol::intern(st)
914     }
915
916     pub fn check_unused_macros(&self) {
917         self.resolver.check_unused_macros();
918     }
919 }
920
921 /// Extracts a string literal from the macro expanded version of `expr`,
922 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
923 /// compilation on error, merely emits a non-fatal error and returns `None`.
924 pub fn expr_to_spanned_string<'a>(
925     cx: &'a mut ExtCtxt<'_>,
926     mut expr: P<ast::Expr>,
927     err_msg: &str,
928 ) -> Result<Spanned<(Symbol, ast::StrStyle)>, Option<DiagnosticBuilder<'a>>> {
929     // Update `expr.span`'s ctxt now in case expr is an `include!` macro invocation.
930     expr.span = expr.span.apply_mark(cx.current_expansion.mark);
931
932     // we want to be able to handle e.g., `concat!("foo", "bar")`
933     cx.expander().visit_expr(&mut expr);
934     Err(match expr.node {
935         ast::ExprKind::Lit(ref l) => match l.node {
936             ast::LitKind::Str(s, style) => return Ok(respan(expr.span, (s, style))),
937             ast::LitKind::Err(_) => None,
938             _ => Some(cx.struct_span_err(l.span, err_msg))
939         },
940         ast::ExprKind::Err => None,
941         _ => Some(cx.struct_span_err(expr.span, err_msg))
942     })
943 }
944
945 pub fn expr_to_string(cx: &mut ExtCtxt<'_>, expr: P<ast::Expr>, err_msg: &str)
946                       -> Option<(Symbol, ast::StrStyle)> {
947     expr_to_spanned_string(cx, expr, err_msg)
948         .map_err(|err| err.map(|mut err| err.emit()))
949         .ok()
950         .map(|s| s.node)
951 }
952
953 /// Non-fatally assert that `tts` is empty. Note that this function
954 /// returns even when `tts` is non-empty, macros that *need* to stop
955 /// compilation should call
956 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
957 /// done as rarely as possible).
958 pub fn check_zero_tts(cx: &ExtCtxt<'_>,
959                       sp: Span,
960                       tts: &[tokenstream::TokenTree],
961                       name: &str) {
962     if !tts.is_empty() {
963         cx.span_err(sp, &format!("{} takes no arguments", name));
964     }
965 }
966
967 /// Interpreting `tts` as a comma-separated sequence of expressions,
968 /// expect exactly one string literal, or emit an error and return `None`.
969 pub fn get_single_str_from_tts(cx: &mut ExtCtxt<'_>,
970                                sp: Span,
971                                tts: &[tokenstream::TokenTree],
972                                name: &str)
973                                -> Option<String> {
974     let mut p = cx.new_parser_from_tts(tts);
975     if p.token == token::Eof {
976         cx.span_err(sp, &format!("{} takes 1 argument", name));
977         return None
978     }
979     let ret = panictry!(p.parse_expr());
980     let _ = p.eat(&token::Comma);
981
982     if p.token != token::Eof {
983         cx.span_err(sp, &format!("{} takes 1 argument", name));
984     }
985     expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
986         s.to_string()
987     })
988 }
989
990 /// Extracts comma-separated expressions from `tts`. If there is a
991 /// parsing error, emit a non-fatal error and return `None`.
992 pub fn get_exprs_from_tts(cx: &mut ExtCtxt<'_>,
993                           sp: Span,
994                           tts: &[tokenstream::TokenTree]) -> Option<Vec<P<ast::Expr>>> {
995     let mut p = cx.new_parser_from_tts(tts);
996     let mut es = Vec::new();
997     while p.token != token::Eof {
998         let mut expr = panictry!(p.parse_expr());
999         cx.expander().visit_expr(&mut expr);
1000         es.push(expr);
1001         if p.eat(&token::Comma) {
1002             continue;
1003         }
1004         if p.token != token::Eof {
1005             cx.span_err(sp, "expected token: `,`");
1006             return None;
1007         }
1008     }
1009     Some(es)
1010 }