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