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