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