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