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