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.
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.
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};
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};
42 use rustc_data_structures::sync::Lrc;
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>>,
55 impl<'a> InvocationData<'a> {
56 pub fn root(graph_root: Module<'a>) -> Self {
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),
66 #[derive(Copy, Clone)]
67 pub enum LegacyScope<'a> {
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>),
74 pub struct LegacyBinding<'a> {
75 pub parent: Cell<LegacyScope<'a>>,
81 pub struct ProcMacError {
86 warn_msg: &'static str,
89 #[derive(Copy, Clone)]
90 pub enum MacroBinding<'a> {
91 Legacy(&'a LegacyBinding<'a>),
92 Global(&'a NameBinding<'a>),
93 Modern(&'a NameBinding<'a>),
96 impl<'a> MacroBinding<'a> {
97 pub fn span(self) -> Span {
99 MacroBinding::Legacy(binding) => binding.span,
100 MacroBinding::Global(binding) | MacroBinding::Modern(binding) => binding.span,
104 pub fn binding(self) -> &'a NameBinding<'a> {
106 MacroBinding::Global(binding) | MacroBinding::Modern(binding) => binding,
107 MacroBinding::Legacy(_) => panic!("unexpected MacroBinding::Legacy"),
111 pub fn def_ignoring_ambiguity(self) -> Def {
113 MacroBinding::Legacy(binding) => Def::Macro(binding.def_id, MacroKind::Bang),
114 MacroBinding::Global(binding) | MacroBinding::Modern(binding) =>
115 binding.def_ignoring_ambiguity(),
120 impl<'a> base::Resolver for Resolver<'a> {
121 fn next_node_id(&mut self) -> ast::NodeId {
122 self.session.next_node_id()
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),
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);
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,
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 }| {
152 ty: self.fold_ty(ty),
153 path_span: self.new_span(path_span),
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)
169 if let Some(qself) = &mut qself {
177 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
178 fold::noop_fold_mac(mac, self)
182 EliminateCrateVar(self, item.span).fold_item(item).expect_one("")
185 fn is_whitelisted_legacy_custom_derive(&self, name: Name) -> bool {
186 self.whitelisted_legacy_custom_derives.contains(&name)
189 fn visit_ast_fragment_with_placeholders(&mut self, mark: Mark, fragment: &AstFragment,
191 let invocation = self.invocations[&mark];
192 self.collect_def_ids(mark, invocation, fragment);
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);
200 let mut visitor = BuildReducedGraphVisitor {
202 legacy_scope: LegacyScope::Invocation(invocation),
205 fragment.visit_with(&mut visitor);
206 invocation.expansion.set(visitor.legacy_scope);
209 fn add_builtin(&mut self, ident: ast::Ident, ext: Lrc<SyntaxExtension>) {
211 krate: BUILTIN_MACROS_CRATE,
212 index: DefIndex::from_array_index(self.macro_map.len(),
213 DefIndexAddressSpace::Low),
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)),
220 vis: ty::Visibility::Invisible,
221 expansion: Mark::root(),
223 self.global_macros.insert(ident.name, binding);
226 fn resolve_imports(&mut self) {
227 ImportResolver { resolver: self }.resolve_imports()
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();
236 if self.session.plugin_attributes.borrow().iter()
237 .any(|&(ref attr_nm, _)| name == &**attr_nm) {
238 attr::mark_known(&attrs[i]);
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))
252 if !allow_derive { return None }
254 // Check for legacy derives
255 for i in 0..attrs.len() {
256 let name = attrs[i].name();
258 if name == "derive" {
259 let result = attrs[i].parse_list(&self.session.parse_sess, |parser| {
260 parser.parse_path_allowing_meta(PathStyle::Mod)
263 let mut traits = match result {
264 Ok(traits) => traits,
271 for j in 0..traits.len() {
272 if traits[j].segments.len() > 1 {
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) {
280 let span = traits.remove(j).span;
281 self.gate_legacy_custom_derive(legacy_name, span);
282 if traits.is_empty() {
285 let mut tokens = Vec::new();
286 for (j, path) in traits.iter().enumerate() {
288 tokens.push(TokenTree::Token(attrs[i].span, Token::Comma).into());
290 for (k, segment) in path.segments.iter().enumerate() {
292 tokens.push(TokenTree::Token(path.span, Token::ModSep).into());
294 let tok = Token::from_ast_ident(segment.ident);
295 tokens.push(TokenTree::Token(path.span, tok).into());
298 attrs[i].tokens = TokenTree::Delimited(attrs[i].span, Delimited {
300 tts: TokenStream::concat(tokens).into(),
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,
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)?,
324 let def_id = def.def_id();
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);
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);
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());
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,
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);
359 bug!("attempted to create unused macro error, but span not available");
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);
373 InvocationKind::Derive { ref path, .. } => {
374 return self.resolve_macro_to_def(scope, path, MacroKind::Derive, force);
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) => {}
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.
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.
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),
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);
422 attrs.push(inert_attr);
425 return Err(Determinacy::Undetermined)
428 Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined,
429 Err(Determinacy::Determined) => {}
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 {
441 &self.session.parse_sess,
442 "proc_macro_path_invoc",
445 "paths of length greater than one in macro invocations are \
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");
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 };
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);
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);
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),
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)
500 PathResult::Module(..) => unreachable!(),
501 PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
503 self.found_unresolved_macro = true;
504 Err(Determinacy::Determined)
507 self.current_module.nearest_item_scope().macro_resolutions.borrow_mut()
508 .push((path.into_boxed_slice(), span));
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))
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),
520 self.found_unresolved_macro = true;
521 Err(Determinacy::Determined)
526 self.current_module.nearest_item_scope().legacy_macro_resolutions.borrow_mut()
527 .push((scope, path[0], kind, result.ok()));
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,
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);
543 if record_used { Determinacy::Determined } else { Determinacy::Undetermined };
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)
555 self.global_macros.get(&ident.name).cloned().ok_or(determinacy)
556 .map(MacroBinding::Global)
558 self.current_module = orig_current_module;
560 match result.map(MacroBinding::binding) {
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 {
575 return potential_illegal_shadower;
578 if binding.expansion != Mark::root() ||
579 (binding.is_glob_import() && module.unwrap().def().is_some()) {
580 potential_illegal_shadower = result;
585 Err(Determinacy::Undetermined) => return Err(Determinacy::Undetermined),
586 Err(Determinacy::Determined) => {}
589 module = match module {
590 Some(module) => self.hygienic_lexical_parent(module, &mut ident.span),
591 None => return potential_illegal_shadower,
596 pub fn resolve_legacy_scope(&mut self,
597 mut scope: &'a Cell<LegacyScope<'a>>,
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;
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);
615 scope = &invocation.legacy_scope;
619 scope = &invocation.expansion;
623 LegacyScope::Invocation(invocation) => {
624 relative_depth = relative_depth.saturating_sub(1);
625 scope = &invocation.legacy_scope;
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);
632 binding = Some(potential_binding);
635 scope = &potential_binding.parent;
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);
646 MacroBinding::Global(binding)
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));
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));
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);
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");
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.
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();
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)
710 assert!(def.is_none());
711 let bang = if kind == MacroKind::Bang { "!" } else { "" };
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);
718 (Some(MacroBinding::Modern(_)), _) | (_, Ok(MacroBinding::Legacy(_))) => {
719 span_bug!(span, "impossible macro resolution result");
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);
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");
733 check_consistency(self, MacroBinding::Global(binding1));
735 self.record_use(ident, MacroNS, binding1, span);
736 self.err_if_macro_use_proc_macro(ident.name, span, binding1);
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)
749 // Then check global macros.
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 {
760 find_best_match_for_name(names, name, None)
761 // Then check modules.
763 if !self.use_extern_macros {
766 let is_macro = |def| {
767 if let Def::Macro(_, def_kind) = def {
773 let ident = Ident::new(Symbol::intern(name), span);
774 self.lookup_typo_candidate(&vec![ident], MacroNS, is_macro, span)
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());
782 err.span_suggestion(span, "try", suggestion.to_string());
785 err.help("have you added the `#[macro_use]` on the module/import?");
790 fn collect_def_ids(&mut self,
792 invocation: &'a InvocationData<'a>,
793 fragment: &AstFragment) {
794 let Resolver { ref mut invocations, arenas, graph_root, .. } = *self;
795 let InvocationData { def_index, .. } = *invocation;
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),
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)
815 pub fn define_macro(&mut self,
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`");
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);
831 let def = match item.node { ast::ItemKind::MacroDef(ref def) => def, _ => unreachable!() };
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,
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(),
844 vis: ty::Visibility::Public,
848 self.unused_macros.insert(def_id);
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);
857 self.define(module, ident, MacroNS, (def, vis, item.span, expansion));
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;
866 // Plugin-based syntax extensions are exempt from this check
867 if krate == BUILTIN_MACROS_CRATE { return; }
869 let ext = binding.get_macro(self);
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; },
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]`",
886 let def_id = self.current_module.normal_ancestor_id;
887 let node_id = self.definitions.as_local_node_id(def_id).unwrap();
889 self.proc_mac_errors.push(ProcMacError {
890 crate_name: self.cstore.crate_name_untracked(krate),
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);
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)
907 "instead, import the procedural macro like any other item",
908 format!("use {}::{};{}", err.crate_name, err.name, found_use),
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))
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);