]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/base.rs
d576397c942c18ef3979f5922649dfc85f4b44c0
[rust.git] / src / libsyntax / ext / base.rs
1 pub use self::SyntaxExtension::*;
2
3 use ast::{self, Attribute, Name, PatKind, MetaItem};
4 use attr::HasAttrs;
5 use source_map::{self, SourceMap, Spanned, respan};
6 use syntax_pos::{Span, MultiSpan, DUMMY_SP};
7 use edition::Edition;
8 use errors::{DiagnosticBuilder, DiagnosticId};
9 use ext::expand::{self, AstFragment, Invocation};
10 use ext::hygiene::{self, Mark, SyntaxContext, Transparency};
11 use fold::{self, Folder};
12 use parse::{self, parser, DirectoryOwnership};
13 use parse::token;
14 use ptr::P;
15 use smallvec::SmallVec;
16 use symbol::{keywords, Ident, Symbol};
17 use ThinVec;
18
19 use rustc_data_structures::fx::FxHashMap;
20 use std::iter;
21 use std::path::PathBuf;
22 use std::rc::Rc;
23 use rustc_data_structures::sync::{self, Lrc};
24 use std::default::Default;
25 use tokenstream::{self, TokenStream};
26
27
28 #[derive(Debug,Clone)]
29 pub enum Annotatable {
30     Item(P<ast::Item>),
31     TraitItem(P<ast::TraitItem>),
32     ImplItem(P<ast::ImplItem>),
33     ForeignItem(P<ast::ForeignItem>),
34     Stmt(P<ast::Stmt>),
35     Expr(P<ast::Expr>),
36 }
37
38 impl HasAttrs for Annotatable {
39     fn attrs(&self) -> &[Attribute] {
40         match *self {
41             Annotatable::Item(ref item) => &item.attrs,
42             Annotatable::TraitItem(ref trait_item) => &trait_item.attrs,
43             Annotatable::ImplItem(ref impl_item) => &impl_item.attrs,
44             Annotatable::ForeignItem(ref foreign_item) => &foreign_item.attrs,
45             Annotatable::Stmt(ref stmt) => stmt.attrs(),
46             Annotatable::Expr(ref expr) => &expr.attrs,
47         }
48     }
49
50     fn map_attrs<F: FnOnce(Vec<Attribute>) -> Vec<Attribute>>(self, f: F) -> Self {
51         match self {
52             Annotatable::Item(item) => Annotatable::Item(item.map_attrs(f)),
53             Annotatable::TraitItem(trait_item) => Annotatable::TraitItem(trait_item.map_attrs(f)),
54             Annotatable::ImplItem(impl_item) => Annotatable::ImplItem(impl_item.map_attrs(f)),
55             Annotatable::ForeignItem(foreign_item) =>
56                 Annotatable::ForeignItem(foreign_item.map_attrs(f)),
57             Annotatable::Stmt(stmt) => Annotatable::Stmt(stmt.map_attrs(f)),
58             Annotatable::Expr(expr) => Annotatable::Expr(expr.map_attrs(f)),
59         }
60     }
61 }
62
63 impl Annotatable {
64     pub fn span(&self) -> Span {
65         match *self {
66             Annotatable::Item(ref item) => item.span,
67             Annotatable::TraitItem(ref trait_item) => trait_item.span,
68             Annotatable::ImplItem(ref impl_item) => impl_item.span,
69             Annotatable::ForeignItem(ref foreign_item) => foreign_item.span,
70             Annotatable::Stmt(ref stmt) => stmt.span,
71             Annotatable::Expr(ref expr) => expr.span,
72         }
73     }
74
75     pub fn expect_item(self) -> P<ast::Item> {
76         match self {
77             Annotatable::Item(i) => i,
78             _ => panic!("expected Item")
79         }
80     }
81
82     pub fn map_item_or<F, G>(self, mut f: F, mut or: G) -> Annotatable
83         where F: FnMut(P<ast::Item>) -> P<ast::Item>,
84               G: FnMut(Annotatable) -> Annotatable
85     {
86         match self {
87             Annotatable::Item(i) => Annotatable::Item(f(i)),
88             _ => or(self)
89         }
90     }
91
92     pub fn expect_trait_item(self) -> ast::TraitItem {
93         match self {
94             Annotatable::TraitItem(i) => i.into_inner(),
95             _ => panic!("expected Item")
96         }
97     }
98
99     pub fn expect_impl_item(self) -> ast::ImplItem {
100         match self {
101             Annotatable::ImplItem(i) => i.into_inner(),
102             _ => panic!("expected Item")
103         }
104     }
105
106     pub fn expect_foreign_item(self) -> ast::ForeignItem {
107         match self {
108             Annotatable::ForeignItem(i) => i.into_inner(),
109             _ => panic!("expected foreign item")
110         }
111     }
112
113     pub fn expect_stmt(self) -> ast::Stmt {
114         match self {
115             Annotatable::Stmt(stmt) => stmt.into_inner(),
116             _ => panic!("expected statement"),
117         }
118     }
119
120     pub fn expect_expr(self) -> P<ast::Expr> {
121         match self {
122             Annotatable::Expr(expr) => expr,
123             _ => panic!("expected expression"),
124         }
125     }
126
127     pub fn derive_allowed(&self) -> bool {
128         match *self {
129             Annotatable::Item(ref item) => match item.node {
130                 ast::ItemKind::Struct(..) |
131                 ast::ItemKind::Enum(..) |
132                 ast::ItemKind::Union(..) => true,
133                 _ => false,
134             },
135             _ => false,
136         }
137     }
138 }
139
140 // A more flexible ItemDecorator.
141 pub trait MultiItemDecorator {
142     fn expand(&self,
143               ecx: &mut ExtCtxt,
144               sp: Span,
145               meta_item: &ast::MetaItem,
146               item: &Annotatable,
147               push: &mut dyn FnMut(Annotatable));
148 }
149
150 impl<F> MultiItemDecorator for F
151     where F : Fn(&mut ExtCtxt, Span, &ast::MetaItem, &Annotatable, &mut dyn FnMut(Annotatable))
152 {
153     fn expand(&self,
154               ecx: &mut ExtCtxt,
155               sp: Span,
156               meta_item: &ast::MetaItem,
157               item: &Annotatable,
158               push: &mut dyn FnMut(Annotatable)) {
159         (*self)(ecx, sp, meta_item, item, push)
160     }
161 }
162
163 // `meta_item` is the annotation, and `item` is the item being modified.
164 // FIXME Decorators should follow the same pattern too.
165 pub trait MultiItemModifier {
166     fn expand(&self,
167               ecx: &mut ExtCtxt,
168               span: Span,
169               meta_item: &ast::MetaItem,
170               item: Annotatable)
171               -> Vec<Annotatable>;
172 }
173
174 impl<F, T> MultiItemModifier for F
175     where F: Fn(&mut ExtCtxt, Span, &ast::MetaItem, Annotatable) -> T,
176           T: Into<Vec<Annotatable>>,
177 {
178     fn expand(&self,
179               ecx: &mut ExtCtxt,
180               span: Span,
181               meta_item: &ast::MetaItem,
182               item: Annotatable)
183               -> Vec<Annotatable> {
184         (*self)(ecx, span, meta_item, item).into()
185     }
186 }
187
188 impl Into<Vec<Annotatable>> for Annotatable {
189     fn into(self) -> Vec<Annotatable> {
190         vec![self]
191     }
192 }
193
194 pub trait ProcMacro {
195     fn expand<'cx>(&self,
196                    ecx: &'cx mut ExtCtxt,
197                    span: Span,
198                    ts: TokenStream)
199                    -> TokenStream;
200 }
201
202 impl<F> ProcMacro for F
203     where F: Fn(TokenStream) -> TokenStream
204 {
205     fn expand<'cx>(&self,
206                    _ecx: &'cx mut ExtCtxt,
207                    _span: Span,
208                    ts: TokenStream)
209                    -> TokenStream {
210         // FIXME setup implicit context in TLS before calling self.
211         (*self)(ts)
212     }
213 }
214
215 pub trait AttrProcMacro {
216     fn expand<'cx>(&self,
217                    ecx: &'cx mut ExtCtxt,
218                    span: Span,
219                    annotation: TokenStream,
220                    annotated: TokenStream)
221                    -> TokenStream;
222 }
223
224 impl<F> AttrProcMacro for F
225     where F: Fn(TokenStream, TokenStream) -> TokenStream
226 {
227     fn expand<'cx>(&self,
228                    _ecx: &'cx mut ExtCtxt,
229                    _span: Span,
230                    annotation: TokenStream,
231                    annotated: TokenStream)
232                    -> TokenStream {
233         // FIXME setup implicit context in TLS before calling self.
234         (*self)(annotation, annotated)
235     }
236 }
237
238 /// Represents a thing that maps token trees to Macro Results
239 pub trait TTMacroExpander {
240     fn expand<'cx>(
241         &self,
242         ecx: &'cx mut ExtCtxt,
243         span: Span,
244         input: TokenStream,
245         def_span: Option<Span>,
246     ) -> Box<dyn MacResult+'cx>;
247 }
248
249 pub type MacroExpanderFn =
250     for<'cx> fn(&'cx mut ExtCtxt, Span, &[tokenstream::TokenTree])
251                 -> Box<dyn MacResult+'cx>;
252
253 impl<F> TTMacroExpander for F
254     where F: for<'cx> Fn(&'cx mut ExtCtxt, Span, &[tokenstream::TokenTree])
255     -> Box<dyn MacResult+'cx>
256 {
257     fn expand<'cx>(
258         &self,
259         ecx: &'cx mut ExtCtxt,
260         span: Span,
261         input: TokenStream,
262         _def_span: Option<Span>,
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<SmallVec<[P<ast::Item>; 1]>> {
336         None
337     }
338
339     /// Create zero or more impl items.
340     fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[ast::ImplItem; 1]>> {
341         None
342     }
343
344     /// Create zero or more trait items.
345     fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[ast::TraitItem; 1]>> {
346         None
347     }
348
349     /// Create zero or more items in an `extern {}` block
350     fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> { 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<SmallVec<[ast::Stmt; 1]>> {
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: SmallVec<[P<ast::Item>; 1]>,
398     impl_items: SmallVec<[ast::ImplItem; 1]>,
399     trait_items: SmallVec<[ast::TraitItem; 1]>,
400     foreign_items: SmallVec<[ast::ForeignItem; 1]>,
401     stmts: SmallVec<[ast::Stmt; 1]>,
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<SmallVec<[P<ast::Item>; 1]>> {
411         self.items
412     }
413
414     fn make_impl_items(self: Box<Self>) -> Option<SmallVec<[ast::ImplItem; 1]>> {
415         self.impl_items
416     }
417
418     fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[ast::TraitItem; 1]>> {
419         self.trait_items
420     }
421
422     fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> {
423         self.foreign_items
424     }
425
426     fn make_stmts(self: Box<Self>) -> Option<SmallVec<[ast::Stmt; 1]>> {
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(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<SmallVec<[P<ast::Item>; 1]>> {
518         // this code needs a comment... why not always just return the Some() ?
519         if self.expr_only {
520             None
521         } else {
522             Some(SmallVec::new())
523         }
524     }
525
526     fn make_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[ast::ImplItem; 1]>> {
527         if self.expr_only {
528             None
529         } else {
530             Some(SmallVec::new())
531         }
532     }
533
534     fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[ast::TraitItem; 1]>> {
535         if self.expr_only {
536             None
537         } else {
538             Some(SmallVec::new())
539         }
540     }
541
542     fn make_foreign_items(self: Box<Self>) -> Option<SmallVec<[ast::ForeignItem; 1]>> {
543         if self.expr_only {
544             None
545         } else {
546             Some(SmallVec::new())
547         }
548     }
549
550     fn make_stmts(self: Box<DummyResult>) -> Option<SmallVec<[ast::Stmt; 1]>> {
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     pub fn article(self) -> &'static str {
590         match self {
591             MacroKind::Attr => "an",
592             _ => "a",
593         }
594     }
595 }
596
597 /// An enum representing the different kinds of syntax extensions.
598 pub enum SyntaxExtension {
599     /// A trivial "extension" that does nothing, only keeps the attribute and marks it as known.
600     NonMacroAttr { mark_used: bool },
601
602     /// A syntax extension that is attached to an item and creates new items
603     /// based upon it.
604     ///
605     /// `#[derive(...)]` is a `MultiItemDecorator`.
606     ///
607     /// Prefer ProcMacro or MultiModifier since they are more flexible.
608     MultiDecorator(Box<dyn MultiItemDecorator + sync::Sync + sync::Send>),
609
610     /// A syntax extension that is attached to an item and modifies it
611     /// in-place. Also allows decoration, i.e., creating new items.
612     MultiModifier(Box<dyn MultiItemModifier + sync::Sync + sync::Send>),
613
614     /// A function-like procedural macro. TokenStream -> TokenStream.
615     ProcMacro {
616         expander: Box<dyn ProcMacro + sync::Sync + sync::Send>,
617         allow_internal_unstable: bool,
618         edition: Edition,
619     },
620
621     /// An attribute-like procedural macro. TokenStream, TokenStream -> TokenStream.
622     /// The first TokenSteam is the attribute, the second is the annotated item.
623     /// Allows modification of the input items and adding new items, similar to
624     /// MultiModifier, but uses TokenStreams, rather than AST nodes.
625     AttrProcMacro(Box<dyn AttrProcMacro + sync::Sync + sync::Send>, Edition),
626
627     /// A normal, function-like syntax extension.
628     ///
629     /// `bytes!` is a `NormalTT`.
630     NormalTT {
631         expander: Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
632         def_info: Option<(ast::NodeId, Span)>,
633         /// Whether the contents of the macro can
634         /// directly use `#[unstable]` things (true == yes).
635         allow_internal_unstable: bool,
636         /// Whether the contents of the macro can use `unsafe`
637         /// without triggering the `unsafe_code` lint.
638         allow_internal_unsafe: bool,
639         /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`)
640         /// for a given macro.
641         local_inner_macros: bool,
642         /// The macro's feature name if it is unstable, and the stability feature
643         unstable_feature: Option<(Symbol, u32)>,
644         /// Edition of the crate in which the macro is defined
645         edition: Edition,
646     },
647
648     /// A function-like syntax extension that has an extra ident before
649     /// the block.
650     ///
651     IdentTT(Box<dyn IdentMacroExpander + sync::Sync + sync::Send>, Option<Span>, bool),
652
653     /// An attribute-like procedural macro. TokenStream -> TokenStream.
654     /// The input is the annotated item.
655     /// Allows generating code to implement a Trait for a given struct
656     /// or enum item.
657     ProcMacroDerive(Box<dyn MultiItemModifier + sync::Sync + sync::Send>,
658                     Vec<Symbol> /* inert attribute names */, Edition),
659
660     /// An attribute-like procedural macro that derives a builtin trait.
661     BuiltinDerive(BuiltinDeriveFn),
662
663     /// A declarative macro, e.g., `macro m() {}`.
664     DeclMacro {
665         expander: Box<dyn TTMacroExpander + sync::Sync + sync::Send>,
666         def_info: Option<(ast::NodeId, Span)>,
667         is_transparent: bool,
668         edition: Edition,
669     }
670 }
671
672 impl SyntaxExtension {
673     /// Return which kind of macro calls this syntax extension.
674     pub fn kind(&self) -> MacroKind {
675         match *self {
676             SyntaxExtension::DeclMacro { .. } |
677             SyntaxExtension::NormalTT { .. } |
678             SyntaxExtension::IdentTT(..) |
679             SyntaxExtension::ProcMacro { .. } =>
680                 MacroKind::Bang,
681             SyntaxExtension::NonMacroAttr { .. } |
682             SyntaxExtension::MultiDecorator(..) |
683             SyntaxExtension::MultiModifier(..) |
684             SyntaxExtension::AttrProcMacro(..) =>
685                 MacroKind::Attr,
686             SyntaxExtension::ProcMacroDerive(..) |
687             SyntaxExtension::BuiltinDerive(..) =>
688                 MacroKind::Derive,
689         }
690     }
691
692     pub fn default_transparency(&self) -> Transparency {
693         match *self {
694             SyntaxExtension::ProcMacro { .. } |
695             SyntaxExtension::AttrProcMacro(..) |
696             SyntaxExtension::ProcMacroDerive(..) |
697             SyntaxExtension::DeclMacro { is_transparent: false, .. } => Transparency::Opaque,
698             SyntaxExtension::DeclMacro { is_transparent: true, .. } => Transparency::Transparent,
699             _ => Transparency::SemiTransparent,
700         }
701     }
702
703     pub fn edition(&self) -> Edition {
704         match *self {
705             SyntaxExtension::NormalTT { edition, .. } |
706             SyntaxExtension::DeclMacro { edition, .. } |
707             SyntaxExtension::ProcMacro { edition, .. } |
708             SyntaxExtension::AttrProcMacro(.., edition) |
709             SyntaxExtension::ProcMacroDerive(.., edition) => edition,
710             // Unstable legacy stuff
711             SyntaxExtension::NonMacroAttr { .. } |
712             SyntaxExtension::IdentTT(..) |
713             SyntaxExtension::MultiDecorator(..) |
714             SyntaxExtension::MultiModifier(..) |
715             SyntaxExtension::BuiltinDerive(..) => hygiene::default_edition(),
716         }
717     }
718 }
719
720 pub type NamedSyntaxExtension = (Name, SyntaxExtension);
721
722 pub trait Resolver {
723     fn next_node_id(&mut self) -> ast::NodeId;
724     fn get_module_scope(&mut self, id: ast::NodeId) -> Mark;
725
726     fn visit_ast_fragment_with_placeholders(&mut self, mark: Mark, fragment: &AstFragment,
727                                             derives: &[Mark]);
728     fn add_builtin(&mut self, ident: ast::Ident, ext: Lrc<SyntaxExtension>);
729
730     fn resolve_imports(&mut self);
731
732     fn resolve_macro_invocation(&mut self, invoc: &Invocation, invoc_id: Mark, force: bool)
733                                 -> Result<Option<Lrc<SyntaxExtension>>, Determinacy>;
734     fn resolve_macro_path(&mut self, path: &ast::Path, kind: MacroKind, invoc_id: Mark,
735                           derives_in_scope: Vec<ast::Path>, force: bool)
736                           -> Result<Lrc<SyntaxExtension>, Determinacy>;
737
738     fn check_unused_macros(&self);
739 }
740
741 #[derive(Copy, Clone, PartialEq, Debug)]
742 pub enum Determinacy {
743     Determined,
744     Undetermined,
745 }
746
747 impl Determinacy {
748     pub fn determined(determined: bool) -> Determinacy {
749         if determined { Determinacy::Determined } else { Determinacy::Undetermined }
750     }
751 }
752
753 pub struct DummyResolver;
754
755 impl Resolver for DummyResolver {
756     fn next_node_id(&mut self) -> ast::NodeId { ast::DUMMY_NODE_ID }
757     fn get_module_scope(&mut self, _id: ast::NodeId) -> Mark { Mark::root() }
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 resolve_macro_invocation(&mut self, _invoc: &Invocation, _invoc_id: Mark, _force: bool)
765                                 -> Result<Option<Lrc<SyntaxExtension>>, Determinacy> {
766         Err(Determinacy::Determined)
767     }
768     fn resolve_macro_path(&mut self, _path: &ast::Path, _kind: MacroKind, _invoc_id: Mark,
769                           _derives_in_scope: Vec<ast::Path>, _force: bool)
770                           -> Result<Lrc<SyntaxExtension>, Determinacy> {
771         Err(Determinacy::Determined)
772     }
773     fn check_unused_macros(&self) {}
774 }
775
776 #[derive(Clone)]
777 pub struct ModuleData {
778     pub mod_path: Vec<ast::Ident>,
779     pub directory: PathBuf,
780 }
781
782 #[derive(Clone)]
783 pub struct ExpansionData {
784     pub mark: Mark,
785     pub depth: usize,
786     pub module: Rc<ModuleData>,
787     pub directory_ownership: DirectoryOwnership,
788     pub crate_span: Option<Span>,
789 }
790
791 /// One of these is made during expansion and incrementally updated as we go;
792 /// when a macro expansion occurs, the resulting nodes have the `backtrace()
793 /// -> expn_info` of their expansion context stored into their span.
794 pub struct ExtCtxt<'a> {
795     pub parse_sess: &'a parse::ParseSess,
796     pub ecfg: expand::ExpansionConfig<'a>,
797     pub root_path: PathBuf,
798     pub resolver: &'a mut dyn Resolver,
799     pub resolve_err_count: usize,
800     pub current_expansion: ExpansionData,
801     pub expansions: FxHashMap<Span, Vec<String>>,
802 }
803
804 impl<'a> ExtCtxt<'a> {
805     pub fn new(parse_sess: &'a parse::ParseSess,
806                ecfg: expand::ExpansionConfig<'a>,
807                resolver: &'a mut dyn Resolver)
808                -> ExtCtxt<'a> {
809         ExtCtxt {
810             parse_sess,
811             ecfg,
812             root_path: PathBuf::new(),
813             resolver,
814             resolve_err_count: 0,
815             current_expansion: ExpansionData {
816                 mark: Mark::root(),
817                 depth: 0,
818                 module: Rc::new(ModuleData { mod_path: Vec::new(), directory: PathBuf::new() }),
819                 directory_ownership: DirectoryOwnership::Owned { relative: None },
820                 crate_span: None,
821             },
822             expansions: FxHashMap::default(),
823         }
824     }
825
826     /// Returns a `Folder` for deeply expanding all macros in an AST node.
827     pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
828         expand::MacroExpander::new(self, false)
829     }
830
831     /// Returns a `Folder` that deeply expands all macros and assigns all node ids in an AST node.
832     /// Once node ids are assigned, the node may not be expanded, removed, or otherwise modified.
833     pub fn monotonic_expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
834         expand::MacroExpander::new(self, true)
835     }
836
837     pub fn new_parser_from_tts(&self, tts: &[tokenstream::TokenTree]) -> parser::Parser<'a> {
838         parse::stream_to_parser(self.parse_sess, tts.iter().cloned().collect())
839     }
840     pub fn source_map(&self) -> &'a SourceMap { self.parse_sess.source_map() }
841     pub fn parse_sess(&self) -> &'a parse::ParseSess { self.parse_sess }
842     pub fn cfg(&self) -> &ast::CrateConfig { &self.parse_sess.config }
843     pub fn call_site(&self) -> Span {
844         match self.current_expansion.mark.expn_info() {
845             Some(expn_info) => expn_info.call_site,
846             None => DUMMY_SP,
847         }
848     }
849     pub fn backtrace(&self) -> SyntaxContext {
850         SyntaxContext::empty().apply_mark(self.current_expansion.mark)
851     }
852
853     /// Returns span for the macro which originally caused the current expansion to happen.
854     ///
855     /// Stops backtracing at include! boundary.
856     pub fn expansion_cause(&self) -> Option<Span> {
857         let mut ctxt = self.backtrace();
858         let mut last_macro = None;
859         loop {
860             if ctxt.outer().expn_info().map_or(None, |info| {
861                 if info.format.name() == "include" {
862                     // Stop going up the backtrace once include! is encountered
863                     return None;
864                 }
865                 ctxt = info.call_site.ctxt();
866                 last_macro = Some(info.call_site);
867                 Some(())
868             }).is_none() {
869                 break
870             }
871         }
872         last_macro
873     }
874
875     pub fn struct_span_warn<S: Into<MultiSpan>>(&self,
876                                                 sp: S,
877                                                 msg: &str)
878                                                 -> DiagnosticBuilder<'a> {
879         self.parse_sess.span_diagnostic.struct_span_warn(sp, msg)
880     }
881     pub fn struct_span_err<S: Into<MultiSpan>>(&self,
882                                                sp: S,
883                                                msg: &str)
884                                                -> DiagnosticBuilder<'a> {
885         self.parse_sess.span_diagnostic.struct_span_err(sp, msg)
886     }
887     pub fn struct_span_fatal<S: Into<MultiSpan>>(&self,
888                                                  sp: S,
889                                                  msg: &str)
890                                                  -> DiagnosticBuilder<'a> {
891         self.parse_sess.span_diagnostic.struct_span_fatal(sp, msg)
892     }
893
894     /// Emit `msg` attached to `sp`, and stop compilation immediately.
895     ///
896     /// `span_err` should be strongly preferred where-ever possible:
897     /// this should *only* be used when:
898     ///
899     /// - continuing has a high risk of flow-on errors (e.g., errors in
900     ///   declaring a macro would cause all uses of that macro to
901     ///   complain about "undefined macro"), or
902     /// - there is literally nothing else that can be done (however,
903     ///   in most cases one can construct a dummy expression/item to
904     ///   substitute; we never hit resolve/type-checking so the dummy
905     ///   value doesn't have to match anything)
906     pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
907         self.parse_sess.span_diagnostic.span_fatal(sp, msg).raise();
908     }
909
910     /// Emit `msg` attached to `sp`, without immediately stopping
911     /// compilation.
912     ///
913     /// Compilation will be stopped in the near future (at the end of
914     /// the macro expansion phase).
915     pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
916         self.parse_sess.span_diagnostic.span_err(sp, msg);
917     }
918     pub fn span_err_with_code<S: Into<MultiSpan>>(&self, sp: S, msg: &str, code: DiagnosticId) {
919         self.parse_sess.span_diagnostic.span_err_with_code(sp, msg, code);
920     }
921     pub fn mut_span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str)
922                         -> DiagnosticBuilder<'a> {
923         self.parse_sess.span_diagnostic.mut_span_err(sp, msg)
924     }
925     pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) {
926         self.parse_sess.span_diagnostic.span_warn(sp, msg);
927     }
928     pub fn span_unimpl<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
929         self.parse_sess.span_diagnostic.span_unimpl(sp, msg);
930     }
931     pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! {
932         self.parse_sess.span_diagnostic.span_bug(sp, msg);
933     }
934     pub fn trace_macros_diag(&mut self) {
935         for (sp, notes) in self.expansions.iter() {
936             let mut db = self.parse_sess.span_diagnostic.span_note_diag(*sp, "trace_macro");
937             for note in notes {
938                 db.note(note);
939             }
940             db.emit();
941         }
942         // Fixme: does this result in errors?
943         self.expansions.clear();
944     }
945     pub fn bug(&self, msg: &str) -> ! {
946         self.parse_sess.span_diagnostic.bug(msg);
947     }
948     pub fn trace_macros(&self) -> bool {
949         self.ecfg.trace_mac
950     }
951     pub fn set_trace_macros(&mut self, x: bool) {
952         self.ecfg.trace_mac = x
953     }
954     pub fn ident_of(&self, st: &str) -> ast::Ident {
955         ast::Ident::from_str(st)
956     }
957     pub fn std_path(&self, components: &[&str]) -> Vec<ast::Ident> {
958         let def_site = DUMMY_SP.apply_mark(self.current_expansion.mark);
959         iter::once(Ident::new(keywords::DollarCrate.name(), def_site))
960             .chain(components.iter().map(|s| self.ident_of(s)))
961             .collect()
962     }
963     pub fn name_of(&self, st: &str) -> ast::Name {
964         Symbol::intern(st)
965     }
966
967     pub fn check_unused_macros(&self) {
968         self.resolver.check_unused_macros();
969     }
970 }
971
972 /// Extract a string literal from the macro expanded version of `expr`,
973 /// emitting `err_msg` if `expr` is not a string literal. This does not stop
974 /// compilation on error, merely emits a non-fatal error and returns None.
975 pub fn expr_to_spanned_string<'a>(
976     cx: &'a mut ExtCtxt,
977     expr: P<ast::Expr>,
978     err_msg: &str,
979 ) -> Result<Spanned<(Symbol, ast::StrStyle)>, DiagnosticBuilder<'a>> {
980     // Update `expr.span`'s ctxt now in case expr is an `include!` macro invocation.
981     let expr = expr.map(|mut expr| {
982         expr.span = expr.span.apply_mark(cx.current_expansion.mark);
983         expr
984     });
985
986     // we want to be able to handle e.g., `concat!("foo", "bar")`
987     let expr = cx.expander().fold_expr(expr);
988     Err(match expr.node {
989         ast::ExprKind::Lit(ref l) => match l.node {
990             ast::LitKind::Str(s, style) => return Ok(respan(expr.span, (s, style))),
991             _ => cx.struct_span_err(l.span, err_msg)
992         },
993         _ => cx.struct_span_err(expr.span, err_msg)
994     })
995 }
996
997 pub fn expr_to_string(cx: &mut ExtCtxt, expr: P<ast::Expr>, err_msg: &str)
998                       -> Option<(Symbol, ast::StrStyle)> {
999     expr_to_spanned_string(cx, expr, err_msg)
1000         .map_err(|mut err| err.emit())
1001         .ok()
1002         .map(|s| s.node)
1003 }
1004
1005 /// Non-fatally assert that `tts` is empty. Note that this function
1006 /// returns even when `tts` is non-empty, macros that *need* to stop
1007 /// compilation should call
1008 /// `cx.parse_sess.span_diagnostic.abort_if_errors()` (this should be
1009 /// done as rarely as possible).
1010 pub fn check_zero_tts(cx: &ExtCtxt,
1011                       sp: Span,
1012                       tts: &[tokenstream::TokenTree],
1013                       name: &str) {
1014     if !tts.is_empty() {
1015         cx.span_err(sp, &format!("{} takes no arguments", name));
1016     }
1017 }
1018
1019 /// Interpreting `tts` as a comma-separated sequence of expressions,
1020 /// expect exactly one string literal, or emit an error and return None.
1021 pub fn get_single_str_from_tts(cx: &mut ExtCtxt,
1022                                sp: Span,
1023                                tts: &[tokenstream::TokenTree],
1024                                name: &str)
1025                                -> Option<String> {
1026     let mut p = cx.new_parser_from_tts(tts);
1027     if p.token == token::Eof {
1028         cx.span_err(sp, &format!("{} takes 1 argument", name));
1029         return None
1030     }
1031     let ret = panictry!(p.parse_expr());
1032     let _ = p.eat(&token::Comma);
1033
1034     if p.token != token::Eof {
1035         cx.span_err(sp, &format!("{} takes 1 argument", name));
1036     }
1037     expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| {
1038         s.to_string()
1039     })
1040 }
1041
1042 /// Extract comma-separated expressions from `tts`. If there is a
1043 /// parsing error, emit a non-fatal error and return None.
1044 pub fn get_exprs_from_tts(cx: &mut ExtCtxt,
1045                           sp: Span,
1046                           tts: &[tokenstream::TokenTree]) -> Option<Vec<P<ast::Expr>>> {
1047     let mut p = cx.new_parser_from_tts(tts);
1048     let mut es = Vec::new();
1049     while p.token != token::Eof {
1050         es.push(cx.expander().fold_expr(panictry!(p.parse_expr())));
1051         if p.eat(&token::Comma) {
1052             continue;
1053         }
1054         if p.token != token::Eof {
1055             cx.span_err(sp, "expected token: `,`");
1056             return None;
1057         }
1058     }
1059     Some(es)
1060 }