1 use crate::{AmbiguityError, AmbiguityKind, AmbiguityErrorMisc};
2 use crate::{CrateLint, Resolver, ResolutionError, ScopeSet, Weak};
3 use crate::{Module, ModuleKind, NameBinding, NameBindingKind, PathResult, Segment, ToNameBinding};
4 use crate::{is_known_tool, resolve_error};
5 use crate::ModuleOrUniformRoot;
6 use crate::Namespace::*;
7 use crate::build_reduced_graph::{BuildReducedGraphVisitor, IsMacroExport};
8 use crate::resolve_imports::ImportResolver;
9 use rustc::hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX};
10 use rustc::hir::def::{self, DefKind, NonMacroAttrKind};
11 use rustc::hir::map::{self, DefCollector};
12 use rustc::{ty, lint};
13 use rustc::{bug, span_bug};
14 use syntax::ast::{self, Ident};
16 use syntax::errors::DiagnosticBuilder;
17 use syntax::ext::base::{self, Determinacy};
18 use syntax::ext::base::{MacroKind, SyntaxExtension};
19 use syntax::ext::expand::{AstFragment, Invocation, InvocationKind};
20 use syntax::ext::hygiene::{self, Mark};
21 use syntax::ext::tt::macro_rules;
22 use syntax::feature_gate::{
23 feature_err, is_builtin_attr_name, AttributeGate, GateIssue, Stability, BUILTIN_ATTRIBUTES,
25 use syntax::symbol::{Symbol, keywords, sym};
26 use syntax::visit::Visitor;
27 use syntax::util::lev_distance::find_best_match_for_name;
28 use syntax_pos::{Span, DUMMY_SP};
29 use errors::Applicability;
33 use rustc_data_structures::sync::Lrc;
35 type Res = def::Res<ast::NodeId>;
37 #[derive(Clone, Debug)]
38 pub struct InvocationData<'a> {
40 /// The module in which the macro was invoked.
41 crate module: Cell<Module<'a>>,
42 /// The legacy scope in which the macro was invoked.
43 /// The invocation path is resolved in this scope.
44 crate parent_legacy_scope: Cell<LegacyScope<'a>>,
45 /// The legacy scope *produced* by expanding this macro invocation,
46 /// includes all the macro_rules items, other invocations, etc generated by it.
47 /// `None` if the macro is not expanded yet.
48 crate output_legacy_scope: Cell<Option<LegacyScope<'a>>>,
51 impl<'a> InvocationData<'a> {
52 pub fn root(graph_root: Module<'a>) -> Self {
54 module: Cell::new(graph_root),
55 def_index: CRATE_DEF_INDEX,
56 parent_legacy_scope: Cell::new(LegacyScope::Empty),
57 output_legacy_scope: Cell::new(Some(LegacyScope::Empty)),
62 /// Binding produced by a `macro_rules` item.
63 /// Not modularized, can shadow previous legacy bindings, etc.
65 pub struct LegacyBinding<'a> {
66 binding: &'a NameBinding<'a>,
67 /// Legacy scope into which the `macro_rules` item was planted.
68 parent_legacy_scope: LegacyScope<'a>,
72 /// The scope introduced by a `macro_rules!` macro.
73 /// This starts at the macro's definition and ends at the end of the macro's parent
74 /// module (named or unnamed), or even further if it escapes with `#[macro_use]`.
75 /// Some macro invocations need to introduce legacy scopes too because they
76 /// can potentially expand into macro definitions.
77 #[derive(Copy, Clone, Debug)]
78 pub enum LegacyScope<'a> {
79 /// Created when invocation data is allocated in the arena;
80 /// must be replaced with a proper scope later.
82 /// Empty "root" scope at the crate start containing no names.
84 /// The scope introduced by a `macro_rules!` macro definition.
85 Binding(&'a LegacyBinding<'a>),
86 /// The scope introduced by a macro invocation that can potentially
87 /// create a `macro_rules!` macro definition.
88 Invocation(&'a InvocationData<'a>),
91 /// Everything you need to resolve a macro or import path.
92 #[derive(Clone, Debug)]
93 pub struct ParentScope<'a> {
94 crate module: Module<'a>,
95 crate expansion: Mark,
96 crate legacy: LegacyScope<'a>,
97 crate derives: Vec<ast::Path>,
100 // Macro namespace is separated into two sub-namespaces, one for bang macros and
101 // one for attribute-like macros (attributes, derives).
102 // We ignore resolutions from one sub-namespace when searching names in scope for another.
103 fn sub_namespace_match(candidate: Option<MacroKind>, requirement: Option<MacroKind>) -> bool {
105 enum SubNS { Bang, AttrLike }
106 let sub_ns = |kind| match kind {
107 MacroKind::Bang => Some(SubNS::Bang),
108 MacroKind::Attr | MacroKind::Derive => Some(SubNS::AttrLike),
109 MacroKind::ProcMacroStub => None,
111 let requirement = requirement.and_then(|kind| sub_ns(kind));
112 let candidate = candidate.and_then(|kind| sub_ns(kind));
113 // "No specific sub-namespace" means "matches anything" for both requirements and candidates.
114 candidate.is_none() || requirement.is_none() || candidate == requirement
117 impl<'a> base::Resolver for Resolver<'a> {
118 fn next_node_id(&mut self) -> ast::NodeId {
119 self.session.next_node_id()
122 fn get_module_scope(&mut self, id: ast::NodeId) -> Mark {
123 let mark = Mark::fresh(Mark::root());
124 let module = self.module_map[&self.definitions.local_def_id(id)];
125 self.invocations.insert(mark, self.arenas.alloc_invocation_data(InvocationData {
126 module: Cell::new(module),
127 def_index: module.def_id().unwrap().index,
128 parent_legacy_scope: Cell::new(LegacyScope::Empty),
129 output_legacy_scope: Cell::new(Some(LegacyScope::Empty)),
134 fn resolve_dollar_crates(&mut self, fragment: &AstFragment) {
135 struct ResolveDollarCrates<'a, 'b: 'a> {
136 resolver: &'a mut Resolver<'b>
138 impl<'a> Visitor<'a> for ResolveDollarCrates<'a, '_> {
139 fn visit_ident(&mut self, ident: Ident) {
140 if ident.name == keywords::DollarCrate.name() {
141 let name = match self.resolver.resolve_crate_root(ident).kind {
142 ModuleKind::Def(.., name) if name != keywords::Invalid.name() => name,
143 _ => keywords::Crate.name(),
145 ident.span.ctxt().set_dollar_crate_name(name);
148 fn visit_mac(&mut self, _: &ast::Mac) {}
151 fragment.visit_with(&mut ResolveDollarCrates { resolver: self });
154 fn visit_ast_fragment_with_placeholders(&mut self, mark: Mark, fragment: &AstFragment,
156 let invocation = self.invocations[&mark];
157 self.collect_def_ids(mark, invocation, fragment);
159 self.current_module = invocation.module.get();
160 self.current_module.unresolved_invocations.borrow_mut().remove(&mark);
161 self.current_module.unresolved_invocations.borrow_mut().extend(derives);
162 self.invocations.extend(derives.iter().map(|&derive| (derive, invocation)));
163 let mut visitor = BuildReducedGraphVisitor {
165 current_legacy_scope: invocation.parent_legacy_scope.get(),
168 fragment.visit_with(&mut visitor);
169 invocation.output_legacy_scope.set(Some(visitor.current_legacy_scope));
172 fn add_builtin(&mut self, ident: ast::Ident, ext: Lrc<SyntaxExtension>) {
174 krate: CrateNum::BuiltinMacros,
175 index: DefIndex::from(self.macro_map.len()),
177 let kind = ext.kind();
178 self.macro_map.insert(def_id, ext);
179 let binding = self.arenas.alloc_name_binding(NameBinding {
180 kind: NameBindingKind::Res(Res::Def(DefKind::Macro(kind), def_id), false),
183 vis: ty::Visibility::Public,
184 expansion: Mark::root(),
186 if self.builtin_macros.insert(ident.name, binding).is_some() {
187 self.session.span_err(ident.span,
188 &format!("built-in macro `{}` was already defined", ident));
192 fn resolve_imports(&mut self) {
193 ImportResolver { resolver: self }.resolve_imports()
196 fn resolve_macro_invocation(&mut self, invoc: &Invocation, invoc_id: Mark, force: bool)
197 -> Result<Option<Lrc<SyntaxExtension>>, Determinacy> {
198 let (path, kind, derives_in_scope, after_derive) = match invoc.kind {
199 InvocationKind::Attr { attr: None, .. } =>
201 InvocationKind::Attr { attr: Some(ref attr), ref traits, after_derive, .. } =>
202 (&attr.path, MacroKind::Attr, traits.clone(), after_derive),
203 InvocationKind::Bang { ref mac, .. } =>
204 (&mac.node.path, MacroKind::Bang, Vec::new(), false),
205 InvocationKind::Derive { ref path, .. } =>
206 (path, MacroKind::Derive, Vec::new(), false),
209 let parent_scope = self.invoc_parent_scope(invoc_id, derives_in_scope);
210 let (res, ext) = match self.resolve_macro_to_res(path, kind, &parent_scope, true, force) {
211 Ok((res, ext)) => (res, ext),
212 Err(Determinacy::Determined) if kind == MacroKind::Attr => {
213 // Replace unresolved attributes with used inert attributes for better recovery.
214 return Ok(Some(Lrc::new(SyntaxExtension::NonMacroAttr { mark_used: true })));
216 Err(determinacy) => return Err(determinacy),
219 if let Res::Def(DefKind::Macro(_), def_id) = res {
221 self.session.span_err(invoc.span(),
222 "macro attributes must be placed before `#[derive]`");
224 self.macro_defs.insert(invoc.expansion_data.mark, def_id);
225 let normal_module_def_id =
226 self.macro_def_scope(invoc.expansion_data.mark).normal_ancestor_id;
227 self.definitions.add_parent_module_of_macro_def(invoc.expansion_data.mark,
228 normal_module_def_id);
229 invoc.expansion_data.mark.set_default_transparency(ext.default_transparency());
235 fn resolve_macro_path(&mut self, path: &ast::Path, kind: MacroKind, invoc_id: Mark,
236 derives_in_scope: Vec<ast::Path>, force: bool)
237 -> Result<Lrc<SyntaxExtension>, Determinacy> {
238 let parent_scope = self.invoc_parent_scope(invoc_id, derives_in_scope);
239 Ok(self.resolve_macro_to_res(path, kind, &parent_scope, false, force)?.1)
242 fn check_unused_macros(&self) {
243 for did in self.unused_macros.iter() {
244 let id_span = match *self.macro_map[did] {
245 SyntaxExtension::NormalTT { def_info, .. } |
246 SyntaxExtension::DeclMacro { def_info, .. } => def_info,
249 if let Some((id, span)) = id_span {
250 let lint = lint::builtin::UNUSED_MACROS;
251 let msg = "unused macro definition";
252 self.session.buffer_lint(lint, id, span, msg);
254 bug!("attempted to create unused macro error, but span not available");
260 impl<'a> Resolver<'a> {
261 pub fn dummy_parent_scope(&self) -> ParentScope<'a> {
262 self.invoc_parent_scope(Mark::root(), Vec::new())
265 fn invoc_parent_scope(&self, invoc_id: Mark, derives: Vec<ast::Path>) -> ParentScope<'a> {
266 let invoc = self.invocations[&invoc_id];
268 module: invoc.module.get().nearest_item_scope(),
269 expansion: invoc_id.parent(),
270 legacy: invoc.parent_legacy_scope.get(),
275 fn resolve_macro_to_res(
279 parent_scope: &ParentScope<'a>,
282 ) -> Result<(Res, Lrc<SyntaxExtension>), Determinacy> {
283 let res = self.resolve_macro_to_res_inner(path, kind, parent_scope, trace, force);
285 // Report errors and enforce feature gates for the resolved macro.
286 if res != Err(Determinacy::Undetermined) {
287 // Do not report duplicated errors on every undetermined resolution.
288 for segment in &path.segments {
289 if let Some(args) = &segment.args {
290 self.session.span_err(args.span(), "generic arguments in macro path");
298 Res::Def(DefKind::Macro(macro_kind), def_id) => {
299 self.unused_macros.remove(&def_id);
300 if macro_kind == MacroKind::ProcMacroStub {
301 let msg = "can't use a procedural macro from the same crate that defines it";
302 self.session.span_err(path.span, msg);
303 return Err(Determinacy::Determined);
306 Res::NonMacroAttr(attr_kind) => {
307 if kind == MacroKind::Attr {
308 let features = self.session.features_untracked();
309 if attr_kind == NonMacroAttrKind::Custom {
310 assert!(path.segments.len() == 1);
311 let name = path.segments[0].ident.as_str();
312 if name.starts_with("rustc_") {
313 if !features.rustc_attrs {
314 let msg = "unless otherwise specified, attributes with the prefix \
315 `rustc_` are reserved for internal compiler diagnostics";
316 self.report_unknown_attribute(path.span, &name, msg,
319 } else if !features.custom_attribute {
320 let msg = format!("The attribute `{}` is currently unknown to the \
321 compiler and may have meaning added to it in the \
323 self.report_unknown_attribute(
327 sym::custom_attribute,
332 // Not only attributes, but anything in macro namespace can result in
333 // `Res::NonMacroAttr` definition (e.g., `inline!()`), so we must report
334 // an error for those cases.
335 let msg = format!("expected a macro, found {}", res.descr());
336 self.session.span_err(path.span, &msg);
337 return Err(Determinacy::Determined);
341 return Err(Determinacy::Determined);
343 _ => panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"),
346 Ok((res, self.get_macro(res)))
349 fn report_unknown_attribute(&self, span: Span, name: &str, msg: &str, feature: Symbol) {
350 let mut err = feature_err(
351 &self.session.parse_sess,
358 let features = self.session.features_untracked();
360 let attr_candidates = BUILTIN_ATTRIBUTES
362 .filter_map(|&(name, _, _, ref gate)| {
363 if name.as_str().starts_with("rustc_") && !features.rustc_attrs {
368 AttributeGate::Gated(Stability::Unstable, ..)
369 if self.session.opts.unstable_features.is_nightly_build() =>
373 AttributeGate::Gated(Stability::Deprecated(..), ..) => Some(name),
374 AttributeGate::Ungated => Some(name),
379 // Add built-in macro attributes as well.
380 self.builtin_macros.iter().filter_map(|(name, binding)| {
381 match binding.macro_kind() {
382 Some(MacroKind::Attr) => Some(*name),
387 .collect::<Vec<_>>();
389 let lev_suggestion = find_best_match_for_name(attr_candidates.iter(), &name, None);
391 if let Some(suggestion) = lev_suggestion {
394 "a built-in attribute with a similar name exists",
395 suggestion.to_string(),
396 Applicability::MaybeIncorrect,
403 pub fn resolve_macro_to_res_inner(
407 parent_scope: &ParentScope<'a>,
410 ) -> Result<Res, Determinacy> {
411 let path_span = path.span;
412 let mut path = Segment::from_path(path);
414 // Possibly apply the macro helper hack
415 if kind == MacroKind::Bang && path.len() == 1 &&
416 path[0].ident.span.ctxt().outer().expn_info()
417 .map_or(false, |info| info.local_inner_macros) {
418 let root = Ident::new(keywords::DollarCrate.name(), path[0].ident.span);
419 path.insert(0, Segment::from_ident(root));
423 let res = match self.resolve_path(&path, Some(MacroNS), parent_scope,
424 false, path_span, CrateLint::No) {
425 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
426 Ok(path_res.base_res())
428 PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
429 PathResult::NonModule(..)
430 | PathResult::Indeterminate
431 | PathResult::Failed { .. } => Err(Determinacy::Determined),
432 PathResult::Module(..) => unreachable!(),
436 parent_scope.module.multi_segment_macro_resolutions.borrow_mut()
437 .push((path, path_span, kind, parent_scope.clone(), res.ok()));
440 self.prohibit_imported_non_macro_attrs(None, res.ok(), path_span);
443 let binding = self.early_resolve_ident_in_lexical_scope(
444 path[0].ident, ScopeSet::Macro(kind), parent_scope, false, force, path_span
446 if let Err(Determinacy::Undetermined) = binding {
447 return Err(Determinacy::Undetermined);
451 parent_scope.module.single_segment_macro_resolutions.borrow_mut()
452 .push((path[0].ident, kind, parent_scope.clone(), binding.ok()));
455 let res = binding.map(|binding| binding.res());
456 self.prohibit_imported_non_macro_attrs(binding.ok(), res.ok(), path_span);
461 // Resolve an identifier in lexical scope.
462 // This is a variation of `fn resolve_ident_in_lexical_scope` that can be run during
463 // expansion and import resolution (perhaps they can be merged in the future).
464 // The function is used for resolving initial segments of macro paths (e.g., `foo` in
465 // `foo::bar!(); or `foo!();`) and also for import paths on 2018 edition.
466 crate fn early_resolve_ident_in_lexical_scope(
470 parent_scope: &ParentScope<'a>,
474 ) -> Result<&'a NameBinding<'a>, Determinacy> {
475 // General principles:
476 // 1. Not controlled (user-defined) names should have higher priority than controlled names
477 // built into the language or standard library. This way we can add new names into the
478 // language or standard library without breaking user code.
479 // 2. "Closed set" below means new names cannot appear after the current resolution attempt.
480 // Places to search (in order of decreasing priority):
482 // 1. FIXME: Ribs (type parameters), there's no necessary infrastructure yet
483 // (open set, not controlled).
484 // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
485 // (open, not controlled).
486 // 3. Extern prelude (closed, not controlled).
487 // 4. Tool modules (closed, controlled right now, but not in the future).
488 // 5. Standard library prelude (de-facto closed, controlled).
489 // 6. Language prelude (closed, controlled).
491 // 1. FIXME: Ribs (local variables), there's no necessary infrastructure yet
492 // (open set, not controlled).
493 // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
494 // (open, not controlled).
495 // 3. Standard library prelude (de-facto closed, controlled).
497 // 1-3. Derive helpers (open, not controlled). All ambiguities with other names
498 // are currently reported as errors. They should be higher in priority than preludes
499 // and probably even names in modules according to the "general principles" above. They
500 // also should be subject to restricted shadowing because are effectively produced by
501 // derives (you need to resolve the derive first to add helpers into scope), but they
502 // should be available before the derive is expanded for compatibility.
503 // It's mess in general, so we are being conservative for now.
504 // 1-3. `macro_rules` (open, not controlled), loop through legacy scopes. Have higher
505 // priority than prelude macros, but create ambiguities with macros in modules.
506 // 1-3. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
507 // (open, not controlled). Have higher priority than prelude macros, but create
508 // ambiguities with `macro_rules`.
509 // 4. `macro_use` prelude (open, the open part is from macro expansions, not controlled).
510 // 4a. User-defined prelude from macro-use
511 // (open, the open part is from macro expansions, not controlled).
512 // 4b. Standard library prelude is currently implemented as `macro-use` (closed, controlled)
513 // 5. Language prelude: builtin macros (closed, controlled, except for legacy plugins).
514 // 6. Language prelude: builtin attributes (closed, controlled).
515 // 4-6. Legacy plugin helpers (open, not controlled). Similar to derive helpers,
516 // but introduced by legacy plugins using `register_attribute`. Priority is somewhere
517 // in prelude, not sure where exactly (creates ambiguities with any other prelude names).
519 enum WhereToResolve<'a> {
521 MacroRules(LegacyScope<'a>),
534 bitflags::bitflags! {
536 const MACRO_RULES = 1 << 0;
537 const MODULE = 1 << 1;
538 const PRELUDE = 1 << 2;
539 const MISC_SUGGEST_CRATE = 1 << 3;
540 const MISC_SUGGEST_SELF = 1 << 4;
541 const MISC_FROM_PRELUDE = 1 << 5;
545 assert!(force || !record_used); // `record_used` implies `force`
546 let mut ident = orig_ident.modern();
548 // Make sure `self`, `super` etc produce an error when passed to here.
549 if ident.is_path_segment_keyword() {
550 return Err(Determinacy::Determined);
553 // This is *the* result, resolution from the scope closest to the resolved identifier.
554 // However, sometimes this result is "weak" because it comes from a glob import or
555 // a macro expansion, and in this case it cannot shadow names from outer scopes, e.g.
556 // mod m { ... } // solution in outer scope
558 // use prefix::*; // imports another `m` - innermost solution
559 // // weak, cannot shadow the outer `m`, need to report ambiguity error
562 // So we have to save the innermost solution and continue searching in outer scopes
563 // to detect potential ambiguities.
564 let mut innermost_result: Option<(&NameBinding<'_>, Flags)> = None;
566 // Go through all the scopes and try to resolve the name.
567 let rust_2015 = orig_ident.span.rust_2015();
568 let (ns, macro_kind, is_import, is_absolute_path) = match scope_set {
569 ScopeSet::Import(ns) => (ns, None, true, false),
570 ScopeSet::AbsolutePath(ns) => (ns, None, false, true),
571 ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind), false, false),
572 ScopeSet::Module => (TypeNS, None, false, false),
574 let mut where_to_resolve = match ns {
575 _ if is_absolute_path => WhereToResolve::CrateRoot,
576 TypeNS | ValueNS => WhereToResolve::Module(parent_scope.module),
577 MacroNS => WhereToResolve::DeriveHelpers,
579 let mut use_prelude = !parent_scope.module.no_implicit_prelude;
580 let mut determinacy = Determinacy::Determined;
582 let result = match where_to_resolve {
583 WhereToResolve::DeriveHelpers => {
584 let mut result = Err(Determinacy::Determined);
585 for derive in &parent_scope.derives {
586 let parent_scope = ParentScope { derives: Vec::new(), ..*parent_scope };
587 match self.resolve_macro_to_res(derive, MacroKind::Derive,
588 &parent_scope, true, force) {
590 if let SyntaxExtension::ProcMacroDerive(_, helpers, _) = &*ext {
591 if helpers.contains(&ident.name) {
593 (Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper),
594 ty::Visibility::Public, derive.span, Mark::root())
595 .to_name_binding(self.arenas);
596 result = Ok((binding, Flags::empty()));
601 Err(Determinacy::Determined) => {}
602 Err(Determinacy::Undetermined) =>
603 result = Err(Determinacy::Undetermined),
608 WhereToResolve::MacroRules(legacy_scope) => match legacy_scope {
609 LegacyScope::Binding(legacy_binding) if ident == legacy_binding.ident =>
610 Ok((legacy_binding.binding, Flags::MACRO_RULES)),
611 LegacyScope::Invocation(invoc) if invoc.output_legacy_scope.get().is_none() =>
612 Err(Determinacy::Undetermined),
613 _ => Err(Determinacy::Determined),
615 WhereToResolve::CrateRoot => {
616 let root_ident = Ident::new(keywords::PathRoot.name(), orig_ident.span);
617 let root_module = self.resolve_crate_root(root_ident);
618 let binding = self.resolve_ident_in_module_ext(
619 ModuleOrUniformRoot::Module(root_module),
627 Ok(binding) => Ok((binding, Flags::MODULE | Flags::MISC_SUGGEST_CRATE)),
628 Err((Determinacy::Undetermined, Weak::No)) =>
629 return Err(Determinacy::determined(force)),
630 Err((Determinacy::Undetermined, Weak::Yes)) =>
631 Err(Determinacy::Undetermined),
632 Err((Determinacy::Determined, _)) => Err(Determinacy::Determined),
635 WhereToResolve::Module(module) => {
636 let orig_current_module = mem::replace(&mut self.current_module, module);
637 let binding = self.resolve_ident_in_module_unadjusted_ext(
638 ModuleOrUniformRoot::Module(module),
646 self.current_module = orig_current_module;
649 let misc_flags = if ptr::eq(module, self.graph_root) {
650 Flags::MISC_SUGGEST_CRATE
651 } else if module.is_normal() {
652 Flags::MISC_SUGGEST_SELF
656 Ok((binding, Flags::MODULE | misc_flags))
658 Err((Determinacy::Undetermined, Weak::No)) =>
659 return Err(Determinacy::determined(force)),
660 Err((Determinacy::Undetermined, Weak::Yes)) =>
661 Err(Determinacy::Undetermined),
662 Err((Determinacy::Determined, _)) => Err(Determinacy::Determined),
665 WhereToResolve::MacroUsePrelude => {
666 if use_prelude || rust_2015 {
667 match self.macro_use_prelude.get(&ident.name).cloned() {
669 Ok((binding, Flags::PRELUDE | Flags::MISC_FROM_PRELUDE)),
670 None => Err(Determinacy::determined(
671 self.graph_root.unresolved_invocations.borrow().is_empty()
675 Err(Determinacy::Determined)
678 WhereToResolve::BuiltinMacros => {
679 match self.builtin_macros.get(&ident.name).cloned() {
680 Some(binding) => Ok((binding, Flags::PRELUDE)),
681 None => Err(Determinacy::Determined),
684 WhereToResolve::BuiltinAttrs => {
685 if is_builtin_attr_name(ident.name) {
686 let binding = (Res::NonMacroAttr(NonMacroAttrKind::Builtin),
687 ty::Visibility::Public, DUMMY_SP, Mark::root())
688 .to_name_binding(self.arenas);
689 Ok((binding, Flags::PRELUDE))
691 Err(Determinacy::Determined)
694 WhereToResolve::LegacyPluginHelpers => {
695 if (use_prelude || rust_2015) &&
696 self.session.plugin_attributes.borrow().iter()
697 .any(|(name, _)| ident.name == *name) {
698 let binding = (Res::NonMacroAttr(NonMacroAttrKind::LegacyPluginHelper),
699 ty::Visibility::Public, DUMMY_SP, Mark::root())
700 .to_name_binding(self.arenas);
701 Ok((binding, Flags::PRELUDE))
703 Err(Determinacy::Determined)
706 WhereToResolve::ExternPrelude => {
707 if use_prelude || is_absolute_path {
708 match self.extern_prelude_get(ident, !record_used) {
709 Some(binding) => Ok((binding, Flags::PRELUDE)),
710 None => Err(Determinacy::determined(
711 self.graph_root.unresolved_invocations.borrow().is_empty()
715 Err(Determinacy::Determined)
718 WhereToResolve::ToolPrelude => {
719 if use_prelude && is_known_tool(ident.name) {
720 let binding = (Res::ToolMod, ty::Visibility::Public,
721 DUMMY_SP, Mark::root()).to_name_binding(self.arenas);
722 Ok((binding, Flags::PRELUDE))
724 Err(Determinacy::Determined)
727 WhereToResolve::StdLibPrelude => {
728 let mut result = Err(Determinacy::Determined);
730 if let Some(prelude) = self.prelude {
731 if let Ok(binding) = self.resolve_ident_in_module_unadjusted(
732 ModuleOrUniformRoot::Module(prelude),
738 result = Ok((binding, Flags::PRELUDE | Flags::MISC_FROM_PRELUDE));
744 WhereToResolve::BuiltinTypes => {
745 match self.primitive_type_table.primitive_types.get(&ident.name).cloned() {
747 let binding = (Res::PrimTy(prim_ty), ty::Visibility::Public,
748 DUMMY_SP, Mark::root()).to_name_binding(self.arenas);
749 Ok((binding, Flags::PRELUDE))
751 None => Err(Determinacy::Determined)
757 Ok((binding, flags)) if sub_namespace_match(binding.macro_kind(), macro_kind) => {
762 if let Some((innermost_binding, innermost_flags)) = innermost_result {
763 // Found another solution, if the first one was "weak", report an error.
764 let (res, innermost_res) = (binding.res(), innermost_binding.res());
765 if res != innermost_res {
766 let builtin = Res::NonMacroAttr(NonMacroAttrKind::Builtin);
767 let derive_helper = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
769 Res::NonMacroAttr(NonMacroAttrKind::LegacyPluginHelper);
771 let ambiguity_error_kind = if is_import {
772 Some(AmbiguityKind::Import)
773 } else if innermost_res == builtin || res == builtin {
774 Some(AmbiguityKind::BuiltinAttr)
775 } else if innermost_res == derive_helper || res == derive_helper {
776 Some(AmbiguityKind::DeriveHelper)
777 } else if innermost_res == legacy_helper &&
778 flags.contains(Flags::PRELUDE) ||
779 res == legacy_helper &&
780 innermost_flags.contains(Flags::PRELUDE) {
781 Some(AmbiguityKind::LegacyHelperVsPrelude)
782 } else if innermost_flags.contains(Flags::MACRO_RULES) &&
783 flags.contains(Flags::MODULE) &&
784 !self.disambiguate_legacy_vs_modern(innermost_binding,
786 flags.contains(Flags::MACRO_RULES) &&
787 innermost_flags.contains(Flags::MODULE) &&
788 !self.disambiguate_legacy_vs_modern(binding,
790 Some(AmbiguityKind::LegacyVsModern)
791 } else if innermost_binding.is_glob_import() {
792 Some(AmbiguityKind::GlobVsOuter)
793 } else if innermost_binding.may_appear_after(parent_scope.expansion,
795 Some(AmbiguityKind::MoreExpandedVsOuter)
799 if let Some(kind) = ambiguity_error_kind {
800 let misc = |f: Flags| if f.contains(Flags::MISC_SUGGEST_CRATE) {
801 AmbiguityErrorMisc::SuggestCrate
802 } else if f.contains(Flags::MISC_SUGGEST_SELF) {
803 AmbiguityErrorMisc::SuggestSelf
804 } else if f.contains(Flags::MISC_FROM_PRELUDE) {
805 AmbiguityErrorMisc::FromPrelude
807 AmbiguityErrorMisc::None
809 self.ambiguity_errors.push(AmbiguityError {
812 b1: innermost_binding,
814 misc1: misc(innermost_flags),
817 return Ok(innermost_binding);
821 // Found the first solution.
822 innermost_result = Some((binding, flags));
825 Ok(..) | Err(Determinacy::Determined) => {}
826 Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined
829 where_to_resolve = match where_to_resolve {
830 WhereToResolve::DeriveHelpers =>
831 WhereToResolve::MacroRules(parent_scope.legacy),
832 WhereToResolve::MacroRules(legacy_scope) => match legacy_scope {
833 LegacyScope::Binding(binding) => WhereToResolve::MacroRules(
834 binding.parent_legacy_scope
836 LegacyScope::Invocation(invoc) => WhereToResolve::MacroRules(
837 invoc.output_legacy_scope.get().unwrap_or(invoc.parent_legacy_scope.get())
839 LegacyScope::Empty => WhereToResolve::Module(parent_scope.module),
840 LegacyScope::Uninitialized => unreachable!(),
842 WhereToResolve::CrateRoot => match ns {
844 ident.span.adjust(Mark::root());
845 WhereToResolve::ExternPrelude
847 ValueNS | MacroNS => break,
849 WhereToResolve::Module(module) => {
850 match self.hygienic_lexical_parent(module, &mut ident.span) {
851 Some(parent_module) => WhereToResolve::Module(parent_module),
853 use_prelude = !module.no_implicit_prelude;
855 TypeNS => WhereToResolve::ExternPrelude,
856 ValueNS => WhereToResolve::StdLibPrelude,
857 MacroNS => WhereToResolve::MacroUsePrelude,
862 WhereToResolve::MacroUsePrelude => WhereToResolve::BuiltinMacros,
863 WhereToResolve::BuiltinMacros => WhereToResolve::BuiltinAttrs,
864 WhereToResolve::BuiltinAttrs => WhereToResolve::LegacyPluginHelpers,
865 WhereToResolve::LegacyPluginHelpers => break, // nowhere else to search
866 WhereToResolve::ExternPrelude if is_absolute_path => break,
867 WhereToResolve::ExternPrelude => WhereToResolve::ToolPrelude,
868 WhereToResolve::ToolPrelude => WhereToResolve::StdLibPrelude,
869 WhereToResolve::StdLibPrelude => match ns {
870 TypeNS => WhereToResolve::BuiltinTypes,
871 ValueNS => break, // nowhere else to search
872 MacroNS => unreachable!(),
874 WhereToResolve::BuiltinTypes => break, // nowhere else to search
880 // The first found solution was the only one, return it.
881 if let Some((binding, _)) = innermost_result {
885 let determinacy = Determinacy::determined(determinacy == Determinacy::Determined || force);
886 if determinacy == Determinacy::Determined && macro_kind == Some(MacroKind::Attr) {
887 // For single-segment attributes interpret determinate "no resolution" as a custom
888 // attribute. (Lexical resolution implies the first segment and attr kind should imply
889 // the last segment, so we are certainly working with a single-segment attribute here.)
890 assert!(ns == MacroNS);
891 let binding = (Res::NonMacroAttr(NonMacroAttrKind::Custom),
892 ty::Visibility::Public, ident.span, Mark::root())
893 .to_name_binding(self.arenas);
900 pub fn finalize_current_module_macro_resolutions(&mut self) {
901 let module = self.current_module;
903 let check_consistency = |this: &mut Self, path: &[Segment], span, kind: MacroKind,
904 initial_res: Option<Res>, res: Res| {
905 if let Some(initial_res) = initial_res {
906 if res != initial_res && res != Res::Err && this.ambiguity_errors.is_empty() {
907 // Make sure compilation does not succeed if preferred macro resolution
908 // has changed after the macro had been expanded. In theory all such
909 // situations should be reported as ambiguity errors, so this is a bug.
910 if initial_res == Res::NonMacroAttr(NonMacroAttrKind::Custom) {
911 // Yeah, legacy custom attributes are implemented using forced resolution
912 // (which is a best effort error recovery tool, basically), so we can't
913 // promise their resolution won't change later.
914 let msg = format!("inconsistent resolution for a macro: first {}, then {}",
915 initial_res.descr(), res.descr());
916 this.session.span_err(span, &msg);
918 span_bug!(span, "inconsistent resolution for a macro");
922 // It's possible that the macro was unresolved (indeterminate) and silently
923 // expanded into a dummy fragment for recovery during expansion.
924 // Now, post-expansion, the resolution may succeed, but we can't change the
925 // past and need to report an error.
926 // However, non-speculative `resolve_path` can successfully return private items
927 // even if speculative `resolve_path` returned nothing previously, so we skip this
928 // less informative error if the privacy error is reported elsewhere.
929 if this.privacy_errors.is_empty() {
930 let msg = format!("cannot determine resolution for the {} `{}`",
931 kind.descr(), Segment::names_to_string(path));
932 let msg_note = "import resolution is stuck, try simplifying macro imports";
933 this.session.struct_span_err(span, &msg).note(msg_note).emit();
938 let macro_resolutions =
939 mem::replace(&mut *module.multi_segment_macro_resolutions.borrow_mut(), Vec::new());
940 for (mut path, path_span, kind, parent_scope, initial_res) in macro_resolutions {
941 // FIXME: Path resolution will ICE if segment IDs present.
942 for seg in &mut path { seg.id = None; }
943 match self.resolve_path(&path, Some(MacroNS), &parent_scope,
944 true, path_span, CrateLint::No) {
945 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
946 let res = path_res.base_res();
947 check_consistency(self, &path, path_span, kind, initial_res, res);
949 path_res @ PathResult::NonModule(..) | path_res @ PathResult::Failed { .. } => {
950 let (span, label) = if let PathResult::Failed { span, label, .. } = path_res {
953 (path_span, format!("partially resolved path in {} {}",
954 kind.article(), kind.descr()))
956 resolve_error(self, span, ResolutionError::FailedToResolve {
961 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
965 let macro_resolutions =
966 mem::replace(&mut *module.single_segment_macro_resolutions.borrow_mut(), Vec::new());
967 for (ident, kind, parent_scope, initial_binding) in macro_resolutions {
968 match self.early_resolve_ident_in_lexical_scope(ident, ScopeSet::Macro(kind),
969 &parent_scope, true, true, ident.span) {
971 let initial_res = initial_binding.map(|initial_binding| {
972 self.record_use(ident, MacroNS, initial_binding, false);
973 initial_binding.res()
975 let res = binding.res();
976 let seg = Segment::from_ident(ident);
977 check_consistency(self, &[seg], ident.span, kind, initial_res, res);
980 assert!(initial_binding.is_none());
981 let bang = if kind == MacroKind::Bang { "!" } else { "" };
983 format!("cannot find {} `{}{}` in this scope", kind.descr(), ident, bang);
984 let mut err = self.session.struct_span_err(ident.span, &msg);
985 self.suggest_macro_name(ident.name, kind, &mut err, ident.span);
991 let builtin_attrs = mem::replace(&mut *module.builtin_attrs.borrow_mut(), Vec::new());
992 for (ident, parent_scope) in builtin_attrs {
993 let _ = self.early_resolve_ident_in_lexical_scope(
994 ident, ScopeSet::Macro(MacroKind::Attr), &parent_scope, true, true, ident.span
999 fn prohibit_imported_non_macro_attrs(&self, binding: Option<&'a NameBinding<'a>>,
1000 res: Option<Res>, span: Span) {
1001 if let Some(Res::NonMacroAttr(kind)) = res {
1002 if kind != NonMacroAttrKind::Tool && binding.map_or(true, |b| b.is_import()) {
1003 let msg = format!("cannot use a {} through an import", kind.descr());
1004 let mut err = self.session.struct_span_err(span, &msg);
1005 if let Some(binding) = binding {
1006 err.span_note(binding.span, &format!("the {} imported here", kind.descr()));
1013 fn suggest_macro_name(&mut self, name: Symbol, kind: MacroKind,
1014 err: &mut DiagnosticBuilder<'a>, span: Span) {
1015 // First check if this is a locally-defined bang macro.
1016 let suggestion = if let MacroKind::Bang = kind {
1017 find_best_match_for_name(
1018 self.macro_names.iter().map(|ident| &ident.name), &name.as_str(), None)
1021 // Then check global macros.
1023 let names = self.builtin_macros.iter().chain(self.macro_use_prelude.iter())
1024 .filter_map(|(name, binding)| {
1025 if binding.macro_kind() == Some(kind) { Some(name) } else { None }
1027 find_best_match_for_name(names, &name.as_str(), None)
1028 // Then check modules.
1030 let is_macro = |res| {
1031 if let Res::Def(DefKind::Macro(def_kind), _) = res {
1037 let ident = Ident::new(name, span);
1038 self.lookup_typo_candidate(&[Segment::from_ident(ident)], MacroNS, is_macro, span)
1039 .map(|suggestion| suggestion.candidate)
1042 if let Some(suggestion) = suggestion {
1043 if suggestion != name {
1044 if let MacroKind::Bang = kind {
1045 err.span_suggestion(
1047 "you could try the macro",
1048 suggestion.to_string(),
1049 Applicability::MaybeIncorrect
1052 err.span_suggestion(
1055 suggestion.to_string(),
1056 Applicability::MaybeIncorrect
1060 err.help("have you added the `#[macro_use]` on the module/import?");
1065 fn collect_def_ids(&mut self,
1067 invocation: &'a InvocationData<'a>,
1068 fragment: &AstFragment) {
1069 let Resolver { ref mut invocations, arenas, graph_root, .. } = *self;
1070 let InvocationData { def_index, .. } = *invocation;
1072 let visit_macro_invoc = &mut |invoc: map::MacroInvocationData| {
1073 invocations.entry(invoc.mark).or_insert_with(|| {
1074 arenas.alloc_invocation_data(InvocationData {
1075 def_index: invoc.def_index,
1076 module: Cell::new(graph_root),
1077 parent_legacy_scope: Cell::new(LegacyScope::Uninitialized),
1078 output_legacy_scope: Cell::new(None),
1083 let mut def_collector = DefCollector::new(&mut self.definitions, mark);
1084 def_collector.visit_macro_invoc = Some(visit_macro_invoc);
1085 def_collector.with_parent(def_index, |def_collector| {
1086 fragment.visit_with(def_collector)
1090 pub fn define_macro(&mut self,
1093 current_legacy_scope: &mut LegacyScope<'a>) {
1094 self.local_macro_def_scopes.insert(item.id, self.current_module);
1095 let ident = item.ident;
1096 if ident.name == sym::macro_rules {
1097 self.session.span_err(item.span, "user-defined macros may not be named `macro_rules`");
1100 let def_id = self.definitions.local_def_id(item.id);
1101 let ext = Lrc::new(macro_rules::compile(&self.session.parse_sess,
1102 &self.session.features_untracked(),
1103 item, hygiene::default_edition()));
1104 self.macro_map.insert(def_id, ext);
1106 let def = match item.node { ast::ItemKind::MacroDef(ref def) => def, _ => unreachable!() };
1108 let ident = ident.modern();
1109 self.macro_names.insert(ident);
1110 let res = Res::Def(DefKind::Macro(MacroKind::Bang), def_id);
1111 let is_macro_export = attr::contains_name(&item.attrs, sym::macro_export);
1112 let vis = if is_macro_export {
1113 ty::Visibility::Public
1115 ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))
1117 let binding = (res, vis, item.span, expansion).to_name_binding(self.arenas);
1118 self.set_binding_parent_module(binding, self.current_module);
1119 let legacy_binding = self.arenas.alloc_legacy_binding(LegacyBinding {
1120 parent_legacy_scope: *current_legacy_scope, binding, ident
1122 *current_legacy_scope = LegacyScope::Binding(legacy_binding);
1123 self.all_macros.insert(ident.name, res);
1124 if is_macro_export {
1125 let module = self.graph_root;
1126 self.define(module, ident, MacroNS,
1127 (res, vis, item.span, expansion, IsMacroExport));
1129 if !attr::contains_name(&item.attrs, sym::rustc_doc_only_macro) {
1130 self.check_reserved_macro_name(ident, MacroNS);
1132 self.unused_macros.insert(def_id);
1135 let module = self.current_module;
1136 let res = Res::Def(DefKind::Macro(MacroKind::Bang), def_id);
1137 let vis = self.resolve_visibility(&item.vis);
1138 if vis != ty::Visibility::Public {
1139 self.unused_macros.insert(def_id);
1141 self.define(module, ident, MacroNS, (res, vis, item.span, expansion));