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