]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/expand.rs
Make #[doc(include)] paths behave like other paths
[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::{ExpnId, SyntaxContext, ExpnInfo, ExpnKind};
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::{sym, Symbol};
17 use crate::tokenstream::{TokenStream, TokenTree};
18 use crate::visit::{self, Visitor};
19 use crate::util::map_in_place::MapInPlace;
20 use crate::util::path;
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) -> AstFragment {
163         self.make_from(DummyResult::any(span)).expect("couldn't create a dummy AST fragment")
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         span: Span,
201     },
202     Attr {
203         attr: ast::Attribute,
204         item: Annotatable,
205         // Required for resolving derive helper attributes.
206         derives: Vec<Path>,
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         item_with_markers: Annotatable,
214     },
215     /// "Invocation" that contains all derives from an item,
216     /// broken into multiple `Derive` invocations when expanded.
217     /// FIXME: Find a way to remove it.
218     DeriveContainer {
219         derives: Vec<Path>,
220         item: Annotatable,
221     },
222 }
223
224 impl Invocation {
225     pub fn span(&self) -> Span {
226         match &self.kind {
227             InvocationKind::Bang { span, .. } => *span,
228             InvocationKind::Attr { attr, .. } => attr.span,
229             InvocationKind::Derive { path, .. } => path.span,
230             InvocationKind::DeriveContainer { item, .. } => item.span(),
231         }
232     }
233 }
234
235 pub struct MacroExpander<'a, 'b> {
236     pub cx: &'a mut ExtCtxt<'b>,
237     monotonic: bool, // cf. `cx.monotonic_expander()`
238 }
239
240 impl<'a, 'b> MacroExpander<'a, 'b> {
241     pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self {
242         MacroExpander { cx, monotonic }
243     }
244
245     pub fn expand_crate(&mut self, mut krate: ast::Crate) -> ast::Crate {
246         let mut module = ModuleData {
247             mod_path: vec![Ident::from_str(&self.cx.ecfg.crate_name)],
248             directory: match self.cx.source_map().span_to_unmapped_path(krate.span) {
249                 FileName::Real(path) => path,
250                 other => PathBuf::from(other.to_string()),
251             },
252         };
253         module.directory.pop();
254         self.cx.root_path = module.directory.clone();
255         self.cx.current_expansion.module = Rc::new(module);
256
257         let orig_mod_span = krate.module.inner;
258
259         let krate_item = AstFragment::Items(smallvec![P(ast::Item {
260             attrs: krate.attrs,
261             span: krate.span,
262             node: ast::ItemKind::Mod(krate.module),
263             ident: Ident::invalid(),
264             id: ast::DUMMY_NODE_ID,
265             vis: respan(krate.span.shrink_to_lo(), ast::VisibilityKind::Public),
266             tokens: None,
267         })]);
268
269         match self.expand_fragment(krate_item).make_items().pop().map(P::into_inner) {
270             Some(ast::Item { attrs, node: ast::ItemKind::Mod(module), .. }) => {
271                 krate.attrs = attrs;
272                 krate.module = module;
273             },
274             None => {
275                 // Resolution failed so we return an empty expansion
276                 krate.attrs = vec![];
277                 krate.module = ast::Mod {
278                     inner: orig_mod_span,
279                     items: vec![],
280                     inline: true,
281                 };
282             },
283             _ => unreachable!(),
284         };
285         self.cx.trace_macros_diag();
286         krate
287     }
288
289     // Fully expand all macro invocations in this AST fragment.
290     fn expand_fragment(&mut self, input_fragment: AstFragment) -> AstFragment {
291         let orig_expansion_data = self.cx.current_expansion.clone();
292         self.cx.current_expansion.depth = 0;
293
294         // Collect all macro invocations and replace them with placeholders.
295         let (mut fragment_with_placeholders, mut invocations)
296             = self.collect_invocations(input_fragment, &[]);
297
298         // Optimization: if we resolve all imports now,
299         // we'll be able to immediately resolve most of imported macros.
300         self.resolve_imports();
301
302         // Resolve paths in all invocations and produce output expanded fragments for them, but
303         // do not insert them into our input AST fragment yet, only store in `expanded_fragments`.
304         // The output fragments also go through expansion recursively until no invocations are left.
305         // Unresolved macros produce dummy outputs as a recovery measure.
306         invocations.reverse();
307         let mut expanded_fragments = Vec::new();
308         let mut derives: FxHashMap<ExpnId, Vec<_>> = FxHashMap::default();
309         let mut undetermined_invocations = Vec::new();
310         let (mut progress, mut force) = (false, !self.monotonic);
311         loop {
312             let invoc = if let Some(invoc) = invocations.pop() {
313                 invoc
314             } else {
315                 self.resolve_imports();
316                 if undetermined_invocations.is_empty() { break }
317                 invocations = mem::take(&mut undetermined_invocations);
318                 force = !mem::replace(&mut progress, false);
319                 continue
320             };
321
322             let scope =
323                 if self.monotonic { invoc.expansion_data.id } else { orig_expansion_data.id };
324             let ext = match self.cx.resolver.resolve_macro_invocation(&invoc, scope, force) {
325                 Ok(ext) => ext,
326                 Err(Indeterminate) => {
327                     undetermined_invocations.push(invoc);
328                     continue
329                 }
330             };
331
332             progress = true;
333             let ExpansionData { depth, id: expn_id, .. } = invoc.expansion_data;
334             self.cx.current_expansion = invoc.expansion_data.clone();
335             self.cx.current_expansion.id = scope;
336
337             // FIXME(jseyfried): Refactor out the following logic
338             let (expanded_fragment, new_invocations) = if let Some(ext) = ext {
339                 let fragment = self.expand_invoc(invoc, &ext.kind);
340                 self.collect_invocations(fragment, &[])
341             } else if let InvocationKind::DeriveContainer { derives: traits, item } = invoc.kind {
342                 if !item.derive_allowed() {
343                     let attr = attr::find_by_name(item.attrs(), sym::derive)
344                         .expect("`derive` attribute should exist");
345                     let span = attr.span;
346                     let mut err = self.cx.mut_span_err(span,
347                                                         "`derive` may only be applied to \
348                                                         structs, enums and unions");
349                     if let ast::AttrStyle::Inner = attr.style {
350                         let trait_list = traits.iter()
351                             .map(|t| t.to_string()).collect::<Vec<_>>();
352                         let suggestion = format!("#[derive({})]", trait_list.join(", "));
353                         err.span_suggestion(
354                             span, "try an outer attribute", suggestion,
355                             // We don't 𝑘𝑛𝑜𝑤 that the following item is an ADT
356                             Applicability::MaybeIncorrect
357                         );
358                     }
359                     err.emit();
360                 }
361
362                 let mut item = self.fully_configure(item);
363                 item.visit_attrs(|attrs| attrs.retain(|a| a.path != sym::derive));
364                 let mut item_with_markers = item.clone();
365                 add_derived_markers(&mut self.cx, item.span(), &traits, &mut item_with_markers);
366                 let derives = derives.entry(invoc.expansion_data.id).or_default();
367
368                 derives.reserve(traits.len());
369                 invocations.reserve(traits.len());
370                 for path in traits {
371                     let expn_id = ExpnId::fresh(self.cx.current_expansion.id, None);
372                     derives.push(expn_id);
373                     invocations.push(Invocation {
374                         kind: InvocationKind::Derive {
375                             path,
376                             item: item.clone(),
377                             item_with_markers: item_with_markers.clone(),
378                         },
379                         fragment_kind: invoc.fragment_kind,
380                         expansion_data: ExpansionData {
381                             id: expn_id,
382                             ..invoc.expansion_data.clone()
383                         },
384                     });
385                 }
386                 let fragment = invoc.fragment_kind
387                     .expect_from_annotatables(::std::iter::once(item_with_markers));
388                 self.collect_invocations(fragment, derives)
389             } else {
390                 unreachable!()
391             };
392
393             if expanded_fragments.len() < depth {
394                 expanded_fragments.push(Vec::new());
395             }
396             expanded_fragments[depth - 1].push((expn_id, expanded_fragment));
397             if !self.cx.ecfg.single_step {
398                 invocations.extend(new_invocations.into_iter().rev());
399             }
400         }
401
402         self.cx.current_expansion = orig_expansion_data;
403
404         // Finally incorporate all the expanded macros into the input AST fragment.
405         let mut placeholder_expander = PlaceholderExpander::new(self.cx, self.monotonic);
406         while let Some(expanded_fragments) = expanded_fragments.pop() {
407             for (mark, expanded_fragment) in expanded_fragments.into_iter().rev() {
408                 let derives = derives.remove(&mark).unwrap_or_else(Vec::new);
409                 placeholder_expander.add(NodeId::placeholder_from_expn_id(mark),
410                                          expanded_fragment, derives);
411             }
412         }
413         fragment_with_placeholders.mut_visit_with(&mut placeholder_expander);
414         fragment_with_placeholders
415     }
416
417     fn resolve_imports(&mut self) {
418         if self.monotonic {
419             self.cx.resolver.resolve_imports();
420         }
421     }
422
423     /// Collects all macro invocations reachable at this time in this AST fragment, and replace
424     /// them with "placeholders" - dummy macro invocations with specially crafted `NodeId`s.
425     /// Then call into resolver that builds a skeleton ("reduced graph") of the fragment and
426     /// prepares data for resolving paths of macro invocations.
427     fn collect_invocations(&mut self, mut fragment: AstFragment, derives: &[ExpnId])
428                            -> (AstFragment, Vec<Invocation>) {
429         // Resolve `$crate`s in the fragment for pretty-printing.
430         self.cx.resolver.resolve_dollar_crates();
431
432         let invocations = {
433             let mut collector = InvocationCollector {
434                 cfg: StripUnconfigured {
435                     sess: self.cx.parse_sess,
436                     features: self.cx.ecfg.features,
437                 },
438                 cx: self.cx,
439                 invocations: Vec::new(),
440                 monotonic: self.monotonic,
441             };
442             fragment.mut_visit_with(&mut collector);
443             collector.invocations
444         };
445
446         if self.monotonic {
447             self.cx.resolver.visit_ast_fragment_with_placeholders(
448                 self.cx.current_expansion.id, &fragment, derives);
449         }
450
451         (fragment, invocations)
452     }
453
454     fn fully_configure(&mut self, item: Annotatable) -> Annotatable {
455         let mut cfg = StripUnconfigured {
456             sess: self.cx.parse_sess,
457             features: self.cx.ecfg.features,
458         };
459         // Since the item itself has already been configured by the InvocationCollector,
460         // we know that fold result vector will contain exactly one element
461         match item {
462             Annotatable::Item(item) => {
463                 Annotatable::Item(cfg.flat_map_item(item).pop().unwrap())
464             }
465             Annotatable::TraitItem(item) => {
466                 Annotatable::TraitItem(
467                     item.map(|item| cfg.flat_map_trait_item(item).pop().unwrap()))
468             }
469             Annotatable::ImplItem(item) => {
470                 Annotatable::ImplItem(item.map(|item| cfg.flat_map_impl_item(item).pop().unwrap()))
471             }
472             Annotatable::ForeignItem(item) => {
473                 Annotatable::ForeignItem(
474                     item.map(|item| cfg.flat_map_foreign_item(item).pop().unwrap())
475                 )
476             }
477             Annotatable::Stmt(stmt) => {
478                 Annotatable::Stmt(stmt.map(|stmt| cfg.flat_map_stmt(stmt).pop().unwrap()))
479             }
480             Annotatable::Expr(mut expr) => {
481                 Annotatable::Expr({ cfg.visit_expr(&mut expr); expr })
482             }
483         }
484     }
485
486     fn expand_invoc(&mut self, invoc: Invocation, ext: &SyntaxExtensionKind) -> AstFragment {
487         let (fragment_kind, span) = (invoc.fragment_kind, invoc.span());
488         if fragment_kind == AstFragmentKind::ForeignItems && !self.cx.ecfg.macros_in_extern() {
489             if let SyntaxExtensionKind::NonMacroAttr { .. } = ext {} else {
490                 emit_feature_err(&self.cx.parse_sess, sym::macros_in_extern,
491                                  span, GateIssue::Language,
492                                  "macro invocations in `extern {}` blocks are experimental");
493             }
494         }
495
496         if self.cx.current_expansion.depth > self.cx.ecfg.recursion_limit {
497             let info = self.cx.current_expansion.id.expn_info().unwrap();
498             let suggested_limit = self.cx.ecfg.recursion_limit * 2;
499             let mut err = self.cx.struct_span_err(info.call_site,
500                 &format!("recursion limit reached while expanding the macro `{}`",
501                          info.kind.descr()));
502             err.help(&format!(
503                 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
504                 suggested_limit));
505             err.emit();
506             self.cx.trace_macros_diag();
507             FatalError.raise();
508         }
509
510         match invoc.kind {
511             InvocationKind::Bang { mac, .. } => match ext {
512                 SyntaxExtensionKind::Bang(expander) => {
513                     self.gate_proc_macro_expansion_kind(span, fragment_kind);
514                     let tok_result = expander.expand(self.cx, span, mac.node.stream());
515                     let result =
516                         self.parse_ast_fragment(tok_result, fragment_kind, &mac.node.path, span);
517                     self.gate_proc_macro_expansion(span, &result);
518                     result
519                 }
520                 SyntaxExtensionKind::LegacyBang(expander) => {
521                     let tok_result = expander.expand(self.cx, span, mac.node.stream());
522                     if let Some(result) = fragment_kind.make_from(tok_result) {
523                         result
524                     } else {
525                         let msg = format!("non-{kind} macro in {kind} position: {path}",
526                                           kind = fragment_kind.name(), path = mac.node.path);
527                         self.cx.span_err(span, &msg);
528                         self.cx.trace_macros_diag();
529                         fragment_kind.dummy(span)
530                     }
531                 }
532                 _ => unreachable!()
533             }
534             InvocationKind::Attr { attr, mut item, .. } => match ext {
535                 SyntaxExtensionKind::Attr(expander) => {
536                     self.gate_proc_macro_attr_item(span, &item);
537                     let item_tok = TokenTree::token(token::Interpolated(Lrc::new(match item {
538                         Annotatable::Item(item) => token::NtItem(item),
539                         Annotatable::TraitItem(item) => token::NtTraitItem(item.into_inner()),
540                         Annotatable::ImplItem(item) => token::NtImplItem(item.into_inner()),
541                         Annotatable::ForeignItem(item) => token::NtForeignItem(item.into_inner()),
542                         Annotatable::Stmt(stmt) => token::NtStmt(stmt.into_inner()),
543                         Annotatable::Expr(expr) => token::NtExpr(expr),
544                     })), DUMMY_SP).into();
545                     let input = self.extract_proc_macro_attr_input(attr.tokens, span);
546                     let tok_result = expander.expand(self.cx, span, input, item_tok);
547                     let res = self.parse_ast_fragment(tok_result, fragment_kind, &attr.path, span);
548                     self.gate_proc_macro_expansion(span, &res);
549                     res
550                 }
551                 SyntaxExtensionKind::LegacyAttr(expander) => {
552                     match attr.parse_meta(self.cx.parse_sess) {
553                         Ok(meta) => {
554                             let item = expander.expand(self.cx, span, &meta, item);
555                             fragment_kind.expect_from_annotatables(item)
556                         }
557                         Err(mut err) => {
558                             err.emit();
559                             fragment_kind.dummy(span)
560                         }
561                     }
562                 }
563                 SyntaxExtensionKind::NonMacroAttr { mark_used } => {
564                     attr::mark_known(&attr);
565                     if *mark_used {
566                         attr::mark_used(&attr);
567                     }
568                     item.visit_attrs(|attrs| attrs.push(attr));
569                     fragment_kind.expect_from_annotatables(iter::once(item))
570                 }
571                 _ => unreachable!()
572             }
573             InvocationKind::Derive { path, item, item_with_markers } => match ext {
574                 SyntaxExtensionKind::Derive(expander) |
575                 SyntaxExtensionKind::LegacyDerive(expander) => {
576                     let (path, item) = match ext {
577                         SyntaxExtensionKind::LegacyDerive(..) => (path, item_with_markers),
578                         _ => (path, item),
579                     };
580                     if !item.derive_allowed() {
581                         return fragment_kind.dummy(span);
582                     }
583                     let meta = ast::MetaItem { node: ast::MetaItemKind::Word, span, path };
584                     let span = span.with_ctxt(self.cx.backtrace());
585                     let items = expander.expand(self.cx, span, &meta, item);
586                     fragment_kind.expect_from_annotatables(items)
587                 }
588                 _ => unreachable!()
589             }
590             InvocationKind::DeriveContainer { .. } => unreachable!()
591         }
592     }
593
594     fn extract_proc_macro_attr_input(&self, tokens: TokenStream, span: Span) -> TokenStream {
595         let mut trees = tokens.trees();
596         match trees.next() {
597             Some(TokenTree::Delimited(_, _, tts)) => {
598                 if trees.next().is_none() {
599                     return tts.into()
600                 }
601             }
602             Some(TokenTree::Token(..)) => {}
603             None => return TokenStream::empty(),
604         }
605         self.cx.span_err(span, "custom attribute invocations must be \
606             of the form #[foo] or #[foo(..)], the macro name must only be \
607             followed by a delimiter token");
608         TokenStream::empty()
609     }
610
611     fn gate_proc_macro_attr_item(&self, span: Span, item: &Annotatable) {
612         let (kind, gate) = match *item {
613             Annotatable::Item(ref item) => {
614                 match item.node {
615                     ItemKind::Mod(_) if self.cx.ecfg.proc_macro_hygiene() => return,
616                     ItemKind::Mod(_) => ("modules", sym::proc_macro_hygiene),
617                     _ => return,
618                 }
619             }
620             Annotatable::TraitItem(_) => return,
621             Annotatable::ImplItem(_) => return,
622             Annotatable::ForeignItem(_) => return,
623             Annotatable::Stmt(_) |
624             Annotatable::Expr(_) if self.cx.ecfg.proc_macro_hygiene() => return,
625             Annotatable::Stmt(_) => ("statements", sym::proc_macro_hygiene),
626             Annotatable::Expr(_) => ("expressions", sym::proc_macro_hygiene),
627         };
628         emit_feature_err(
629             self.cx.parse_sess,
630             gate,
631             span,
632             GateIssue::Language,
633             &format!("custom attributes cannot be applied to {}", kind),
634         );
635     }
636
637     fn gate_proc_macro_expansion(&self, span: Span, fragment: &AstFragment) {
638         if self.cx.ecfg.proc_macro_hygiene() {
639             return
640         }
641
642         fragment.visit_with(&mut DisallowMacros {
643             span,
644             parse_sess: self.cx.parse_sess,
645         });
646
647         struct DisallowMacros<'a> {
648             span: Span,
649             parse_sess: &'a ParseSess,
650         }
651
652         impl<'ast, 'a> Visitor<'ast> for DisallowMacros<'a> {
653             fn visit_item(&mut self, i: &'ast ast::Item) {
654                 if let ast::ItemKind::MacroDef(_) = i.node {
655                     emit_feature_err(
656                         self.parse_sess,
657                         sym::proc_macro_hygiene,
658                         self.span,
659                         GateIssue::Language,
660                         "procedural macros cannot expand to macro definitions",
661                     );
662                 }
663                 visit::walk_item(self, i);
664             }
665
666             fn visit_mac(&mut self, _mac: &'ast ast::Mac) {
667                 // ...
668             }
669         }
670     }
671
672     fn gate_proc_macro_expansion_kind(&self, span: Span, kind: AstFragmentKind) {
673         let kind = match kind {
674             AstFragmentKind::Expr => "expressions",
675             AstFragmentKind::OptExpr => "expressions",
676             AstFragmentKind::Pat => "patterns",
677             AstFragmentKind::Ty => "types",
678             AstFragmentKind::Stmts => "statements",
679             AstFragmentKind::Items => return,
680             AstFragmentKind::TraitItems => return,
681             AstFragmentKind::ImplItems => return,
682             AstFragmentKind::ForeignItems => return,
683         };
684         if self.cx.ecfg.proc_macro_hygiene() {
685             return
686         }
687         emit_feature_err(
688             self.cx.parse_sess,
689             sym::proc_macro_hygiene,
690             span,
691             GateIssue::Language,
692             &format!("procedural macros cannot be expanded to {}", kind),
693         );
694     }
695
696     fn parse_ast_fragment(&mut self,
697                           toks: TokenStream,
698                           kind: AstFragmentKind,
699                           path: &Path,
700                           span: Span)
701                           -> AstFragment {
702         let mut parser = self.cx.new_parser_from_tts(&toks.into_trees().collect::<Vec<_>>());
703         match parser.parse_ast_fragment(kind, false) {
704             Ok(fragment) => {
705                 parser.ensure_complete_parse(path, kind.name(), span);
706                 fragment
707             }
708             Err(mut err) => {
709                 err.set_span(span);
710                 err.emit();
711                 self.cx.trace_macros_diag();
712                 kind.dummy(span)
713             }
714         }
715     }
716 }
717
718 impl<'a> Parser<'a> {
719     pub fn parse_ast_fragment(&mut self, kind: AstFragmentKind, macro_legacy_warnings: bool)
720                               -> PResult<'a, AstFragment> {
721         Ok(match kind {
722             AstFragmentKind::Items => {
723                 let mut items = SmallVec::new();
724                 while let Some(item) = self.parse_item()? {
725                     items.push(item);
726                 }
727                 AstFragment::Items(items)
728             }
729             AstFragmentKind::TraitItems => {
730                 let mut items = SmallVec::new();
731                 while self.token != token::Eof {
732                     items.push(self.parse_trait_item(&mut false)?);
733                 }
734                 AstFragment::TraitItems(items)
735             }
736             AstFragmentKind::ImplItems => {
737                 let mut items = SmallVec::new();
738                 while self.token != token::Eof {
739                     items.push(self.parse_impl_item(&mut false)?);
740                 }
741                 AstFragment::ImplItems(items)
742             }
743             AstFragmentKind::ForeignItems => {
744                 let mut items = SmallVec::new();
745                 while self.token != token::Eof {
746                     items.push(self.parse_foreign_item(DUMMY_SP)?);
747                 }
748                 AstFragment::ForeignItems(items)
749             }
750             AstFragmentKind::Stmts => {
751                 let mut stmts = SmallVec::new();
752                 while self.token != token::Eof &&
753                       // won't make progress on a `}`
754                       self.token != token::CloseDelim(token::Brace) {
755                     if let Some(stmt) = self.parse_full_stmt(macro_legacy_warnings)? {
756                         stmts.push(stmt);
757                     }
758                 }
759                 AstFragment::Stmts(stmts)
760             }
761             AstFragmentKind::Expr => AstFragment::Expr(self.parse_expr()?),
762             AstFragmentKind::OptExpr => {
763                 if self.token != token::Eof {
764                     AstFragment::OptExpr(Some(self.parse_expr()?))
765                 } else {
766                     AstFragment::OptExpr(None)
767                 }
768             },
769             AstFragmentKind::Ty => AstFragment::Ty(self.parse_ty()?),
770             AstFragmentKind::Pat => AstFragment::Pat(self.parse_pat(None)?),
771         })
772     }
773
774     pub fn ensure_complete_parse(&mut self, macro_path: &Path, kind_name: &str, span: Span) {
775         if self.token != token::Eof {
776             let msg = format!("macro expansion ignores token `{}` and any following",
777                               self.this_token_to_string());
778             // Avoid emitting backtrace info twice.
779             let def_site_span = self.token.span.with_ctxt(SyntaxContext::empty());
780             let mut err = self.diagnostic().struct_span_err(def_site_span, &msg);
781             err.span_label(span, "caused by the macro expansion here");
782             let msg = format!(
783                 "the usage of `{}!` is likely invalid in {} context",
784                 macro_path,
785                 kind_name,
786             );
787             err.note(&msg);
788             let semi_span = self.sess.source_map().next_point(span);
789
790             let semi_full_span = semi_span.to(self.sess.source_map().next_point(semi_span));
791             match self.sess.source_map().span_to_snippet(semi_full_span) {
792                 Ok(ref snippet) if &snippet[..] != ";" && kind_name == "expression" => {
793                     err.span_suggestion(
794                         semi_span,
795                         "you might be missing a semicolon here",
796                         ";".to_owned(),
797                         Applicability::MaybeIncorrect,
798                     );
799                 }
800                 _ => {}
801             }
802             err.emit();
803         }
804     }
805 }
806
807 struct InvocationCollector<'a, 'b> {
808     cx: &'a mut ExtCtxt<'b>,
809     cfg: StripUnconfigured<'a>,
810     invocations: Vec<Invocation>,
811     monotonic: bool,
812 }
813
814 impl<'a, 'b> InvocationCollector<'a, 'b> {
815     fn collect(&mut self, fragment_kind: AstFragmentKind, kind: InvocationKind) -> AstFragment {
816         // Expansion info for all the collected invocations is set upon their resolution,
817         // with exception of the derive container case which is not resolved and can get
818         // its expansion info immediately.
819         let expn_info = match &kind {
820             InvocationKind::DeriveContainer { item, .. } => Some(ExpnInfo::default(
821                 ExpnKind::Macro(MacroKind::Attr, sym::derive),
822                 item.span(), self.cx.parse_sess.edition,
823             )),
824             _ => None,
825         };
826         let expn_id = ExpnId::fresh(self.cx.current_expansion.id, expn_info);
827         self.invocations.push(Invocation {
828             kind,
829             fragment_kind,
830             expansion_data: ExpansionData {
831                 id: expn_id,
832                 depth: self.cx.current_expansion.depth + 1,
833                 ..self.cx.current_expansion.clone()
834             },
835         });
836         placeholder(fragment_kind, NodeId::placeholder_from_expn_id(expn_id))
837     }
838
839     fn collect_bang(&mut self, mac: ast::Mac, span: Span, kind: AstFragmentKind) -> AstFragment {
840         self.collect(kind, InvocationKind::Bang { mac, span })
841     }
842
843     fn collect_attr(&mut self,
844                     attr: Option<ast::Attribute>,
845                     derives: Vec<Path>,
846                     item: Annotatable,
847                     kind: AstFragmentKind,
848                     after_derive: bool)
849                     -> AstFragment {
850         self.collect(kind, match attr {
851             Some(attr) => InvocationKind::Attr { attr, item, derives, after_derive },
852             None => InvocationKind::DeriveContainer { derives, item },
853         })
854     }
855
856     fn find_attr_invoc(&self, attrs: &mut Vec<ast::Attribute>, after_derive: &mut bool)
857                        -> Option<ast::Attribute> {
858         let attr = attrs.iter()
859                         .position(|a| {
860                             if a.path == sym::derive {
861                                 *after_derive = true;
862                             }
863                             !attr::is_known(a) && !is_builtin_attr(a)
864                         })
865                         .map(|i| attrs.remove(i));
866         if let Some(attr) = &attr {
867             if !self.cx.ecfg.custom_inner_attributes() &&
868                attr.style == ast::AttrStyle::Inner && attr.path != sym::test {
869                 emit_feature_err(&self.cx.parse_sess, sym::custom_inner_attributes,
870                                  attr.span, GateIssue::Language,
871                                  "non-builtin inner attributes are unstable");
872             }
873         }
874         attr
875     }
876
877     /// If `item` is an attr invocation, remove and return the macro attribute and derive traits.
878     fn classify_item<T>(&mut self, item: &mut T)
879                         -> (Option<ast::Attribute>, Vec<Path>, /* after_derive */ bool)
880         where T: HasAttrs,
881     {
882         let (mut attr, mut traits, mut after_derive) = (None, Vec::new(), false);
883
884         item.visit_attrs(|mut attrs| {
885             attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
886             traits = collect_derives(&mut self.cx, &mut attrs);
887         });
888
889         (attr, traits, after_derive)
890     }
891
892     /// Alternative to `classify_item()` that ignores `#[derive]` so invocations fallthrough
893     /// to the unused-attributes lint (making it an error on statements and expressions
894     /// is a breaking change)
895     fn classify_nonitem<T: HasAttrs>(&mut self, nonitem: &mut T)
896                                      -> (Option<ast::Attribute>, /* after_derive */ bool) {
897         let (mut attr, mut after_derive) = (None, false);
898
899         nonitem.visit_attrs(|mut attrs| {
900             attr = self.find_attr_invoc(&mut attrs, &mut after_derive);
901         });
902
903         (attr, after_derive)
904     }
905
906     fn configure<T: HasAttrs>(&mut self, node: T) -> Option<T> {
907         self.cfg.configure(node)
908     }
909
910     // Detect use of feature-gated or invalid attributes on macro invocations
911     // since they will not be detected after macro expansion.
912     fn check_attributes(&mut self, attrs: &[ast::Attribute]) {
913         let features = self.cx.ecfg.features.unwrap();
914         for attr in attrs.iter() {
915             self.check_attribute_inner(attr, features);
916
917             // macros are expanded before any lint passes so this warning has to be hardcoded
918             if attr.path == sym::derive {
919                 self.cx.struct_span_warn(attr.span, "`#[derive]` does nothing on macro invocations")
920                     .note("this may become a hard error in a future release")
921                     .emit();
922             }
923         }
924     }
925
926     fn check_attribute(&mut self, at: &ast::Attribute) {
927         let features = self.cx.ecfg.features.unwrap();
928         self.check_attribute_inner(at, features);
929     }
930
931     fn check_attribute_inner(&mut self, at: &ast::Attribute, features: &Features) {
932         feature_gate::check_attribute(at, self.cx.parse_sess, features);
933     }
934 }
935
936 impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> {
937     fn visit_expr(&mut self, expr: &mut P<ast::Expr>) {
938         self.cfg.configure_expr(expr);
939         visit_clobber(expr.deref_mut(), |mut expr| {
940             self.cfg.configure_expr_kind(&mut expr.node);
941
942             // ignore derives so they remain unused
943             let (attr, after_derive) = self.classify_nonitem(&mut expr);
944
945             if attr.is_some() {
946                 // Collect the invoc regardless of whether or not attributes are permitted here
947                 // expansion will eat the attribute so it won't error later.
948                 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
949
950                 // AstFragmentKind::Expr requires the macro to emit an expression.
951                 return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)),
952                                           AstFragmentKind::Expr, after_derive)
953                     .make_expr()
954                     .into_inner()
955             }
956
957             if let ast::ExprKind::Mac(mac) = expr.node {
958                 self.check_attributes(&expr.attrs);
959                 self.collect_bang(mac, expr.span, AstFragmentKind::Expr)
960                     .make_expr()
961                     .into_inner()
962             } else {
963                 noop_visit_expr(&mut expr, self);
964                 expr
965             }
966         });
967     }
968
969     fn filter_map_expr(&mut self, expr: P<ast::Expr>) -> Option<P<ast::Expr>> {
970         let expr = configure!(self, expr);
971         expr.filter_map(|mut expr| {
972             self.cfg.configure_expr_kind(&mut expr.node);
973
974             // Ignore derives so they remain unused.
975             let (attr, after_derive) = self.classify_nonitem(&mut expr);
976
977             if attr.is_some() {
978                 attr.as_ref().map(|a| self.cfg.maybe_emit_expr_attr_err(a));
979
980                 return self.collect_attr(attr, vec![], Annotatable::Expr(P(expr)),
981                                          AstFragmentKind::OptExpr, after_derive)
982                     .make_opt_expr()
983                     .map(|expr| expr.into_inner())
984             }
985
986             if let ast::ExprKind::Mac(mac) = expr.node {
987                 self.check_attributes(&expr.attrs);
988                 self.collect_bang(mac, expr.span, AstFragmentKind::OptExpr)
989                     .make_opt_expr()
990                     .map(|expr| expr.into_inner())
991             } else {
992                 Some({ noop_visit_expr(&mut expr, self); expr })
993             }
994         })
995     }
996
997     fn visit_pat(&mut self, pat: &mut P<ast::Pat>) {
998         self.cfg.configure_pat(pat);
999         match pat.node {
1000             PatKind::Mac(_) => {}
1001             _ => return noop_visit_pat(pat, self),
1002         }
1003
1004         visit_clobber(pat, |mut pat| {
1005             match mem::replace(&mut pat.node, PatKind::Wild) {
1006                 PatKind::Mac(mac) =>
1007                     self.collect_bang(mac, pat.span, AstFragmentKind::Pat).make_pat(),
1008                 _ => unreachable!(),
1009             }
1010         });
1011     }
1012
1013     fn flat_map_stmt(&mut self, stmt: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> {
1014         let mut stmt = configure!(self, stmt);
1015
1016         // we'll expand attributes on expressions separately
1017         if !stmt.is_expr() {
1018             let (attr, derives, after_derive) = if stmt.is_item() {
1019                 self.classify_item(&mut stmt)
1020             } else {
1021                 // ignore derives on non-item statements so it falls through
1022                 // to the unused-attributes lint
1023                 let (attr, after_derive) = self.classify_nonitem(&mut stmt);
1024                 (attr, vec![], after_derive)
1025             };
1026
1027             if attr.is_some() || !derives.is_empty() {
1028                 return self.collect_attr(attr, derives, Annotatable::Stmt(P(stmt)),
1029                                          AstFragmentKind::Stmts, after_derive).make_stmts();
1030             }
1031         }
1032
1033         if let StmtKind::Mac(mac) = stmt.node {
1034             let (mac, style, attrs) = mac.into_inner();
1035             self.check_attributes(&attrs);
1036             let mut placeholder = self.collect_bang(mac, stmt.span, AstFragmentKind::Stmts)
1037                                         .make_stmts();
1038
1039             // If this is a macro invocation with a semicolon, then apply that
1040             // semicolon to the final statement produced by expansion.
1041             if style == MacStmtStyle::Semicolon {
1042                 if let Some(stmt) = placeholder.pop() {
1043                     placeholder.push(stmt.add_trailing_semicolon());
1044                 }
1045             }
1046
1047             return placeholder;
1048         }
1049
1050         // The placeholder expander gives ids to statements, so we avoid folding the id here.
1051         let ast::Stmt { id, node, span } = stmt;
1052         noop_flat_map_stmt_kind(node, self).into_iter().map(|node| {
1053             ast::Stmt { id, node, span }
1054         }).collect()
1055
1056     }
1057
1058     fn visit_block(&mut self, block: &mut P<Block>) {
1059         let old_directory_ownership = self.cx.current_expansion.directory_ownership;
1060         self.cx.current_expansion.directory_ownership = DirectoryOwnership::UnownedViaBlock;
1061         noop_visit_block(block, self);
1062         self.cx.current_expansion.directory_ownership = old_directory_ownership;
1063     }
1064
1065     fn flat_map_item(&mut self, item: P<ast::Item>) -> SmallVec<[P<ast::Item>; 1]> {
1066         let mut item = configure!(self, item);
1067
1068         let (attr, traits, after_derive) = self.classify_item(&mut item);
1069         if attr.is_some() || !traits.is_empty() {
1070             return self.collect_attr(attr, traits, Annotatable::Item(item),
1071                                      AstFragmentKind::Items, after_derive).make_items();
1072         }
1073
1074         match item.node {
1075             ast::ItemKind::Mac(..) => {
1076                 self.check_attributes(&item.attrs);
1077                 item.and_then(|item| match item.node {
1078                     ItemKind::Mac(mac) => self.collect(
1079                         AstFragmentKind::Items, InvocationKind::Bang { mac, span: item.span }
1080                     ).make_items(),
1081                     _ => unreachable!(),
1082                 })
1083             }
1084             ast::ItemKind::Mod(ast::Mod { inner, .. }) => {
1085                 if item.ident == Ident::invalid() {
1086                     return noop_flat_map_item(item, self);
1087                 }
1088
1089                 let orig_directory_ownership = self.cx.current_expansion.directory_ownership;
1090                 let mut module = (*self.cx.current_expansion.module).clone();
1091                 module.mod_path.push(item.ident);
1092
1093                 // Detect if this is an inline module (`mod m { ... }` as opposed to `mod m;`).
1094                 // In the non-inline case, `inner` is never the dummy span (cf. `parse_item_mod`).
1095                 // Thus, if `inner` is the dummy span, we know the module is inline.
1096                 let inline_module = item.span.contains(inner) || inner.is_dummy();
1097
1098                 if inline_module {
1099                     if let Some(path) = attr::first_attr_value_str_by_name(&item.attrs, sym::path) {
1100                         self.cx.current_expansion.directory_ownership =
1101                             DirectoryOwnership::Owned { relative: None };
1102                         module.directory.push(&*path.as_str());
1103                     } else {
1104                         module.directory.push(&*item.ident.as_str());
1105                     }
1106                 } else {
1107                     let path = self.cx.parse_sess.source_map().span_to_unmapped_path(inner);
1108                     let mut path = match path {
1109                         FileName::Real(path) => path,
1110                         other => PathBuf::from(other.to_string()),
1111                     };
1112                     let directory_ownership = match path.file_name().unwrap().to_str() {
1113                         Some("mod.rs") => DirectoryOwnership::Owned { relative: None },
1114                         Some(_) => DirectoryOwnership::Owned {
1115                             relative: Some(item.ident),
1116                         },
1117                         None => DirectoryOwnership::UnownedViaMod(false),
1118                     };
1119                     path.pop();
1120                     module.directory = path;
1121                     self.cx.current_expansion.directory_ownership = directory_ownership;
1122                 }
1123
1124                 let orig_module =
1125                     mem::replace(&mut self.cx.current_expansion.module, Rc::new(module));
1126                 let result = noop_flat_map_item(item, self);
1127                 self.cx.current_expansion.module = orig_module;
1128                 self.cx.current_expansion.directory_ownership = orig_directory_ownership;
1129                 result
1130             }
1131
1132             _ => noop_flat_map_item(item, self),
1133         }
1134     }
1135
1136     fn flat_map_trait_item(&mut self, item: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
1137         let mut item = configure!(self, item);
1138
1139         let (attr, traits, after_derive) = self.classify_item(&mut item);
1140         if attr.is_some() || !traits.is_empty() {
1141             return self.collect_attr(attr, traits, Annotatable::TraitItem(P(item)),
1142                                      AstFragmentKind::TraitItems, after_derive).make_trait_items()
1143         }
1144
1145         match item.node {
1146             ast::TraitItemKind::Macro(mac) => {
1147                 let ast::TraitItem { attrs, span, .. } = item;
1148                 self.check_attributes(&attrs);
1149                 self.collect_bang(mac, span, AstFragmentKind::TraitItems).make_trait_items()
1150             }
1151             _ => noop_flat_map_trait_item(item, self),
1152         }
1153     }
1154
1155     fn flat_map_impl_item(&mut self, item: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> {
1156         let mut item = configure!(self, item);
1157
1158         let (attr, traits, after_derive) = self.classify_item(&mut item);
1159         if attr.is_some() || !traits.is_empty() {
1160             return self.collect_attr(attr, traits, Annotatable::ImplItem(P(item)),
1161                                      AstFragmentKind::ImplItems, after_derive).make_impl_items();
1162         }
1163
1164         match item.node {
1165             ast::ImplItemKind::Macro(mac) => {
1166                 let ast::ImplItem { attrs, span, .. } = item;
1167                 self.check_attributes(&attrs);
1168                 self.collect_bang(mac, span, AstFragmentKind::ImplItems).make_impl_items()
1169             }
1170             _ => noop_flat_map_impl_item(item, self),
1171         }
1172     }
1173
1174     fn visit_ty(&mut self, ty: &mut P<ast::Ty>) {
1175         match ty.node {
1176             ast::TyKind::Mac(_) => {}
1177             _ => return noop_visit_ty(ty, self),
1178         };
1179
1180         visit_clobber(ty, |mut ty| {
1181             match mem::replace(&mut ty.node, ast::TyKind::Err) {
1182                 ast::TyKind::Mac(mac) =>
1183                     self.collect_bang(mac, ty.span, AstFragmentKind::Ty).make_ty(),
1184                 _ => unreachable!(),
1185             }
1186         });
1187     }
1188
1189     fn visit_foreign_mod(&mut self, foreign_mod: &mut ast::ForeignMod) {
1190         self.cfg.configure_foreign_mod(foreign_mod);
1191         noop_visit_foreign_mod(foreign_mod, self);
1192     }
1193
1194     fn flat_map_foreign_item(&mut self, mut foreign_item: ast::ForeignItem)
1195         -> SmallVec<[ast::ForeignItem; 1]>
1196     {
1197         let (attr, traits, after_derive) = self.classify_item(&mut foreign_item);
1198
1199         if attr.is_some() || !traits.is_empty() {
1200             return self.collect_attr(attr, traits, Annotatable::ForeignItem(P(foreign_item)),
1201                                      AstFragmentKind::ForeignItems, after_derive)
1202                                      .make_foreign_items();
1203         }
1204
1205         if let ast::ForeignItemKind::Macro(mac) = foreign_item.node {
1206             self.check_attributes(&foreign_item.attrs);
1207             return self.collect_bang(mac, foreign_item.span, AstFragmentKind::ForeignItems)
1208                 .make_foreign_items();
1209         }
1210
1211         noop_flat_map_foreign_item(foreign_item, self)
1212     }
1213
1214     fn visit_item_kind(&mut self, item: &mut ast::ItemKind) {
1215         match item {
1216             ast::ItemKind::MacroDef(..) => {}
1217             _ => {
1218                 self.cfg.configure_item_kind(item);
1219                 noop_visit_item_kind(item, self);
1220             }
1221         }
1222     }
1223
1224     fn visit_generic_params(&mut self, params: &mut Vec<ast::GenericParam>) {
1225         self.cfg.configure_generic_params(params);
1226         noop_visit_generic_params(params, self);
1227     }
1228
1229     fn visit_attribute(&mut self, at: &mut ast::Attribute) {
1230         // turn `#[doc(include="filename")]` attributes into `#[doc(include(file="filename",
1231         // contents="file contents")]` attributes
1232         if !at.check_name(sym::doc) {
1233             return noop_visit_attribute(at, self);
1234         }
1235
1236         if let Some(list) = at.meta_item_list() {
1237             if !list.iter().any(|it| it.check_name(sym::include)) {
1238                 return noop_visit_attribute(at, self);
1239             }
1240
1241             let mut items = vec![];
1242
1243             for mut it in list {
1244                 if !it.check_name(sym::include) {
1245                     items.push({ noop_visit_meta_list_item(&mut it, self); it });
1246                     continue;
1247                 }
1248
1249                 if let Some(file) = it.value_str() {
1250                     let err_count = self.cx.parse_sess.span_diagnostic.err_count();
1251                     self.check_attribute(&at);
1252                     if self.cx.parse_sess.span_diagnostic.err_count() > err_count {
1253                         // avoid loading the file if they haven't enabled the feature
1254                         return noop_visit_attribute(at, self);
1255                     }
1256
1257                     let filename = path::resolve(&*file.as_str(), it.span(), self.cx.source_map());
1258                     match fs::read_to_string(&filename) {
1259                         Ok(src) => {
1260                             let src_interned = Symbol::intern(&src);
1261
1262                             // Add this input file to the code map to make it available as
1263                             // dependency information
1264                             self.cx.source_map().new_source_file(filename.into(), src);
1265
1266                             let include_info = vec![
1267                                 ast::NestedMetaItem::MetaItem(
1268                                     attr::mk_name_value_item_str(
1269                                         Ident::with_empty_ctxt(sym::file),
1270                                         dummy_spanned(file),
1271                                     ),
1272                                 ),
1273                                 ast::NestedMetaItem::MetaItem(
1274                                     attr::mk_name_value_item_str(
1275                                         Ident::with_empty_ctxt(sym::contents),
1276                                         dummy_spanned(src_interned),
1277                                     ),
1278                                 ),
1279                             ];
1280
1281                             let include_ident = Ident::with_empty_ctxt(sym::include);
1282                             let item = attr::mk_list_item(DUMMY_SP, include_ident, include_info);
1283                             items.push(ast::NestedMetaItem::MetaItem(item));
1284                         }
1285                         Err(e) => {
1286                             let lit = it
1287                                 .meta_item()
1288                                 .and_then(|item| item.name_value_literal())
1289                                 .unwrap();
1290
1291                             if e.kind() == ErrorKind::InvalidData {
1292                                 self.cx
1293                                     .struct_span_err(
1294                                         lit.span,
1295                                         &format!("{} wasn't a utf-8 file", filename.display()),
1296                                     )
1297                                     .span_label(lit.span, "contains invalid utf-8")
1298                                     .emit();
1299                             } else {
1300                                 let mut err = self.cx.struct_span_err(
1301                                     lit.span,
1302                                     &format!("couldn't read {}: {}", filename.display(), e),
1303                                 );
1304                                 err.span_label(lit.span, "couldn't read file");
1305
1306                                 err.emit();
1307                             }
1308                         }
1309                     }
1310                 } else {
1311                     let mut err = self.cx.struct_span_err(
1312                         it.span(),
1313                         &format!("expected path to external documentation"),
1314                     );
1315
1316                     // Check if the user erroneously used `doc(include(...))` syntax.
1317                     let literal = it.meta_item_list().and_then(|list| {
1318                         if list.len() == 1 {
1319                             list[0].literal().map(|literal| &literal.node)
1320                         } else {
1321                             None
1322                         }
1323                     });
1324
1325                     let (path, applicability) = match &literal {
1326                         Some(LitKind::Str(path, ..)) => {
1327                             (path.to_string(), Applicability::MachineApplicable)
1328                         }
1329                         _ => (String::from("<path>"), Applicability::HasPlaceholders),
1330                     };
1331
1332                     err.span_suggestion(
1333                         it.span(),
1334                         "provide a file path with `=`",
1335                         format!("include = \"{}\"", path),
1336                         applicability,
1337                     );
1338
1339                     err.emit();
1340                 }
1341             }
1342
1343             let meta = attr::mk_list_item(DUMMY_SP, Ident::with_empty_ctxt(sym::doc), items);
1344             match at.style {
1345                 ast::AttrStyle::Inner => *at = attr::mk_spanned_attr_inner(at.span, at.id, meta),
1346                 ast::AttrStyle::Outer => *at = attr::mk_spanned_attr_outer(at.span, at.id, meta),
1347             }
1348         } else {
1349             noop_visit_attribute(at, self)
1350         }
1351     }
1352
1353     fn visit_id(&mut self, id: &mut ast::NodeId) {
1354         if self.monotonic {
1355             debug_assert_eq!(*id, ast::DUMMY_NODE_ID);
1356             *id = self.cx.resolver.next_node_id()
1357         }
1358     }
1359
1360     fn visit_fn_decl(&mut self, mut fn_decl: &mut P<ast::FnDecl>) {
1361         self.cfg.configure_fn_decl(&mut fn_decl);
1362         noop_visit_fn_decl(fn_decl, self);
1363     }
1364 }
1365
1366 pub struct ExpansionConfig<'feat> {
1367     pub crate_name: String,
1368     pub features: Option<&'feat Features>,
1369     pub recursion_limit: usize,
1370     pub trace_mac: bool,
1371     pub should_test: bool, // If false, strip `#[test]` nodes
1372     pub single_step: bool,
1373     pub keep_macs: bool,
1374 }
1375
1376 impl<'feat> ExpansionConfig<'feat> {
1377     pub fn default(crate_name: String) -> ExpansionConfig<'static> {
1378         ExpansionConfig {
1379             crate_name,
1380             features: None,
1381             recursion_limit: 1024,
1382             trace_mac: false,
1383             should_test: false,
1384             single_step: false,
1385             keep_macs: false,
1386         }
1387     }
1388
1389     fn macros_in_extern(&self) -> bool {
1390         self.features.map_or(false, |features| features.macros_in_extern)
1391     }
1392     fn proc_macro_hygiene(&self) -> bool {
1393         self.features.map_or(false, |features| features.proc_macro_hygiene)
1394     }
1395     fn custom_inner_attributes(&self) -> bool {
1396         self.features.map_or(false, |features| features.custom_inner_attributes)
1397     }
1398 }
1399
1400 // A Marker adds the given mark to the syntax context.
1401 #[derive(Debug)]
1402 pub struct Marker(pub ExpnId);
1403
1404 impl MutVisitor for Marker {
1405     fn visit_span(&mut self, span: &mut Span) {
1406         *span = span.apply_mark(self.0)
1407     }
1408
1409     fn visit_mac(&mut self, mac: &mut ast::Mac) {
1410         noop_visit_mac(mac, self)
1411     }
1412 }