]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/macros.rs
8957312e1521712656f4e6812abaab4374dc7028
[rust.git] / src / librustc_resolve / macros.rs
1 // Copyright 2016 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 {AmbiguityError, Resolver, ResolutionError, resolve_error};
12 use {Module, ModuleKind, NameBinding, NameBindingKind, PathResult};
13 use Namespace::{self, MacroNS};
14 use build_reduced_graph::BuildReducedGraphVisitor;
15 use resolve_imports::ImportResolver;
16 use rustc::hir::def_id::{DefId, BUILTIN_MACROS_CRATE, CRATE_DEF_INDEX, DefIndex};
17 use rustc::hir::def::{Def, Export};
18 use rustc::hir::map::{self, DefCollector};
19 use rustc::{ty, lint};
20 use syntax::ast::{self, Name, Ident};
21 use syntax::attr::{self, HasAttrs};
22 use syntax::errors::DiagnosticBuilder;
23 use syntax::ext::base::{self, Annotatable, Determinacy, MultiModifier, MultiDecorator};
24 use syntax::ext::base::{MacroKind, SyntaxExtension, Resolver as SyntaxResolver};
25 use syntax::ext::expand::{Expansion, ExpansionKind, Invocation, InvocationKind, find_attr_invoc};
26 use syntax::ext::hygiene::Mark;
27 use syntax::ext::placeholders::placeholder;
28 use syntax::ext::tt::macro_rules;
29 use syntax::feature_gate::{self, emit_feature_err, GateIssue};
30 use syntax::fold::{self, Folder};
31 use syntax::parse::parser::PathStyle;
32 use syntax::parse::token::{self, Token};
33 use syntax::ptr::P;
34 use syntax::symbol::{Symbol, keywords};
35 use syntax::tokenstream::{TokenStream, TokenTree, Delimited};
36 use syntax::util::lev_distance::find_best_match_for_name;
37 use syntax_pos::{Span, DUMMY_SP};
38
39 use std::cell::Cell;
40 use std::mem;
41 use std::rc::Rc;
42
43 #[derive(Clone)]
44 pub struct InvocationData<'a> {
45     pub module: Cell<Module<'a>>,
46     pub def_index: DefIndex,
47     // True if this expansion is in a `const_expr` position, for example `[u32; m!()]`.
48     // c.f. `DefCollector::visit_const_expr`.
49     pub const_expr: bool,
50     // The scope in which the invocation path is resolved.
51     pub legacy_scope: Cell<LegacyScope<'a>>,
52     // The smallest scope that includes this invocation's expansion,
53     // or `Empty` if this invocation has not been expanded yet.
54     pub expansion: Cell<LegacyScope<'a>>,
55 }
56
57 impl<'a> InvocationData<'a> {
58     pub fn root(graph_root: Module<'a>) -> Self {
59         InvocationData {
60             module: Cell::new(graph_root),
61             def_index: CRATE_DEF_INDEX,
62             const_expr: false,
63             legacy_scope: Cell::new(LegacyScope::Empty),
64             expansion: Cell::new(LegacyScope::Empty),
65         }
66     }
67 }
68
69 #[derive(Copy, Clone)]
70 pub enum LegacyScope<'a> {
71     Empty,
72     Invocation(&'a InvocationData<'a>), // The scope of the invocation, not including its expansion
73     Expansion(&'a InvocationData<'a>), // The scope of the invocation, including its expansion
74     Binding(&'a LegacyBinding<'a>),
75 }
76
77 pub struct LegacyBinding<'a> {
78     pub parent: Cell<LegacyScope<'a>>,
79     pub ident: Ident,
80     def_id: DefId,
81     pub span: Span,
82 }
83
84 #[derive(Copy, Clone)]
85 pub enum MacroBinding<'a> {
86     Legacy(&'a LegacyBinding<'a>),
87     Global(&'a NameBinding<'a>),
88     Modern(&'a NameBinding<'a>),
89 }
90
91 impl<'a> MacroBinding<'a> {
92     pub fn span(self) -> Span {
93         match self {
94             MacroBinding::Legacy(binding) => binding.span,
95             MacroBinding::Global(binding) | MacroBinding::Modern(binding) => binding.span,
96         }
97     }
98
99     pub fn binding(self) -> &'a NameBinding<'a> {
100         match self {
101             MacroBinding::Global(binding) | MacroBinding::Modern(binding) => binding,
102             MacroBinding::Legacy(_) => panic!("unexpected MacroBinding::Legacy"),
103         }
104     }
105 }
106
107 impl<'a> base::Resolver for Resolver<'a> {
108     fn next_node_id(&mut self) -> ast::NodeId {
109         self.session.next_node_id()
110     }
111
112     fn get_module_scope(&mut self, id: ast::NodeId) -> Mark {
113         let mark = Mark::fresh(Mark::root());
114         let module = self.module_map[&self.definitions.local_def_id(id)];
115         self.invocations.insert(mark, self.arenas.alloc_invocation_data(InvocationData {
116             module: Cell::new(module),
117             def_index: module.def_id().unwrap().index,
118             const_expr: false,
119             legacy_scope: Cell::new(LegacyScope::Empty),
120             expansion: Cell::new(LegacyScope::Empty),
121         }));
122         mark
123     }
124
125     fn eliminate_crate_var(&mut self, item: P<ast::Item>) -> P<ast::Item> {
126         struct EliminateCrateVar<'b, 'a: 'b>(&'b mut Resolver<'a>, Span);
127
128         impl<'a, 'b> Folder for EliminateCrateVar<'a, 'b> {
129             fn fold_path(&mut self, mut path: ast::Path) -> ast::Path {
130                 let ident = path.segments[0].identifier;
131                 if ident.name == "$crate" {
132                     path.segments[0].identifier.name = keywords::CrateRoot.name();
133                     let module = self.0.resolve_crate_root(ident.ctxt);
134                     if !module.is_local() {
135                         let span = path.segments[0].span;
136                         path.segments.insert(1, match module.kind {
137                             ModuleKind::Def(_, name) => ast::PathSegment::from_ident(
138                                 ast::Ident::with_empty_ctxt(name), span
139                             ),
140                             _ => unreachable!(),
141                         })
142                     }
143                 }
144                 path
145             }
146
147             fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
148                 fold::noop_fold_mac(mac, self)
149             }
150         }
151
152         EliminateCrateVar(self, item.span).fold_item(item).expect_one("")
153     }
154
155     fn is_whitelisted_legacy_custom_derive(&self, name: Name) -> bool {
156         self.whitelisted_legacy_custom_derives.contains(&name)
157     }
158
159     fn visit_expansion(&mut self, mark: Mark, expansion: &Expansion, derives: &[Mark]) {
160         let invocation = self.invocations[&mark];
161         self.collect_def_ids(mark, invocation, expansion);
162
163         self.current_module = invocation.module.get();
164         self.current_module.unresolved_invocations.borrow_mut().remove(&mark);
165         self.current_module.unresolved_invocations.borrow_mut().extend(derives);
166         for &derive in derives {
167             self.invocations.insert(derive, invocation);
168         }
169         let mut visitor = BuildReducedGraphVisitor {
170             resolver: self,
171             legacy_scope: LegacyScope::Invocation(invocation),
172             expansion: mark,
173         };
174         expansion.visit_with(&mut visitor);
175         invocation.expansion.set(visitor.legacy_scope);
176     }
177
178     fn add_builtin(&mut self, ident: ast::Ident, ext: Rc<SyntaxExtension>) {
179         let def_id = DefId {
180             krate: BUILTIN_MACROS_CRATE,
181             index: DefIndex::new(self.macro_map.len()),
182         };
183         let kind = ext.kind();
184         self.macro_map.insert(def_id, ext);
185         let binding = self.arenas.alloc_name_binding(NameBinding {
186             kind: NameBindingKind::Def(Def::Macro(def_id, kind)),
187             span: DUMMY_SP,
188             vis: ty::Visibility::Invisible,
189             expansion: Mark::root(),
190         });
191         self.global_macros.insert(ident.name, binding);
192     }
193
194     fn resolve_imports(&mut self) {
195         ImportResolver { resolver: self }.resolve_imports()
196     }
197
198     // Resolves attribute and derive legacy macros from `#![plugin(..)]`.
199     fn find_legacy_attr_invoc(&mut self, attrs: &mut Vec<ast::Attribute>)
200                               -> Option<ast::Attribute> {
201         for i in 0..attrs.len() {
202             let name = unwrap_or!(attrs[i].name(), continue);
203
204             if self.session.plugin_attributes.borrow().iter()
205                     .any(|&(ref attr_nm, _)| name == &**attr_nm) {
206                 attr::mark_known(&attrs[i]);
207             }
208
209             match self.global_macros.get(&name).cloned() {
210                 Some(binding) => match *binding.get_macro(self) {
211                     MultiModifier(..) | MultiDecorator(..) | SyntaxExtension::AttrProcMacro(..) => {
212                         return Some(attrs.remove(i))
213                     }
214                     _ => {}
215                 },
216                 None => {}
217             }
218         }
219
220         // Check for legacy derives
221         for i in 0..attrs.len() {
222             let name = unwrap_or!(attrs[i].name(), continue);
223
224             if name == "derive" {
225                 let result = attrs[i].parse_list(&self.session.parse_sess, |parser| {
226                     parser.parse_path_allowing_meta(PathStyle::Mod)
227                 });
228
229                 let mut traits = match result {
230                     Ok(traits) => traits,
231                     Err(mut e) => {
232                         e.cancel();
233                         continue
234                     }
235                 };
236
237                 for j in 0..traits.len() {
238                     if traits[j].segments.len() > 1 {
239                         continue
240                     }
241                     let trait_name = traits[j].segments[0].identifier.name;
242                     let legacy_name = Symbol::intern(&format!("derive_{}", trait_name));
243                     if !self.global_macros.contains_key(&legacy_name) {
244                         continue
245                     }
246                     let span = traits.remove(j).span;
247                     self.gate_legacy_custom_derive(legacy_name, span);
248                     if traits.is_empty() {
249                         attrs.remove(i);
250                     } else {
251                         let mut tokens = Vec::new();
252                         for (j, path) in traits.iter().enumerate() {
253                             if j > 0 {
254                                 tokens.push(TokenTree::Token(attrs[i].span, Token::Comma).into());
255                             }
256                             for (k, segment) in path.segments.iter().enumerate() {
257                                 if k > 0 {
258                                     tokens.push(TokenTree::Token(path.span, Token::ModSep).into());
259                                 }
260                                 let tok = Token::Ident(segment.identifier);
261                                 tokens.push(TokenTree::Token(path.span, tok).into());
262                             }
263                         }
264                         attrs[i].tokens = TokenTree::Delimited(attrs[i].span, Delimited {
265                             delim: token::Paren,
266                             tts: TokenStream::concat(tokens).into(),
267                         }).into();
268                     }
269                     return Some(ast::Attribute {
270                         path: ast::Path::from_ident(span, Ident::with_empty_ctxt(legacy_name)),
271                         tokens: TokenStream::empty(),
272                         id: attr::mk_attr_id(),
273                         style: ast::AttrStyle::Outer,
274                         is_sugared_doc: false,
275                         span: span,
276                     });
277                 }
278             }
279         }
280
281         None
282     }
283
284     fn resolve_invoc(&mut self, invoc: &mut Invocation, scope: Mark, force: bool)
285                      -> Result<Option<Rc<SyntaxExtension>>, Determinacy> {
286         let def = match invoc.kind {
287             InvocationKind::Attr { attr: None, .. } => return Ok(None),
288             _ => match self.resolve_invoc_to_def(invoc, scope, force) {
289                 Ok(def) => def,
290                 Err(determinacy) => return Err(determinacy),
291             },
292         };
293
294         self.macro_defs.insert(invoc.expansion_data.mark, def.def_id());
295         let normal_module_def_id =
296             self.macro_def_scope(invoc.expansion_data.mark).normal_ancestor_id;
297         self.definitions.add_macro_def_scope(invoc.expansion_data.mark, normal_module_def_id);
298
299         self.unused_macros.remove(&def.def_id());
300         let ext = self.get_macro(def);
301         if ext.is_modern() {
302             invoc.expansion_data.mark.set_modern();
303         }
304         Ok(Some(ext))
305     }
306
307     fn resolve_macro(&mut self, scope: Mark, path: &ast::Path, kind: MacroKind, force: bool)
308                      -> Result<Rc<SyntaxExtension>, Determinacy> {
309         self.resolve_macro_to_def(scope, path, kind, force).map(|def| {
310             self.unused_macros.remove(&def.def_id());
311             self.get_macro(def)
312         })
313     }
314
315     fn check_unused_macros(&self) {
316         for did in self.unused_macros.iter() {
317             let id_span = match *self.macro_map[did] {
318                 SyntaxExtension::NormalTT(_, isp, _) => isp,
319                 _ => None,
320             };
321             if let Some((id, span)) = id_span {
322                 let lint = lint::builtin::UNUSED_MACROS;
323                 let msg = "unused macro definition".to_string();
324                 self.session.add_lint(lint, id, span, msg);
325             } else {
326                 bug!("attempted to create unused macro error, but span not available");
327             }
328         }
329     }
330 }
331
332 impl<'a> Resolver<'a> {
333     fn resolve_invoc_to_def(&mut self, invoc: &mut Invocation, scope: Mark, force: bool)
334                             -> Result<Def, Determinacy> {
335         let (attr, traits, item) = match invoc.kind {
336             InvocationKind::Attr { ref mut attr, ref traits, ref mut item } => (attr, traits, item),
337             InvocationKind::Bang { ref mac, .. } => {
338                 return self.resolve_macro_to_def(scope, &mac.node.path, MacroKind::Bang, force);
339             }
340             InvocationKind::Derive { ref path, .. } => {
341                 return self.resolve_macro_to_def(scope, path, MacroKind::Derive, force);
342             }
343         };
344
345
346         let path = attr.as_ref().unwrap().path.clone();
347         let mut determinacy = Determinacy::Determined;
348         match self.resolve_macro_to_def(scope, &path, MacroKind::Attr, force) {
349             Ok(def) => return Ok(def),
350             Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined,
351             Err(Determinacy::Determined) if force => return Err(Determinacy::Determined),
352             Err(Determinacy::Determined) => {}
353         }
354
355         let attr_name = match path.segments.len() {
356             1 => path.segments[0].identifier.name,
357             _ => return Err(determinacy),
358         };
359         for path in traits {
360             match self.resolve_macro(scope, path, MacroKind::Derive, force) {
361                 Ok(ext) => if let SyntaxExtension::ProcMacroDerive(_, ref inert_attrs) = *ext {
362                     if inert_attrs.contains(&attr_name) {
363                         // FIXME(jseyfried) Avoid `mem::replace` here.
364                         let dummy_item = placeholder(ExpansionKind::Items, ast::DUMMY_NODE_ID)
365                             .make_items().pop().unwrap();
366                         let dummy_item = Annotatable::Item(dummy_item);
367                         *item = mem::replace(item, dummy_item).map_attrs(|mut attrs| {
368                             let inert_attr = attr.take().unwrap();
369                             attr::mark_known(&inert_attr);
370                             if self.proc_macro_enabled {
371                                 *attr = find_attr_invoc(&mut attrs);
372                             }
373                             attrs.push(inert_attr);
374                             attrs
375                         });
376                     }
377                     return Err(Determinacy::Undetermined);
378                 },
379                 Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined,
380                 Err(Determinacy::Determined) => {}
381             }
382         }
383
384         Err(determinacy)
385     }
386
387     fn resolve_macro_to_def(&mut self, scope: Mark, path: &ast::Path, kind: MacroKind, force: bool)
388                             -> Result<Def, Determinacy> {
389         let ast::Path { ref segments, span } = *path;
390         if segments.iter().any(|segment| segment.parameters.is_some()) {
391             let kind =
392                 if segments.last().unwrap().parameters.is_some() { "macro" } else { "module" };
393             let msg = format!("type parameters are not allowed on {}s", kind);
394             self.session.span_err(path.span, &msg);
395             return Err(Determinacy::Determined);
396         }
397
398         let path: Vec<_> = segments.iter().map(|seg| seg.identifier).collect();
399         let invocation = self.invocations[&scope];
400         self.current_module = invocation.module.get();
401
402         if path.len() > 1 {
403             if !self.use_extern_macros && self.gated_errors.insert(span) {
404                 let msg = "non-ident macro paths are experimental";
405                 let feature = "use_extern_macros";
406                 emit_feature_err(&self.session.parse_sess, feature, span, GateIssue::Language, msg);
407                 self.found_unresolved_macro = true;
408                 return Err(Determinacy::Determined);
409             }
410
411             let def = match self.resolve_path(&path, Some(MacroNS), false, span) {
412                 PathResult::NonModule(path_res) => match path_res.base_def() {
413                     Def::Err => Err(Determinacy::Determined),
414                     def @ _ => Ok(def),
415                 },
416                 PathResult::Module(..) => unreachable!(),
417                 PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
418                 _ => {
419                     self.found_unresolved_macro = true;
420                     Err(Determinacy::Determined)
421                 },
422             };
423             self.current_module.nearest_item_scope().macro_resolutions.borrow_mut()
424                 .push((path.into_boxed_slice(), span));
425             return def;
426         }
427
428         let legacy_resolution = self.resolve_legacy_scope(&invocation.legacy_scope, path[0], false);
429         let result = if let Some(MacroBinding::Legacy(binding)) = legacy_resolution {
430             Ok(Def::Macro(binding.def_id, MacroKind::Bang))
431         } else {
432             match self.resolve_lexical_macro_path_segment(path[0], MacroNS, false, span) {
433                 Ok(binding) => Ok(binding.binding().def_ignoring_ambiguity()),
434                 Err(Determinacy::Undetermined) if !force => return Err(Determinacy::Undetermined),
435                 Err(_) => {
436                     self.found_unresolved_macro = true;
437                     Err(Determinacy::Determined)
438                 }
439             }
440         };
441
442         self.current_module.nearest_item_scope().legacy_macro_resolutions.borrow_mut()
443             .push((scope, path[0], span, kind));
444
445         result
446     }
447
448     // Resolve the initial segment of a non-global macro path (e.g. `foo` in `foo::bar!();`)
449     pub fn resolve_lexical_macro_path_segment(&mut self,
450                                               mut ident: Ident,
451                                               ns: Namespace,
452                                               record_used: bool,
453                                               path_span: Span)
454                                               -> Result<MacroBinding<'a>, Determinacy> {
455         ident = ident.modern();
456         let mut module = Some(self.current_module);
457         let mut potential_illegal_shadower = Err(Determinacy::Determined);
458         let determinacy =
459             if record_used { Determinacy::Determined } else { Determinacy::Undetermined };
460         loop {
461             let orig_current_module = self.current_module;
462             let result = if let Some(module) = module {
463                 self.current_module = module; // Lexical resolutions can never be a privacy error.
464                 // Since expanded macros may not shadow the lexical scope and
465                 // globs may not shadow global macros (both enforced below),
466                 // we resolve with restricted shadowing (indicated by the penultimate argument).
467                 self.resolve_ident_in_module_unadjusted(
468                     module, ident, ns, true, record_used, path_span,
469                 ).map(MacroBinding::Modern)
470             } else {
471                 self.global_macros.get(&ident.name).cloned().ok_or(determinacy)
472                     .map(MacroBinding::Global)
473             };
474             self.current_module = orig_current_module;
475
476             match result.map(MacroBinding::binding) {
477                 Ok(binding) => {
478                     if !record_used {
479                         return result;
480                     }
481                     if let Ok(MacroBinding::Modern(shadower)) = potential_illegal_shadower {
482                         if shadower.def() != binding.def() {
483                             let name = ident.name;
484                             self.ambiguity_errors.push(AmbiguityError {
485                                 span: path_span,
486                                 name: name,
487                                 b1: shadower,
488                                 b2: binding,
489                                 lexical: true,
490                                 legacy: false,
491                             });
492                             return potential_illegal_shadower;
493                         }
494                     }
495                     if binding.expansion != Mark::root() ||
496                        (binding.is_glob_import() && module.unwrap().def().is_some()) {
497                         potential_illegal_shadower = result;
498                     } else {
499                         return result;
500                     }
501                 },
502                 Err(Determinacy::Undetermined) => return Err(Determinacy::Undetermined),
503                 Err(Determinacy::Determined) => {}
504             }
505
506             module = match module {
507                 Some(module) => self.hygienic_lexical_parent(module, &mut ident.ctxt),
508                 None => return potential_illegal_shadower,
509             }
510         }
511     }
512
513     pub fn resolve_legacy_scope(&mut self,
514                                 mut scope: &'a Cell<LegacyScope<'a>>,
515                                 ident: Ident,
516                                 record_used: bool)
517                                 -> Option<MacroBinding<'a>> {
518         let ident = ident.modern();
519         let mut possible_time_travel = None;
520         let mut relative_depth: u32 = 0;
521         let mut binding = None;
522         loop {
523             match scope.get() {
524                 LegacyScope::Empty => break,
525                 LegacyScope::Expansion(invocation) => {
526                     match invocation.expansion.get() {
527                         LegacyScope::Invocation(_) => scope.set(invocation.legacy_scope.get()),
528                         LegacyScope::Empty => {
529                             if possible_time_travel.is_none() {
530                                 possible_time_travel = Some(scope);
531                             }
532                             scope = &invocation.legacy_scope;
533                         }
534                         _ => {
535                             relative_depth += 1;
536                             scope = &invocation.expansion;
537                         }
538                     }
539                 }
540                 LegacyScope::Invocation(invocation) => {
541                     relative_depth = relative_depth.saturating_sub(1);
542                     scope = &invocation.legacy_scope;
543                 }
544                 LegacyScope::Binding(potential_binding) => {
545                     if potential_binding.ident == ident {
546                         if (!self.use_extern_macros || record_used) && relative_depth > 0 {
547                             self.disallowed_shadowing.push(potential_binding);
548                         }
549                         binding = Some(potential_binding);
550                         break
551                     }
552                     scope = &potential_binding.parent;
553                 }
554             };
555         }
556
557         let binding = if let Some(binding) = binding {
558             MacroBinding::Legacy(binding)
559         } else if let Some(binding) = self.global_macros.get(&ident.name).cloned() {
560             if !self.use_extern_macros {
561                 self.record_use(ident, MacroNS, binding, DUMMY_SP);
562             }
563             MacroBinding::Global(binding)
564         } else {
565             return None;
566         };
567
568         if !self.use_extern_macros {
569             if let Some(scope) = possible_time_travel {
570                 // Check for disallowed shadowing later
571                 self.lexical_macro_resolutions.push((ident, scope));
572             }
573         }
574
575         Some(binding)
576     }
577
578     pub fn finalize_current_module_macro_resolutions(&mut self) {
579         let module = self.current_module;
580         for &(ref path, span) in module.macro_resolutions.borrow().iter() {
581             match self.resolve_path(path, Some(MacroNS), true, span) {
582                 PathResult::NonModule(_) => {},
583                 PathResult::Failed(msg, _) => {
584                     resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
585                 }
586                 _ => unreachable!(),
587             }
588         }
589
590         for &(mark, ident, span, kind) in module.legacy_macro_resolutions.borrow().iter() {
591             let legacy_scope = &self.invocations[&mark].legacy_scope;
592             let legacy_resolution = self.resolve_legacy_scope(legacy_scope, ident, true);
593             let resolution = self.resolve_lexical_macro_path_segment(ident, MacroNS, true, span);
594             match (legacy_resolution, resolution) {
595                 (Some(MacroBinding::Legacy(legacy_binding)), Ok(MacroBinding::Modern(binding))) => {
596                     let msg1 = format!("`{}` could refer to the macro defined here", ident);
597                     let msg2 = format!("`{}` could also refer to the macro imported here", ident);
598                     self.session.struct_span_err(span, &format!("`{}` is ambiguous", ident))
599                         .span_note(legacy_binding.span, &msg1)
600                         .span_note(binding.span, &msg2)
601                         .emit();
602                 },
603                 (Some(MacroBinding::Global(binding)), Ok(MacroBinding::Global(_))) => {
604                     self.record_use(ident, MacroNS, binding, span);
605                     self.err_if_macro_use_proc_macro(ident.name, span, binding);
606                 },
607                 (None, Err(_)) => {
608                     let msg = match kind {
609                         MacroKind::Bang =>
610                             format!("cannot find macro `{}!` in this scope", ident),
611                         MacroKind::Attr =>
612                             format!("cannot find attribute macro `{}` in this scope", ident),
613                         MacroKind::Derive =>
614                             format!("cannot find derive macro `{}` in this scope", ident),
615                     };
616                     let mut err = self.session.struct_span_err(span, &msg);
617                     self.suggest_macro_name(&ident.name.as_str(), kind, &mut err, span);
618                     err.emit();
619                 },
620                 _ => {},
621             };
622         }
623     }
624
625     fn suggest_macro_name(&mut self, name: &str, kind: MacroKind,
626                           err: &mut DiagnosticBuilder<'a>, span: Span) {
627         // First check if this is a locally-defined bang macro.
628         let suggestion = if let MacroKind::Bang = kind {
629             find_best_match_for_name(self.macro_names.iter().map(|ident| &ident.name), name, None)
630         } else {
631             None
632         // Then check global macros.
633         }.or_else(|| {
634             // FIXME: get_macro needs an &mut Resolver, can we do it without cloning?
635             let global_macros = self.global_macros.clone();
636             let names = global_macros.iter().filter_map(|(name, binding)| {
637                 if binding.get_macro(self).kind() == kind {
638                     Some(name)
639                 } else {
640                     None
641                 }
642             });
643             find_best_match_for_name(names, name, None)
644         // Then check modules.
645         }).or_else(|| {
646             if !self.use_extern_macros {
647                 return None;
648             }
649             let is_macro = |def| {
650                 if let Def::Macro(_, def_kind) = def {
651                     def_kind == kind
652                 } else {
653                     false
654                 }
655             };
656             let ident = Ident::from_str(name);
657             self.lookup_typo_candidate(&vec![ident], MacroNS, is_macro, span)
658         });
659
660         if let Some(suggestion) = suggestion {
661             if suggestion != name {
662                 if let MacroKind::Bang = kind {
663                     err.help(&format!("did you mean `{}!`?", suggestion));
664                 } else {
665                     err.help(&format!("did you mean `{}`?", suggestion));
666                 }
667             } else {
668                 err.help("have you added the `#[macro_use]` on the module/import?");
669             }
670         }
671     }
672
673     fn collect_def_ids(&mut self,
674                        mark: Mark,
675                        invocation: &'a InvocationData<'a>,
676                        expansion: &Expansion) {
677         let Resolver { ref mut invocations, arenas, graph_root, .. } = *self;
678         let InvocationData { def_index, const_expr, .. } = *invocation;
679
680         let visit_macro_invoc = &mut |invoc: map::MacroInvocationData| {
681             invocations.entry(invoc.mark).or_insert_with(|| {
682                 arenas.alloc_invocation_data(InvocationData {
683                     def_index: invoc.def_index,
684                     const_expr: invoc.const_expr,
685                     module: Cell::new(graph_root),
686                     expansion: Cell::new(LegacyScope::Empty),
687                     legacy_scope: Cell::new(LegacyScope::Empty),
688                 })
689             });
690         };
691
692         let mut def_collector = DefCollector::new(&mut self.definitions, mark);
693         def_collector.visit_macro_invoc = Some(visit_macro_invoc);
694         def_collector.with_parent(def_index, |def_collector| {
695             if const_expr {
696                 if let Expansion::Expr(ref expr) = *expansion {
697                     def_collector.visit_const_expr(expr);
698                 }
699             }
700             expansion.visit_with(def_collector)
701         });
702     }
703
704     pub fn define_macro(&mut self,
705                         item: &ast::Item,
706                         expansion: Mark,
707                         legacy_scope: &mut LegacyScope<'a>) {
708         self.local_macro_def_scopes.insert(item.id, self.current_module);
709         let ident = item.ident;
710         if ident.name == "macro_rules" {
711             self.session.span_err(item.span, "user-defined macros may not be named `macro_rules`");
712         }
713
714         let def_id = self.definitions.local_def_id(item.id);
715         let ext = Rc::new(macro_rules::compile(&self.session.parse_sess,
716                                                &self.session.features,
717                                                item));
718         self.macro_map.insert(def_id, ext);
719
720         let def = match item.node { ast::ItemKind::MacroDef(ref def) => def, _ => unreachable!() };
721         if def.legacy {
722             let ident = ident.modern();
723             self.macro_names.insert(ident);
724             *legacy_scope = LegacyScope::Binding(self.arenas.alloc_legacy_binding(LegacyBinding {
725                 parent: Cell::new(*legacy_scope), ident: ident, def_id: def_id, span: item.span,
726             }));
727             if attr::contains_name(&item.attrs, "macro_export") {
728                 let def = Def::Macro(def_id, MacroKind::Bang);
729                 self.macro_exports.push(Export { name: ident.name, def: def, span: item.span });
730             } else {
731                 self.unused_macros.insert(def_id);
732             }
733         } else {
734             let module = self.current_module;
735             let def = Def::Macro(def_id, MacroKind::Bang);
736             let vis = self.resolve_visibility(&item.vis);
737             self.define(module, ident, MacroNS, (def, vis, item.span, expansion));
738         }
739     }
740
741     /// Error if `ext` is a Macros 1.1 procedural macro being imported by `#[macro_use]`
742     fn err_if_macro_use_proc_macro(&mut self, name: Name, use_span: Span,
743                                    binding: &NameBinding<'a>) {
744         use self::SyntaxExtension::*;
745
746         let krate = binding.def().def_id().krate;
747
748         // Plugin-based syntax extensions are exempt from this check
749         if krate == BUILTIN_MACROS_CRATE { return; }
750
751         let ext = binding.get_macro(self);
752
753         match *ext {
754             // If `ext` is a procedural macro, check if we've already warned about it
755             AttrProcMacro(_) | ProcMacro(_) => if !self.warned_proc_macros.insert(name) { return; },
756             _ => return,
757         }
758
759         let warn_msg = match *ext {
760             AttrProcMacro(_) => "attribute procedural macros cannot be \
761                                  imported with `#[macro_use]`",
762             ProcMacro(_) => "procedural macros cannot be imported with `#[macro_use]`",
763             _ => return,
764         };
765
766         let crate_name = self.session.cstore.crate_name(krate);
767
768         self.session.struct_span_err(use_span, warn_msg)
769             .help(&format!("instead, import the procedural macro like any other item: \
770                              `use {}::{};`", crate_name, name))
771             .emit();
772     }
773
774     fn gate_legacy_custom_derive(&mut self, name: Symbol, span: Span) {
775         if !self.session.features.borrow().custom_derive {
776             let sess = &self.session.parse_sess;
777             let explain = feature_gate::EXPLAIN_CUSTOM_DERIVE;
778             emit_feature_err(sess, "custom_derive", span, GateIssue::Language, explain);
779         } else if !self.is_whitelisted_legacy_custom_derive(name) {
780             self.session.span_warn(span, feature_gate::EXPLAIN_DEPR_CUSTOM_DERIVE);
781         }
782     }
783 }