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