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