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