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