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