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