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