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