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