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