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