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