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::{self, 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 errors::Applicability;
34 use rustc_data_structures::sync::Lrc;
36 type Def = def::Def<ast::NodeId>;
38 #[derive(Clone, Debug)]
39 pub struct InvocationData<'a> {
41 /// The module in which the macro was invoked.
42 crate module: Cell<Module<'a>>,
43 /// The legacy scope in which the macro was invoked.
44 /// The invocation path is resolved in this scope.
45 crate parent_legacy_scope: Cell<LegacyScope<'a>>,
46 /// The legacy scope *produced* by expanding this macro invocation,
47 /// includes all the macro_rules items, other invocations, etc generated by it.
48 /// `None` if the macro is not expanded yet.
49 crate output_legacy_scope: Cell<Option<LegacyScope<'a>>>,
52 impl<'a> InvocationData<'a> {
53 pub fn root(graph_root: Module<'a>) -> Self {
55 module: Cell::new(graph_root),
56 def_index: CRATE_DEF_INDEX,
57 parent_legacy_scope: Cell::new(LegacyScope::Empty),
58 output_legacy_scope: Cell::new(Some(LegacyScope::Empty)),
63 /// Binding produced by a `macro_rules` item.
64 /// Not modularized, can shadow previous legacy bindings, etc.
66 pub struct LegacyBinding<'a> {
67 binding: &'a NameBinding<'a>,
68 /// Legacy scope into which the `macro_rules` item was planted.
69 parent_legacy_scope: LegacyScope<'a>,
73 /// The scope introduced by a `macro_rules!` macro.
74 /// This starts at the macro's definition and ends at the end of the macro's parent
75 /// module (named or unnamed), or even further if it escapes with `#[macro_use]`.
76 /// Some macro invocations need to introduce legacy scopes too because they
77 /// can potentially expand into macro definitions.
78 #[derive(Copy, Clone, Debug)]
79 pub enum LegacyScope<'a> {
80 /// Created when invocation data is allocated in the arena;
81 /// must be replaced with a proper scope later.
83 /// Empty "root" scope at the crate start containing no names.
85 /// The scope introduced by a `macro_rules!` macro definition.
86 Binding(&'a LegacyBinding<'a>),
87 /// The scope introduced by a macro invocation that can potentially
88 /// create a `macro_rules!` macro definition.
89 Invocation(&'a InvocationData<'a>),
92 /// Everything you need to resolve a macro or import path.
93 #[derive(Clone, Debug)]
94 pub struct ParentScope<'a> {
95 crate module: Module<'a>,
96 crate expansion: Mark,
97 crate legacy: LegacyScope<'a>,
98 crate derives: Vec<ast::Path>,
101 // Macro namespace is separated into two sub-namespaces, one for bang macros and
102 // one for attribute-like macros (attributes, derives).
103 // We ignore resolutions from one sub-namespace when searching names in scope for another.
104 fn sub_namespace_match(candidate: Option<MacroKind>, requirement: Option<MacroKind>) -> bool {
106 enum SubNS { Bang, AttrLike }
107 let sub_ns = |kind| match kind {
108 MacroKind::Bang => Some(SubNS::Bang),
109 MacroKind::Attr | MacroKind::Derive => Some(SubNS::AttrLike),
110 MacroKind::ProcMacroStub => None,
112 let requirement = requirement.and_then(|kind| sub_ns(kind));
113 let candidate = candidate.and_then(|kind| sub_ns(kind));
114 // "No specific sub-namespace" means "matches anything" for both requirements and candidates.
115 candidate.is_none() || requirement.is_none() || candidate == requirement
118 impl<'a> base::Resolver for Resolver<'a> {
119 fn next_node_id(&mut self) -> ast::NodeId {
120 self.session.next_node_id()
123 fn get_module_scope(&mut self, id: ast::NodeId) -> Mark {
124 let mark = Mark::fresh(Mark::root());
125 let module = self.module_map[&self.definitions.local_def_id(id)];
126 self.invocations.insert(mark, self.arenas.alloc_invocation_data(InvocationData {
127 module: Cell::new(module),
128 def_index: module.def_id().unwrap().index,
129 parent_legacy_scope: Cell::new(LegacyScope::Empty),
130 output_legacy_scope: Cell::new(Some(LegacyScope::Empty)),
135 fn resolve_dollar_crates(&mut self, fragment: &AstFragment) {
136 struct ResolveDollarCrates<'a, 'b: 'a> {
137 resolver: &'a mut Resolver<'b>
139 impl<'a> Visitor<'a> for ResolveDollarCrates<'a, '_> {
140 fn visit_ident(&mut self, ident: Ident) {
141 if ident.name == keywords::DollarCrate.name() {
142 let name = match self.resolver.resolve_crate_root(ident).kind {
143 ModuleKind::Def(_, name) if name != keywords::Invalid.name() => name,
144 _ => keywords::Crate.name(),
146 ident.span.ctxt().set_dollar_crate_name(name);
149 fn visit_mac(&mut self, _: &ast::Mac) {}
152 fragment.visit_with(&mut ResolveDollarCrates { resolver: self });
155 fn visit_ast_fragment_with_placeholders(&mut self, mark: Mark, fragment: &AstFragment,
157 let invocation = self.invocations[&mark];
158 self.collect_def_ids(mark, invocation, fragment);
160 self.current_module = invocation.module.get();
161 self.current_module.unresolved_invocations.borrow_mut().remove(&mark);
162 self.current_module.unresolved_invocations.borrow_mut().extend(derives);
163 self.invocations.extend(derives.iter().map(|&derive| (derive, invocation)));
164 let mut visitor = BuildReducedGraphVisitor {
166 current_legacy_scope: invocation.parent_legacy_scope.get(),
169 fragment.visit_with(&mut visitor);
170 invocation.output_legacy_scope.set(Some(visitor.current_legacy_scope));
173 fn add_builtin(&mut self, ident: ast::Ident, ext: Lrc<SyntaxExtension>) {
175 krate: CrateNum::BuiltinMacros,
176 index: DefIndex::from_array_index(self.macro_map.len(),
177 DefIndexAddressSpace::Low),
179 let kind = ext.kind();
180 self.macro_map.insert(def_id, ext);
181 let binding = self.arenas.alloc_name_binding(NameBinding {
182 kind: NameBindingKind::Def(Def::Macro(def_id, kind), false),
185 vis: ty::Visibility::Public,
186 expansion: Mark::root(),
188 if self.builtin_macros.insert(ident.name, binding).is_some() {
189 self.session.span_err(ident.span,
190 &format!("built-in macro `{}` was already defined", ident));
194 fn resolve_imports(&mut self) {
195 ImportResolver { resolver: self }.resolve_imports()
198 fn resolve_macro_invocation(&mut self, invoc: &Invocation, invoc_id: Mark, force: bool)
199 -> Result<Option<Lrc<SyntaxExtension>>, Determinacy> {
200 let (path, kind, derives_in_scope, after_derive) = match invoc.kind {
201 InvocationKind::Attr { attr: None, .. } =>
203 InvocationKind::Attr { attr: Some(ref attr), ref traits, after_derive, .. } =>
204 (&attr.path, MacroKind::Attr, traits.clone(), after_derive),
205 InvocationKind::Bang { ref mac, .. } =>
206 (&mac.node.path, MacroKind::Bang, Vec::new(), false),
207 InvocationKind::Derive { ref path, .. } =>
208 (path, MacroKind::Derive, Vec::new(), false),
211 let parent_scope = self.invoc_parent_scope(invoc_id, derives_in_scope);
212 let (def, ext) = match self.resolve_macro_to_def(path, kind, &parent_scope, true, force) {
213 Ok((def, ext)) => (def, ext),
214 Err(Determinacy::Determined) if kind == MacroKind::Attr => {
215 // Replace unresolved attributes with used inert attributes for better recovery.
216 return Ok(Some(Lrc::new(SyntaxExtension::NonMacroAttr { mark_used: true })));
218 Err(determinacy) => return Err(determinacy),
221 if let Def::Macro(def_id, _) = def {
223 self.session.span_err(invoc.span(),
224 "macro attributes must be placed before `#[derive]`");
226 self.macro_defs.insert(invoc.expansion_data.mark, def_id);
227 let normal_module_def_id =
228 self.macro_def_scope(invoc.expansion_data.mark).normal_ancestor_id;
229 self.definitions.add_parent_module_of_macro_def(invoc.expansion_data.mark,
230 normal_module_def_id);
231 invoc.expansion_data.mark.set_default_transparency(ext.default_transparency());
237 fn resolve_macro_path(&mut self, path: &ast::Path, kind: MacroKind, invoc_id: Mark,
238 derives_in_scope: Vec<ast::Path>, force: bool)
239 -> Result<Lrc<SyntaxExtension>, Determinacy> {
240 let parent_scope = self.invoc_parent_scope(invoc_id, derives_in_scope);
241 Ok(self.resolve_macro_to_def(path, kind, &parent_scope, false, force)?.1)
244 fn check_unused_macros(&self) {
245 for did in self.unused_macros.iter() {
246 let id_span = match *self.macro_map[did] {
247 SyntaxExtension::NormalTT { def_info, .. } |
248 SyntaxExtension::DeclMacro { def_info, .. } => def_info,
251 if let Some((id, span)) = id_span {
252 let lint = lint::builtin::UNUSED_MACROS;
253 let msg = "unused macro definition";
254 self.session.buffer_lint(lint, id, span, msg);
256 bug!("attempted to create unused macro error, but span not available");
262 impl<'a> Resolver<'a> {
263 pub fn dummy_parent_scope(&self) -> ParentScope<'a> {
264 self.invoc_parent_scope(Mark::root(), Vec::new())
267 fn invoc_parent_scope(&self, invoc_id: Mark, derives: Vec<ast::Path>) -> ParentScope<'a> {
268 let invoc = self.invocations[&invoc_id];
270 module: invoc.module.get().nearest_item_scope(),
271 expansion: invoc_id.parent(),
272 legacy: invoc.parent_legacy_scope.get(),
277 fn resolve_macro_to_def(
281 parent_scope: &ParentScope<'a>,
284 ) -> Result<(Def, Lrc<SyntaxExtension>), Determinacy> {
285 let def = self.resolve_macro_to_def_inner(path, kind, parent_scope, trace, force);
287 // Report errors and enforce feature gates for the resolved macro.
288 if def != Err(Determinacy::Undetermined) {
289 // Do not report duplicated errors on every undetermined resolution.
290 for segment in &path.segments {
291 if let Some(args) = &segment.args {
292 self.session.span_err(args.span(), "generic arguments in macro path");
300 Def::Macro(def_id, macro_kind) => {
301 self.unused_macros.remove(&def_id);
302 if macro_kind == MacroKind::ProcMacroStub {
303 let msg = "can't use a procedural macro from the same crate that defines it";
304 self.session.span_err(path.span, msg);
305 return Err(Determinacy::Determined);
308 Def::NonMacroAttr(attr_kind) => {
309 if kind == MacroKind::Attr {
310 let features = self.session.features_untracked();
311 if attr_kind == NonMacroAttrKind::Custom {
312 assert!(path.segments.len() == 1);
313 let name = path.segments[0].ident.as_str();
314 if name.starts_with("rustc_") {
315 if !features.rustc_attrs {
316 let msg = "unless otherwise specified, attributes with the prefix \
317 `rustc_` are reserved for internal compiler diagnostics";
318 self.report_unknown_attribute(path.span, &name, msg, "rustc_attrs");
320 } else if !features.custom_attribute {
321 let msg = format!("The attribute `{}` is currently unknown to the \
322 compiler and may have meaning added to it in the \
324 self.report_unknown_attribute(
333 // Not only attributes, but anything in macro namespace can result in
334 // `Def::NonMacroAttr` definition (e.g., `inline!()`), so we must report
335 // an error for those cases.
336 let msg = format!("expected a macro, found {}", def.kind_name());
337 self.session.span_err(path.span, &msg);
338 return Err(Determinacy::Determined);
342 return Err(Determinacy::Determined);
344 _ => panic!("expected `Def::Macro` or `Def::NonMacroAttr`"),
347 Ok((def, self.get_macro(def)))
350 fn report_unknown_attribute(&self, span: Span, name: &str, msg: &str, feature: &str) {
351 let mut err = feature_err(
352 &self.session.parse_sess,
359 let features = self.session.features_untracked();
361 let attr_candidates = BUILTIN_ATTRIBUTES
363 .filter_map(|&(name, _, _, ref gate)| {
364 if name.as_str().starts_with("rustc_") && !features.rustc_attrs {
369 AttributeGate::Gated(Stability::Unstable, ..)
370 if self.session.opts.unstable_features.is_nightly_build() =>
374 AttributeGate::Gated(Stability::Deprecated(..), ..) => Some(name),
375 AttributeGate::Ungated => Some(name),
380 // Add built-in macro attributes as well.
381 self.builtin_macros.iter().filter_map(|(name, binding)| {
382 match binding.macro_kind() {
383 Some(MacroKind::Attr) => Some(*name),
388 .collect::<Vec<_>>();
390 let lev_suggestion = find_best_match_for_name(attr_candidates.iter(), &name, None);
392 if let Some(suggestion) = lev_suggestion {
395 "a built-in attribute with a similar name exists",
396 suggestion.to_string(),
397 Applicability::MaybeIncorrect,
404 pub fn resolve_macro_to_def_inner(
408 parent_scope: &ParentScope<'a>,
411 ) -> Result<Def, Determinacy> {
412 let path_span = path.span;
413 let mut path = Segment::from_path(path);
415 // Possibly apply the macro helper hack
416 if kind == MacroKind::Bang && path.len() == 1 &&
417 path[0].ident.span.ctxt().outer().expn_info()
418 .map_or(false, |info| info.local_inner_macros) {
419 let root = Ident::new(keywords::DollarCrate.name(), path[0].ident.span);
420 path.insert(0, Segment::from_ident(root));
424 let def = match self.resolve_path(&path, Some(MacroNS), parent_scope,
425 false, path_span, CrateLint::No) {
426 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
427 Ok(path_res.base_def())
429 PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
430 PathResult::NonModule(..)
431 | PathResult::Indeterminate
432 | PathResult::Failed { .. } => Err(Determinacy::Determined),
433 PathResult::Module(..) => unreachable!(),
437 parent_scope.module.multi_segment_macro_resolutions.borrow_mut()
438 .push((path, path_span, kind, parent_scope.clone(), def.ok()));
441 self.prohibit_imported_non_macro_attrs(None, def.ok(), path_span);
444 let binding = self.early_resolve_ident_in_lexical_scope(
445 path[0].ident, ScopeSet::Macro(kind), parent_scope, false, force, path_span
447 if let Err(Determinacy::Undetermined) = binding {
448 return Err(Determinacy::Undetermined);
452 parent_scope.module.single_segment_macro_resolutions.borrow_mut()
453 .push((path[0].ident, kind, parent_scope.clone(), binding.ok()));
456 let def = binding.map(|binding| binding.def());
457 self.prohibit_imported_non_macro_attrs(binding.ok(), def.ok(), path_span);
462 // Resolve an identifier in lexical scope.
463 // This is a variation of `fn resolve_ident_in_lexical_scope` that can be run during
464 // expansion and import resolution (perhaps they can be merged in the future).
465 // The function is used for resolving initial segments of macro paths (e.g., `foo` in
466 // `foo::bar!(); or `foo!();`) and also for import paths on 2018 edition.
467 crate fn early_resolve_ident_in_lexical_scope(
471 parent_scope: &ParentScope<'a>,
475 ) -> Result<&'a NameBinding<'a>, Determinacy> {
476 // General principles:
477 // 1. Not controlled (user-defined) names should have higher priority than controlled names
478 // built into the language or standard library. This way we can add new names into the
479 // language or standard library without breaking user code.
480 // 2. "Closed set" below means new names cannot appear after the current resolution attempt.
481 // Places to search (in order of decreasing priority):
483 // 1. FIXME: Ribs (type parameters), there's no necessary infrastructure yet
484 // (open set, not controlled).
485 // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
486 // (open, not controlled).
487 // 3. Extern prelude (closed, not controlled).
488 // 4. Tool modules (closed, controlled right now, but not in the future).
489 // 5. Standard library prelude (de-facto closed, controlled).
490 // 6. Language prelude (closed, controlled).
492 // 1. FIXME: Ribs (local variables), there's no necessary infrastructure yet
493 // (open set, not controlled).
494 // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
495 // (open, not controlled).
496 // 3. Standard library prelude (de-facto closed, controlled).
498 // 1-3. Derive helpers (open, not controlled). All ambiguities with other names
499 // are currently reported as errors. They should be higher in priority than preludes
500 // and probably even names in modules according to the "general principles" above. They
501 // also should be subject to restricted shadowing because are effectively produced by
502 // derives (you need to resolve the derive first to add helpers into scope), but they
503 // should be available before the derive is expanded for compatibility.
504 // It's mess in general, so we are being conservative for now.
505 // 1-3. `macro_rules` (open, not controlled), loop through legacy scopes. Have higher
506 // priority than prelude macros, but create ambiguities with macros in modules.
507 // 1-3. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
508 // (open, not controlled). Have higher priority than prelude macros, but create
509 // ambiguities with `macro_rules`.
510 // 4. `macro_use` prelude (open, the open part is from macro expansions, not controlled).
511 // 4a. User-defined prelude from macro-use
512 // (open, the open part is from macro expansions, not controlled).
513 // 4b. Standard library prelude is currently implemented as `macro-use` (closed, controlled)
514 // 5. Language prelude: builtin macros (closed, controlled, except for legacy plugins).
515 // 6. Language prelude: builtin attributes (closed, controlled).
516 // 4-6. Legacy plugin helpers (open, not controlled). Similar to derive helpers,
517 // but introduced by legacy plugins using `register_attribute`. Priority is somewhere
518 // in prelude, not sure where exactly (creates ambiguities with any other prelude names).
520 enum WhereToResolve<'a> {
522 MacroRules(LegacyScope<'a>),
535 bitflags::bitflags! {
537 const MACRO_RULES = 1 << 0;
538 const MODULE = 1 << 1;
539 const PRELUDE = 1 << 2;
540 const MISC_SUGGEST_CRATE = 1 << 3;
541 const MISC_SUGGEST_SELF = 1 << 4;
542 const MISC_FROM_PRELUDE = 1 << 5;
546 assert!(force || !record_used); // `record_used` implies `force`
547 let mut ident = orig_ident.modern();
549 // Make sure `self`, `super` etc produce an error when passed to here.
550 if ident.is_path_segment_keyword() {
551 return Err(Determinacy::Determined);
554 // This is *the* result, resolution from the scope closest to the resolved identifier.
555 // However, sometimes this result is "weak" because it comes from a glob import or
556 // a macro expansion, and in this case it cannot shadow names from outer scopes, e.g.
557 // mod m { ... } // solution in outer scope
559 // use prefix::*; // imports another `m` - innermost solution
560 // // weak, cannot shadow the outer `m`, need to report ambiguity error
563 // So we have to save the innermost solution and continue searching in outer scopes
564 // to detect potential ambiguities.
565 let mut innermost_result: Option<(&NameBinding<'_>, Flags)> = None;
567 // Go through all the scopes and try to resolve the name.
568 let rust_2015 = orig_ident.span.rust_2015();
569 let (ns, macro_kind, is_import, is_absolute_path) = match scope_set {
570 ScopeSet::Import(ns) => (ns, None, true, false),
571 ScopeSet::AbsolutePath(ns) => (ns, None, false, true),
572 ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind), false, false),
573 ScopeSet::Module => (TypeNS, None, false, false),
575 let mut where_to_resolve = match ns {
576 _ if is_absolute_path => WhereToResolve::CrateRoot,
577 TypeNS | ValueNS => WhereToResolve::Module(parent_scope.module),
578 MacroNS => WhereToResolve::DeriveHelpers,
580 let mut use_prelude = !parent_scope.module.no_implicit_prelude;
581 let mut determinacy = Determinacy::Determined;
583 let result = match where_to_resolve {
584 WhereToResolve::DeriveHelpers => {
585 let mut result = Err(Determinacy::Determined);
586 for derive in &parent_scope.derives {
587 let parent_scope = ParentScope { derives: Vec::new(), ..*parent_scope };
588 match self.resolve_macro_to_def(derive, MacroKind::Derive,
589 &parent_scope, true, force) {
591 if let SyntaxExtension::ProcMacroDerive(_, helpers, _) = &*ext {
592 if helpers.contains(&ident.name) {
594 (Def::NonMacroAttr(NonMacroAttrKind::DeriveHelper),
595 ty::Visibility::Public, derive.span, Mark::root())
596 .to_name_binding(self.arenas);
597 result = Ok((binding, Flags::empty()));
602 Err(Determinacy::Determined) => {}
603 Err(Determinacy::Undetermined) =>
604 result = Err(Determinacy::Undetermined),
609 WhereToResolve::MacroRules(legacy_scope) => match legacy_scope {
610 LegacyScope::Binding(legacy_binding) if ident == legacy_binding.ident =>
611 Ok((legacy_binding.binding, Flags::MACRO_RULES)),
612 LegacyScope::Invocation(invoc) if invoc.output_legacy_scope.get().is_none() =>
613 Err(Determinacy::Undetermined),
614 _ => Err(Determinacy::Determined),
616 WhereToResolve::CrateRoot => {
617 let root_ident = Ident::new(keywords::PathRoot.name(), orig_ident.span);
618 let root_module = self.resolve_crate_root(root_ident);
619 let binding = self.resolve_ident_in_module_ext(
620 ModuleOrUniformRoot::Module(root_module),
628 Ok(binding) => Ok((binding, Flags::MODULE | Flags::MISC_SUGGEST_CRATE)),
629 Err((Determinacy::Undetermined, Weak::No)) =>
630 return Err(Determinacy::determined(force)),
631 Err((Determinacy::Undetermined, Weak::Yes)) =>
632 Err(Determinacy::Undetermined),
633 Err((Determinacy::Determined, _)) => Err(Determinacy::Determined),
636 WhereToResolve::Module(module) => {
637 let orig_current_module = mem::replace(&mut self.current_module, module);
638 let binding = self.resolve_ident_in_module_unadjusted_ext(
639 ModuleOrUniformRoot::Module(module),
647 self.current_module = orig_current_module;
650 let misc_flags = if ptr::eq(module, self.graph_root) {
651 Flags::MISC_SUGGEST_CRATE
652 } else if module.is_normal() {
653 Flags::MISC_SUGGEST_SELF
657 Ok((binding, Flags::MODULE | misc_flags))
659 Err((Determinacy::Undetermined, Weak::No)) =>
660 return Err(Determinacy::determined(force)),
661 Err((Determinacy::Undetermined, Weak::Yes)) =>
662 Err(Determinacy::Undetermined),
663 Err((Determinacy::Determined, _)) => Err(Determinacy::Determined),
666 WhereToResolve::MacroUsePrelude => {
667 if use_prelude || rust_2015 {
668 match self.macro_use_prelude.get(&ident.name).cloned() {
670 Ok((binding, Flags::PRELUDE | Flags::MISC_FROM_PRELUDE)),
671 None => Err(Determinacy::determined(
672 self.graph_root.unresolved_invocations.borrow().is_empty()
676 Err(Determinacy::Determined)
679 WhereToResolve::BuiltinMacros => {
680 match self.builtin_macros.get(&ident.name).cloned() {
681 Some(binding) => Ok((binding, Flags::PRELUDE)),
682 None => Err(Determinacy::Determined),
685 WhereToResolve::BuiltinAttrs => {
686 if is_builtin_attr_name(ident.name) {
687 let binding = (Def::NonMacroAttr(NonMacroAttrKind::Builtin),
688 ty::Visibility::Public, DUMMY_SP, Mark::root())
689 .to_name_binding(self.arenas);
690 Ok((binding, Flags::PRELUDE))
692 Err(Determinacy::Determined)
695 WhereToResolve::LegacyPluginHelpers => {
696 if (use_prelude || rust_2015) &&
697 self.session.plugin_attributes.borrow().iter()
698 .any(|(name, _)| ident.name == &**name) {
699 let binding = (Def::NonMacroAttr(NonMacroAttrKind::LegacyPluginHelper),
700 ty::Visibility::Public, DUMMY_SP, Mark::root())
701 .to_name_binding(self.arenas);
702 Ok((binding, Flags::PRELUDE))
704 Err(Determinacy::Determined)
707 WhereToResolve::ExternPrelude => {
708 if use_prelude || is_absolute_path {
709 match self.extern_prelude_get(ident, !record_used) {
710 Some(binding) => Ok((binding, Flags::PRELUDE)),
711 None => Err(Determinacy::determined(
712 self.graph_root.unresolved_invocations.borrow().is_empty()
716 Err(Determinacy::Determined)
719 WhereToResolve::ToolPrelude => {
720 if use_prelude && is_known_tool(ident.name) {
721 let binding = (Def::ToolMod, ty::Visibility::Public,
722 DUMMY_SP, Mark::root()).to_name_binding(self.arenas);
723 Ok((binding, Flags::PRELUDE))
725 Err(Determinacy::Determined)
728 WhereToResolve::StdLibPrelude => {
729 let mut result = Err(Determinacy::Determined);
731 if let Some(prelude) = self.prelude {
732 if let Ok(binding) = self.resolve_ident_in_module_unadjusted(
733 ModuleOrUniformRoot::Module(prelude),
739 result = Ok((binding, Flags::PRELUDE | Flags::MISC_FROM_PRELUDE));
745 WhereToResolve::BuiltinTypes => {
746 match self.primitive_type_table.primitive_types.get(&ident.name).cloned() {
748 let binding = (Def::PrimTy(prim_ty), ty::Visibility::Public,
749 DUMMY_SP, Mark::root()).to_name_binding(self.arenas);
750 Ok((binding, Flags::PRELUDE))
752 None => Err(Determinacy::Determined)
758 Ok((binding, flags)) if sub_namespace_match(binding.macro_kind(), macro_kind) => {
763 if let Some((innermost_binding, innermost_flags)) = innermost_result {
764 // Found another solution, if the first one was "weak", report an error.
765 let (def, innermost_def) = (binding.def(), innermost_binding.def());
766 if def != innermost_def {
767 let builtin = Def::NonMacroAttr(NonMacroAttrKind::Builtin);
768 let derive_helper = Def::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
770 Def::NonMacroAttr(NonMacroAttrKind::LegacyPluginHelper);
772 let ambiguity_error_kind = if is_import {
773 Some(AmbiguityKind::Import)
774 } else if innermost_def == builtin || def == builtin {
775 Some(AmbiguityKind::BuiltinAttr)
776 } else if innermost_def == derive_helper || def == derive_helper {
777 Some(AmbiguityKind::DeriveHelper)
778 } else if innermost_def == legacy_helper &&
779 flags.contains(Flags::PRELUDE) ||
780 def == legacy_helper &&
781 innermost_flags.contains(Flags::PRELUDE) {
782 Some(AmbiguityKind::LegacyHelperVsPrelude)
783 } else if innermost_flags.contains(Flags::MACRO_RULES) &&
784 flags.contains(Flags::MODULE) &&
785 !self.disambiguate_legacy_vs_modern(innermost_binding,
787 flags.contains(Flags::MACRO_RULES) &&
788 innermost_flags.contains(Flags::MODULE) &&
789 !self.disambiguate_legacy_vs_modern(binding,
791 Some(AmbiguityKind::LegacyVsModern)
792 } else if innermost_binding.is_glob_import() {
793 Some(AmbiguityKind::GlobVsOuter)
794 } else if innermost_binding.may_appear_after(parent_scope.expansion,
796 Some(AmbiguityKind::MoreExpandedVsOuter)
800 if let Some(kind) = ambiguity_error_kind {
801 let misc = |f: Flags| if f.contains(Flags::MISC_SUGGEST_CRATE) {
802 AmbiguityErrorMisc::SuggestCrate
803 } else if f.contains(Flags::MISC_SUGGEST_SELF) {
804 AmbiguityErrorMisc::SuggestSelf
805 } else if f.contains(Flags::MISC_FROM_PRELUDE) {
806 AmbiguityErrorMisc::FromPrelude
808 AmbiguityErrorMisc::None
810 self.ambiguity_errors.push(AmbiguityError {
813 b1: innermost_binding,
815 misc1: misc(innermost_flags),
818 return Ok(innermost_binding);
822 // Found the first solution.
823 innermost_result = Some((binding, flags));
826 Ok(..) | Err(Determinacy::Determined) => {}
827 Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined
830 where_to_resolve = match where_to_resolve {
831 WhereToResolve::DeriveHelpers =>
832 WhereToResolve::MacroRules(parent_scope.legacy),
833 WhereToResolve::MacroRules(legacy_scope) => match legacy_scope {
834 LegacyScope::Binding(binding) => WhereToResolve::MacroRules(
835 binding.parent_legacy_scope
837 LegacyScope::Invocation(invoc) => WhereToResolve::MacroRules(
838 invoc.output_legacy_scope.get().unwrap_or(invoc.parent_legacy_scope.get())
840 LegacyScope::Empty => WhereToResolve::Module(parent_scope.module),
841 LegacyScope::Uninitialized => unreachable!(),
843 WhereToResolve::CrateRoot => match ns {
845 ident.span.adjust(Mark::root());
846 WhereToResolve::ExternPrelude
848 ValueNS | MacroNS => break,
850 WhereToResolve::Module(module) => {
851 match self.hygienic_lexical_parent(module, &mut ident.span) {
852 Some(parent_module) => WhereToResolve::Module(parent_module),
854 use_prelude = !module.no_implicit_prelude;
856 TypeNS => WhereToResolve::ExternPrelude,
857 ValueNS => WhereToResolve::StdLibPrelude,
858 MacroNS => WhereToResolve::MacroUsePrelude,
863 WhereToResolve::MacroUsePrelude => WhereToResolve::BuiltinMacros,
864 WhereToResolve::BuiltinMacros => WhereToResolve::BuiltinAttrs,
865 WhereToResolve::BuiltinAttrs => WhereToResolve::LegacyPluginHelpers,
866 WhereToResolve::LegacyPluginHelpers => break, // nowhere else to search
867 WhereToResolve::ExternPrelude if is_absolute_path => break,
868 WhereToResolve::ExternPrelude => WhereToResolve::ToolPrelude,
869 WhereToResolve::ToolPrelude => WhereToResolve::StdLibPrelude,
870 WhereToResolve::StdLibPrelude => match ns {
871 TypeNS => WhereToResolve::BuiltinTypes,
872 ValueNS => break, // nowhere else to search
873 MacroNS => unreachable!(),
875 WhereToResolve::BuiltinTypes => break, // nowhere else to search
881 // The first found solution was the only one, return it.
882 if let Some((binding, _)) = innermost_result {
886 let determinacy = Determinacy::determined(determinacy == Determinacy::Determined || force);
887 if determinacy == Determinacy::Determined && macro_kind == Some(MacroKind::Attr) {
888 // For single-segment attributes interpret determinate "no resolution" as a custom
889 // attribute. (Lexical resolution implies the first segment and attr kind should imply
890 // the last segment, so we are certainly working with a single-segment attribute here.)
891 assert!(ns == MacroNS);
892 let binding = (Def::NonMacroAttr(NonMacroAttrKind::Custom),
893 ty::Visibility::Public, ident.span, Mark::root())
894 .to_name_binding(self.arenas);
901 pub fn finalize_current_module_macro_resolutions(&mut self) {
902 let module = self.current_module;
904 let check_consistency = |this: &mut Self, path: &[Segment], span, kind: MacroKind,
905 initial_def: Option<Def>, def: Def| {
906 if let Some(initial_def) = initial_def {
907 if def != initial_def && def != Def::Err && this.ambiguity_errors.is_empty() {
908 // Make sure compilation does not succeed if preferred macro resolution
909 // has changed after the macro had been expanded. In theory all such
910 // situations should be reported as ambiguity errors, so this is a bug.
911 if initial_def == Def::NonMacroAttr(NonMacroAttrKind::Custom) {
912 // Yeah, legacy custom attributes are implemented using forced resolution
913 // (which is a best effort error recovery tool, basically), so we can't
914 // promise their resolution won't change later.
915 let msg = format!("inconsistent resolution for a macro: first {}, then {}",
916 initial_def.kind_name(), def.kind_name());
917 this.session.span_err(span, &msg);
919 span_bug!(span, "inconsistent resolution for a macro");
923 // It's possible that the macro was unresolved (indeterminate) and silently
924 // expanded into a dummy fragment for recovery during expansion.
925 // Now, post-expansion, the resolution may succeed, but we can't change the
926 // past and need to report an error.
927 // However, non-speculative `resolve_path` can successfully return private items
928 // even if speculative `resolve_path` returned nothing previously, so we skip this
929 // less informative error if the privacy error is reported elsewhere.
930 if this.privacy_errors.is_empty() {
931 let msg = format!("cannot determine resolution for the {} `{}`",
932 kind.descr(), Segment::names_to_string(path));
933 let msg_note = "import resolution is stuck, try simplifying macro imports";
934 this.session.struct_span_err(span, &msg).note(msg_note).emit();
939 let macro_resolutions =
940 mem::replace(&mut *module.multi_segment_macro_resolutions.borrow_mut(), Vec::new());
941 for (mut path, path_span, kind, parent_scope, initial_def) in macro_resolutions {
942 // FIXME: Path resolution will ICE if segment IDs present.
943 for seg in &mut path { seg.id = None; }
944 match self.resolve_path(&path, Some(MacroNS), &parent_scope,
945 true, path_span, CrateLint::No) {
946 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
947 let def = path_res.base_def();
948 check_consistency(self, &path, path_span, kind, initial_def, def);
950 path_res @ PathResult::NonModule(..) | path_res @ PathResult::Failed { .. } => {
951 let (span, label) = if let PathResult::Failed { span, label, .. } = path_res {
954 (path_span, format!("partially resolved path in {} {}",
955 kind.article(), kind.descr()))
957 resolve_error(self, span, ResolutionError::FailedToResolve {
962 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
966 let macro_resolutions =
967 mem::replace(&mut *module.single_segment_macro_resolutions.borrow_mut(), Vec::new());
968 for (ident, kind, parent_scope, initial_binding) in macro_resolutions {
969 match self.early_resolve_ident_in_lexical_scope(ident, ScopeSet::Macro(kind),
970 &parent_scope, true, true, ident.span) {
972 let initial_def = initial_binding.map(|initial_binding| {
973 self.record_use(ident, MacroNS, initial_binding, false);
974 initial_binding.def()
976 let def = binding.def();
977 let seg = Segment::from_ident(ident);
978 check_consistency(self, &[seg], ident.span, kind, initial_def, def);
981 assert!(initial_binding.is_none());
982 let bang = if kind == MacroKind::Bang { "!" } else { "" };
984 format!("cannot find {} `{}{}` in this scope", kind.descr(), ident, bang);
985 let mut err = self.session.struct_span_err(ident.span, &msg);
986 self.suggest_macro_name(&ident.as_str(), kind, &mut err, ident.span);
992 let builtin_attrs = mem::replace(&mut *module.builtin_attrs.borrow_mut(), Vec::new());
993 for (ident, parent_scope) in builtin_attrs {
994 let _ = self.early_resolve_ident_in_lexical_scope(
995 ident, ScopeSet::Macro(MacroKind::Attr), &parent_scope, true, true, ident.span
1000 fn prohibit_imported_non_macro_attrs(&self, binding: Option<&'a NameBinding<'a>>,
1001 def: Option<Def>, span: Span) {
1002 if let Some(Def::NonMacroAttr(kind)) = def {
1003 if kind != NonMacroAttrKind::Tool && binding.map_or(true, |b| b.is_import()) {
1004 let msg = format!("cannot use a {} through an import", kind.descr());
1005 let mut err = self.session.struct_span_err(span, &msg);
1006 if let Some(binding) = binding {
1007 err.span_note(binding.span, &format!("the {} imported here", kind.descr()));
1014 fn suggest_macro_name(&mut self, name: &str, kind: MacroKind,
1015 err: &mut DiagnosticBuilder<'a>, span: Span) {
1016 // First check if this is a locally-defined bang macro.
1017 let suggestion = if let MacroKind::Bang = kind {
1018 find_best_match_for_name(self.macro_names.iter().map(|ident| &ident.name), name, 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, None)
1028 // Then check modules.
1030 let is_macro = |def| {
1031 if let Def::Macro(_, def_kind) = def {
1037 let ident = Ident::new(Symbol::intern(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 == "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 def = Def::Macro(def_id, MacroKind::Bang);
1111 let is_macro_export = attr::contains_name(&item.attrs, "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 = (def, 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, def);
1124 if is_macro_export {
1125 let module = self.graph_root;
1126 self.define(module, ident, MacroNS,
1127 (def, vis, item.span, expansion, IsMacroExport));
1129 if !attr::contains_name(&item.attrs, "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 def = Def::Macro(def_id, MacroKind::Bang);
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, (def, vis, item.span, expansion));