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::{DefId, CRATE_DEF_INDEX, DefIndex,
10 CrateNum, DefIndexAddressSpace};
11 use rustc::hir::def::{Def, NonMacroAttrKind};
12 use rustc::hir::map::{self, DefCollector};
13 use rustc::{ty, lint};
14 use rustc::{bug, span_bug};
15 use syntax::ast::{self, Ident};
17 use syntax::errors::DiagnosticBuilder;
18 use syntax::ext::base::{self, Determinacy};
19 use syntax::ext::base::{MacroKind, SyntaxExtension};
20 use syntax::ext::expand::{AstFragment, Invocation, InvocationKind};
21 use syntax::ext::hygiene::{self, Mark};
22 use syntax::ext::tt::macro_rules;
23 use syntax::feature_gate::{
24 feature_err, is_builtin_attr_name, AttributeGate, GateIssue, Stability, BUILTIN_ATTRIBUTES,
26 use syntax::symbol::{Symbol, keywords};
27 use syntax::visit::Visitor;
28 use syntax::util::lev_distance::find_best_match_for_name;
29 use syntax_pos::{Span, DUMMY_SP};
30 use crate::errors::Applicability;
34 use rustc_data_structures::sync::Lrc;
36 #[derive(Clone, Debug)]
37 pub struct InvocationData<'a> {
39 /// The module in which the macro was invoked.
40 crate module: Cell<Module<'a>>,
41 /// The legacy scope in which the macro was invoked.
42 /// The invocation path is resolved in this scope.
43 crate parent_legacy_scope: Cell<LegacyScope<'a>>,
44 /// The legacy scope *produced* by expanding this macro invocation,
45 /// includes all the macro_rules items, other invocations, etc generated by it.
46 /// `None` if the macro is not expanded yet.
47 crate output_legacy_scope: Cell<Option<LegacyScope<'a>>>,
50 impl<'a> InvocationData<'a> {
51 pub fn root(graph_root: Module<'a>) -> Self {
53 module: Cell::new(graph_root),
54 def_index: CRATE_DEF_INDEX,
55 parent_legacy_scope: Cell::new(LegacyScope::Empty),
56 output_legacy_scope: Cell::new(Some(LegacyScope::Empty)),
61 /// Binding produced by a `macro_rules` item.
62 /// Not modularized, can shadow previous legacy bindings, etc.
64 pub struct LegacyBinding<'a> {
65 binding: &'a NameBinding<'a>,
66 /// Legacy scope into which the `macro_rules` item was planted.
67 parent_legacy_scope: LegacyScope<'a>,
71 /// The scope introduced by a `macro_rules!` macro.
72 /// This starts at the macro's definition and ends at the end of the macro's parent
73 /// module (named or unnamed), or even further if it escapes with `#[macro_use]`.
74 /// Some macro invocations need to introduce legacy scopes too because they
75 /// can potentially expand into macro definitions.
76 #[derive(Copy, Clone, Debug)]
77 pub enum LegacyScope<'a> {
78 /// Created when invocation data is allocated in the arena;
79 /// must be replaced with a proper scope later.
81 /// Empty "root" scope at the crate start containing no names.
83 /// The scope introduced by a `macro_rules!` macro definition.
84 Binding(&'a LegacyBinding<'a>),
85 /// The scope introduced by a macro invocation that can potentially
86 /// create a `macro_rules!` macro definition.
87 Invocation(&'a InvocationData<'a>),
90 /// Everything you need to resolve a macro or import path.
91 #[derive(Clone, Debug)]
92 pub struct ParentScope<'a> {
93 crate module: Module<'a>,
94 crate expansion: Mark,
95 crate legacy: LegacyScope<'a>,
96 crate derives: Vec<ast::Path>,
99 // Macro namespace is separated into two sub-namespaces, one for bang macros and
100 // one for attribute-like macros (attributes, derives).
101 // We ignore resolutions from one sub-namespace when searching names in scope for another.
102 fn sub_namespace_match(candidate: Option<MacroKind>, requirement: Option<MacroKind>) -> bool {
104 enum SubNS { Bang, AttrLike }
105 let sub_ns = |kind| match kind {
106 MacroKind::Bang => Some(SubNS::Bang),
107 MacroKind::Attr | MacroKind::Derive => Some(SubNS::AttrLike),
108 MacroKind::ProcMacroStub => None,
110 let requirement = requirement.and_then(|kind| sub_ns(kind));
111 let candidate = candidate.and_then(|kind| sub_ns(kind));
112 // "No specific sub-namespace" means "matches anything" for both requirements and candidates.
113 candidate.is_none() || requirement.is_none() || candidate == requirement
116 impl<'a> base::Resolver for Resolver<'a> {
117 fn next_node_id(&mut self) -> ast::NodeId {
118 self.session.next_node_id()
121 fn get_module_scope(&mut self, id: ast::NodeId) -> Mark {
122 let mark = Mark::fresh(Mark::root());
123 let module = self.module_map[&self.definitions.local_def_id(id)];
124 self.invocations.insert(mark, self.arenas.alloc_invocation_data(InvocationData {
125 module: Cell::new(module),
126 def_index: module.def_id().unwrap().index,
127 parent_legacy_scope: Cell::new(LegacyScope::Empty),
128 output_legacy_scope: Cell::new(Some(LegacyScope::Empty)),
133 fn resolve_dollar_crates(&mut self, fragment: &AstFragment) {
134 struct ResolveDollarCrates<'a, 'b: 'a> {
135 resolver: &'a mut Resolver<'b>
137 impl<'a> Visitor<'a> for ResolveDollarCrates<'a, '_> {
138 fn visit_ident(&mut self, ident: Ident) {
139 if ident.name == keywords::DollarCrate.name() {
140 let name = match self.resolver.resolve_crate_root(ident).kind {
141 ModuleKind::Def(_, name) if name != keywords::Invalid.name() => name,
142 _ => keywords::Crate.name(),
144 ident.span.ctxt().set_dollar_crate_name(name);
147 fn visit_mac(&mut self, _: &ast::Mac) {}
150 fragment.visit_with(&mut ResolveDollarCrates { resolver: self });
153 fn visit_ast_fragment_with_placeholders(&mut self, mark: Mark, fragment: &AstFragment,
155 let invocation = self.invocations[&mark];
156 self.collect_def_ids(mark, invocation, fragment);
158 self.current_module = invocation.module.get();
159 self.current_module.unresolved_invocations.borrow_mut().remove(&mark);
160 self.current_module.unresolved_invocations.borrow_mut().extend(derives);
161 self.invocations.extend(derives.iter().map(|&derive| (derive, invocation)));
162 let mut visitor = BuildReducedGraphVisitor {
164 current_legacy_scope: invocation.parent_legacy_scope.get(),
167 fragment.visit_with(&mut visitor);
168 invocation.output_legacy_scope.set(Some(visitor.current_legacy_scope));
171 fn add_builtin(&mut self, ident: ast::Ident, ext: Lrc<SyntaxExtension>) {
173 krate: CrateNum::BuiltinMacros,
174 index: DefIndex::from_array_index(self.macro_map.len(),
175 DefIndexAddressSpace::Low),
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::Def(Def::Macro(def_id, kind), 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 (def, ext) = match self.resolve_macro_to_def(path, kind, &parent_scope, true, force) {
211 Ok((def, ext)) => (def, 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 Def::Macro(def_id, _) = def {
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_def(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_def(
279 parent_scope: &ParentScope<'a>,
282 ) -> Result<(Def, Lrc<SyntaxExtension>), Determinacy> {
283 let def = self.resolve_macro_to_def_inner(path, kind, parent_scope, trace, force);
285 // Report errors and enforce feature gates for the resolved macro.
286 if def != 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 Def::Macro(def_id, macro_kind) => {
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 Def::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, "rustc_attrs");
318 } else if !features.custom_attribute {
319 let msg = format!("The attribute `{}` is currently unknown to the \
320 compiler and may have meaning added to it in the \
322 self.report_unknown_attribute(
331 // Not only attributes, but anything in macro namespace can result in
332 // `Def::NonMacroAttr` definition (e.g., `inline!()`), so we must report
333 // an error for those cases.
334 let msg = format!("expected a macro, found {}", def.kind_name());
335 self.session.span_err(path.span, &msg);
336 return Err(Determinacy::Determined);
340 return Err(Determinacy::Determined);
342 _ => panic!("expected `Def::Macro` or `Def::NonMacroAttr`"),
345 Ok((def, self.get_macro(def)))
348 fn report_unknown_attribute(&self, span: Span, name: &str, msg: &str, feature: &str) {
349 let mut err = feature_err(
350 &self.session.parse_sess,
357 let features = self.session.features_untracked();
359 let attr_candidates = BUILTIN_ATTRIBUTES
361 .filter_map(|(name, _, _, gate)| {
362 if name.starts_with("rustc_") && !features.rustc_attrs {
367 AttributeGate::Gated(Stability::Unstable, ..)
368 if self.session.opts.unstable_features.is_nightly_build() =>
372 AttributeGate::Gated(Stability::Deprecated(..), ..) => Some(name),
373 AttributeGate::Ungated => Some(name),
377 .map(|name| Symbol::intern(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_def_inner(
407 parent_scope: &ParentScope<'a>,
410 ) -> Result<Def, 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 def = 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_def())
428 PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
429 PathResult::NonModule(..) | PathResult::Indeterminate | PathResult::Failed(..) => {
430 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(), def.ok()));
440 self.prohibit_imported_non_macro_attrs(None, def.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 def = binding.map(|binding| binding.def());
456 self.prohibit_imported_non_macro_attrs(binding.ok(), def.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 || is_import && rust_2015 => 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_def(derive, MacroKind::Derive,
588 &parent_scope, true, force) {
590 if let SyntaxExtension::ProcMacroDerive(_, helpers, _) = &*ext {
591 if helpers.contains(&ident.name) {
593 (Def::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 = (Def::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 = (Def::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 = (Def::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 = (Def::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 (def, innermost_def) = (binding.def(), innermost_binding.def());
765 if def != innermost_def {
766 let builtin = Def::NonMacroAttr(NonMacroAttrKind::Builtin);
767 let derive_helper = Def::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
769 Def::NonMacroAttr(NonMacroAttrKind::LegacyPluginHelper);
771 let ambiguity_error_kind = if is_import {
772 Some(AmbiguityKind::Import)
773 } else if is_absolute_path {
774 Some(AmbiguityKind::AbsolutePath)
775 } else if innermost_def == builtin || def == builtin {
776 Some(AmbiguityKind::BuiltinAttr)
777 } else if innermost_def == derive_helper || def == derive_helper {
778 Some(AmbiguityKind::DeriveHelper)
779 } else if innermost_def == legacy_helper &&
780 flags.contains(Flags::PRELUDE) ||
781 def == legacy_helper &&
782 innermost_flags.contains(Flags::PRELUDE) {
783 Some(AmbiguityKind::LegacyHelperVsPrelude)
784 } else if innermost_flags.contains(Flags::MACRO_RULES) &&
785 flags.contains(Flags::MODULE) &&
786 !self.disambiguate_legacy_vs_modern(innermost_binding,
788 flags.contains(Flags::MACRO_RULES) &&
789 innermost_flags.contains(Flags::MODULE) &&
790 !self.disambiguate_legacy_vs_modern(binding,
792 Some(AmbiguityKind::LegacyVsModern)
793 } else if innermost_binding.is_glob_import() {
794 Some(AmbiguityKind::GlobVsOuter)
795 } else if innermost_binding.may_appear_after(parent_scope.expansion,
797 Some(AmbiguityKind::MoreExpandedVsOuter)
801 if let Some(kind) = ambiguity_error_kind {
802 let misc = |f: Flags| if f.contains(Flags::MISC_SUGGEST_CRATE) {
803 AmbiguityErrorMisc::SuggestCrate
804 } else if f.contains(Flags::MISC_SUGGEST_SELF) {
805 AmbiguityErrorMisc::SuggestSelf
806 } else if f.contains(Flags::MISC_FROM_PRELUDE) {
807 AmbiguityErrorMisc::FromPrelude
809 AmbiguityErrorMisc::None
811 self.ambiguity_errors.push(AmbiguityError {
814 b1: innermost_binding,
816 misc1: misc(innermost_flags),
819 return Ok(innermost_binding);
823 // Found the first solution.
824 innermost_result = Some((binding, flags));
827 Ok(..) | Err(Determinacy::Determined) => {}
828 Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined
831 where_to_resolve = match where_to_resolve {
832 WhereToResolve::DeriveHelpers =>
833 WhereToResolve::MacroRules(parent_scope.legacy),
834 WhereToResolve::MacroRules(legacy_scope) => match legacy_scope {
835 LegacyScope::Binding(binding) => WhereToResolve::MacroRules(
836 binding.parent_legacy_scope
838 LegacyScope::Invocation(invoc) => WhereToResolve::MacroRules(
839 invoc.output_legacy_scope.get().unwrap_or(invoc.parent_legacy_scope.get())
841 LegacyScope::Empty => WhereToResolve::Module(parent_scope.module),
842 LegacyScope::Uninitialized => unreachable!(),
844 WhereToResolve::CrateRoot if is_import => match ns {
845 TypeNS | ValueNS => WhereToResolve::Module(parent_scope.module),
846 MacroNS => WhereToResolve::DeriveHelpers,
848 WhereToResolve::CrateRoot if is_absolute_path => match ns {
850 ident.span.adjust(Mark::root());
851 WhereToResolve::ExternPrelude
853 ValueNS | MacroNS => break,
855 WhereToResolve::CrateRoot => unreachable!(),
856 WhereToResolve::Module(module) => {
857 match self.hygienic_lexical_parent(module, &mut ident.span) {
858 Some(parent_module) => WhereToResolve::Module(parent_module),
860 use_prelude = !module.no_implicit_prelude;
862 TypeNS => WhereToResolve::ExternPrelude,
863 ValueNS => WhereToResolve::StdLibPrelude,
864 MacroNS => WhereToResolve::MacroUsePrelude,
869 WhereToResolve::MacroUsePrelude => WhereToResolve::BuiltinMacros,
870 WhereToResolve::BuiltinMacros => WhereToResolve::BuiltinAttrs,
871 WhereToResolve::BuiltinAttrs => WhereToResolve::LegacyPluginHelpers,
872 WhereToResolve::LegacyPluginHelpers => break, // nowhere else to search
873 WhereToResolve::ExternPrelude if is_absolute_path => break,
874 WhereToResolve::ExternPrelude => WhereToResolve::ToolPrelude,
875 WhereToResolve::ToolPrelude => WhereToResolve::StdLibPrelude,
876 WhereToResolve::StdLibPrelude => match ns {
877 TypeNS => WhereToResolve::BuiltinTypes,
878 ValueNS => break, // nowhere else to search
879 MacroNS => unreachable!(),
881 WhereToResolve::BuiltinTypes => break, // nowhere else to search
887 // The first found solution was the only one, return it.
888 if let Some((binding, flags)) = innermost_result {
889 // We get to here only if there's no ambiguity, in ambiguous cases an error will
890 // be reported anyway, so there's no reason to report an additional feature error.
891 // The `binding` can actually be introduced by something other than `--extern`,
892 // but its `Def` should coincide with a crate passed with `--extern`
893 // (otherwise there would be ambiguity) and we can skip feature error in this case.
895 if !is_import || !rust_2015 {
898 if ns == TypeNS && use_prelude && self.extern_prelude_get(ident, true).is_some() {
901 let root_ident = Ident::new(keywords::PathRoot.name(), orig_ident.span);
902 let root_module = self.resolve_crate_root(root_ident);
903 if self.resolve_ident_in_module_ext(ModuleOrUniformRoot::Module(root_module),
904 orig_ident, ns, None, false, path_span)
909 let msg = "imports can only refer to extern crate names passed with \
910 `--extern` in macros originating from 2015 edition";
911 let mut err = self.session.struct_span_err(ident.span, msg);
912 let what = self.binding_description(binding, ident,
913 flags.contains(Flags::MISC_FROM_PRELUDE));
914 let note_msg = format!("this import refers to {what}", what = what);
915 let label_span = if binding.span.is_dummy() {
919 err.span_note(binding.span, ¬e_msg);
922 err.span_label(label_span, "not an extern crate passed with `--extern`");
929 let determinacy = Determinacy::determined(determinacy == Determinacy::Determined || force);
930 if determinacy == Determinacy::Determined && macro_kind == Some(MacroKind::Attr) {
931 // For single-segment attributes interpret determinate "no resolution" as a custom
932 // attribute. (Lexical resolution implies the first segment and attr kind should imply
933 // the last segment, so we are certainly working with a single-segment attribute here.)
934 assert!(ns == MacroNS);
935 let binding = (Def::NonMacroAttr(NonMacroAttrKind::Custom),
936 ty::Visibility::Public, ident.span, Mark::root())
937 .to_name_binding(self.arenas);
944 pub fn finalize_current_module_macro_resolutions(&mut self) {
945 let module = self.current_module;
947 let check_consistency = |this: &mut Self, path: &[Segment], span, kind: MacroKind,
948 initial_def: Option<Def>, def: Def| {
949 if let Some(initial_def) = initial_def {
950 if def != initial_def && def != Def::Err && this.ambiguity_errors.is_empty() {
951 // Make sure compilation does not succeed if preferred macro resolution
952 // has changed after the macro had been expanded. In theory all such
953 // situations should be reported as ambiguity errors, so this is a bug.
954 if initial_def == Def::NonMacroAttr(NonMacroAttrKind::Custom) {
955 // Yeah, legacy custom attributes are implemented using forced resolution
956 // (which is a best effort error recovery tool, basically), so we can't
957 // promise their resolution won't change later.
958 let msg = format!("inconsistent resolution for a macro: first {}, then {}",
959 initial_def.kind_name(), def.kind_name());
960 this.session.span_err(span, &msg);
962 span_bug!(span, "inconsistent resolution for a macro");
966 // It's possible that the macro was unresolved (indeterminate) and silently
967 // expanded into a dummy fragment for recovery during expansion.
968 // Now, post-expansion, the resolution may succeed, but we can't change the
969 // past and need to report an error.
970 // However, non-speculative `resolve_path` can successfully return private items
971 // even if speculative `resolve_path` returned nothing previously, so we skip this
972 // less informative error if the privacy error is reported elsewhere.
973 if this.privacy_errors.is_empty() {
974 let msg = format!("cannot determine resolution for the {} `{}`",
975 kind.descr(), Segment::names_to_string(path));
976 let msg_note = "import resolution is stuck, try simplifying macro imports";
977 this.session.struct_span_err(span, &msg).note(msg_note).emit();
982 let macro_resolutions =
983 mem::replace(&mut *module.multi_segment_macro_resolutions.borrow_mut(), Vec::new());
984 for (mut path, path_span, kind, parent_scope, initial_def) in macro_resolutions {
985 // FIXME: Path resolution will ICE if segment IDs present.
986 for seg in &mut path { seg.id = None; }
987 match self.resolve_path(&path, Some(MacroNS), &parent_scope,
988 true, path_span, CrateLint::No) {
989 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
990 let def = path_res.base_def();
991 check_consistency(self, &path, path_span, kind, initial_def, def);
993 path_res @ PathResult::NonModule(..) | path_res @ PathResult::Failed(..) => {
994 let (span, msg) = if let PathResult::Failed(span, msg, ..) = path_res {
997 (path_span, format!("partially resolved path in {} {}",
998 kind.article(), kind.descr()))
1000 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
1002 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
1006 let macro_resolutions =
1007 mem::replace(&mut *module.single_segment_macro_resolutions.borrow_mut(), Vec::new());
1008 for (ident, kind, parent_scope, initial_binding) in macro_resolutions {
1009 match self.early_resolve_ident_in_lexical_scope(ident, ScopeSet::Macro(kind),
1010 &parent_scope, true, true, ident.span) {
1012 let initial_def = initial_binding.map(|initial_binding| {
1013 self.record_use(ident, MacroNS, initial_binding, false);
1014 initial_binding.def()
1016 let def = binding.def();
1017 let seg = Segment::from_ident(ident);
1018 check_consistency(self, &[seg], ident.span, kind, initial_def, def);
1021 assert!(initial_binding.is_none());
1022 let bang = if kind == MacroKind::Bang { "!" } else { "" };
1024 format!("cannot find {} `{}{}` in this scope", kind.descr(), ident, bang);
1025 let mut err = self.session.struct_span_err(ident.span, &msg);
1026 self.suggest_macro_name(&ident.as_str(), kind, &mut err, ident.span);
1032 let builtin_attrs = mem::replace(&mut *module.builtin_attrs.borrow_mut(), Vec::new());
1033 for (ident, parent_scope) in builtin_attrs {
1034 let _ = self.early_resolve_ident_in_lexical_scope(
1035 ident, ScopeSet::Macro(MacroKind::Attr), &parent_scope, true, true, ident.span
1040 fn prohibit_imported_non_macro_attrs(&self, binding: Option<&'a NameBinding<'a>>,
1041 def: Option<Def>, span: Span) {
1042 if let Some(Def::NonMacroAttr(kind)) = def {
1043 if kind != NonMacroAttrKind::Tool && binding.map_or(true, |b| b.is_import()) {
1044 let msg = format!("cannot use a {} through an import", kind.descr());
1045 let mut err = self.session.struct_span_err(span, &msg);
1046 if let Some(binding) = binding {
1047 err.span_note(binding.span, &format!("the {} imported here", kind.descr()));
1054 fn suggest_macro_name(&mut self, name: &str, kind: MacroKind,
1055 err: &mut DiagnosticBuilder<'a>, span: Span) {
1056 // First check if this is a locally-defined bang macro.
1057 let suggestion = if let MacroKind::Bang = kind {
1058 find_best_match_for_name(self.macro_names.iter().map(|ident| &ident.name), name, None)
1061 // Then check global macros.
1063 let names = self.builtin_macros.iter().chain(self.macro_use_prelude.iter())
1064 .filter_map(|(name, binding)| {
1065 if binding.macro_kind() == Some(kind) { Some(name) } else { None }
1067 find_best_match_for_name(names, name, None)
1068 // Then check modules.
1070 let is_macro = |def| {
1071 if let Def::Macro(_, def_kind) = def {
1077 let ident = Ident::new(Symbol::intern(name), span);
1078 self.lookup_typo_candidate(&[Segment::from_ident(ident)], MacroNS, is_macro, span)
1079 .map(|suggestion| suggestion.candidate)
1082 if let Some(suggestion) = suggestion {
1083 if suggestion != name {
1084 if let MacroKind::Bang = kind {
1085 err.span_suggestion(
1087 "you could try the macro",
1088 suggestion.to_string(),
1089 Applicability::MaybeIncorrect
1092 err.span_suggestion(
1095 suggestion.to_string(),
1096 Applicability::MaybeIncorrect
1100 err.help("have you added the `#[macro_use]` on the module/import?");
1105 fn collect_def_ids(&mut self,
1107 invocation: &'a InvocationData<'a>,
1108 fragment: &AstFragment) {
1109 let Resolver { ref mut invocations, arenas, graph_root, .. } = *self;
1110 let InvocationData { def_index, .. } = *invocation;
1112 let visit_macro_invoc = &mut |invoc: map::MacroInvocationData| {
1113 invocations.entry(invoc.mark).or_insert_with(|| {
1114 arenas.alloc_invocation_data(InvocationData {
1115 def_index: invoc.def_index,
1116 module: Cell::new(graph_root),
1117 parent_legacy_scope: Cell::new(LegacyScope::Uninitialized),
1118 output_legacy_scope: Cell::new(None),
1123 let mut def_collector = DefCollector::new(&mut self.definitions, mark);
1124 def_collector.visit_macro_invoc = Some(visit_macro_invoc);
1125 def_collector.with_parent(def_index, |def_collector| {
1126 fragment.visit_with(def_collector)
1130 pub fn define_macro(&mut self,
1133 current_legacy_scope: &mut LegacyScope<'a>) {
1134 self.local_macro_def_scopes.insert(item.id, self.current_module);
1135 let ident = item.ident;
1136 if ident.name == "macro_rules" {
1137 self.session.span_err(item.span, "user-defined macros may not be named `macro_rules`");
1140 let def_id = self.definitions.local_def_id(item.id);
1141 let ext = Lrc::new(macro_rules::compile(&self.session.parse_sess,
1142 &self.session.features_untracked(),
1143 item, hygiene::default_edition()));
1144 self.macro_map.insert(def_id, ext);
1146 let def = match item.node { ast::ItemKind::MacroDef(ref def) => def, _ => unreachable!() };
1148 let ident = ident.modern();
1149 self.macro_names.insert(ident);
1150 let def = Def::Macro(def_id, MacroKind::Bang);
1151 let is_macro_export = attr::contains_name(&item.attrs, "macro_export");
1152 let vis = if is_macro_export {
1153 ty::Visibility::Public
1155 ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))
1157 let binding = (def, vis, item.span, expansion).to_name_binding(self.arenas);
1158 self.set_binding_parent_module(binding, self.current_module);
1159 let legacy_binding = self.arenas.alloc_legacy_binding(LegacyBinding {
1160 parent_legacy_scope: *current_legacy_scope, binding, ident
1162 *current_legacy_scope = LegacyScope::Binding(legacy_binding);
1163 self.all_macros.insert(ident.name, def);
1164 if is_macro_export {
1165 let module = self.graph_root;
1166 self.define(module, ident, MacroNS,
1167 (def, vis, item.span, expansion, IsMacroExport));
1169 if !attr::contains_name(&item.attrs, "rustc_doc_only_macro") {
1170 self.check_reserved_macro_name(ident, MacroNS);
1172 self.unused_macros.insert(def_id);
1175 let module = self.current_module;
1176 let def = Def::Macro(def_id, MacroKind::Bang);
1177 let vis = self.resolve_visibility(&item.vis);
1178 if vis != ty::Visibility::Public {
1179 self.unused_macros.insert(def_id);
1181 self.define(module, ident, MacroNS, (def, vis, item.span, expansion));