1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use {AmbiguityError, AmbiguityKind, AmbiguityErrorMisc};
12 use {CrateLint, Resolver, ResolutionError, ScopeSet, Weak};
13 use {Module, NameBinding, NameBindingKind, PathResult, Segment, ToNameBinding};
14 use {is_known_tool, resolve_error};
15 use ModuleOrUniformRoot;
17 use build_reduced_graph::{BuildReducedGraphVisitor, IsMacroExport};
18 use resolve_imports::ImportResolver;
19 use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX, DefIndex,
20 CrateNum, DefIndexAddressSpace};
21 use rustc::hir::def::{Def, NonMacroAttrKind};
22 use rustc::hir::map::{self, DefCollector};
23 use rustc::{ty, lint};
24 use syntax::ast::{self, Ident};
26 use syntax::errors::DiagnosticBuilder;
27 use syntax::ext::base::{self, Determinacy};
28 use syntax::ext::base::{MacroKind, SyntaxExtension};
29 use syntax::ext::expand::{AstFragment, Invocation, InvocationKind};
30 use syntax::ext::hygiene::{self, Mark};
31 use syntax::ext::tt::macro_rules;
32 use syntax::feature_gate::{feature_err, is_builtin_attr_name, GateIssue};
33 use syntax::symbol::{Symbol, keywords};
34 use syntax::util::lev_distance::find_best_match_for_name;
35 use syntax_pos::{Span, DUMMY_SP};
36 use errors::Applicability;
40 use rustc_data_structures::sync::Lrc;
42 #[derive(Clone, Debug)]
43 pub struct InvocationData<'a> {
45 /// Module in which the macro was invoked.
46 crate module: Cell<Module<'a>>,
47 /// Legacy scope in which the macro was invoked.
48 /// The invocation path is resolved in this scope.
49 crate parent_legacy_scope: Cell<LegacyScope<'a>>,
50 /// Legacy scope *produced* by expanding this macro invocation,
51 /// includes all the macro_rules items, other invocations, etc generated by it.
52 /// `None` if the macro is not expanded yet.
53 crate output_legacy_scope: Cell<Option<LegacyScope<'a>>>,
56 impl<'a> InvocationData<'a> {
57 pub fn root(graph_root: Module<'a>) -> Self {
59 module: Cell::new(graph_root),
60 def_index: CRATE_DEF_INDEX,
61 parent_legacy_scope: Cell::new(LegacyScope::Empty),
62 output_legacy_scope: Cell::new(Some(LegacyScope::Empty)),
67 /// Binding produced by a `macro_rules` item.
68 /// Not modularized, can shadow previous legacy bindings, etc.
70 pub struct LegacyBinding<'a> {
71 binding: &'a NameBinding<'a>,
72 /// Legacy scope into which the `macro_rules` item was planted.
73 parent_legacy_scope: LegacyScope<'a>,
77 /// Scope introduced by a `macro_rules!` macro.
78 /// Starts at the macro's definition and ends at the end of the macro's parent module
79 /// (named or unnamed), or even further if it escapes with `#[macro_use]`.
80 /// Some macro invocations need to introduce legacy scopes too because they
81 /// potentially can expand into macro definitions.
82 #[derive(Copy, Clone, Debug)]
83 pub enum LegacyScope<'a> {
84 /// Created when invocation data is allocated in the arena,
85 /// must be replaced with a proper scope later.
87 /// Empty "root" scope at the crate start containing no names.
89 /// Scope introduced by a `macro_rules!` macro definition.
90 Binding(&'a LegacyBinding<'a>),
91 /// Scope introduced by a macro invocation that can potentially
92 /// create a `macro_rules!` macro definition.
93 Invocation(&'a InvocationData<'a>),
96 /// Everything you need to resolve a macro or import path.
97 #[derive(Clone, Debug)]
98 pub struct ParentScope<'a> {
99 crate module: Module<'a>,
100 crate expansion: Mark,
101 crate legacy: LegacyScope<'a>,
102 crate derives: Vec<ast::Path>,
105 // Macro namespace is separated into two sub-namespaces, one for bang macros and
106 // one for attribute-like macros (attributes, derives).
107 // We ignore resolutions from one sub-namespace when searching names in scope for another.
108 fn sub_namespace_match(candidate: Option<MacroKind>, requirement: Option<MacroKind>) -> bool {
110 enum SubNS { Bang, AttrLike }
111 let sub_ns = |kind| match kind {
112 MacroKind::Bang => Some(SubNS::Bang),
113 MacroKind::Attr | MacroKind::Derive => Some(SubNS::AttrLike),
114 MacroKind::ProcMacroStub => None,
116 let requirement = requirement.and_then(|kind| sub_ns(kind));
117 let candidate = candidate.and_then(|kind| sub_ns(kind));
118 // "No specific sub-namespace" means "matches anything" for both requirements and candidates.
119 candidate.is_none() || requirement.is_none() || candidate == requirement
122 impl<'a> base::Resolver for Resolver<'a> {
123 fn next_node_id(&mut self) -> ast::NodeId {
124 self.session.next_node_id()
127 fn get_module_scope(&mut self, id: ast::NodeId) -> Mark {
128 let mark = Mark::fresh(Mark::root());
129 let module = self.module_map[&self.definitions.local_def_id(id)];
130 self.invocations.insert(mark, self.arenas.alloc_invocation_data(InvocationData {
131 module: Cell::new(module),
132 def_index: module.def_id().unwrap().index,
133 parent_legacy_scope: Cell::new(LegacyScope::Empty),
134 output_legacy_scope: Cell::new(Some(LegacyScope::Empty)),
139 fn visit_ast_fragment_with_placeholders(&mut self, mark: Mark, fragment: &AstFragment,
141 let invocation = self.invocations[&mark];
142 self.collect_def_ids(mark, invocation, fragment);
144 self.current_module = invocation.module.get();
145 self.current_module.unresolved_invocations.borrow_mut().remove(&mark);
146 self.current_module.unresolved_invocations.borrow_mut().extend(derives);
147 self.invocations.extend(derives.iter().map(|&derive| (derive, invocation)));
148 let mut visitor = BuildReducedGraphVisitor {
150 current_legacy_scope: invocation.parent_legacy_scope.get(),
153 fragment.visit_with(&mut visitor);
154 invocation.output_legacy_scope.set(Some(visitor.current_legacy_scope));
157 fn add_builtin(&mut self, ident: ast::Ident, ext: Lrc<SyntaxExtension>) {
159 krate: CrateNum::BuiltinMacros,
160 index: DefIndex::from_array_index(self.macro_map.len(),
161 DefIndexAddressSpace::Low),
163 let kind = ext.kind();
164 self.macro_map.insert(def_id, ext);
165 let binding = self.arenas.alloc_name_binding(NameBinding {
166 kind: NameBindingKind::Def(Def::Macro(def_id, kind), false),
168 vis: ty::Visibility::Public,
169 expansion: Mark::root(),
171 if self.builtin_macros.insert(ident.name, binding).is_some() {
172 self.session.span_err(ident.span,
173 &format!("built-in macro `{}` was already defined", ident));
177 fn resolve_imports(&mut self) {
178 ImportResolver { resolver: self }.resolve_imports()
181 fn resolve_macro_invocation(&mut self, invoc: &Invocation, invoc_id: Mark, force: bool)
182 -> Result<Option<Lrc<SyntaxExtension>>, Determinacy> {
183 let (path, kind, derives_in_scope, after_derive) = match invoc.kind {
184 InvocationKind::Attr { attr: None, .. } =>
186 InvocationKind::Attr { attr: Some(ref attr), ref traits, after_derive, .. } =>
187 (&attr.path, MacroKind::Attr, traits.clone(), after_derive),
188 InvocationKind::Bang { ref mac, .. } =>
189 (&mac.node.path, MacroKind::Bang, Vec::new(), false),
190 InvocationKind::Derive { ref path, .. } =>
191 (path, MacroKind::Derive, Vec::new(), false),
194 let parent_scope = self.invoc_parent_scope(invoc_id, derives_in_scope);
195 let (def, ext) = self.resolve_macro_to_def(path, kind, &parent_scope, true, force)?;
197 if let Def::Macro(def_id, _) = def {
199 self.session.span_err(invoc.span(),
200 "macro attributes must be placed before `#[derive]`");
202 self.macro_defs.insert(invoc.expansion_data.mark, def_id);
203 let normal_module_def_id =
204 self.macro_def_scope(invoc.expansion_data.mark).normal_ancestor_id;
205 self.definitions.add_parent_module_of_macro_def(invoc.expansion_data.mark,
206 normal_module_def_id);
207 invoc.expansion_data.mark.set_default_transparency(ext.default_transparency());
213 fn resolve_macro_path(&mut self, path: &ast::Path, kind: MacroKind, invoc_id: Mark,
214 derives_in_scope: Vec<ast::Path>, force: bool)
215 -> Result<Lrc<SyntaxExtension>, Determinacy> {
216 let parent_scope = self.invoc_parent_scope(invoc_id, derives_in_scope);
217 Ok(self.resolve_macro_to_def(path, kind, &parent_scope, false, force)?.1)
220 fn check_unused_macros(&self) {
221 for did in self.unused_macros.iter() {
222 let id_span = match *self.macro_map[did] {
223 SyntaxExtension::NormalTT { def_info, .. } |
224 SyntaxExtension::DeclMacro { def_info, .. } => def_info,
227 if let Some((id, span)) = id_span {
228 let lint = lint::builtin::UNUSED_MACROS;
229 let msg = "unused macro definition";
230 self.session.buffer_lint(lint, id, span, msg);
232 bug!("attempted to create unused macro error, but span not available");
238 impl<'a> Resolver<'a> {
239 pub fn dummy_parent_scope(&self) -> ParentScope<'a> {
240 self.invoc_parent_scope(Mark::root(), Vec::new())
243 fn invoc_parent_scope(&self, invoc_id: Mark, derives: Vec<ast::Path>) -> ParentScope<'a> {
244 let invoc = self.invocations[&invoc_id];
246 module: invoc.module.get().nearest_item_scope(),
247 expansion: invoc_id.parent(),
248 legacy: invoc.parent_legacy_scope.get(),
253 fn resolve_macro_to_def(
257 parent_scope: &ParentScope<'a>,
260 ) -> Result<(Def, Lrc<SyntaxExtension>), Determinacy> {
261 let def = self.resolve_macro_to_def_inner(path, kind, parent_scope, trace, force);
263 // Report errors and enforce feature gates for the resolved macro.
264 if def != Err(Determinacy::Undetermined) {
265 // Do not report duplicated errors on every undetermined resolution.
266 for segment in &path.segments {
267 if let Some(args) = &segment.args {
268 self.session.span_err(args.span(), "generic arguments in macro path");
276 Def::Macro(def_id, macro_kind) => {
277 self.unused_macros.remove(&def_id);
278 if macro_kind == MacroKind::ProcMacroStub {
279 let msg = "can't use a procedural macro from the same crate that defines it";
280 self.session.span_err(path.span, msg);
281 return Err(Determinacy::Determined);
284 Def::NonMacroAttr(attr_kind) => {
285 if kind == MacroKind::Attr {
286 let features = self.session.features_untracked();
287 if attr_kind == NonMacroAttrKind::Custom {
288 assert!(path.segments.len() == 1);
289 let name = path.segments[0].ident.name.as_str();
290 if name.starts_with("rustc_") {
291 if !features.rustc_attrs {
292 let msg = "unless otherwise specified, attributes with the prefix \
293 `rustc_` are reserved for internal compiler diagnostics";
294 feature_err(&self.session.parse_sess, "rustc_attrs", path.span,
295 GateIssue::Language, &msg).emit();
297 } else if !features.custom_attribute {
298 let msg = format!("The attribute `{}` is currently unknown to the \
299 compiler and may have meaning added to it in the \
301 feature_err(&self.session.parse_sess, "custom_attribute", path.span,
302 GateIssue::Language, &msg).emit();
306 // Not only attributes, but anything in macro namespace can result in
307 // `Def::NonMacroAttr` definition (e.g., `inline!()`), so we must report
308 // an error for those cases.
309 let msg = format!("expected a macro, found {}", def.kind_name());
310 self.session.span_err(path.span, &msg);
311 return Err(Determinacy::Determined);
315 return Err(Determinacy::Determined);
317 _ => panic!("expected `Def::Macro` or `Def::NonMacroAttr`"),
320 Ok((def, self.get_macro(def)))
323 pub fn resolve_macro_to_def_inner(
327 parent_scope: &ParentScope<'a>,
330 ) -> Result<Def, Determinacy> {
331 let path_span = path.span;
332 let mut path = Segment::from_path(path);
334 // Possibly apply the macro helper hack
335 if kind == MacroKind::Bang && path.len() == 1 &&
336 path[0].ident.span.ctxt().outer().expn_info()
337 .map_or(false, |info| info.local_inner_macros) {
338 let root = Ident::new(keywords::DollarCrate.name(), path[0].ident.span);
339 path.insert(0, Segment::from_ident(root));
343 let def = match self.resolve_path(&path, Some(MacroNS), parent_scope,
344 false, path_span, CrateLint::No) {
345 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
346 Ok(path_res.base_def())
348 PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
349 PathResult::NonModule(..) | PathResult::Indeterminate | PathResult::Failed(..) => {
350 self.found_unresolved_macro = true;
351 Err(Determinacy::Determined)
353 PathResult::Module(..) => unreachable!(),
357 parent_scope.module.multi_segment_macro_resolutions.borrow_mut()
358 .push((path, path_span, kind, parent_scope.clone(), def.ok()));
363 let binding = self.early_resolve_ident_in_lexical_scope(
364 path[0].ident, ScopeSet::Macro(kind), parent_scope, false, force, path_span
368 Err(Determinacy::Determined) => self.found_unresolved_macro = true,
369 Err(Determinacy::Undetermined) => return Err(Determinacy::Undetermined),
373 parent_scope.module.single_segment_macro_resolutions.borrow_mut()
374 .push((path[0].ident, kind, parent_scope.clone(), binding.ok()));
377 binding.map(|binding| binding.def_ignoring_ambiguity())
381 // Resolve an identifier in lexical scope.
382 // This is a variation of `fn resolve_ident_in_lexical_scope` that can be run during
383 // expansion and import resolution (perhaps they can be merged in the future).
384 // The function is used for resolving initial segments of macro paths (e.g., `foo` in
385 // `foo::bar!(); or `foo!();`) and also for import paths on 2018 edition.
386 crate fn early_resolve_ident_in_lexical_scope(
390 parent_scope: &ParentScope<'a>,
394 ) -> Result<&'a NameBinding<'a>, Determinacy> {
395 // General principles:
396 // 1. Not controlled (user-defined) names should have higher priority than controlled names
397 // built into the language or standard library. This way we can add new names into the
398 // language or standard library without breaking user code.
399 // 2. "Closed set" below means new names cannot appear after the current resolution attempt.
400 // Places to search (in order of decreasing priority):
402 // 1. FIXME: Ribs (type parameters), there's no necessary infrastructure yet
403 // (open set, not controlled).
404 // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
405 // (open, not controlled).
406 // 3. Extern prelude (closed, not controlled).
407 // 4. Tool modules (closed, controlled right now, but not in the future).
408 // 5. Standard library prelude (de-facto closed, controlled).
409 // 6. Language prelude (closed, controlled).
411 // 1. FIXME: Ribs (local variables), there's no necessary infrastructure yet
412 // (open set, not controlled).
413 // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
414 // (open, not controlled).
415 // 3. Standard library prelude (de-facto closed, controlled).
417 // 1-3. Derive helpers (open, not controlled). All ambiguities with other names
418 // are currently reported as errors. They should be higher in priority than preludes
419 // and probably even names in modules according to the "general principles" above. They
420 // also should be subject to restricted shadowing because are effectively produced by
421 // derives (you need to resolve the derive first to add helpers into scope), but they
422 // should be available before the derive is expanded for compatibility.
423 // It's mess in general, so we are being conservative for now.
424 // 1-3. `macro_rules` (open, not controlled), loop through legacy scopes. Have higher
425 // priority than prelude macros, but create ambiguities with macros in modules.
426 // 1-3. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
427 // (open, not controlled). Have higher priority than prelude macros, but create
428 // ambiguities with `macro_rules`.
429 // 4. `macro_use` prelude (open, the open part is from macro expansions, not controlled).
430 // 4a. User-defined prelude from macro-use
431 // (open, the open part is from macro expansions, not controlled).
432 // 4b. Standard library prelude is currently implemented as `macro-use` (closed, controlled)
433 // 5. Language prelude: builtin macros (closed, controlled, except for legacy plugins).
434 // 6. Language prelude: builtin attributes (closed, controlled).
435 // 4-6. Legacy plugin helpers (open, not controlled). Similar to derive helpers,
436 // but introduced by legacy plugins using `register_attribute`. Priority is somewhere
437 // in prelude, not sure where exactly (creates ambiguities with any other prelude names).
439 enum WhereToResolve<'a> {
441 MacroRules(LegacyScope<'a>),
456 const MACRO_RULES = 1 << 0;
457 const MODULE = 1 << 1;
458 const PRELUDE = 1 << 2;
459 const MISC_SUGGEST_CRATE = 1 << 3;
460 const MISC_SUGGEST_SELF = 1 << 4;
461 const MISC_FROM_PRELUDE = 1 << 5;
465 assert!(force || !record_used); // `record_used` implies `force`
466 let mut ident = orig_ident.modern();
468 // Make sure `self`, `super` etc produce an error when passed to here.
469 if ident.is_path_segment_keyword() {
470 return Err(Determinacy::Determined);
473 // This is *the* result, resolution from the scope closest to the resolved identifier.
474 // However, sometimes this result is "weak" because it comes from a glob import or
475 // a macro expansion, and in this case it cannot shadow names from outer scopes, e.g.
476 // mod m { ... } // solution in outer scope
478 // use prefix::*; // imports another `m` - innermost solution
479 // // weak, cannot shadow the outer `m`, need to report ambiguity error
482 // So we have to save the innermost solution and continue searching in outer scopes
483 // to detect potential ambiguities.
484 let mut innermost_result: Option<(&NameBinding, Flags)> = None;
486 // Go through all the scopes and try to resolve the name.
487 let rust_2015 = orig_ident.span.rust_2015();
488 let (ns, macro_kind, is_import, is_absolute_path) = match scope_set {
489 ScopeSet::Import(ns) => (ns, None, true, false),
490 ScopeSet::AbsolutePath(ns) => (ns, None, false, true),
491 ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind), false, false),
492 ScopeSet::Module => (TypeNS, None, false, false),
494 let mut where_to_resolve = match ns {
495 _ if is_absolute_path || is_import && rust_2015 => WhereToResolve::CrateRoot,
496 TypeNS | ValueNS => WhereToResolve::Module(parent_scope.module),
497 MacroNS => WhereToResolve::DeriveHelpers,
499 let mut use_prelude = !parent_scope.module.no_implicit_prelude;
500 let mut determinacy = Determinacy::Determined;
502 let result = match where_to_resolve {
503 WhereToResolve::DeriveHelpers => {
504 let mut result = Err(Determinacy::Determined);
505 for derive in &parent_scope.derives {
506 let parent_scope = ParentScope { derives: Vec::new(), ..*parent_scope };
507 match self.resolve_macro_to_def(derive, MacroKind::Derive,
508 &parent_scope, true, force) {
510 if let SyntaxExtension::ProcMacroDerive(_, helpers, _) = &*ext {
511 if helpers.contains(&ident.name) {
513 (Def::NonMacroAttr(NonMacroAttrKind::DeriveHelper),
514 ty::Visibility::Public, derive.span, Mark::root())
515 .to_name_binding(self.arenas);
516 result = Ok((binding, Flags::empty()));
521 Err(Determinacy::Determined) => {}
522 Err(Determinacy::Undetermined) =>
523 result = Err(Determinacy::Undetermined),
528 WhereToResolve::MacroRules(legacy_scope) => match legacy_scope {
529 LegacyScope::Binding(legacy_binding) if ident == legacy_binding.ident =>
530 Ok((legacy_binding.binding, Flags::MACRO_RULES)),
531 LegacyScope::Invocation(invoc) if invoc.output_legacy_scope.get().is_none() =>
532 Err(Determinacy::Undetermined),
533 _ => Err(Determinacy::Determined),
535 WhereToResolve::CrateRoot => {
536 let root_ident = Ident::new(keywords::PathRoot.name(), orig_ident.span);
537 let root_module = self.resolve_crate_root(root_ident);
538 let binding = self.resolve_ident_in_module_ext(
539 ModuleOrUniformRoot::Module(root_module),
547 Ok(binding) => Ok((binding, Flags::MODULE | Flags::MISC_SUGGEST_CRATE)),
548 Err((Determinacy::Undetermined, Weak::No)) =>
549 return Err(Determinacy::determined(force)),
550 Err((Determinacy::Undetermined, Weak::Yes)) =>
551 Err(Determinacy::Undetermined),
552 Err((Determinacy::Determined, _)) => Err(Determinacy::Determined),
555 WhereToResolve::Module(module) => {
556 let orig_current_module = mem::replace(&mut self.current_module, module);
557 let binding = self.resolve_ident_in_module_unadjusted_ext(
558 ModuleOrUniformRoot::Module(module),
566 self.current_module = orig_current_module;
569 let misc_flags = if ptr::eq(module, self.graph_root) {
570 Flags::MISC_SUGGEST_CRATE
571 } else if module.is_normal() {
572 Flags::MISC_SUGGEST_SELF
576 Ok((binding, Flags::MODULE | misc_flags))
578 Err((Determinacy::Undetermined, Weak::No)) =>
579 return Err(Determinacy::determined(force)),
580 Err((Determinacy::Undetermined, Weak::Yes)) =>
581 Err(Determinacy::Undetermined),
582 Err((Determinacy::Determined, _)) => Err(Determinacy::Determined),
585 WhereToResolve::MacroUsePrelude => {
586 if use_prelude || rust_2015 {
587 match self.macro_use_prelude.get(&ident.name).cloned() {
589 Ok((binding, Flags::PRELUDE | Flags::MISC_FROM_PRELUDE)),
590 None => Err(Determinacy::determined(
591 self.graph_root.unresolved_invocations.borrow().is_empty()
595 Err(Determinacy::Determined)
598 WhereToResolve::BuiltinMacros => {
599 match self.builtin_macros.get(&ident.name).cloned() {
600 Some(binding) => Ok((binding, Flags::PRELUDE)),
601 None => Err(Determinacy::Determined),
604 WhereToResolve::BuiltinAttrs => {
605 if is_builtin_attr_name(ident.name) {
606 let binding = (Def::NonMacroAttr(NonMacroAttrKind::Builtin),
607 ty::Visibility::Public, DUMMY_SP, Mark::root())
608 .to_name_binding(self.arenas);
609 Ok((binding, Flags::PRELUDE))
611 Err(Determinacy::Determined)
614 WhereToResolve::LegacyPluginHelpers => {
615 if (use_prelude || rust_2015) &&
616 self.session.plugin_attributes.borrow().iter()
617 .any(|(name, _)| ident.name == &**name) {
618 let binding = (Def::NonMacroAttr(NonMacroAttrKind::LegacyPluginHelper),
619 ty::Visibility::Public, DUMMY_SP, Mark::root())
620 .to_name_binding(self.arenas);
621 Ok((binding, Flags::PRELUDE))
623 Err(Determinacy::Determined)
626 WhereToResolve::ExternPrelude => {
627 if use_prelude || is_absolute_path {
628 match self.extern_prelude_get(ident, !record_used) {
629 Some(binding) => Ok((binding, Flags::PRELUDE)),
630 None => Err(Determinacy::determined(
631 self.graph_root.unresolved_invocations.borrow().is_empty()
635 Err(Determinacy::Determined)
638 WhereToResolve::ToolPrelude => {
639 if use_prelude && is_known_tool(ident.name) {
640 let binding = (Def::ToolMod, ty::Visibility::Public,
641 DUMMY_SP, Mark::root()).to_name_binding(self.arenas);
642 Ok((binding, Flags::PRELUDE))
644 Err(Determinacy::Determined)
647 WhereToResolve::StdLibPrelude => {
648 let mut result = Err(Determinacy::Determined);
650 if let Some(prelude) = self.prelude {
651 if let Ok(binding) = self.resolve_ident_in_module_unadjusted(
652 ModuleOrUniformRoot::Module(prelude),
658 result = Ok((binding, Flags::PRELUDE | Flags::MISC_FROM_PRELUDE));
664 WhereToResolve::BuiltinTypes => {
665 match self.primitive_type_table.primitive_types.get(&ident.name).cloned() {
667 let binding = (Def::PrimTy(prim_ty), ty::Visibility::Public,
668 DUMMY_SP, Mark::root()).to_name_binding(self.arenas);
669 Ok((binding, Flags::PRELUDE))
671 None => Err(Determinacy::Determined)
677 Ok((binding, flags)) if sub_namespace_match(binding.macro_kind(), macro_kind) => {
682 if let Some((innermost_binding, innermost_flags)) = innermost_result {
683 // Found another solution, if the first one was "weak", report an error.
684 let (def, innermost_def) = (binding.def(), innermost_binding.def());
685 if def != innermost_def {
686 let builtin = Def::NonMacroAttr(NonMacroAttrKind::Builtin);
687 let derive_helper = Def::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
689 Def::NonMacroAttr(NonMacroAttrKind::LegacyPluginHelper);
691 let ambiguity_error_kind = if is_import {
692 Some(AmbiguityKind::Import)
693 } else if is_absolute_path {
694 Some(AmbiguityKind::AbsolutePath)
695 } else if innermost_def == builtin || def == builtin {
696 Some(AmbiguityKind::BuiltinAttr)
697 } else if innermost_def == derive_helper || def == derive_helper {
698 Some(AmbiguityKind::DeriveHelper)
699 } else if innermost_def == legacy_helper &&
700 flags.contains(Flags::PRELUDE) ||
701 def == legacy_helper &&
702 innermost_flags.contains(Flags::PRELUDE) {
703 Some(AmbiguityKind::LegacyHelperVsPrelude)
704 } else if innermost_flags.contains(Flags::MACRO_RULES) &&
705 flags.contains(Flags::MODULE) &&
706 !self.disambiguate_legacy_vs_modern(innermost_binding,
708 flags.contains(Flags::MACRO_RULES) &&
709 innermost_flags.contains(Flags::MODULE) &&
710 !self.disambiguate_legacy_vs_modern(binding,
712 Some(AmbiguityKind::LegacyVsModern)
713 } else if innermost_binding.is_glob_import() {
714 Some(AmbiguityKind::GlobVsOuter)
715 } else if innermost_binding.may_appear_after(parent_scope.expansion,
717 Some(AmbiguityKind::MoreExpandedVsOuter)
721 if let Some(kind) = ambiguity_error_kind {
722 let misc = |f: Flags| if f.contains(Flags::MISC_SUGGEST_CRATE) {
723 AmbiguityErrorMisc::SuggestCrate
724 } else if f.contains(Flags::MISC_SUGGEST_SELF) {
725 AmbiguityErrorMisc::SuggestSelf
726 } else if f.contains(Flags::MISC_FROM_PRELUDE) {
727 AmbiguityErrorMisc::FromPrelude
729 AmbiguityErrorMisc::None
731 self.ambiguity_errors.push(AmbiguityError {
734 b1: innermost_binding,
736 misc1: misc(innermost_flags),
739 return Ok(innermost_binding);
743 // Found the first solution.
744 innermost_result = Some((binding, flags));
747 Ok(..) | Err(Determinacy::Determined) => {}
748 Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined
751 where_to_resolve = match where_to_resolve {
752 WhereToResolve::DeriveHelpers =>
753 WhereToResolve::MacroRules(parent_scope.legacy),
754 WhereToResolve::MacroRules(legacy_scope) => match legacy_scope {
755 LegacyScope::Binding(binding) => WhereToResolve::MacroRules(
756 binding.parent_legacy_scope
758 LegacyScope::Invocation(invoc) => WhereToResolve::MacroRules(
759 invoc.output_legacy_scope.get().unwrap_or(invoc.parent_legacy_scope.get())
761 LegacyScope::Empty => WhereToResolve::Module(parent_scope.module),
762 LegacyScope::Uninitialized => unreachable!(),
764 WhereToResolve::CrateRoot if is_import => match ns {
765 TypeNS | ValueNS => WhereToResolve::Module(parent_scope.module),
766 MacroNS => WhereToResolve::DeriveHelpers,
768 WhereToResolve::CrateRoot if is_absolute_path => match ns {
770 ident.span.adjust(Mark::root());
771 WhereToResolve::ExternPrelude
773 ValueNS | MacroNS => break,
775 WhereToResolve::CrateRoot => unreachable!(),
776 WhereToResolve::Module(module) => {
777 match self.hygienic_lexical_parent(module, &mut ident.span) {
778 Some(parent_module) => WhereToResolve::Module(parent_module),
780 use_prelude = !module.no_implicit_prelude;
782 TypeNS => WhereToResolve::ExternPrelude,
783 ValueNS => WhereToResolve::StdLibPrelude,
784 MacroNS => WhereToResolve::MacroUsePrelude,
789 WhereToResolve::MacroUsePrelude => WhereToResolve::BuiltinMacros,
790 WhereToResolve::BuiltinMacros => WhereToResolve::BuiltinAttrs,
791 WhereToResolve::BuiltinAttrs => WhereToResolve::LegacyPluginHelpers,
792 WhereToResolve::LegacyPluginHelpers => break, // nowhere else to search
793 WhereToResolve::ExternPrelude if is_absolute_path => break,
794 WhereToResolve::ExternPrelude => WhereToResolve::ToolPrelude,
795 WhereToResolve::ToolPrelude => WhereToResolve::StdLibPrelude,
796 WhereToResolve::StdLibPrelude => match ns {
797 TypeNS => WhereToResolve::BuiltinTypes,
798 ValueNS => break, // nowhere else to search
799 MacroNS => unreachable!(),
801 WhereToResolve::BuiltinTypes => break, // nowhere else to search
807 // The first found solution was the only one, return it.
808 if let Some((binding, flags)) = innermost_result {
809 // We get to here only if there's no ambiguity, in ambiguous cases an error will
810 // be reported anyway, so there's no reason to report an additional feature error.
811 // The `binding` can actually be introduced by something other than `--extern`,
812 // but its `Def` should coincide with a crate passed with `--extern`
813 // (otherwise there would be ambiguity) and we can skip feature error in this case.
815 if !is_import || self.session.features_untracked().uniform_paths {
818 if ns == TypeNS && use_prelude && self.extern_prelude_get(ident, true).is_some() {
822 let root_ident = Ident::new(keywords::PathRoot.name(), orig_ident.span);
823 let root_module = self.resolve_crate_root(root_ident);
824 if self.resolve_ident_in_module_ext(ModuleOrUniformRoot::Module(root_module),
825 orig_ident, ns, None, false, path_span)
831 let msg = "imports can only refer to extern crate names \
832 passed with `--extern` on stable channel";
833 let mut err = feature_err(&self.session.parse_sess, "uniform_paths",
834 ident.span, GateIssue::Language, msg);
836 let what = self.binding_description(binding, ident,
837 flags.contains(Flags::MISC_FROM_PRELUDE));
838 let note_msg = format!("this import refers to {what}", what = what);
839 let label_span = if binding.span.is_dummy() {
843 err.span_note(binding.span, ¬e_msg);
846 err.span_label(label_span, "not an extern crate passed with `--extern`");
853 let determinacy = Determinacy::determined(determinacy == Determinacy::Determined || force);
854 if determinacy == Determinacy::Determined && macro_kind == Some(MacroKind::Attr) {
855 // For single-segment attributes interpret determinate "no resolution" as a custom
856 // attribute. (Lexical resolution implies the first segment and attr kind should imply
857 // the last segment, so we are certainly working with a single-segment attribute here.)
858 assert!(ns == MacroNS);
859 let binding = (Def::NonMacroAttr(NonMacroAttrKind::Custom),
860 ty::Visibility::Public, ident.span, Mark::root())
861 .to_name_binding(self.arenas);
868 pub fn finalize_current_module_macro_resolutions(&mut self) {
869 let module = self.current_module;
871 let check_consistency = |this: &mut Self, path: &[Segment], span,
872 kind: MacroKind, initial_def, def| {
873 if let Some(initial_def) = initial_def {
874 if def != initial_def && def != Def::Err && this.ambiguity_errors.is_empty() {
875 // Make sure compilation does not succeed if preferred macro resolution
876 // has changed after the macro had been expanded. In theory all such
877 // situations should be reported as ambiguity errors, so this is a bug.
878 span_bug!(span, "inconsistent resolution for a macro");
881 // It's possible that the macro was unresolved (indeterminate) and silently
882 // expanded into a dummy fragment for recovery during expansion.
883 // Now, post-expansion, the resolution may succeed, but we can't change the
884 // past and need to report an error.
885 // However, non-speculative `resolve_path` can successfully return private items
886 // even if speculative `resolve_path` returned nothing previously, so we skip this
887 // less informative error if the privacy error is reported elsewhere.
888 if this.privacy_errors.is_empty() {
889 let msg = format!("cannot determine resolution for the {} `{}`",
890 kind.descr(), Segment::names_to_string(path));
891 let msg_note = "import resolution is stuck, try simplifying macro imports";
892 this.session.struct_span_err(span, &msg).note(msg_note).emit();
897 let macro_resolutions =
898 mem::replace(&mut *module.multi_segment_macro_resolutions.borrow_mut(), Vec::new());
899 for (mut path, path_span, kind, parent_scope, initial_def) in macro_resolutions {
900 // FIXME: Path resolution will ICE if segment IDs present.
901 for seg in &mut path { seg.id = None; }
902 match self.resolve_path(&path, Some(MacroNS), &parent_scope,
903 true, path_span, CrateLint::No) {
904 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
905 let def = path_res.base_def();
906 check_consistency(self, &path, path_span, kind, initial_def, def);
908 path_res @ PathResult::NonModule(..) | path_res @ PathResult::Failed(..) => {
909 let (span, msg) = if let PathResult::Failed(span, msg, ..) = path_res {
912 (path_span, format!("partially resolved path in {} {}",
913 kind.article(), kind.descr()))
915 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
917 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
921 let macro_resolutions =
922 mem::replace(&mut *module.single_segment_macro_resolutions.borrow_mut(), Vec::new());
923 for (ident, kind, parent_scope, initial_binding) in macro_resolutions {
924 match self.early_resolve_ident_in_lexical_scope(ident, ScopeSet::Macro(kind),
925 &parent_scope, true, true, ident.span) {
927 let initial_def = initial_binding.map(|initial_binding| {
928 self.record_use(ident, MacroNS, initial_binding, false);
929 initial_binding.def_ignoring_ambiguity()
931 let def = binding.def_ignoring_ambiguity();
932 let seg = Segment::from_ident(ident);
933 check_consistency(self, &[seg], ident.span, kind, initial_def, def);
936 assert!(initial_binding.is_none());
937 let bang = if kind == MacroKind::Bang { "!" } else { "" };
939 format!("cannot find {} `{}{}` in this scope", kind.descr(), ident, bang);
940 let mut err = self.session.struct_span_err(ident.span, &msg);
941 self.suggest_macro_name(&ident.as_str(), kind, &mut err, ident.span);
947 let builtin_attrs = mem::replace(&mut *module.builtin_attrs.borrow_mut(), Vec::new());
948 for (ident, parent_scope) in builtin_attrs {
949 let _ = self.early_resolve_ident_in_lexical_scope(
950 ident, ScopeSet::Macro(MacroKind::Attr), &parent_scope, true, true, ident.span
955 fn suggest_macro_name(&mut self, name: &str, kind: MacroKind,
956 err: &mut DiagnosticBuilder<'a>, span: Span) {
957 // First check if this is a locally-defined bang macro.
958 let suggestion = if let MacroKind::Bang = kind {
959 find_best_match_for_name(self.macro_names.iter().map(|ident| &ident.name), name, None)
962 // Then check global macros.
964 let names = self.builtin_macros.iter().chain(self.macro_use_prelude.iter())
965 .filter_map(|(name, binding)| {
966 if binding.macro_kind() == Some(kind) { Some(name) } else { None }
968 find_best_match_for_name(names, name, None)
969 // Then check modules.
971 let is_macro = |def| {
972 if let Def::Macro(_, def_kind) = def {
978 let ident = Ident::new(Symbol::intern(name), span);
979 self.lookup_typo_candidate(&[Segment::from_ident(ident)], MacroNS, is_macro, span)
982 if let Some(suggestion) = suggestion {
983 if suggestion != name {
984 if let MacroKind::Bang = kind {
985 err.span_suggestion_with_applicability(
987 "you could try the macro",
988 suggestion.to_string(),
989 Applicability::MaybeIncorrect
992 err.span_suggestion_with_applicability(
995 suggestion.to_string(),
996 Applicability::MaybeIncorrect
1000 err.help("have you added the `#[macro_use]` on the module/import?");
1005 fn collect_def_ids(&mut self,
1007 invocation: &'a InvocationData<'a>,
1008 fragment: &AstFragment) {
1009 let Resolver { ref mut invocations, arenas, graph_root, .. } = *self;
1010 let InvocationData { def_index, .. } = *invocation;
1012 let visit_macro_invoc = &mut |invoc: map::MacroInvocationData| {
1013 invocations.entry(invoc.mark).or_insert_with(|| {
1014 arenas.alloc_invocation_data(InvocationData {
1015 def_index: invoc.def_index,
1016 module: Cell::new(graph_root),
1017 parent_legacy_scope: Cell::new(LegacyScope::Uninitialized),
1018 output_legacy_scope: Cell::new(None),
1023 let mut def_collector = DefCollector::new(&mut self.definitions, mark);
1024 def_collector.visit_macro_invoc = Some(visit_macro_invoc);
1025 def_collector.with_parent(def_index, |def_collector| {
1026 fragment.visit_with(def_collector)
1030 pub fn define_macro(&mut self,
1033 current_legacy_scope: &mut LegacyScope<'a>) {
1034 self.local_macro_def_scopes.insert(item.id, self.current_module);
1035 let ident = item.ident;
1036 if ident.name == "macro_rules" {
1037 self.session.span_err(item.span, "user-defined macros may not be named `macro_rules`");
1040 let def_id = self.definitions.local_def_id(item.id);
1041 let ext = Lrc::new(macro_rules::compile(&self.session.parse_sess,
1042 &self.session.features_untracked(),
1043 item, hygiene::default_edition()));
1044 self.macro_map.insert(def_id, ext);
1046 let def = match item.node { ast::ItemKind::MacroDef(ref def) => def, _ => unreachable!() };
1048 let ident = ident.modern();
1049 self.macro_names.insert(ident);
1050 let def = Def::Macro(def_id, MacroKind::Bang);
1051 let vis = ty::Visibility::Invisible; // Doesn't matter for legacy bindings
1052 let binding = (def, vis, item.span, expansion).to_name_binding(self.arenas);
1053 self.set_binding_parent_module(binding, self.current_module);
1054 let legacy_binding = self.arenas.alloc_legacy_binding(LegacyBinding {
1055 parent_legacy_scope: *current_legacy_scope, binding, ident
1057 *current_legacy_scope = LegacyScope::Binding(legacy_binding);
1058 self.all_macros.insert(ident.name, def);
1059 if attr::contains_name(&item.attrs, "macro_export") {
1060 let module = self.graph_root;
1061 let vis = ty::Visibility::Public;
1062 self.define(module, ident, MacroNS,
1063 (def, vis, item.span, expansion, IsMacroExport));
1065 if !attr::contains_name(&item.attrs, "rustc_doc_only_macro") {
1066 self.check_reserved_macro_name(ident, MacroNS);
1068 self.unused_macros.insert(def_id);
1071 let module = self.current_module;
1072 let def = Def::Macro(def_id, MacroKind::Bang);
1073 let vis = self.resolve_visibility(&item.vis);
1074 if vis != ty::Visibility::Public {
1075 self.unused_macros.insert(def_id);
1077 self.define(module, ident, MacroNS, (def, vis, item.span, expansion));