]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/expand.rs
14f19c493b33f965259a9ba820852221247d3e14
[rust.git] / src / libsyntax / ext / expand.rs
1 // Copyright 2012-2014 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 use ast::{self, Block, Ident, NodeId, PatKind, Path};
12 use ast::{MacStmtStyle, StmtKind, ItemKind};
13 use attr::{self, HasAttrs};
14 use source_map::{ExpnInfo, MacroBang, MacroAttribute, dummy_spanned, respan};
15 use config::StripUnconfigured;
16 use errors::{Applicability, FatalError};
17 use ext::base::*;
18 use ext::derive::{add_derived_markers, collect_derives};
19 use ext::hygiene::{self, Mark, SyntaxContext};
20 use ext::placeholders::{placeholder, PlaceholderExpander};
21 use feature_gate::{self, Features, GateIssue, is_builtin_attr, emit_feature_err};
22 use fold;
23 use fold::*;
24 use parse::{DirectoryOwnership, PResult, ParseSess};
25 use parse::token::{self, Token};
26 use parse::parser::Parser;
27 use ptr::P;
28 use smallvec::SmallVec;
29 use symbol::Symbol;
30 use symbol::keywords;
31 use syntax_pos::{Span, DUMMY_SP, FileName};
32 use syntax_pos::hygiene::ExpnFormat;
33 use tokenstream::{TokenStream, TokenTree};
34 use visit::{self, Visitor};
35
36 use rustc_data_structures::fx::FxHashMap;
37 use std::fs::File;
38 use std::io::Read;
39 use std::{iter, mem};
40 use std::rc::Rc;
41 use std::path::PathBuf;
42
43 macro_rules! ast_fragments {
44     (
45         $($Kind:ident($AstTy:ty) {
46             $kind_name:expr;
47             // FIXME: HACK: this should be `$(one ...)?` and `$(many ...)?` but `?` macro
48             // repetition was removed from 2015 edition in #51587 because of ambiguities.
49             $(one fn $fold_ast:ident; fn $visit_ast:ident;)*
50             $(many fn $fold_ast_elt:ident; fn $visit_ast_elt:ident;)*
51             fn $make_ast:ident;
52         })*
53     ) => {
54         /// A fragment of AST that can be produced by a single macro expansion.
55         /// Can also serve as an input and intermediate result for macro expansion operations.
56         pub enum AstFragment {
57             OptExpr(Option<P<ast::Expr>>),
58             $($Kind($AstTy),)*
59         }
60
61         /// "Discriminant" of an AST fragment.
62         #[derive(Copy, Clone, PartialEq, Eq)]
63         pub enum AstFragmentKind {
64             OptExpr,
65             $($Kind,)*
66         }
67
68         impl AstFragmentKind {
69             pub fn name(self) -> &'static str {
70                 match self {
71                     AstFragmentKind::OptExpr => "expression",
72                     $(AstFragmentKind::$Kind => $kind_name,)*
73                 }
74             }
75
76             fn make_from<'a>(self, result: Box<dyn MacResult + 'a>) -> Option<AstFragment> {
77                 match self {
78                     AstFragmentKind::OptExpr =>
79                         result.make_expr().map(Some).map(AstFragment::OptExpr),
80                     $(AstFragmentKind::$Kind => result.$make_ast().map(AstFragment::$Kind),)*
81                 }
82             }
83         }
84
85         impl AstFragment {
86             pub fn make_opt_expr(self) -> Option<P<ast::Expr>> {
87                 match self {
88                     AstFragment::OptExpr(expr) => expr,
89                     _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
90                 }
91             }
92
93             $(pub fn $make_ast(self) -> $AstTy {
94                 match self {
95                     AstFragment::$Kind(ast) => ast,
96                     _ => panic!("AstFragment::make_* called on the wrong kind of fragment"),
97                 }
98             })*
99
100             pub fn fold_with<F: Folder>(self, folder: &mut F) -> Self {
101                 match self {
102                     AstFragment::OptExpr(expr) =>
103                         AstFragment::OptExpr(expr.and_then(|expr| folder.fold_opt_expr(expr))),
104                     $($(AstFragment::$Kind(ast) =>
105                         AstFragment::$Kind(folder.$fold_ast(ast)),)*)*
106                     $($(AstFragment::$Kind(ast) =>
107                         AstFragment::$Kind(ast.into_iter()
108                                               .flat_map(|ast| folder.$fold_ast_elt(ast))
109                                               .collect()),)*)*
110                 }
111             }
112
113             pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) {
114                 match *self {
115                     AstFragment::OptExpr(Some(ref expr)) => visitor.visit_expr(expr),
116                     AstFragment::OptExpr(None) => {}
117                     $($(AstFragment::$Kind(ref ast) => visitor.$visit_ast(ast),)*)*
118                     $($(AstFragment::$Kind(ref ast) => for ast_elt in &ast[..] {
119                         visitor.$visit_ast_elt(ast_elt);
120                     })*)*
121                 }
122             }
123         }
124
125         impl<'a, 'b> Folder for MacroExpander<'a, 'b> {
126             fn fold_opt_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
127                 self.expand_fragment(AstFragment::OptExpr(Some(expr))).make_opt_expr()
128             }
129             $($(fn $fold_ast(&mut self, ast: $AstTy) -> $AstTy {
130                 self.expand_fragment(AstFragment::$Kind(ast)).$make_ast()
131             })*)*
132             $($(fn $fold_ast_elt(&mut self, ast_elt: <$AstTy as IntoIterator>::Item) -> $AstTy {
133                 self.expand_fragment(AstFragment::$Kind(smallvec![ast_elt])).$make_ast()
134             })*)*
135         }
136
137         impl<'a> MacResult for ::ext::tt::macro_rules::ParserAnyMacro<'a> {
138             $(fn $make_ast(self: Box<::ext::tt::macro_rules::ParserAnyMacro<'a>>)
139                            -> Option<$AstTy> {
140                 Some(self.make(AstFragmentKind::$Kind).$make_ast())
141             })*
142         }
143     }
144 }
145
146 ast_fragments! {
147     Expr(P<ast::Expr>) { "expression"; one fn fold_expr; fn visit_expr; fn make_expr; }
148     Pat(P<ast::Pat>) { "pattern"; one fn fold_pat; fn visit_pat; fn make_pat; }
149     Ty(P<ast::Ty>) { "type"; one fn fold_ty; fn visit_ty; fn make_ty; }
150     Stmts(SmallVec<[ast::Stmt; 1]>) {
151         "statement"; many fn fold_stmt; fn visit_stmt; fn make_stmts;
152     }
153     Items(SmallVec<[P<ast::Item>; 1]>) {
154         "item"; many fn fold_item; fn visit_item; fn make_items;
155     }
156     TraitItems(SmallVec<[ast::TraitItem; 1]>) {
157         "trait item"; many fn fold_trait_item; fn visit_trait_item; fn make_trait_items;
158     }
159     ImplItems(SmallVec<[ast::ImplItem; 1]>) {
160         "impl item"; many fn fold_impl_item; fn visit_impl_item; fn make_impl_items;
161     }
162     ForeignItems(SmallVec<[ast::ForeignItem; 1]>) {
163         "foreign item"; many fn fold_foreign_item; fn visit_foreign_item; fn make_foreign_items;
164     }
165 }
166
167 impl AstFragmentKind {
168     fn dummy(self, span: Span) -> Option<AstFragment> {
169         self.make_from(DummyResult::any(span))
170     }
171
172     fn expect_from_annotatables<I: IntoIterator<Item = Annotatable>>(self, items: I)
173                                                                      -> AstFragment {
174         let mut items = items.into_iter();
175         match self {
176             AstFragmentKind::Items =>
177                 AstFragment::Items(items.map(Annotatable::expect_item).collect()),
178             AstFragmentKind::ImplItems =>
179                 AstFragment::ImplItems(items.map(Annotatable::expect_impl_item).collect()),
180             AstFragmentKind::TraitItems =>
181                 AstFragment::TraitItems(items.map(Annotatable::expect_trait_item).collect()),
182             AstFragmentKind::ForeignItems =>
183                 AstFragment::ForeignItems(items.map(Annotatable::expect_foreign_item).collect()),
184             AstFragmentKind::Stmts =>
185                 AstFragment::Stmts(items.map(Annotatable::expect_stmt).collect()),
186             AstFragmentKind::Expr => AstFragment::Expr(
187                 items.next().expect("expected exactly one expression").expect_expr()
188             ),
189             AstFragmentKind::OptExpr =>
190                 AstFragment::OptExpr(items.next().map(Annotatable::expect_expr)),
191             AstFragmentKind::Pat | AstFragmentKind::Ty =>
192                 panic!("patterns and types aren't annotatable"),
193         }
194     }
195 }
196
197 fn macro_bang_format(path: &ast::Path) -> ExpnFormat {
198     // We don't want to format a path using pretty-printing,
199     // `format!("{}", path)`, because that tries to insert
200     // line-breaks and is slow.
201     let mut path_str = String::with_capacity(64);
202     for (i, segment) in path.segments.iter().enumerate() {
203         if i != 0 {
204             path_str.push_str("::");
205         }
206
207         if segment.ident.name != keywords::PathRoot.name() &&
208             segment.ident.name != keywords::DollarCrate.name()
209         {
210             path_str.push_str(&segment.ident.as_str())
211         }
212     }
213
214     MacroBang(Symbol::intern(&path_str))
215 }
216
217 pub struct Invocation {
218     pub kind: InvocationKind,
219     fragment_kind: AstFragmentKind,
220     pub expansion_data: ExpansionData,
221 }
222
223 pub enum InvocationKind {
224     Bang {
225         mac: ast::Mac,
226         ident: Option<Ident>,
227         span: Span,
228     },
229     Attr {
230         attr: Option<ast::Attribute>,
231         traits: Vec<Path>,
232         item: Annotatable,
233         // We temporarily report errors for attribute macros placed after derives
234         after_derive: bool,
235     },
236     Derive {
237         path: Path,
238         item: Annotatable,
239     },
240 }
241
242 impl Invocation {
243     pub fn span(&self) -> Span {
244         match self.kind {
245             InvocationKind::Bang { span, .. } => span,
246             InvocationKind::Attr { attr: Some(ref attr), .. } => attr.span,
247             InvocationKind::Attr { attr: None, .. } => DUMMY_SP,
248             InvocationKind::Derive { ref path, .. } => path.span,
249         }
250     }
251 }
252
253 pub struct MacroExpander<'a, 'b:'a> {
254     pub cx: &'a mut ExtCtxt<'b>,
255     monotonic: bool, // cf. `cx.monotonic_expander()`
256 }
257
258 impl<'a, 'b> MacroExpander<'a, 'b> {
259     pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self {
260         MacroExpander { cx: cx, monotonic: monotonic }
261     }
262
263     pub fn expand_crate(&mut self, mut krate: ast::Crate) -> ast::Crate {
264         let mut module = ModuleData {
265             mod_path: vec![Ident::from_str(&self.cx.ecfg.crate_name)],
266             directory: match self.cx.source_map().span_to_unmapped_path(krate.span) {
267                 FileName::Real(path) => path,
268                 other => PathBuf::from(other.to_string()),
269             },
270         };
271         module.directory.pop();
272         self.cx.root_path = module.directory.clone();
273         self.cx.current_expansion.module = Rc::new(module);
274         self.cx.current_expansion.crate_span = Some(krate.span);
275
276         let orig_mod_span = krate.module.inner;
277
278         let krate_item = AstFragment::Items(smallvec![P(ast::Item {
279             attrs: krate.attrs,
280             span: krate.span,
281             node: ast::ItemKind::Mod(krate.module),
282             ident: keywords::Invalid.ident(),
283             id: ast::DUMMY_NODE_ID,
284             vis: respan(krate.span.shrink_to_lo(), ast::VisibilityKind::Public),
285             tokens: None,
286         })]);
287
288         match self.expand_fragment(krate_item).make_items().pop().map(P::into_inner) {
289             Some(ast::Item { attrs, node: ast::ItemKind::Mod(module), .. }) => {
290                 krate.attrs = attrs;
291                 krate.module = module;
292             },
293             None => {
294                 // Resolution failed so we return an empty expansion
295                 krate.attrs = vec![];
296                 krate.module = ast::Mod {
297                     inner: orig_mod_span,
298                     items: vec![],
299                     inline: true,
300                 };
301             },
302             _ => unreachable!(),
303         };
304         self.cx.trace_macros_diag();
305         krate
306     }
307
308     // Fully expand all macro invocations in this AST fragment.
309     fn expand_fragment(&mut self, input_fragment: AstFragment) -> AstFragment {
310         let orig_expansion_data = self.cx.current_expansion.clone();
311         self.cx.current_expansion.depth = 0;
312
313         // Collect all macro invocations and replace them with placeholders.
314         let (fragment_with_placeholders, mut invocations)
315             = self.collect_invocations(input_fragment, &[]);
316
317         // Optimization: if we resolve all imports now,
318         // we'll be able to immediately resolve most of imported macros.
319         self.resolve_imports();
320
321         // Resolve paths in all invocations and produce output expanded fragments for them, but
322         // do not insert them into our input AST fragment yet, only store in `expanded_fragments`.
323         // The output fragments also go through expansion recursively until no invocations are left.
324         // Unresolved macros produce dummy outputs as a recovery measure.
325         invocations.reverse();
326         let mut expanded_fragments = Vec::new();
327         let mut derives: FxHashMap<Mark, Vec<_>> = FxHashMap::default();
328         let mut undetermined_invocations = Vec::new();
329         let (mut progress, mut force) = (false, !self.monotonic);
330         loop {
331             let invoc = if let Some(invoc) = invocations.pop() {
332                 invoc
333             } else {
334                 self.resolve_imports();
335                 if undetermined_invocations.is_empty() { break }
336                 invocations = mem::replace(&mut undetermined_invocations, Vec::new());
337                 force = !mem::replace(&mut progress, false);
338                 continue
339             };
340
341             let scope =
342                 if self.monotonic { invoc.expansion_data.mark } else { orig_expansion_data.mark };
343             let ext = match self.cx.resolver.resolve_macro_invocation(&invoc, scope, force) {
344                 Ok(ext) => Some(ext),
345                 Err(Determinacy::Determined) => None,
346                 Err(Determinacy::Undetermined) => {
347                     undetermined_invocations.push(invoc);
348                     continue
349                 }
350             };
351
352             progress = true;
353             let ExpansionData { depth, mark, .. } = invoc.expansion_data;
354             self.cx.current_expansion = invoc.expansion_data.clone();
355
356             self.cx.current_expansion.mark = scope;
357             // FIXME(jseyfried): Refactor out the following logic
358             let (expanded_fragment, new_invocations) = if let Some(ext) = ext {
359                 if let Some(ext) = ext {
360                     let dummy = invoc.fragment_kind.dummy(invoc.span()).unwrap();
361                     let fragment = self.expand_invoc(invoc, &*ext).unwrap_or(dummy);
362                     self.collect_invocations(fragment, &[])
363                 } else if let InvocationKind::Attr { attr: None, traits, item, .. } = invoc.kind {
364                     if !item.derive_allowed() {
365                         let attr = attr::find_by_name(item.attrs(), "derive")
366                             .expect("`derive` attribute should exist");
367                         let span = attr.span;
368                         let mut err = self.cx.mut_span_err(span,
369                                                            "`derive` may only be applied to \
370                                                             structs, enums and unions");
371                         if let ast::AttrStyle::Inner = attr.style {
372                             let trait_list = traits.iter()
373                                 .map(|t| t.to_string()).collect::<Vec<_>>();
374                             let suggestion = format!("#[derive({})]", trait_list.join(", "));
375                             err.span_suggestion_with_applicability(
376                                 span, "try an outer attribute", suggestion,
377                                 // We don't 𝑘𝑛𝑜𝑤 that the following item is an ADT
378                                 Applicability::MaybeIncorrect
379                             );
380                         }
381                         err.emit();
382                     }
383
384                     let item = self.fully_configure(item)
385                         .map_attrs(|mut attrs| { attrs.retain(|a| a.path != "derive"); attrs });
386                     let item_with_markers =
387                         add_derived_markers(&mut self.cx, item.span(), &traits, item.clone());
388                     let derives = derives.entry(invoc.expansion_data.mark).or_default();
389
390                     derives.reserve(traits.len());
391                     invocations.reserve(traits.len());
392                     for path in &traits {
393                         let mark = Mark::fresh(self.cx.current_expansion.mark);
394                         derives.push(mark);
395                         let item = match self.cx.resolver.resolve_macro_path(
396                                 path, MacroKind::Derive, Mark::root(), Vec::new(), false) {
397                             Ok(ext) => match *ext {
398                                 BuiltinDerive(..) => item_with_markers.clone(),
399                                 _ => item.clone(),
400                             },
401                             _ => item.clone(),
402                         };
403                         invocations.push(Invocation {
404                             kind: InvocationKind::Derive { path: path.clone(), item: item },
405                             fragment_kind: invoc.fragment_kind,
406                             expansion_data: ExpansionData {
407                                 mark,
408                                 ..invoc.expansion_data.clone()
409                             },
410                         });
411                     }
412                     let fragment = invoc.fragment_kind
413                         .expect_from_annotatables(::std::iter::once(item_with_markers));
414                     self.collect_invocations(fragment, derives)
415                 } else {
416                     unreachable!()
417                 }
418             } else {
419                 self.collect_invocations(invoc.fragment_kind.dummy(invoc.span()).unwrap(), &[])
420             };
421
422             if expanded_fragments.len() < depth {
423                 expanded_fragments.push(Vec::new());
424             }
425             expanded_fragments[depth - 1].push((mark, expanded_fragment));
426             if !self.cx.ecfg.single_step {
427                 invocations.extend(new_invocations.into_iter().rev());
428             }
429         }
430
431         self.cx.current_expansion = orig_expansion_data;
432
433         // Finally incorporate all the expanded macros into the input AST fragment.
434         let mut placeholder_expander = PlaceholderExpander::new(self.cx, self.monotonic);
435         while let Some(expanded_fragments) = expanded_fragments.pop() {
436             for (mark, expanded_fragment) in expanded_fragments.into_iter().rev() {
437                 let derives = derives.remove(&mark).unwrap_or_else(Vec::new);
438                 placeholder_expander.add(NodeId::placeholder_from_mark(mark),
439                                          expanded_fragment, derives);
440             }
441         }
442         fragment_with_placeholders.fold_with(&mut placeholder_expander)
443     }
444
445     fn resolve_imports(&mut self) {
446         if self.monotonic {
447             let err_count = self.cx.parse_sess.span_diagnostic.err_count();
448             self.cx.resolver.resolve_imports();
449             self.cx.resolve_err_count += self.cx.parse_sess.span_diagnostic.err_count() - err_count;
450         }
451     }
452
453     /// Collect all macro invocations reachable at this time in this AST fragment, and replace
454     /// them with "placeholders" - dummy macro invocations with specially crafted `NodeId`s.
455     /// Then call into resolver that builds a skeleton ("reduced graph") of the fragment and
456     /// prepares data for resolving paths of macro invocations.
457     fn collect_invocations(&mut self, fragment: AstFragment, derives: &[Mark])
458                            -> (AstFragment, Vec<Invocation>) {
459         let (fragment_with_placeholders, invocations) = {
460             let mut collector = InvocationCollector {
461                 cfg: StripUnconfigured {
462                     sess: self.cx.parse_sess,
463                     features: self.cx.ecfg.features,
464                 },
465                 cx: self.cx,
466                 invocations: Vec::new(),
467                 monotonic: self.monotonic,
468             };
469             (fragment.fold_with(&mut collector), collector.invocations)
470         };
471
472         if self.monotonic {
473             let err_count = self.cx.parse_sess.span_diagnostic.err_count();
474             let mark = self.cx.current_expansion.mark;
475             self.cx.resolver.visit_ast_fragment_with_placeholders(mark, &fragment_with_placeholders,
476                                                                   derives);
477             self.cx.resolve_err_count += self.cx.parse_sess.span_diagnostic.err_count() - err_count;
478         }
479
480         (fragment_with_placeholders, invocations)
481     }
482
483     fn fully_configure(&mut self, item: Annotatable) -> Annotatable {
484         let mut cfg = StripUnconfigured {
485             sess: self.cx.parse_sess,
486             features: self.cx.ecfg.features,
487         };
488         // Since the item itself has already been configured by the InvocationCollector,
489         // we know that fold result vector will contain exactly one element
490         match item {
491             Annotatable::Item(item) => {
492                 Annotatable::Item(cfg.fold_item(item).pop().unwrap())
493             }
494             Annotatable::TraitItem(item) => {
495                 Annotatable::TraitItem(item.map(|item| cfg.fold_trait_item(item).pop().unwrap()))
496             }
497             Annotatable::ImplItem(item) => {
498                 Annotatable::ImplItem(item.map(|item| cfg.fold_impl_item(item).pop().unwrap()))
499             }
500             Annotatable::ForeignItem(item) => {
501                 Annotatable::ForeignItem(
502                     item.map(|item| cfg.fold_foreign_item(item).pop().unwrap())
503                 )
504             }
505             Annotatable::Stmt(stmt) => {
506                 Annotatable::Stmt(stmt.map(|stmt| cfg.fold_stmt(stmt).pop().unwrap()))
507             }
508             Annotatable::Expr(expr) => {
509                 Annotatable::Expr(cfg.fold_expr(expr))
510             }
511         }
512     }
513
514     fn expand_invoc(&mut self, invoc: Invocation, ext: &SyntaxExtension) -> Option<AstFragment> {
515         if invoc.fragment_kind == AstFragmentKind::ForeignItems &&
516            !self.cx.ecfg.macros_in_extern_enabled() {
517             if let SyntaxExtension::NonMacroAttr { .. } = *ext {} else {
518                 emit_feature_err(&self.cx.parse_sess, "macros_in_extern",
519                                  invoc.span(), GateIssue::Language,
520                                  "macro invocations in `extern {}` blocks are experimental");
521             }
522         }
523
524         let result = match invoc.kind {
525             InvocationKind::Bang { .. } => self.expand_bang_invoc(invoc, ext)?,
526             InvocationKind::Attr { .. } => self.expand_attr_invoc(invoc, ext)?,
527             InvocationKind::Derive { .. } => self.expand_derive_invoc(invoc, ext)?,
528         };
529
530         if self.cx.current_expansion.depth > self.cx.ecfg.recursion_limit {
531             let info = self.cx.current_expansion.mark.expn_info().unwrap();
532             let suggested_limit = self.cx.ecfg.recursion_limit * 2;
533             let mut err = self.cx.struct_span_err(info.call_site,
534                 &format!("recursion limit reached while expanding the macro `{}`",
535                          info.format.name()));
536             err.help(&format!(
537                 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
538                 suggested_limit));
539             err.emit();
540             self.cx.trace_macros_diag();
541             FatalError.raise();
542         }
543
544         Some(result)
545     }
546
547     fn expand_attr_invoc(&mut self,
548                          invoc: Invocation,
549                          ext: &SyntaxExtension)
550                          -> Option<AstFragment> {
551         let (attr, item) = match invoc.kind {
552             InvocationKind::Attr { attr, item, .. } => (attr?, item),
553             _ => unreachable!(),
554         };
555
556         if let NonMacroAttr { mark_used: false } = *ext {} else {
557             // Macro attrs are always used when expanded,
558             // non-macro attrs are considered used when the field says so.
559             attr::mark_used(&attr);
560         }
561         invoc.expansion_data.mark.set_expn_info(ExpnInfo {
562             call_site: attr.span,
563             def_site: None,
564             format: MacroAttribute(Symbol::intern(&attr.path.to_string())),
565             allow_internal_unstable: false,
566             allow_internal_unsafe: false,
567             local_inner_macros: false,
568             edition: ext.edition(),
569         });
570
571         match *ext {
572             NonMacroAttr { .. } => {
573                 attr::mark_known(&attr);
574                 let item = item.map_attrs(|mut attrs| { attrs.push(attr); attrs });
575                 Some(invoc.fragment_kind.expect_from_annotatables(iter::once(item)))
576             }
577             MultiModifier(ref mac) => {
578                 let meta = attr.parse_meta(self.cx.parse_sess)
579                                .map_err(|mut e| { e.emit(); }).ok()?;
580                 let item = mac.expand(self.cx, attr.span, &meta, item);
581                 Some(invoc.fragment_kind.expect_from_annotatables(item))
582             }
583             MultiDecorator(ref mac) => {
584                 let mut items = Vec::new();
585                 let meta = attr.parse_meta(self.cx.parse_sess)
586                                .expect("derive meta should already have been parsed");
587                 mac.expand(self.cx, attr.span, &meta, &item, &mut |item| items.push(item));
588                 items.push(item);
589                 Some(invoc.fragment_kind.expect_from_annotatables(items))
590             }
591             AttrProcMacro(ref mac, ..) => {
592                 self.gate_proc_macro_attr_item(attr.span, &item);
593                 let item_tok = TokenTree::Token(DUMMY_SP, Token::interpolated(match item {
594                     Annotatable::Item(item) => token::NtItem(item),
595                     Annotatable::TraitItem(item) => token::NtTraitItem(item.into_inner()),
596                     Annotatable::ImplItem(item) => token::NtImplItem(item.into_inner()),
597                     Annotatable::ForeignItem(item) => token::NtForeignItem(item.into_inner()),
598                     Annotatable::Stmt(stmt) => token::NtStmt(stmt.into_inner()),
599                     Annotatable::Expr(expr) => token::NtExpr(expr),
600                 })).into();
601                 let input = self.extract_proc_macro_attr_input(attr.tokens, attr.span);
602                 let tok_result = mac.expand(self.cx, attr.span, input, item_tok);
603                 let res = self.parse_ast_fragment(tok_result, invoc.fragment_kind,
604                                                   &attr.path, attr.span);
605                 self.gate_proc_macro_expansion(attr.span, &res);
606                 res
607             }
608             ProcMacroDerive(..) | BuiltinDerive(..) => {
609                 self.cx.span_err(attr.span, &format!("`{}` is a derive mode", attr.path));
610                 self.cx.trace_macros_diag();
611                 invoc.fragment_kind.dummy(attr.span)
612             }
613             _ => {
614                 let msg = &format!("macro `{}` may not be used in attributes", attr.path);
615                 self.cx.span_err(attr.span, msg);
616                 self.cx.trace_macros_diag();
617                 invoc.fragment_kind.dummy(attr.span)
618             }
619         }
620     }
621
622     fn extract_proc_macro_attr_input(&self, tokens: TokenStream, span: Span) -> TokenStream {
623         let mut trees = tokens.trees();
624         match trees.next() {
625             Some(TokenTree::Delimited(_, delim)) => {
626                 if trees.next().is_none() {
627                     return delim.tts.into()
628                 }
629             }
630             Some(TokenTree::Token(..)) => {}
631             None => return TokenStream::empty(),
632         }
633         self.cx.span_err(span, "custom attribute invocations must be \
634             of the form #[foo] or #[foo(..)], the macro name must only be \
635             followed by a delimiter token");
636         TokenStream::empty()
637     }
638
639     fn gate_proc_macro_attr_item(&self, span: Span, item: &Annotatable) {
640         let (kind, gate) = match *item {
641             Annotatable::Item(ref item) => {
642                 match item.node {
643                     ItemKind::Mod(_) if self.cx.ecfg.proc_macro_hygiene() => return,
644                     ItemKind::Mod(_) => ("modules", "proc_macro_hygiene"),
645                     _ => return,
646                 }
647             }
648             Annotatable::TraitItem(_) => return,
649             Annotatable::ImplItem(_) => return,
650             Annotatable::ForeignItem(_) => return,
651             Annotatable::Stmt(_) |
652             Annotatable::Expr(_) if self.cx.ecfg.proc_macro_hygiene() => return,
653             Annotatable::Stmt(_) => ("statements", "proc_macro_hygiene"),
654             Annotatable::Expr(_) => ("expressions", "proc_macro_hygiene"),
655         };
656         emit_feature_err(
657             self.cx.parse_sess,
658             gate,
659             span,
660             GateIssue::Language,
661             &format!("custom attributes cannot be applied to {}", kind),
662         );
663     }
664
665     fn gate_proc_macro_expansion(&self, span: Span, fragment: &Option<AstFragment>) {
666         if self.cx.ecfg.proc_macro_hygiene() {
667             return
668         }
669         let fragment = match fragment {
670             Some(fragment) => fragment,
671             None => return,
672         };
673
674         fragment.visit_with(&mut DisallowMacros {
675             span,
676             parse_sess: self.cx.parse_sess,
677         });
678
679         struct DisallowMacros<'a> {
680             span: Span,
681             parse_sess: &'a ParseSess,
682         }
683
684         impl<'ast, 'a> Visitor<'ast> for DisallowMacros<'a> {
685             fn visit_item(&mut self, i: &'ast ast::Item) {
686                 if let ast::ItemKind::MacroDef(_) = i.node {
687                     emit_feature_err(
688                         self.parse_sess,
689                         "proc_macro_hygiene",
690                         self.span,
691                         GateIssue::Language,
692                         "procedural macros cannot expand to macro definitions",
693                     );
694                 }
695                 visit::walk_item(self, i);
696             }
697
698             fn visit_mac(&mut self, _mac: &'ast ast::Mac) {
699                 // ...
700             }
701         }
702     }
703
704     /// Expand a macro invocation. Returns the resulting expanded AST fragment.
705     fn expand_bang_invoc(&mut self,
706                          invoc: Invocation,
707                          ext: &SyntaxExtension)
708                          -> Option<AstFragment> {
709         let (mark, kind) = (invoc.expansion_data.mark, invoc.fragment_kind);
710         let (mac, ident, span) = match invoc.kind {
711             InvocationKind::Bang { mac, ident, span } => (mac, ident, span),
712             _ => unreachable!(),
713         };
714         let path = &mac.node.path;
715
716         let ident = ident.unwrap_or_else(|| keywords::Invalid.ident());
717         let validate_and_set_expn_info = |this: &mut Self, // arg instead of capture
718                                           def_site_span: Option<Span>,
719                                           allow_internal_unstable,
720                                           allow_internal_unsafe,
721                                           local_inner_macros,
722                                           // can't infer this type
723                                           unstable_feature: Option<(Symbol, u32)>,
724                                           edition| {
725
726             // feature-gate the macro invocation
727             if let Some((feature, issue)) = unstable_feature {
728                 let crate_span = this.cx.current_expansion.crate_span.unwrap();
729                 // don't stability-check macros in the same crate
730                 // (the only time this is null is for syntax extensions registered as macros)
731                 if def_site_span.map_or(false, |def_span| !crate_span.contains(def_span))
732                     && !span.allows_unstable() && this.cx.ecfg.features.map_or(true, |feats| {
733                     // macro features will count as lib features
734                     !feats.declared_lib_features.iter().any(|&(feat, _)| feat == feature)
735                 }) {
736                     let explain = format!("macro {}! is unstable", path);
737                     emit_feature_err(this.cx.parse_sess, &*feature.as_str(), span,
738                                      GateIssue::Library(Some(issue)), &explain);
739                     this.cx.trace_macros_diag();
740                     return Err(kind.dummy(span));
741                 }
742             }
743
744             if ident.name != keywords::Invalid.name() {
745                 let msg = format!("macro {}! expects no ident argument, given '{}'", path, ident);
746                 this.cx.span_err(path.span, &msg);
747                 this.cx.trace_macros_diag();
748                 return Err(kind.dummy(span));
749             }
750             mark.set_expn_info(ExpnInfo {
751                 call_site: span,
752                 def_site: def_site_span,
753                 format: macro_bang_format(path),
754                 allow_internal_unstable,
755                 allow_internal_unsafe,
756                 local_inner_macros,
757                 edition,
758             });
759             Ok(())
760         };
761
762         let opt_expanded = match *ext {
763             DeclMacro { ref expander, def_info, edition, .. } => {
764                 if let Err(dummy_span) = validate_and_set_expn_info(self, def_info.map(|(_, s)| s),
765                                                                     false, false, false, None,
766                                                                     edition) {
767                     dummy_span
768                 } else {
769                     kind.make_from(expander.expand(self.cx, span, mac.node.stream(), None))
770                 }
771             }
772
773             NormalTT {
774                 ref expander,
775                 def_info,
776                 allow_internal_unstable,
777                 allow_internal_unsafe,
778                 local_inner_macros,
779                 unstable_feature,
780                 edition,
781             } => {
782                 if let Err(dummy_span) = validate_and_set_expn_info(self, def_info.map(|(_, s)| s),
783                                                                     allow_internal_unstable,
784                                                                     allow_internal_unsafe,
785                                                                     local_inner_macros,
786                                                                     unstable_feature,
787                                                                     edition) {
788                     dummy_span
789                 } else {
790                     kind.make_from(expander.expand(
791                         self.cx,
792                         span,
793                         mac.node.stream(),
794                         def_info.map(|(_, s)| s),
795                     ))
796                 }
797             }
798
799             IdentTT(ref expander, tt_span, allow_internal_unstable) => {
800                 if ident.name == keywords::Invalid.name() {
801                     self.cx.span_err(path.span,
802                                     &format!("macro {}! expects an ident argument", path));
803                     self.cx.trace_macros_diag();
804                     kind.dummy(span)
805                 } else {
806                     invoc.expansion_data.mark.set_expn_info(ExpnInfo {
807                         call_site: span,
808                         def_site: tt_span,
809                         format: macro_bang_format(path),
810                         allow_internal_unstable,
811                         allow_internal_unsafe: false,
812                         local_inner_macros: false,
813                         edition: hygiene::default_edition(),
814                     });
815
816                     let input: Vec<_> = mac.node.stream().into_trees().collect();
817                     kind.make_from(expander.expand(self.cx, span, ident, input))
818                 }
819             }
820
821             MultiDecorator(..) | MultiModifier(..) |
822             AttrProcMacro(..) | SyntaxExtension::NonMacroAttr { .. } => {
823                 self.cx.span_err(path.span,
824                                  &format!("`{}` can only be used in attributes", path));
825                 self.cx.trace_macros_diag();
826                 kind.dummy(span)
827             }
828
829             ProcMacroDerive(..) | BuiltinDerive(..) => {
830                 self.cx.span_err(path.span, &format!("`{}` is a derive mode", path));
831                 self.cx.trace_macros_diag();
832                 kind.dummy(span)
833             }
834
835             SyntaxExtension::ProcMacro { ref expander, allow_internal_unstable, edition } => {
836                 if ident.name != keywords::Invalid.name() {
837                     let msg =
838                         format!("macro {}! expects no ident argument, given '{}'", path, ident);
839                     self.cx.span_err(path.span, &msg);
840                     self.cx.trace_macros_diag();
841                     kind.dummy(span)
842                 } else {
843                     self.gate_proc_macro_expansion_kind(span, kind);
844                     invoc.expansion_data.mark.set_expn_info(ExpnInfo {
845                         call_site: span,
846                         // FIXME procedural macros do not have proper span info
847                         // yet, when they do, we should use it here.
848                         def_site: None,
849                         format: macro_bang_format(path),
850                         // FIXME probably want to follow macro_rules macros here.
851                         allow_internal_unstable,
852                         allow_internal_unsafe: false,
853                         local_inner_macros: false,
854                         edition,
855                     });
856
857                     let tok_result = expander.expand(self.cx, span, mac.node.stream());
858                     let result = self.parse_ast_fragment(tok_result, kind, path, span);
859                     self.gate_proc_macro_expansion(span, &result);
860                     result
861                 }
862             }
863         };
864
865         if opt_expanded.is_some() {
866             opt_expanded
867         } else {
868             let msg = format!("non-{kind} macro in {kind} position: {name}",
869                               name = path.segments[0].ident.name, kind = kind.name());
870             self.cx.span_err(path.span, &msg);
871             self.cx.trace_macros_diag();
872             kind.dummy(span)
873         }
874     }
875
876     fn gate_proc_macro_expansion_kind(&self, span: Span, kind: AstFragmentKind) {
877         let kind = match kind {
878             AstFragmentKind::Expr => "expressions",
879             AstFragmentKind::OptExpr => "expressions",
880             AstFragmentKind::Pat => "patterns",
881             AstFragmentKind::Ty => "types",
882             AstFragmentKind::Stmts => "statements",
883             AstFragmentKind::Items => return,
884             AstFragmentKind::TraitItems => return,
885             AstFragmentKind::ImplItems => return,
886             AstFragmentKind::ForeignItems => return,
887         };
888         if self.cx.ecfg.proc_macro_hygiene() {
889             return
890         }
891         emit_feature_err(
892             self.cx.parse_sess,
893             "proc_macro_hygiene",
894             span,
895             GateIssue::Language,
896             &format!("procedural macros cannot be expanded to {}", kind),
897         );
898     }
899
900     /// Expand a derive invocation. Returns the resulting expanded AST fragment.
901     fn expand_derive_invoc(&mut self,
902                            invoc: Invocation,
903                            ext: &SyntaxExtension)
904                            -> Option<AstFragment> {
905         let (path, item) = match invoc.kind {
906             InvocationKind::Derive { path, item } => (path, item),
907             _ => unreachable!(),
908         };
909         if !item.derive_allowed() {
910             return None;
911         }
912
913         let pretty_name = Symbol::intern(&format!("derive({})", path));
914         let span = path.span;
915         let attr = ast::Attribute {
916             path, span,
917             tokens: TokenStream::empty(),
918             // irrelevant:
919             id: ast::AttrId(0), style: ast::AttrStyle::Outer, is_sugared_doc: false,
920         };
921
922         let mut expn_info = ExpnInfo {
923             call_site: span,
924             def_site: None,
925             format: MacroAttribute(pretty_name),
926             allow_internal_unstable: false,
927             allow_internal_unsafe: false,
928             local_inner_macros: false,
929             edition: ext.edition(),
930         };
931
932         match *ext {
933             ProcMacroDerive(ref ext, ..) => {
934                 invoc.expansion_data.mark.set_expn_info(expn_info);
935                 let span = span.with_ctxt(self.cx.backtrace());
936                 let dummy = ast::MetaItem { // FIXME(jseyfried) avoid this
937                     ident: Path::from_ident(keywords::Invalid.ident()),
938                     span: DUMMY_SP,
939                     node: ast::MetaItemKind::Word,
940                 };
941                 let items = ext.expand(self.cx, span, &dummy, item);
942                 Some(invoc.fragment_kind.expect_from_annotatables(items))
943             }
944             BuiltinDerive(func) => {
945                 expn_info.allow_internal_unstable = true;
946                 invoc.expansion_data.mark.set_expn_info(expn_info);
947                 let span = span.with_ctxt(self.cx.backtrace());
948                 let mut items = Vec::new();
949                 func(self.cx, span, &attr.meta()?, &item, &mut |a| items.push(a));
950                 Some(invoc.fragment_kind.expect_from_annotatables(items))
951             }
952             _ => {
953                 let msg = &format!("macro `{}` may not be used for derive attributes", attr.path);
954                 self.cx.span_err(span, msg);
955                 self.cx.trace_macros_diag();
956                 invoc.fragment_kind.dummy(span)
957             }
958         }
959     }
960
961     fn parse_ast_fragment(&mut self,
962                           toks: TokenStream,
963                           kind: AstFragmentKind,
964                           path: &Path,
965                           span: Span)
966                           -> Option<AstFragment> {
967         let mut parser = self.cx.new_parser_from_tts(&toks.into_trees().collect::<Vec<_>>());
968         match parser.parse_ast_fragment(kind, false) {
969             Ok(fragment) => {
970                 parser.ensure_complete_parse(path, kind.name(), span);
971                 Some(fragment)
972             }
973             Err(mut err) => {
974                 err.set_span(span);
975                 err.emit();
976                 self.cx.trace_macros_diag();
977                 kind.dummy(span)
978             }
979         }
980     }
981 }
982
983 impl<'a> Parser<'a> {
984     pub fn parse_ast_fragment(&mut self, kind: AstFragmentKind, macro_legacy_warnings: bool)
985                               -> PResult<'a, AstFragment> {
986         Ok(match kind {
987             AstFragmentKind::Items => {
988                 let mut items = SmallVec::new();
989                 while let Some(item) = self.parse_item()? {
990                     items.push(item);
991                 }
992                 AstFragment::Items(items)
993             }
994             AstFragmentKind::TraitItems => {
995                 let mut items = SmallVec::new();
996                 while self.token != token::Eof {
997                     items.push(self.parse_trait_item(&mut false)?);
998                 }
999                 AstFragment::TraitItems(items)
1000             }
1001             AstFragmentKind::ImplItems => {
1002                 let mut items = SmallVec::new();
1003                 while self.token != token::Eof {
1004                     items.push(self.parse_impl_item(&mut false)?);
1005                 }
1006                 AstFragment::ImplItems(items)
1007             }
1008             AstFragmentKind::ForeignItems => {
1009                 let mut items = SmallVec::new();
1010                 while self.token != token::Eof {
1011                     items.push(self.parse_foreign_item()?);
1012                 }
1013                 AstFragment::ForeignItems(items)
1014             }
1015             AstFragmentKind::Stmts => {
1016                 let mut stmts = SmallVec::new();
1017                 while self.token != token::Eof &&
1018                       // won't make progress on a `}`
1019                       self.token != token::CloseDelim(token::Brace) {
1020                     if let Some(stmt) = self.parse_full_stmt(macro_legacy_warnings)? {
1021                         stmts.push(stmt);
1022                     }
1023                 }
1024                 AstFragment::Stmts(stmts)
1025             }
1026             AstFragmentKind::Expr => AstFragment::Expr(self.parse_expr()?),
1027             AstFragmentKind::OptExpr => {
1028                 if self.token != token::Eof {
1029                     AstFragment::OptExpr(Some(self.parse_expr()?))
1030                 } else {
1031                     AstFragment::OptExpr(None)
1032                 }
1033             },
1034             AstFragmentKind::Ty => AstFragment::Ty(self.parse_ty()?),
1035             AstFragmentKind::Pat => AstFragment::Pat(self.parse_pat(None)?),
1036         })
1037     }
1038
1039     pub fn ensure_complete_parse(&mut self, macro_path: &Path, kind_name: &str, span: Span) {
1040         if self.token != token::Eof {
1041             let msg = format!("macro expansion ignores token `{}` and any following",
1042                               self.this_token_to_string());
1043             // Avoid emitting backtrace info twice.
1044             let def_site_span = self.span.with_ctxt(SyntaxContext::empty());
1045             let mut err = self.diagnostic().struct_span_err(def_site_span, &msg);
1046             err.span_label(span, "caused by the macro expansion here");
1047             let msg = format!(
1048                 "the usage of `{}!` is likely invalid in {} context",
1049                 macro_path,
1050                 kind_name,
1051             );
1052             err.note(&msg);
1053             let semi_span = self.sess.source_map().next_point(span);
1054
1055             let semi_full_span = semi_span.to(self.sess.source_map().next_point(semi_span));
1056             match self.sess.source_map().span_to_snippet(semi_full_span) {
1057                 Ok(ref snippet) if &snippet[..] != ";" && kind_name == "expression" => {
1058                     err.span_suggestion_with_applicability(
1059                         semi_span,
1060                         "you might be missing a semicolon here",
1061                         ";".to_owned(),
1062                         Applicability::MaybeIncorrect,
1063                     );
1064                 }
1065                 _ => {}
1066             }
1067             err.emit();
1068         }
1069     }
1070 }
1071
1072 struct InvocationCollector<'a, 'b: 'a> {
1073     cx: &'a mut ExtCtxt<'b>,
1074     cfg: StripUnconfigured<'a>,
1075     invocations: Vec<Invocation>,
1076     monotonic: bool,
1077 }
1078
1079 impl<'a, 'b> InvocationCollector<'a, 'b> {
1080     fn collect(&mut self, fragment_kind: AstFragmentKind, kind: InvocationKind) -> AstFragment {
1081         let mark = Mark::fresh(self.cx.current_expansion.mark);
1082         self.invocations.push(Invocation {
1083             kind,
1084             fragment_kind,
1085             expansion_data: ExpansionData {
1086                 mark,
1087                 depth: self.cx.current_expansion.depth + 1,
1088                 ..self.cx.current_expansion.clone()
1089             },
1090         });
1091         placeholder(fragment_kind, NodeId::placeholder_from_mark(mark))
1092     }
1093
1094     fn collect_bang(&mut self, mac: ast::Mac, span: Span, kind: AstFragmentKind) -> AstFragment {
1095         self.collect(kind, InvocationKind::Bang { mac: mac, ident: None, span: span })
1096     }
1097
1098     fn collect_attr(&mut self,
1099                     attr: Option<ast::Attribute>,
1100                     traits: Vec<Path>,
1101                     item: Annotatable,
1102                     kind: AstFragmentKind,
1103                     after_derive: bool)
1104                     -> AstFragment {
1105         self.collect(kind, InvocationKind::Attr { attr, traits, item, after_derive })
1106     }
1107
1108     fn find_attr_invoc(&self, attrs: &mut Vec<ast::Attribute>, after_derive: &mut bool)
1109                        -> Option<ast::Attribute> {
1110         let attr = attrs.iter()
1111                         .position(|a| {
1112                             if a.path == "derive" {
1113                                 *after_derive = true;
1114                             }
1115                             !attr::is_known(a) && !is_builtin_attr(a)
1116                         })
1117                         .map(|i| attrs.remove(i));
1118         if let Some(attr) = &attr {
1119             if !self.cx.ecfg.enable_custom_inner_attributes() &&
1120                attr.style == ast::AttrStyle::Inner && attr.path != "test" {
1121                 emit_feature_err(&self.cx.parse_sess, "custom_inner_attributes",
1122                                  attr.span, GateIssue::Language,
1123                                  "non-builtin inner attributes are unstable");
1124             }
1125         }
1126         attr
1127     }
1128
1129     /// If `item` is an attr invocation, remove and return the macro attribute and derive traits.
1130     fn classify_item<T>(&mut self, mut item: T)
1131                         -> (Option<ast::Attribute>, Vec<Path>, T, /* after_derive */ bool)
1132         where T: HasAttrs,
1133     {
1134         let (mut attr, mut traits, mut after_derive) = (None, Vec::new(), false);
1135
1136         item = item.map_attrs(|mut attrs| {
1137             attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
1138             traits = collect_derives(&mut self.cx, &mut attrs);
1139             attrs
1140         });
1141
1142         (attr, traits, item, after_derive)
1143     }
1144
1145     /// Alternative of `classify_item()` that ignores `#[derive]` so invocations fallthrough
1146     /// to the unused-attributes lint (making it an error on statements and expressions
1147     /// is a breaking change)
1148     fn classify_nonitem<T: HasAttrs>(&mut self, mut item: T)
1149                                      -> (Option<ast::Attribute>, T, /* after_derive */ bool) {
1150         let (mut attr, mut after_derive) = (None, false);
1151
1152         item = item.map_attrs(|mut attrs| {
1153             attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
1154             attrs
1155         });
1156
1157         (attr, item, after_derive)
1158     }
1159
1160     fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
1161         self.cfg.configure(node)
1162     }
1163
1164     // Detect use of feature-gated or invalid attributes on macro invocations
1165     // since they will not be detected after macro expansion.
1166     fn check_attributes(&mut self, attrs: &[ast::Attribute]) {
1167         let features = self.cx.ecfg.features.unwrap();
1168         for attr in attrs.iter() {
1169             self.check_attribute_inner(attr, features);
1170
1171             // macros are expanded before any lint passes so this warning has to be hardcoded
1172             if attr.path == "derive" {
1173                 self.cx.struct_span_warn(attr.span, "`#[derive]` does nothing on macro invocations")
1174                     .note("this may become a hard error in a future release")
1175                     .emit();
1176             }
1177         }
1178     }
1179
1180     fn check_attribute(&mut self, at: &ast::Attribute) {
1181         let features = self.cx.ecfg.features.unwrap();
1182         self.check_attribute_inner(at, features);
1183     }
1184
1185     fn check_attribute_inner(&mut self, at: &ast::Attribute, features: &Features) {
1186         feature_gate::check_attribute(at, self.cx.parse_sess, features);
1187     }
1188 }
1189
1190 impl<'a, 'b> Folder for InvocationCollector<'a, 'b> {
1191     fn fold_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> {
1192         let expr = self.cfg.configure_expr(expr);
1193         expr.map(|mut expr| {
1194             expr.node = self.cfg.configure_expr_kind(expr.node);
1195
1196             // ignore derives so they remain unused
1197             let (attr, expr, after_derive) = self.classify_nonitem(expr);
1198
1199             if attr.is_some() {
1200                 // Collect the invoc regardless of whether or not attributes are permitted here
1201                 // expansion will eat the attribute so it won't error later.
1202                 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
1203
1204                 // AstFragmentKind::Expr requires the macro to emit an expression.
1205                 return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)),
1206                                          AstFragmentKind::Expr, after_derive)
1207                     .make_expr()
1208                     .into_inner()
1209             }
1210
1211             if let ast::ExprKind::Mac(mac) = expr.node {
1212                 self.check_attributes(&expr.attrs);
1213                 self.collect_bang(mac, expr.span, AstFragmentKind::Expr)
1214                     .make_expr()
1215                     .into_inner()
1216             } else {
1217                 noop_fold_expr(expr, self)
1218             }
1219         })
1220     }
1221
1222     fn fold_opt_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
1223         let expr = configure!(self, expr);
1224         expr.filter_map(|mut expr| {
1225             expr.node = self.cfg.configure_expr_kind(expr.node);
1226
1227             // Ignore derives so they remain unused.
1228             let (attr, expr, after_derive) = self.classify_nonitem(expr);
1229
1230             if attr.is_some() {
1231                 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
1232
1233                 return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)),
1234                                          AstFragmentKind::OptExpr, after_derive)
1235                     .make_opt_expr()
1236                     .map(|expr| expr.into_inner())
1237             }
1238
1239             if let ast::ExprKind::Mac(mac) = expr.node {
1240                 self.check_attributes(&expr.attrs);
1241                 self.collect_bang(mac, expr.span, AstFragmentKind::OptExpr)
1242                     .make_opt_expr()
1243                     .map(|expr| expr.into_inner())
1244             } else {
1245                 Some(noop_fold_expr(expr, self))
1246             }
1247         })
1248     }
1249
1250     fn fold_pat(&mut self, pat: P<ast::Pat>) -> P<ast::Pat> {
1251         let pat = self.cfg.configure_pat(pat);
1252         match pat.node {
1253             PatKind::Mac(_) => {}
1254             _ => return noop_fold_pat(pat, self),
1255         }
1256
1257         pat.and_then(|pat| match pat.node {
1258             PatKind::Mac(mac) => self.collect_bang(mac, pat.span, AstFragmentKind::Pat).make_pat(),
1259             _ => unreachable!(),
1260         })
1261     }
1262
1263     fn fold_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
1264         let mut stmt = match self.cfg.configure_stmt(stmt) {
1265             Some(stmt) => stmt,
1266             None => return SmallVec::new(),
1267         };
1268
1269         // we'll expand attributes on expressions separately
1270         if !stmt.is_expr() {
1271             let (attr, derives, stmt_, after_derive) = if stmt.is_item() {
1272                 self.classify_item(stmt)
1273             } else {
1274                 // ignore derives on non-item statements so it falls through
1275                 // to the unused-attributes lint
1276                 let (attr, stmt, after_derive) = self.classify_nonitem(stmt);
1277                 (attr, vec![], stmt, after_derive)
1278             };
1279
1280             if attr.is_some() || !derives.is_empty() {
1281                 return self.collect_attr(attr, derives, Annotatable::Stmt(P(stmt_)),
1282                                          AstFragmentKind::Stmts, after_derive).make_stmts();
1283             }
1284
1285             stmt = stmt_;
1286         }
1287
1288         if let StmtKind::Mac(mac) = stmt.node {
1289             let (mac, style, attrs) = mac.into_inner();
1290             self.check_attributes(&attrs);
1291             let mut placeholder = self.collect_bang(mac, stmt.span, AstFragmentKind::Stmts)
1292                                         .make_stmts();
1293
1294             // If this is a macro invocation with a semicolon, then apply that
1295             // semicolon to the final statement produced by expansion.
1296             if style == MacStmtStyle::Semicolon {
1297                 if let Some(stmt) = placeholder.pop() {
1298                     placeholder.push(stmt.add_trailing_semicolon());
1299                 }
1300             }
1301
1302             return placeholder;
1303         }
1304
1305         // The placeholder expander gives ids to statements, so we avoid folding the id here.
1306         let ast::Stmt { id, node, span } = stmt;
1307         noop_fold_stmt_kind(node, self).into_iter().map(|node| {
1308             ast::Stmt { id, node, span }
1309         }).collect()
1310
1311     }
1312
1313     fn fold_block(&mut self, block: P<Block>) -> P<Block> {
1314         let old_directory_ownership = self.cx.current_expansion.directory_ownership;
1315         self.cx.current_expansion.directory_ownership = DirectoryOwnership::UnownedViaBlock;
1316         let result = noop_fold_block(block, self);
1317         self.cx.current_expansion.directory_ownership = old_directory_ownership;
1318         result
1319     }
1320
1321     fn fold_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
1322         let item = configure!(self, item);
1323
1324         let (attr, traits, item, after_derive) = self.classify_item(item);
1325         if attr.is_some() || !traits.is_empty() {
1326             return self.collect_attr(attr, traits, Annotatable::Item(item),
1327                                      AstFragmentKind::Items, after_derive).make_items();
1328         }
1329
1330         match item.node {
1331             ast::ItemKind::Mac(..) => {
1332                 self.check_attributes(&item.attrs);
1333                 item.and_then(|item| match item.node {
1334                     ItemKind::Mac(mac) => {
1335                         self.collect(AstFragmentKind::Items, InvocationKind::Bang {
1336                             mac,
1337                             ident: Some(item.ident),
1338                             span: item.span,
1339                         }).make_items()
1340                     }
1341                     _ => unreachable!(),
1342                 })
1343             }
1344             ast::ItemKind::Mod(ast::Mod { inner, .. }) => {
1345                 if item.ident == keywords::Invalid.ident() {
1346                     return noop_fold_item(item, self);
1347                 }
1348
1349                 let orig_directory_ownership = self.cx.current_expansion.directory_ownership;
1350                 let mut module = (*self.cx.current_expansion.module).clone();
1351                 module.mod_path.push(item.ident);
1352
1353                 // Detect if this is an inline module (`mod m { ... }` as opposed to `mod m;`).
1354                 // In the non-inline case, `inner` is never the dummy span (c.f. `parse_item_mod`).
1355                 // Thus, if `inner` is the dummy span, we know the module is inline.
1356                 let inline_module = item.span.contains(inner) || inner.is_dummy();
1357
1358                 if inline_module {
1359                     if let Some(path) = attr::first_attr_value_str_by_name(&item.attrs, "path") {
1360                         self.cx.current_expansion.directory_ownership =
1361                             DirectoryOwnership::Owned { relative: None };
1362                         module.directory.push(&*path.as_str());
1363                     } else {
1364                         module.directory.push(&*item.ident.as_str());
1365                     }
1366                 } else {
1367                     let path = self.cx.parse_sess.source_map().span_to_unmapped_path(inner);
1368                     let mut path = match path {
1369                         FileName::Real(path) => path,
1370                         other => PathBuf::from(other.to_string()),
1371                     };
1372                     let directory_ownership = match path.file_name().unwrap().to_str() {
1373                         Some("mod.rs") => DirectoryOwnership::Owned { relative: None },
1374                         Some(_) => DirectoryOwnership::Owned {
1375                             relative: Some(item.ident),
1376                         },
1377                         None => DirectoryOwnership::UnownedViaMod(false),
1378                     };
1379                     path.pop();
1380                     module.directory = path;
1381                     self.cx.current_expansion.directory_ownership = directory_ownership;
1382                 }
1383
1384                 let orig_module =
1385                     mem::replace(&mut self.cx.current_expansion.module, Rc::new(module));
1386                 let result = noop_fold_item(item, self);
1387                 self.cx.current_expansion.module = orig_module;
1388                 self.cx.current_expansion.directory_ownership = orig_directory_ownership;
1389                 result
1390             }
1391
1392             _ => noop_fold_item(item, self),
1393         }
1394     }
1395
1396     fn fold_trait_item(&mut self, item: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
1397         let item = configure!(self, item);
1398
1399         let (attr, traits, item, after_derive) = self.classify_item(item);
1400         if attr.is_some() || !traits.is_empty() {
1401             return self.collect_attr(attr, traits, Annotatable::TraitItem(P(item)),
1402                                      AstFragmentKind::TraitItems, after_derive).make_trait_items()
1403         }
1404
1405         match item.node {
1406             ast::TraitItemKind::Macro(mac) => {
1407                 let ast::TraitItem { attrs, span, .. } = item;
1408                 self.check_attributes(&attrs);
1409                 self.collect_bang(mac, span, AstFragmentKind::TraitItems).make_trait_items()
1410             }
1411             _ => fold::noop_fold_trait_item(item, self),
1412         }
1413     }
1414
1415     fn fold_impl_item(&mut self, item: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> {
1416         let item = configure!(self, item);
1417
1418         let (attr, traits, item, after_derive) = self.classify_item(item);
1419         if attr.is_some() || !traits.is_empty() {
1420             return self.collect_attr(attr, traits, Annotatable::ImplItem(P(item)),
1421                                      AstFragmentKind::ImplItems, after_derive).make_impl_items();
1422         }
1423
1424         match item.node {
1425             ast::ImplItemKind::Macro(mac) => {
1426                 let ast::ImplItem { attrs, span, .. } = item;
1427                 self.check_attributes(&attrs);
1428                 self.collect_bang(mac, span, AstFragmentKind::ImplItems).make_impl_items()
1429             }
1430             _ => fold::noop_fold_impl_item(item, self),
1431         }
1432     }
1433
1434     fn fold_ty(&mut self, ty: P<ast::Ty>) -> P<ast::Ty> {
1435         let ty = match ty.node {
1436             ast::TyKind::Mac(_) => ty.into_inner(),
1437             _ => return fold::noop_fold_ty(ty, self),
1438         };
1439
1440         match ty.node {
1441             ast::TyKind::Mac(mac) => self.collect_bang(mac, ty.span, AstFragmentKind::Ty).make_ty(),
1442             _ => unreachable!(),
1443         }
1444     }
1445
1446     fn fold_foreign_mod(&mut self, foreign_mod: ast::ForeignMod) -> ast::ForeignMod {
1447         noop_fold_foreign_mod(self.cfg.configure_foreign_mod(foreign_mod), self)
1448     }
1449
1450     fn fold_foreign_item(&mut self, foreign_item: ast::ForeignItem)
1451         -> SmallVec<[ast::ForeignItem; 1]>
1452     {
1453         let (attr, traits, foreign_item, after_derive) = self.classify_item(foreign_item);
1454
1455         if attr.is_some() || !traits.is_empty() {
1456             return self.collect_attr(attr, traits, Annotatable::ForeignItem(P(foreign_item)),
1457                                      AstFragmentKind::ForeignItems, after_derive)
1458                                      .make_foreign_items();
1459         }
1460
1461         if let ast::ForeignItemKind::Macro(mac) = foreign_item.node {
1462             self.check_attributes(&foreign_item.attrs);
1463             return self.collect_bang(mac, foreign_item.span, AstFragmentKind::ForeignItems)
1464                 .make_foreign_items();
1465         }
1466
1467         noop_fold_foreign_item(foreign_item, self)
1468     }
1469
1470     fn fold_item_kind(&mut self, item: ast::ItemKind) -> ast::ItemKind {
1471         match item {
1472             ast::ItemKind::MacroDef(..) => item,
1473             _ => noop_fold_item_kind(self.cfg.configure_item_kind(item), self),
1474         }
1475     }
1476
1477     fn fold_generic_param(&mut self, param: ast::GenericParam) -> ast::GenericParam {
1478         self.cfg.disallow_cfg_on_generic_param(&param);
1479         noop_fold_generic_param(param, self)
1480     }
1481
1482     fn fold_attribute(&mut self, at: ast::Attribute) -> Option<ast::Attribute> {
1483         // turn `#[doc(include="filename")]` attributes into `#[doc(include(file="filename",
1484         // contents="file contents")]` attributes
1485         if !at.check_name("doc") {
1486             return noop_fold_attribute(at, self);
1487         }
1488
1489         if let Some(list) = at.meta_item_list() {
1490             if !list.iter().any(|it| it.check_name("include")) {
1491                 return noop_fold_attribute(at, self);
1492             }
1493
1494             let mut items = vec![];
1495
1496             for it in list {
1497                 if !it.check_name("include") {
1498                     items.push(noop_fold_meta_list_item(it, self));
1499                     continue;
1500                 }
1501
1502                 if let Some(file) = it.value_str() {
1503                     let err_count = self.cx.parse_sess.span_diagnostic.err_count();
1504                     self.check_attribute(&at);
1505                     if self.cx.parse_sess.span_diagnostic.err_count() > err_count {
1506                         // avoid loading the file if they haven't enabled the feature
1507                         return noop_fold_attribute(at, self);
1508                     }
1509
1510                     let mut buf = vec![];
1511                     let filename = self.cx.root_path.join(file.to_string());
1512
1513                     match File::open(&filename).and_then(|mut f| f.read_to_end(&mut buf)) {
1514                         Ok(..) => {}
1515                         Err(e) => {
1516                             self.cx.span_err(at.span,
1517                                              &format!("couldn't read {}: {}",
1518                                                       filename.display(),
1519                                                       e));
1520                         }
1521                     }
1522
1523                     match String::from_utf8(buf) {
1524                         Ok(src) => {
1525                             let src_interned = Symbol::intern(&src);
1526
1527                             // Add this input file to the code map to make it available as
1528                             // dependency information
1529                             self.cx.source_map().new_source_file(filename.into(), src);
1530
1531                             let include_info = vec![
1532                                 dummy_spanned(ast::NestedMetaItemKind::MetaItem(
1533                                         attr::mk_name_value_item_str(Ident::from_str("file"),
1534                                                                      dummy_spanned(file)))),
1535                                 dummy_spanned(ast::NestedMetaItemKind::MetaItem(
1536                                         attr::mk_name_value_item_str(Ident::from_str("contents"),
1537                                                             dummy_spanned(src_interned)))),
1538                             ];
1539
1540                             let include_ident = Ident::from_str("include");
1541                             let item = attr::mk_list_item(DUMMY_SP, include_ident, include_info);
1542                             items.push(dummy_spanned(ast::NestedMetaItemKind::MetaItem(item)));
1543                         }
1544                         Err(_) => {
1545                             self.cx.span_err(at.span,
1546                                              &format!("{} wasn't a utf-8 file",
1547                                                       filename.display()));
1548                         }
1549                     }
1550                 } else {
1551                     items.push(noop_fold_meta_list_item(it, self));
1552                 }
1553             }
1554
1555             let meta = attr::mk_list_item(DUMMY_SP, Ident::from_str("doc"), items);
1556             match at.style {
1557                 ast::AttrStyle::Inner =>
1558                     Some(attr::mk_spanned_attr_inner(at.span, at.id, meta)),
1559                 ast::AttrStyle::Outer =>
1560                     Some(attr::mk_spanned_attr_outer(at.span, at.id, meta)),
1561             }
1562         } else {
1563             noop_fold_attribute(at, self)
1564         }
1565     }
1566
1567     fn new_id(&mut self, id: ast::NodeId) -> ast::NodeId {
1568         if self.monotonic {
1569             assert_eq!(id, ast::DUMMY_NODE_ID);
1570             self.cx.resolver.next_node_id()
1571         } else {
1572             id
1573         }
1574     }
1575 }
1576
1577 pub struct ExpansionConfig<'feat> {
1578     pub crate_name: String,
1579     pub features: Option<&'feat Features>,
1580     pub recursion_limit: usize,
1581     pub trace_mac: bool,
1582     pub should_test: bool, // If false, strip `#[test]` nodes
1583     pub single_step: bool,
1584     pub keep_macs: bool,
1585 }
1586
1587 macro_rules! feature_tests {
1588     ($( fn $getter:ident = $field:ident, )*) => {
1589         $(
1590             pub fn $getter(&self) -> bool {
1591                 match self.features {
1592                     Some(&Features { $field: true, .. }) => true,
1593                     _ => false,
1594                 }
1595             }
1596         )*
1597     }
1598 }
1599
1600 impl<'feat> ExpansionConfig<'feat> {
1601     pub fn default(crate_name: String) -> ExpansionConfig<'static> {
1602         ExpansionConfig {
1603             crate_name,
1604             features: None,
1605             recursion_limit: 1024,
1606             trace_mac: false,
1607             should_test: false,
1608             single_step: false,
1609             keep_macs: false,
1610         }
1611     }
1612
1613     feature_tests! {
1614         fn enable_asm = asm,
1615         fn enable_custom_test_frameworks = custom_test_frameworks,
1616         fn enable_global_asm = global_asm,
1617         fn enable_log_syntax = log_syntax,
1618         fn enable_concat_idents = concat_idents,
1619         fn enable_trace_macros = trace_macros,
1620         fn enable_allow_internal_unstable = allow_internal_unstable,
1621         fn enable_format_args_nl = format_args_nl,
1622         fn macros_in_extern_enabled = macros_in_extern,
1623         fn proc_macro_hygiene = proc_macro_hygiene,
1624     }
1625
1626     fn enable_custom_inner_attributes(&self) -> bool {
1627         self.features.map_or(false, |features| {
1628             features.custom_inner_attributes || features.custom_attribute || features.rustc_attrs
1629         })
1630     }
1631 }
1632
1633 // A Marker adds the given mark to the syntax context.
1634 #[derive(Debug)]
1635 pub struct Marker(pub Mark);
1636
1637 impl Folder for Marker {
1638     fn new_span(&mut self, span: Span) -> Span {
1639         span.apply_mark(self.0)
1640     }
1641
1642     fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
1643         noop_fold_mac(mac, self)
1644     }
1645 }