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