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