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