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