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