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, ModuleKind, 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::fold::{self, Folder};
35 use syntax::symbol::{Symbol, keywords};
36 use syntax::util::lev_distance::find_best_match_for_name;
37 use syntax_pos::{Span, DUMMY_SP};
38 use errors::Applicability;
42 use rustc_data_structures::sync::Lrc;
44 #[derive(Clone, Debug)]
45 pub struct InvocationData<'a> {
47 /// Module in which the macro was invoked.
48 crate module: Cell<Module<'a>>,
49 /// Legacy scope in which the macro was invoked.
50 /// The invocation path is resolved in this scope.
51 crate parent_legacy_scope: Cell<LegacyScope<'a>>,
52 /// Legacy scope *produced* by expanding this macro invocation,
53 /// includes all the macro_rules items, other invocations, etc generated by it.
54 /// `None` if the macro is not expanded yet.
55 crate output_legacy_scope: Cell<Option<LegacyScope<'a>>>,
58 impl<'a> InvocationData<'a> {
59 pub fn root(graph_root: Module<'a>) -> Self {
61 module: Cell::new(graph_root),
62 def_index: CRATE_DEF_INDEX,
63 parent_legacy_scope: Cell::new(LegacyScope::Empty),
64 output_legacy_scope: Cell::new(Some(LegacyScope::Empty)),
69 /// Binding produced by a `macro_rules` item.
70 /// Not modularized, can shadow previous legacy bindings, etc.
72 pub struct LegacyBinding<'a> {
73 binding: &'a NameBinding<'a>,
74 /// Legacy scope into which the `macro_rules` item was planted.
75 parent_legacy_scope: LegacyScope<'a>,
79 /// Scope introduced by a `macro_rules!` macro.
80 /// Starts at the macro's definition and ends at the end of the macro's parent module
81 /// (named or unnamed), or even further if it escapes with `#[macro_use]`.
82 /// Some macro invocations need to introduce legacy scopes too because they
83 /// potentially can expand into macro definitions.
84 #[derive(Copy, Clone, Debug)]
85 pub enum LegacyScope<'a> {
86 /// Created when invocation data is allocated in the arena,
87 /// must be replaced with a proper scope later.
89 /// Empty "root" scope at the crate start containing no names.
91 /// Scope introduced by a `macro_rules!` macro definition.
92 Binding(&'a LegacyBinding<'a>),
93 /// Scope introduced by a macro invocation that can potentially
94 /// create a `macro_rules!` macro definition.
95 Invocation(&'a InvocationData<'a>),
98 /// Everything you need to resolve a macro or import path.
99 #[derive(Clone, Debug)]
100 pub struct ParentScope<'a> {
101 crate module: Module<'a>,
102 crate expansion: Mark,
103 crate legacy: LegacyScope<'a>,
104 crate derives: Vec<ast::Path>,
107 // Macro namespace is separated into two sub-namespaces, one for bang macros and
108 // one for attribute-like macros (attributes, derives).
109 // We ignore resolutions from one sub-namespace when searching names in scope for another.
110 fn sub_namespace_match(candidate: Option<MacroKind>, requirement: Option<MacroKind>) -> bool {
112 enum SubNS { Bang, AttrLike }
113 let sub_ns = |kind| match kind {
114 MacroKind::Bang => Some(SubNS::Bang),
115 MacroKind::Attr | MacroKind::Derive => Some(SubNS::AttrLike),
116 MacroKind::ProcMacroStub => None,
118 let requirement = requirement.and_then(|kind| sub_ns(kind));
119 let candidate = candidate.and_then(|kind| sub_ns(kind));
120 // "No specific sub-namespace" means "matches anything" for both requirements and candidates.
121 candidate.is_none() || requirement.is_none() || candidate == requirement
124 impl<'a> base::Resolver for Resolver<'a> {
125 fn next_node_id(&mut self) -> ast::NodeId {
126 self.session.next_node_id()
129 fn get_module_scope(&mut self, id: ast::NodeId) -> Mark {
130 let mark = Mark::fresh(Mark::root());
131 let module = self.module_map[&self.definitions.local_def_id(id)];
132 self.invocations.insert(mark, self.arenas.alloc_invocation_data(InvocationData {
133 module: Cell::new(module),
134 def_index: module.def_id().unwrap().index,
135 parent_legacy_scope: Cell::new(LegacyScope::Empty),
136 output_legacy_scope: Cell::new(Some(LegacyScope::Empty)),
141 fn eliminate_crate_var(&mut self, item: P<ast::Item>) -> P<ast::Item> {
142 struct EliminateCrateVar<'b, 'a: 'b>(
143 &'b mut Resolver<'a>, Span
146 impl<'a, 'b> Folder for EliminateCrateVar<'a, 'b> {
147 fn fold_path(&mut self, path: ast::Path) -> ast::Path {
148 match self.fold_qpath(None, path) {
149 (None, path) => path,
154 fn fold_qpath(&mut self, mut qself: Option<ast::QSelf>, mut path: ast::Path)
155 -> (Option<ast::QSelf>, ast::Path) {
156 qself = qself.map(|ast::QSelf { ty, path_span, position }| {
158 ty: self.fold_ty(ty),
159 path_span: self.new_span(path_span),
164 if path.segments[0].ident.name == keywords::DollarCrate.name() {
165 let module = self.0.resolve_crate_root(path.segments[0].ident);
166 path.segments[0].ident.name = keywords::PathRoot.name();
167 if !module.is_local() {
168 let span = path.segments[0].ident.span;
169 path.segments.insert(1, match module.kind {
170 ModuleKind::Def(_, name) => ast::PathSegment::from_ident(
171 ast::Ident::with_empty_ctxt(name).with_span_pos(span)
175 if let Some(qself) = &mut qself {
183 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
184 fold::noop_fold_mac(mac, self)
188 let ret = EliminateCrateVar(self, item.span).fold_item(item);
189 assert!(ret.len() == 1);
190 ret.into_iter().next().unwrap()
193 fn visit_ast_fragment_with_placeholders(&mut self, mark: Mark, fragment: &AstFragment,
195 let invocation = self.invocations[&mark];
196 self.collect_def_ids(mark, invocation, fragment);
198 self.current_module = invocation.module.get();
199 self.current_module.unresolved_invocations.borrow_mut().remove(&mark);
200 self.current_module.unresolved_invocations.borrow_mut().extend(derives);
201 self.invocations.extend(derives.iter().map(|&derive| (derive, invocation)));
202 let mut visitor = BuildReducedGraphVisitor {
204 current_legacy_scope: invocation.parent_legacy_scope.get(),
207 fragment.visit_with(&mut visitor);
208 invocation.output_legacy_scope.set(Some(visitor.current_legacy_scope));
211 fn add_builtin(&mut self, ident: ast::Ident, ext: Lrc<SyntaxExtension>) {
213 krate: CrateNum::BuiltinMacros,
214 index: DefIndex::from_array_index(self.macro_map.len(),
215 DefIndexAddressSpace::Low),
217 let kind = ext.kind();
218 self.macro_map.insert(def_id, ext);
219 let binding = self.arenas.alloc_name_binding(NameBinding {
220 kind: NameBindingKind::Def(Def::Macro(def_id, kind), false),
222 vis: ty::Visibility::Public,
223 expansion: Mark::root(),
225 if self.builtin_macros.insert(ident.name, binding).is_some() {
226 self.session.span_err(ident.span,
227 &format!("built-in macro `{}` was already defined", ident));
231 fn resolve_imports(&mut self) {
232 ImportResolver { resolver: self }.resolve_imports()
235 fn resolve_macro_invocation(&mut self, invoc: &Invocation, invoc_id: Mark, force: bool)
236 -> Result<Option<Lrc<SyntaxExtension>>, Determinacy> {
237 let (path, kind, derives_in_scope, after_derive) = match invoc.kind {
238 InvocationKind::Attr { attr: None, .. } =>
240 InvocationKind::Attr { attr: Some(ref attr), ref traits, after_derive, .. } =>
241 (&attr.path, MacroKind::Attr, traits.clone(), after_derive),
242 InvocationKind::Bang { ref mac, .. } =>
243 (&mac.node.path, MacroKind::Bang, Vec::new(), false),
244 InvocationKind::Derive { ref path, .. } =>
245 (path, MacroKind::Derive, Vec::new(), false),
248 let parent_scope = self.invoc_parent_scope(invoc_id, derives_in_scope);
249 let (def, ext) = self.resolve_macro_to_def(path, kind, &parent_scope, true, force)?;
251 if let Def::Macro(def_id, _) = def {
253 self.session.span_err(invoc.span(),
254 "macro attributes must be placed before `#[derive]`");
256 self.macro_defs.insert(invoc.expansion_data.mark, def_id);
257 let normal_module_def_id =
258 self.macro_def_scope(invoc.expansion_data.mark).normal_ancestor_id;
259 self.definitions.add_parent_module_of_macro_def(invoc.expansion_data.mark,
260 normal_module_def_id);
261 invoc.expansion_data.mark.set_default_transparency(ext.default_transparency());
262 invoc.expansion_data.mark.set_is_builtin(def_id.krate == CrateNum::BuiltinMacros);
268 fn resolve_macro_path(&mut self, path: &ast::Path, kind: MacroKind, invoc_id: Mark,
269 derives_in_scope: Vec<ast::Path>, force: bool)
270 -> Result<Lrc<SyntaxExtension>, Determinacy> {
271 let parent_scope = self.invoc_parent_scope(invoc_id, derives_in_scope);
272 Ok(self.resolve_macro_to_def(path, kind, &parent_scope, false, force)?.1)
275 fn check_unused_macros(&self) {
276 for did in self.unused_macros.iter() {
277 let id_span = match *self.macro_map[did] {
278 SyntaxExtension::NormalTT { def_info, .. } |
279 SyntaxExtension::DeclMacro { def_info, .. } => def_info,
282 if let Some((id, span)) = id_span {
283 let lint = lint::builtin::UNUSED_MACROS;
284 let msg = "unused macro definition";
285 self.session.buffer_lint(lint, id, span, msg);
287 bug!("attempted to create unused macro error, but span not available");
293 impl<'a> Resolver<'a> {
294 pub fn dummy_parent_scope(&self) -> ParentScope<'a> {
295 self.invoc_parent_scope(Mark::root(), Vec::new())
298 fn invoc_parent_scope(&self, invoc_id: Mark, derives: Vec<ast::Path>) -> ParentScope<'a> {
299 let invoc = self.invocations[&invoc_id];
301 module: invoc.module.get().nearest_item_scope(),
302 expansion: invoc_id.parent(),
303 legacy: invoc.parent_legacy_scope.get(),
308 fn resolve_macro_to_def(
312 parent_scope: &ParentScope<'a>,
315 ) -> Result<(Def, Lrc<SyntaxExtension>), Determinacy> {
316 let def = self.resolve_macro_to_def_inner(path, kind, parent_scope, trace, force);
318 // Report errors and enforce feature gates for the resolved macro.
319 if def != Err(Determinacy::Undetermined) {
320 // Do not report duplicated errors on every undetermined resolution.
321 for segment in &path.segments {
322 if let Some(args) = &segment.args {
323 self.session.span_err(args.span(), "generic arguments in macro path");
331 Def::Macro(def_id, macro_kind) => {
332 self.unused_macros.remove(&def_id);
333 if macro_kind == MacroKind::ProcMacroStub {
334 let msg = "can't use a procedural macro from the same crate that defines it";
335 self.session.span_err(path.span, msg);
336 return Err(Determinacy::Determined);
339 Def::NonMacroAttr(attr_kind) => {
340 if kind == MacroKind::Attr {
341 let features = self.session.features_untracked();
342 if attr_kind == NonMacroAttrKind::Custom {
343 assert!(path.segments.len() == 1);
344 let name = path.segments[0].ident.name.as_str();
345 if name.starts_with("rustc_") {
346 if !features.rustc_attrs {
347 let msg = "unless otherwise specified, attributes with the prefix \
348 `rustc_` are reserved for internal compiler diagnostics";
349 feature_err(&self.session.parse_sess, "rustc_attrs", path.span,
350 GateIssue::Language, &msg).emit();
352 } else if !features.custom_attribute {
353 let msg = format!("The attribute `{}` is currently unknown to the \
354 compiler and may have meaning added to it in the \
356 feature_err(&self.session.parse_sess, "custom_attribute", path.span,
357 GateIssue::Language, &msg).emit();
361 // Not only attributes, but anything in macro namespace can result in
362 // `Def::NonMacroAttr` definition (e.g., `inline!()`), so we must report
363 // an error for those cases.
364 let msg = format!("expected a macro, found {}", def.kind_name());
365 self.session.span_err(path.span, &msg);
366 return Err(Determinacy::Determined);
370 return Err(Determinacy::Determined);
372 _ => panic!("expected `Def::Macro` or `Def::NonMacroAttr`"),
375 Ok((def, self.get_macro(def)))
378 pub fn resolve_macro_to_def_inner(
382 parent_scope: &ParentScope<'a>,
385 ) -> Result<Def, Determinacy> {
386 let path_span = path.span;
387 let mut path = Segment::from_path(path);
389 // Possibly apply the macro helper hack
390 if kind == MacroKind::Bang && path.len() == 1 &&
391 path[0].ident.span.ctxt().outer().expn_info()
392 .map_or(false, |info| info.local_inner_macros) {
393 let root = Ident::new(keywords::DollarCrate.name(), path[0].ident.span);
394 path.insert(0, Segment::from_ident(root));
398 let def = match self.resolve_path(&path, Some(MacroNS), parent_scope,
399 false, path_span, CrateLint::No) {
400 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
401 Ok(path_res.base_def())
403 PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
404 PathResult::NonModule(..) | PathResult::Indeterminate | PathResult::Failed(..) => {
405 self.found_unresolved_macro = true;
406 Err(Determinacy::Determined)
408 PathResult::Module(..) => unreachable!(),
412 parent_scope.module.multi_segment_macro_resolutions.borrow_mut()
413 .push((path, path_span, kind, parent_scope.clone(), def.ok()));
418 let binding = self.early_resolve_ident_in_lexical_scope(
419 path[0].ident, ScopeSet::Macro(kind), parent_scope, false, force, path_span
423 Err(Determinacy::Determined) => self.found_unresolved_macro = true,
424 Err(Determinacy::Undetermined) => return Err(Determinacy::Undetermined),
428 parent_scope.module.single_segment_macro_resolutions.borrow_mut()
429 .push((path[0].ident, kind, parent_scope.clone(), binding.ok()));
432 binding.map(|binding| binding.def_ignoring_ambiguity())
436 // Resolve an identifier in lexical scope.
437 // This is a variation of `fn resolve_ident_in_lexical_scope` that can be run during
438 // expansion and import resolution (perhaps they can be merged in the future).
439 // The function is used for resolving initial segments of macro paths (e.g., `foo` in
440 // `foo::bar!(); or `foo!();`) and also for import paths on 2018 edition.
441 crate fn early_resolve_ident_in_lexical_scope(
445 parent_scope: &ParentScope<'a>,
449 ) -> Result<&'a NameBinding<'a>, Determinacy> {
450 // General principles:
451 // 1. Not controlled (user-defined) names should have higher priority than controlled names
452 // built into the language or standard library. This way we can add new names into the
453 // language or standard library without breaking user code.
454 // 2. "Closed set" below means new names cannot appear after the current resolution attempt.
455 // Places to search (in order of decreasing priority):
457 // 1. FIXME: Ribs (type parameters), there's no necessary infrastructure yet
458 // (open set, not controlled).
459 // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
460 // (open, not controlled).
461 // 3. Extern prelude (closed, not controlled).
462 // 4. Tool modules (closed, controlled right now, but not in the future).
463 // 5. Standard library prelude (de-facto closed, controlled).
464 // 6. Language prelude (closed, controlled).
466 // 1. FIXME: Ribs (local variables), there's no necessary infrastructure yet
467 // (open set, not controlled).
468 // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
469 // (open, not controlled).
470 // 3. Standard library prelude (de-facto closed, controlled).
472 // 1-3. Derive helpers (open, not controlled). All ambiguities with other names
473 // are currently reported as errors. They should be higher in priority than preludes
474 // and probably even names in modules according to the "general principles" above. They
475 // also should be subject to restricted shadowing because are effectively produced by
476 // derives (you need to resolve the derive first to add helpers into scope), but they
477 // should be available before the derive is expanded for compatibility.
478 // It's mess in general, so we are being conservative for now.
479 // 1-3. `macro_rules` (open, not controlled), loop through legacy scopes. Have higher
480 // priority than prelude macros, but create ambiguities with macros in modules.
481 // 1-3. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
482 // (open, not controlled). Have higher priority than prelude macros, but create
483 // ambiguities with `macro_rules`.
484 // 4. `macro_use` prelude (open, the open part is from macro expansions, not controlled).
485 // 4a. User-defined prelude from macro-use
486 // (open, the open part is from macro expansions, not controlled).
487 // 4b. Standard library prelude is currently implemented as `macro-use` (closed, controlled)
488 // 5. Language prelude: builtin macros (closed, controlled, except for legacy plugins).
489 // 6. Language prelude: builtin attributes (closed, controlled).
490 // 4-6. Legacy plugin helpers (open, not controlled). Similar to derive helpers,
491 // but introduced by legacy plugins using `register_attribute`. Priority is somewhere
492 // in prelude, not sure where exactly (creates ambiguities with any other prelude names).
494 enum WhereToResolve<'a> {
496 MacroRules(LegacyScope<'a>),
511 const MACRO_RULES = 1 << 0;
512 const MODULE = 1 << 1;
513 const PRELUDE = 1 << 2;
514 const MISC_SUGGEST_CRATE = 1 << 3;
515 const MISC_SUGGEST_SELF = 1 << 4;
516 const MISC_FROM_PRELUDE = 1 << 5;
520 assert!(force || !record_used); // `record_used` implies `force`
521 let mut ident = orig_ident.modern();
523 // Make sure `self`, `super` etc produce an error when passed to here.
524 if ident.is_path_segment_keyword() {
525 return Err(Determinacy::Determined);
528 // This is *the* result, resolution from the scope closest to the resolved identifier.
529 // However, sometimes this result is "weak" because it comes from a glob import or
530 // a macro expansion, and in this case it cannot shadow names from outer scopes, e.g.
531 // mod m { ... } // solution in outer scope
533 // use prefix::*; // imports another `m` - innermost solution
534 // // weak, cannot shadow the outer `m`, need to report ambiguity error
537 // So we have to save the innermost solution and continue searching in outer scopes
538 // to detect potential ambiguities.
539 let mut innermost_result: Option<(&NameBinding, Flags)> = None;
541 // Go through all the scopes and try to resolve the name.
542 let rust_2015 = orig_ident.span.rust_2015();
543 let (ns, macro_kind, is_import, is_absolute_path) = match scope_set {
544 ScopeSet::Import(ns) => (ns, None, true, false),
545 ScopeSet::AbsolutePath(ns) => (ns, None, false, true),
546 ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind), false, false),
547 ScopeSet::Module => (TypeNS, None, false, false),
549 let mut where_to_resolve = match ns {
550 _ if is_absolute_path || is_import && rust_2015 => WhereToResolve::CrateRoot,
551 TypeNS | ValueNS => WhereToResolve::Module(parent_scope.module),
552 MacroNS => WhereToResolve::DeriveHelpers,
554 let mut use_prelude = !parent_scope.module.no_implicit_prelude;
555 let mut determinacy = Determinacy::Determined;
557 let result = match where_to_resolve {
558 WhereToResolve::DeriveHelpers => {
559 let mut result = Err(Determinacy::Determined);
560 for derive in &parent_scope.derives {
561 let parent_scope = ParentScope { derives: Vec::new(), ..*parent_scope };
562 match self.resolve_macro_to_def(derive, MacroKind::Derive,
563 &parent_scope, true, force) {
565 if let SyntaxExtension::ProcMacroDerive(_, helpers, _) = &*ext {
566 if helpers.contains(&ident.name) {
568 (Def::NonMacroAttr(NonMacroAttrKind::DeriveHelper),
569 ty::Visibility::Public, derive.span, Mark::root())
570 .to_name_binding(self.arenas);
571 result = Ok((binding, Flags::empty()));
576 Err(Determinacy::Determined) => {}
577 Err(Determinacy::Undetermined) =>
578 result = Err(Determinacy::Undetermined),
583 WhereToResolve::MacroRules(legacy_scope) => match legacy_scope {
584 LegacyScope::Binding(legacy_binding) if ident == legacy_binding.ident =>
585 Ok((legacy_binding.binding, Flags::MACRO_RULES)),
586 LegacyScope::Invocation(invoc) if invoc.output_legacy_scope.get().is_none() =>
587 Err(Determinacy::Undetermined),
588 _ => Err(Determinacy::Determined),
590 WhereToResolve::CrateRoot => {
591 let root_ident = Ident::new(keywords::PathRoot.name(), orig_ident.span);
592 let root_module = self.resolve_crate_root(root_ident);
593 let binding = self.resolve_ident_in_module_ext(
594 ModuleOrUniformRoot::Module(root_module),
602 Ok(binding) => Ok((binding, Flags::MODULE | Flags::MISC_SUGGEST_CRATE)),
603 Err((Determinacy::Undetermined, Weak::No)) =>
604 return Err(Determinacy::determined(force)),
605 Err((Determinacy::Undetermined, Weak::Yes)) =>
606 Err(Determinacy::Undetermined),
607 Err((Determinacy::Determined, _)) => Err(Determinacy::Determined),
610 WhereToResolve::Module(module) => {
611 let orig_current_module = mem::replace(&mut self.current_module, module);
612 let binding = self.resolve_ident_in_module_unadjusted_ext(
613 ModuleOrUniformRoot::Module(module),
621 self.current_module = orig_current_module;
624 let misc_flags = if ptr::eq(module, self.graph_root) {
625 Flags::MISC_SUGGEST_CRATE
626 } else if module.is_normal() {
627 Flags::MISC_SUGGEST_SELF
631 Ok((binding, Flags::MODULE | misc_flags))
633 Err((Determinacy::Undetermined, Weak::No)) =>
634 return Err(Determinacy::determined(force)),
635 Err((Determinacy::Undetermined, Weak::Yes)) =>
636 Err(Determinacy::Undetermined),
637 Err((Determinacy::Determined, _)) => Err(Determinacy::Determined),
640 WhereToResolve::MacroUsePrelude => {
641 if use_prelude || rust_2015 {
642 match self.macro_use_prelude.get(&ident.name).cloned() {
644 Ok((binding, Flags::PRELUDE | Flags::MISC_FROM_PRELUDE)),
645 None => Err(Determinacy::determined(
646 self.graph_root.unresolved_invocations.borrow().is_empty()
650 Err(Determinacy::Determined)
653 WhereToResolve::BuiltinMacros => {
654 match self.builtin_macros.get(&ident.name).cloned() {
655 Some(binding) => Ok((binding, Flags::PRELUDE)),
656 None => Err(Determinacy::Determined),
659 WhereToResolve::BuiltinAttrs => {
660 if is_builtin_attr_name(ident.name) {
661 let binding = (Def::NonMacroAttr(NonMacroAttrKind::Builtin),
662 ty::Visibility::Public, DUMMY_SP, Mark::root())
663 .to_name_binding(self.arenas);
664 Ok((binding, Flags::PRELUDE))
666 Err(Determinacy::Determined)
669 WhereToResolve::LegacyPluginHelpers => {
670 if (use_prelude || rust_2015) &&
671 self.session.plugin_attributes.borrow().iter()
672 .any(|(name, _)| ident.name == &**name) {
673 let binding = (Def::NonMacroAttr(NonMacroAttrKind::LegacyPluginHelper),
674 ty::Visibility::Public, DUMMY_SP, Mark::root())
675 .to_name_binding(self.arenas);
676 Ok((binding, Flags::PRELUDE))
678 Err(Determinacy::Determined)
681 WhereToResolve::ExternPrelude => {
682 if use_prelude || is_absolute_path {
683 match self.extern_prelude_get(ident, !record_used) {
684 Some(binding) => Ok((binding, Flags::PRELUDE)),
685 None => Err(Determinacy::determined(
686 self.graph_root.unresolved_invocations.borrow().is_empty()
690 Err(Determinacy::Determined)
693 WhereToResolve::ToolPrelude => {
694 if use_prelude && is_known_tool(ident.name) {
695 let binding = (Def::ToolMod, ty::Visibility::Public,
696 DUMMY_SP, Mark::root()).to_name_binding(self.arenas);
697 Ok((binding, Flags::PRELUDE))
699 Err(Determinacy::Determined)
702 WhereToResolve::StdLibPrelude => {
703 let mut result = Err(Determinacy::Determined);
705 if let Some(prelude) = self.prelude {
706 if let Ok(binding) = self.resolve_ident_in_module_unadjusted(
707 ModuleOrUniformRoot::Module(prelude),
713 result = Ok((binding, Flags::PRELUDE | Flags::MISC_FROM_PRELUDE));
719 WhereToResolve::BuiltinTypes => {
720 match self.primitive_type_table.primitive_types.get(&ident.name).cloned() {
722 let binding = (Def::PrimTy(prim_ty), ty::Visibility::Public,
723 DUMMY_SP, Mark::root()).to_name_binding(self.arenas);
724 Ok((binding, Flags::PRELUDE))
726 None => Err(Determinacy::Determined)
732 Ok((binding, flags)) if sub_namespace_match(binding.macro_kind(), macro_kind) => {
737 if let Some((innermost_binding, innermost_flags)) = innermost_result {
738 // Found another solution, if the first one was "weak", report an error.
739 let (def, innermost_def) = (binding.def(), innermost_binding.def());
740 if def != innermost_def {
741 let builtin = Def::NonMacroAttr(NonMacroAttrKind::Builtin);
742 let derive_helper = Def::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
744 Def::NonMacroAttr(NonMacroAttrKind::LegacyPluginHelper);
746 let ambiguity_error_kind = if is_import {
747 Some(AmbiguityKind::Import)
748 } else if is_absolute_path {
749 Some(AmbiguityKind::AbsolutePath)
750 } else if innermost_def == builtin || def == builtin {
751 Some(AmbiguityKind::BuiltinAttr)
752 } else if innermost_def == derive_helper || def == derive_helper {
753 Some(AmbiguityKind::DeriveHelper)
754 } else if innermost_def == legacy_helper &&
755 flags.contains(Flags::PRELUDE) ||
756 def == legacy_helper &&
757 innermost_flags.contains(Flags::PRELUDE) {
758 Some(AmbiguityKind::LegacyHelperVsPrelude)
759 } else if innermost_flags.contains(Flags::MACRO_RULES) &&
760 flags.contains(Flags::MODULE) &&
761 !self.disambiguate_legacy_vs_modern(innermost_binding,
763 flags.contains(Flags::MACRO_RULES) &&
764 innermost_flags.contains(Flags::MODULE) &&
765 !self.disambiguate_legacy_vs_modern(binding,
767 Some(AmbiguityKind::LegacyVsModern)
768 } else if innermost_binding.is_glob_import() {
769 Some(AmbiguityKind::GlobVsOuter)
770 } else if innermost_binding.may_appear_after(parent_scope.expansion,
772 Some(AmbiguityKind::MoreExpandedVsOuter)
776 if let Some(kind) = ambiguity_error_kind {
777 let misc = |f: Flags| if f.contains(Flags::MISC_SUGGEST_CRATE) {
778 AmbiguityErrorMisc::SuggestCrate
779 } else if f.contains(Flags::MISC_SUGGEST_SELF) {
780 AmbiguityErrorMisc::SuggestSelf
781 } else if f.contains(Flags::MISC_FROM_PRELUDE) {
782 AmbiguityErrorMisc::FromPrelude
784 AmbiguityErrorMisc::None
786 self.ambiguity_errors.push(AmbiguityError {
789 b1: innermost_binding,
791 misc1: misc(innermost_flags),
794 return Ok(innermost_binding);
798 // Found the first solution.
799 innermost_result = Some((binding, flags));
802 Ok(..) | Err(Determinacy::Determined) => {}
803 Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined
806 where_to_resolve = match where_to_resolve {
807 WhereToResolve::DeriveHelpers =>
808 WhereToResolve::MacroRules(parent_scope.legacy),
809 WhereToResolve::MacroRules(legacy_scope) => match legacy_scope {
810 LegacyScope::Binding(binding) => WhereToResolve::MacroRules(
811 binding.parent_legacy_scope
813 LegacyScope::Invocation(invoc) => WhereToResolve::MacroRules(
814 invoc.output_legacy_scope.get().unwrap_or(invoc.parent_legacy_scope.get())
816 LegacyScope::Empty => WhereToResolve::Module(parent_scope.module),
817 LegacyScope::Uninitialized => unreachable!(),
819 WhereToResolve::CrateRoot if is_import => match ns {
820 TypeNS | ValueNS => WhereToResolve::Module(parent_scope.module),
821 MacroNS => WhereToResolve::DeriveHelpers,
823 WhereToResolve::CrateRoot if is_absolute_path => match ns {
825 ident.span.adjust(Mark::root());
826 WhereToResolve::ExternPrelude
828 ValueNS | MacroNS => break,
830 WhereToResolve::CrateRoot => unreachable!(),
831 WhereToResolve::Module(module) => {
832 match self.hygienic_lexical_parent(module, &mut ident.span) {
833 Some(parent_module) => WhereToResolve::Module(parent_module),
835 use_prelude = !module.no_implicit_prelude;
837 TypeNS => WhereToResolve::ExternPrelude,
838 ValueNS => WhereToResolve::StdLibPrelude,
839 MacroNS => WhereToResolve::MacroUsePrelude,
844 WhereToResolve::MacroUsePrelude => WhereToResolve::BuiltinMacros,
845 WhereToResolve::BuiltinMacros => WhereToResolve::BuiltinAttrs,
846 WhereToResolve::BuiltinAttrs => WhereToResolve::LegacyPluginHelpers,
847 WhereToResolve::LegacyPluginHelpers => break, // nowhere else to search
848 WhereToResolve::ExternPrelude if is_absolute_path => break,
849 WhereToResolve::ExternPrelude => WhereToResolve::ToolPrelude,
850 WhereToResolve::ToolPrelude => WhereToResolve::StdLibPrelude,
851 WhereToResolve::StdLibPrelude => match ns {
852 TypeNS => WhereToResolve::BuiltinTypes,
853 ValueNS => break, // nowhere else to search
854 MacroNS => unreachable!(),
856 WhereToResolve::BuiltinTypes => break, // nowhere else to search
862 // The first found solution was the only one, return it.
863 if let Some((binding, flags)) = innermost_result {
864 // We get to here only if there's no ambiguity, in ambiguous cases an error will
865 // be reported anyway, so there's no reason to report an additional feature error.
866 // The `binding` can actually be introduced by something other than `--extern`,
867 // but its `Def` should coincide with a crate passed with `--extern`
868 // (otherwise there would be ambiguity) and we can skip feature error in this case.
870 if !is_import || self.session.features_untracked().uniform_paths {
873 if ns == TypeNS && use_prelude && self.extern_prelude_get(ident, true).is_some() {
877 let root_ident = Ident::new(keywords::PathRoot.name(), orig_ident.span);
878 let root_module = self.resolve_crate_root(root_ident);
879 if self.resolve_ident_in_module_ext(ModuleOrUniformRoot::Module(root_module),
880 orig_ident, ns, None, false, path_span)
886 let msg = "imports can only refer to extern crate names \
887 passed with `--extern` on stable channel";
888 let mut err = feature_err(&self.session.parse_sess, "uniform_paths",
889 ident.span, GateIssue::Language, msg);
891 let what = self.binding_description(binding, ident,
892 flags.contains(Flags::MISC_FROM_PRELUDE));
893 let note_msg = format!("this import refers to {what}", what = what);
894 let label_span = if binding.span.is_dummy() {
898 err.span_note(binding.span, ¬e_msg);
901 err.span_label(label_span, "not an extern crate passed with `--extern`");
908 let determinacy = Determinacy::determined(determinacy == Determinacy::Determined || force);
909 if determinacy == Determinacy::Determined && macro_kind == Some(MacroKind::Attr) {
910 // For single-segment attributes interpret determinate "no resolution" as a custom
911 // attribute. (Lexical resolution implies the first segment and attr kind should imply
912 // the last segment, so we are certainly working with a single-segment attribute here.)
913 assert!(ns == MacroNS);
914 let binding = (Def::NonMacroAttr(NonMacroAttrKind::Custom),
915 ty::Visibility::Public, ident.span, Mark::root())
916 .to_name_binding(self.arenas);
923 pub fn finalize_current_module_macro_resolutions(&mut self) {
924 let module = self.current_module;
926 let check_consistency = |this: &mut Self, path: &[Segment], span,
927 kind: MacroKind, initial_def, def| {
928 if let Some(initial_def) = initial_def {
929 if def != initial_def && def != Def::Err && this.ambiguity_errors.is_empty() {
930 // Make sure compilation does not succeed if preferred macro resolution
931 // has changed after the macro had been expanded. In theory all such
932 // situations should be reported as ambiguity errors, so this is a bug.
933 span_bug!(span, "inconsistent resolution for a macro");
936 // It's possible that the macro was unresolved (indeterminate) and silently
937 // expanded into a dummy fragment for recovery during expansion.
938 // Now, post-expansion, the resolution may succeed, but we can't change the
939 // past and need to report an error.
940 // However, non-speculative `resolve_path` can successfully return private items
941 // even if speculative `resolve_path` returned nothing previously, so we skip this
942 // less informative error if the privacy error is reported elsewhere.
943 if this.privacy_errors.is_empty() {
944 let msg = format!("cannot determine resolution for the {} `{}`",
945 kind.descr(), Segment::names_to_string(path));
946 let msg_note = "import resolution is stuck, try simplifying macro imports";
947 this.session.struct_span_err(span, &msg).note(msg_note).emit();
952 let macro_resolutions =
953 mem::replace(&mut *module.multi_segment_macro_resolutions.borrow_mut(), Vec::new());
954 for (mut path, path_span, kind, parent_scope, initial_def) in macro_resolutions {
955 // FIXME: Path resolution will ICE if segment IDs present.
956 for seg in &mut path { seg.id = None; }
957 match self.resolve_path(&path, Some(MacroNS), &parent_scope,
958 true, path_span, CrateLint::No) {
959 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
960 let def = path_res.base_def();
961 check_consistency(self, &path, path_span, kind, initial_def, def);
963 path_res @ PathResult::NonModule(..) | path_res @ PathResult::Failed(..) => {
964 let (span, msg) = if let PathResult::Failed(span, msg, ..) = path_res {
967 (path_span, format!("partially resolved path in {} {}",
968 kind.article(), kind.descr()))
970 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
972 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
976 let macro_resolutions =
977 mem::replace(&mut *module.single_segment_macro_resolutions.borrow_mut(), Vec::new());
978 for (ident, kind, parent_scope, initial_binding) in macro_resolutions {
979 match self.early_resolve_ident_in_lexical_scope(ident, ScopeSet::Macro(kind),
980 &parent_scope, true, true, ident.span) {
982 let initial_def = initial_binding.map(|initial_binding| {
983 self.record_use(ident, MacroNS, initial_binding, false);
984 initial_binding.def_ignoring_ambiguity()
986 let def = binding.def_ignoring_ambiguity();
987 let seg = Segment::from_ident(ident);
988 check_consistency(self, &[seg], ident.span, kind, initial_def, def);
991 assert!(initial_binding.is_none());
992 let bang = if kind == MacroKind::Bang { "!" } else { "" };
994 format!("cannot find {} `{}{}` in this scope", kind.descr(), ident, bang);
995 let mut err = self.session.struct_span_err(ident.span, &msg);
996 self.suggest_macro_name(&ident.as_str(), kind, &mut err, ident.span);
1002 let builtin_attrs = mem::replace(&mut *module.builtin_attrs.borrow_mut(), Vec::new());
1003 for (ident, parent_scope) in builtin_attrs {
1004 let _ = self.early_resolve_ident_in_lexical_scope(
1005 ident, ScopeSet::Macro(MacroKind::Attr), &parent_scope, true, true, ident.span
1010 fn suggest_macro_name(&mut self, name: &str, kind: MacroKind,
1011 err: &mut DiagnosticBuilder<'a>, span: Span) {
1012 // First check if this is a locally-defined bang macro.
1013 let suggestion = if let MacroKind::Bang = kind {
1014 find_best_match_for_name(self.macro_names.iter().map(|ident| &ident.name), name, None)
1017 // Then check global macros.
1019 let names = self.builtin_macros.iter().chain(self.macro_use_prelude.iter())
1020 .filter_map(|(name, binding)| {
1021 if binding.macro_kind() == Some(kind) { Some(name) } else { None }
1023 find_best_match_for_name(names, name, None)
1024 // Then check modules.
1026 let is_macro = |def| {
1027 if let Def::Macro(_, def_kind) = def {
1033 let ident = Ident::new(Symbol::intern(name), span);
1034 self.lookup_typo_candidate(&[Segment::from_ident(ident)], MacroNS, is_macro, span)
1037 if let Some(suggestion) = suggestion {
1038 if suggestion != name {
1039 if let MacroKind::Bang = kind {
1040 err.span_suggestion_with_applicability(
1042 "you could try the macro",
1043 suggestion.to_string(),
1044 Applicability::MaybeIncorrect
1047 err.span_suggestion_with_applicability(
1050 suggestion.to_string(),
1051 Applicability::MaybeIncorrect
1055 err.help("have you added the `#[macro_use]` on the module/import?");
1060 fn collect_def_ids(&mut self,
1062 invocation: &'a InvocationData<'a>,
1063 fragment: &AstFragment) {
1064 let Resolver { ref mut invocations, arenas, graph_root, .. } = *self;
1065 let InvocationData { def_index, .. } = *invocation;
1067 let visit_macro_invoc = &mut |invoc: map::MacroInvocationData| {
1068 invocations.entry(invoc.mark).or_insert_with(|| {
1069 arenas.alloc_invocation_data(InvocationData {
1070 def_index: invoc.def_index,
1071 module: Cell::new(graph_root),
1072 parent_legacy_scope: Cell::new(LegacyScope::Uninitialized),
1073 output_legacy_scope: Cell::new(None),
1078 let mut def_collector = DefCollector::new(&mut self.definitions, mark);
1079 def_collector.visit_macro_invoc = Some(visit_macro_invoc);
1080 def_collector.with_parent(def_index, |def_collector| {
1081 fragment.visit_with(def_collector)
1085 pub fn define_macro(&mut self,
1088 current_legacy_scope: &mut LegacyScope<'a>) {
1089 self.local_macro_def_scopes.insert(item.id, self.current_module);
1090 let ident = item.ident;
1091 if ident.name == "macro_rules" {
1092 self.session.span_err(item.span, "user-defined macros may not be named `macro_rules`");
1095 let def_id = self.definitions.local_def_id(item.id);
1096 let ext = Lrc::new(macro_rules::compile(&self.session.parse_sess,
1097 &self.session.features_untracked(),
1098 item, hygiene::default_edition()));
1099 self.macro_map.insert(def_id, ext);
1101 let def = match item.node { ast::ItemKind::MacroDef(ref def) => def, _ => unreachable!() };
1103 let ident = ident.modern();
1104 self.macro_names.insert(ident);
1105 let def = Def::Macro(def_id, MacroKind::Bang);
1106 let vis = ty::Visibility::Invisible; // Doesn't matter for legacy bindings
1107 let binding = (def, vis, item.span, expansion).to_name_binding(self.arenas);
1108 self.set_binding_parent_module(binding, self.current_module);
1109 let legacy_binding = self.arenas.alloc_legacy_binding(LegacyBinding {
1110 parent_legacy_scope: *current_legacy_scope, binding, ident
1112 *current_legacy_scope = LegacyScope::Binding(legacy_binding);
1113 self.all_macros.insert(ident.name, def);
1114 if attr::contains_name(&item.attrs, "macro_export") {
1115 let module = self.graph_root;
1116 let vis = ty::Visibility::Public;
1117 self.define(module, ident, MacroNS,
1118 (def, vis, item.span, expansion, IsMacroExport));
1120 if !attr::contains_name(&item.attrs, "rustc_doc_only_macro") {
1121 self.check_reserved_macro_name(ident, MacroNS);
1123 self.unused_macros.insert(def_id);
1126 let module = self.current_module;
1127 let def = Def::Macro(def_id, MacroKind::Bang);
1128 let vis = self.resolve_visibility(&item.vis);
1129 if vis != ty::Visibility::Public {
1130 self.unused_macros.insert(def_id);
1132 self.define(module, ident, MacroNS, (def, vis, item.span, expansion));