1 use crate::{AmbiguityError, AmbiguityKind, AmbiguityErrorMisc, Determinacy};
2 use crate::{CrateLint, Resolver, ResolutionError, Scope, ScopeSet, ParentScope, Weak};
3 use crate::{Module, ModuleKind, NameBinding, PathResult, Segment, ToNameBinding};
4 use crate::{ModuleOrUniformRoot, KNOWN_TOOLS};
5 use crate::Namespace::*;
6 use crate::build_reduced_graph::BuildReducedGraphVisitor;
7 use crate::resolve_imports::ImportResolver;
8 use rustc::hir::def::{self, DefKind, NonMacroAttrKind};
9 use rustc::hir::map::DefCollector;
10 use rustc::middle::stability;
11 use rustc::{ty, lint, span_bug};
12 use syntax::ast::{self, Ident};
13 use syntax::attr::StabilityLevel;
14 use syntax::edition::Edition;
15 use syntax::ext::base::{self, Indeterminate, SpecialDerives};
16 use syntax::ext::base::{MacroKind, SyntaxExtension};
17 use syntax::ext::expand::{AstFragment, Invocation, InvocationKind};
18 use syntax::ext::hygiene::{self, ExpnId, ExpnInfo, ExpnKind};
19 use syntax::ext::tt::macro_rules;
20 use syntax::feature_gate::{emit_feature_err, is_builtin_attr_name};
21 use syntax::feature_gate::GateIssue;
22 use syntax::symbol::{Symbol, kw, sym};
23 use syntax_pos::{Span, DUMMY_SP};
27 use rustc_data_structures::sync::Lrc;
29 type Res = def::Res<ast::NodeId>;
31 // FIXME: Merge this with `ParentScope`.
32 #[derive(Clone, Debug)]
33 pub struct InvocationData<'a> {
34 /// The module in which the macro was invoked.
35 crate module: Module<'a>,
36 /// The legacy scope in which the macro was invoked.
37 /// The invocation path is resolved in this scope.
38 crate parent_legacy_scope: LegacyScope<'a>,
39 /// The legacy scope *produced* by expanding this macro invocation,
40 /// includes all the macro_rules items, other invocations, etc generated by it.
41 /// `None` if the macro is not expanded yet.
42 crate output_legacy_scope: Cell<Option<LegacyScope<'a>>>,
45 impl<'a> InvocationData<'a> {
46 pub fn root(graph_root: Module<'a>) -> Self {
49 parent_legacy_scope: LegacyScope::Empty,
50 output_legacy_scope: Cell::new(None),
55 /// Binding produced by a `macro_rules` item.
56 /// Not modularized, can shadow previous legacy bindings, etc.
58 pub struct LegacyBinding<'a> {
59 crate binding: &'a NameBinding<'a>,
60 /// Legacy scope into which the `macro_rules` item was planted.
61 crate parent_legacy_scope: LegacyScope<'a>,
65 /// The scope introduced by a `macro_rules!` macro.
66 /// This starts at the macro's definition and ends at the end of the macro's parent
67 /// module (named or unnamed), or even further if it escapes with `#[macro_use]`.
68 /// Some macro invocations need to introduce legacy scopes too because they
69 /// can potentially expand into macro definitions.
70 #[derive(Copy, Clone, Debug)]
71 pub enum LegacyScope<'a> {
72 /// Empty "root" scope at the crate start containing no names.
74 /// The scope introduced by a `macro_rules!` macro definition.
75 Binding(&'a LegacyBinding<'a>),
76 /// The scope introduced by a macro invocation that can potentially
77 /// create a `macro_rules!` macro definition.
78 Invocation(&'a InvocationData<'a>),
81 // Macro namespace is separated into two sub-namespaces, one for bang macros and
82 // one for attribute-like macros (attributes, derives).
83 // We ignore resolutions from one sub-namespace when searching names in scope for another.
84 fn sub_namespace_match(candidate: Option<MacroKind>, requirement: Option<MacroKind>) -> bool {
86 enum SubNS { Bang, AttrLike }
87 let sub_ns = |kind| match kind {
88 MacroKind::Bang => SubNS::Bang,
89 MacroKind::Attr | MacroKind::Derive => SubNS::AttrLike,
91 let candidate = candidate.map(sub_ns);
92 let requirement = requirement.map(sub_ns);
93 // "No specific sub-namespace" means "matches anything" for both requirements and candidates.
94 candidate.is_none() || requirement.is_none() || candidate == requirement
97 // We don't want to format a path using pretty-printing,
98 // `format!("{}", path)`, because that tries to insert
99 // line-breaks and is slow.
100 fn fast_print_path(path: &ast::Path) -> Symbol {
101 if path.segments.len() == 1 {
102 return path.segments[0].ident.name
104 let mut path_str = String::with_capacity(64);
105 for (i, segment) in path.segments.iter().enumerate() {
107 path_str.push_str("::");
109 if segment.ident.name != kw::PathRoot {
110 path_str.push_str(&segment.ident.as_str())
113 Symbol::intern(&path_str)
117 impl<'a> base::Resolver for Resolver<'a> {
118 fn next_node_id(&mut self) -> ast::NodeId {
119 self.session.next_node_id()
122 fn get_module_scope(&mut self, id: ast::NodeId) -> ExpnId {
123 let span = DUMMY_SP.fresh_expansion(ExpnId::root(), ExpnInfo::default(
124 ExpnKind::Macro(MacroKind::Attr, sym::test_case), DUMMY_SP, self.session.edition()
126 let expn_id = span.ctxt().outer_expn();
127 let module = self.module_map[&self.definitions.local_def_id(id)];
128 self.definitions.set_invocation_parent(expn_id, module.def_id().unwrap().index);
129 self.invocations.insert(expn_id, self.arenas.alloc_invocation_data(InvocationData {
131 parent_legacy_scope: LegacyScope::Empty,
132 output_legacy_scope: Cell::new(None),
137 fn resolve_dollar_crates(&mut self) {
138 hygiene::update_dollar_crate_names(|ctxt| {
139 let ident = Ident::new(kw::DollarCrate, DUMMY_SP.with_ctxt(ctxt));
140 match self.resolve_crate_root(ident).kind {
141 ModuleKind::Def(.., name) if name != kw::Invalid => name,
147 fn visit_ast_fragment_with_placeholders(&mut self, expn_id: ExpnId, fragment: &AstFragment,
148 derives: &[ExpnId]) {
149 fragment.visit_with(&mut DefCollector::new(&mut self.definitions, expn_id));
151 let invocation = self.invocations[&expn_id];
152 invocation.module.unresolved_invocations.borrow_mut().remove(&expn_id);
153 invocation.module.unresolved_invocations.borrow_mut().extend(derives);
154 let parent_def = self.definitions.invocation_parent(expn_id);
155 for &derive_invoc_id in derives {
156 self.definitions.set_invocation_parent(derive_invoc_id, parent_def);
158 self.invocations.extend(derives.iter().map(|&derive| (derive, invocation)));
159 let mut visitor = BuildReducedGraphVisitor {
161 parent_scope: ParentScope {
162 module: invocation.module,
164 legacy: invocation.parent_legacy_scope,
168 fragment.visit_with(&mut visitor);
169 invocation.output_legacy_scope.set(Some(visitor.parent_scope.legacy));
172 fn register_builtin_macro(&mut self, ident: ast::Ident, ext: SyntaxExtension) {
173 if self.builtin_macros.insert(ident.name, ext).is_some() {
174 self.session.span_err(ident.span,
175 &format!("built-in macro `{}` was already defined", ident));
179 fn resolve_imports(&mut self) {
180 ImportResolver { r: self }.resolve_imports()
183 fn resolve_macro_invocation(&mut self, invoc: &Invocation, invoc_id: ExpnId, force: bool)
184 -> Result<Option<Lrc<SyntaxExtension>>, Indeterminate> {
185 let (path, kind, derives_in_scope, after_derive) = match invoc.kind {
186 InvocationKind::Attr { ref attr, ref derives, after_derive, .. } =>
187 (&attr.path, MacroKind::Attr, derives.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),
192 InvocationKind::DeriveContainer { ref derives, .. } => {
193 // Block expansion of derives in the container until we know whether one of them
194 // is a built-in `Copy`. Skip the resolution if there's only one derive - either
195 // it's not a `Copy` and we don't need to do anything, or it's a `Copy` and it
196 // will automatically knows about itself.
197 let mut result = Ok(None);
198 if derives.len() > 1 {
199 let parent_scope = &self.invoc_parent_scope(invoc_id, Vec::new());
200 for path in derives {
201 match self.resolve_macro_path(path, Some(MacroKind::Derive),
202 parent_scope, true, force) {
203 Ok((Some(ref ext), _)) if ext.is_derive_copy => {
204 self.add_derives(invoc.expansion_data.id, SpecialDerives::COPY);
207 Err(Determinacy::Undetermined) => result = Err(Indeterminate),
216 let parent_scope = &self.invoc_parent_scope(invoc_id, derives_in_scope);
217 let (ext, res) = self.smart_resolve_macro_path(path, kind, parent_scope, force)?;
219 let span = invoc.span();
220 invoc.expansion_data.id.set_expn_info(ext.expn_info(span, fast_print_path(path)));
222 if let Res::Def(_, def_id) = res {
224 self.session.span_err(span, "macro attributes must be placed before `#[derive]`");
226 self.macro_defs.insert(invoc.expansion_data.id, def_id);
227 let normal_module_def_id =
228 self.macro_def_scope(invoc.expansion_data.id).normal_ancestor_id;
229 self.definitions.add_parent_module_of_macro_def(invoc.expansion_data.id,
230 normal_module_def_id);
236 fn check_unused_macros(&self) {
237 for (&node_id, &span) in self.unused_macros.iter() {
238 self.session.buffer_lint(
239 lint::builtin::UNUSED_MACROS, node_id, span, "unused macro definition"
244 fn has_derives(&self, expn_id: ExpnId, derives: SpecialDerives) -> bool {
245 self.has_derives(expn_id, derives)
248 fn add_derives(&mut self, expn_id: ExpnId, derives: SpecialDerives) {
249 *self.special_derives.entry(expn_id).or_default() |= derives;
253 impl<'a> Resolver<'a> {
254 pub fn dummy_parent_scope(&self) -> ParentScope<'a> {
255 self.invoc_parent_scope(ExpnId::root(), Vec::new())
258 fn invoc_parent_scope(&self, invoc_id: ExpnId, derives: Vec<ast::Path>) -> ParentScope<'a> {
259 let invoc = self.invocations[&invoc_id];
261 module: invoc.module.nearest_item_scope(),
262 expansion: invoc_id.parent(),
263 legacy: invoc.parent_legacy_scope,
268 /// Resolve macro path with error reporting and recovery.
269 fn smart_resolve_macro_path(
273 parent_scope: &ParentScope<'a>,
275 ) -> Result<(Lrc<SyntaxExtension>, Res), Indeterminate> {
276 let (ext, res) = match self.resolve_macro_path(path, Some(kind), parent_scope,
278 Ok((Some(ext), res)) => (ext, res),
279 // Use dummy syntax extensions for unresolved macros for better recovery.
280 Ok((None, res)) => (self.dummy_ext(kind), res),
281 Err(Determinacy::Determined) => (self.dummy_ext(kind), Res::Err),
282 Err(Determinacy::Undetermined) => return Err(Indeterminate),
285 // Report errors and enforce feature gates for the resolved macro.
286 let features = self.session.features_untracked();
287 for segment in &path.segments {
288 if let Some(args) = &segment.args {
289 self.session.span_err(args.span(), "generic arguments in macro path");
291 if kind == MacroKind::Attr && !features.rustc_attrs &&
292 segment.ident.as_str().starts_with("rustc") {
294 "attributes starting with `rustc` are reserved for use by the `rustc` compiler";
296 &self.session.parse_sess,
306 Res::Def(DefKind::Macro(_), def_id) => {
307 if let Some(node_id) = self.definitions.as_local_node_id(def_id) {
308 self.unused_macros.remove(&node_id);
309 if self.proc_macro_stubs.contains(&node_id) {
310 self.session.span_err(
312 "can't use a procedural macro from the same crate that defines it",
317 Res::NonMacroAttr(..) | Res::Err => {}
318 _ => panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"),
321 self.check_stability_and_deprecation(&ext, path);
323 Ok(if ext.macro_kind() != kind {
324 let expected = if kind == MacroKind::Attr { "attribute" } else { kind.descr() };
325 let msg = format!("expected {}, found {} `{}`", expected, res.descr(), path);
326 self.session.struct_span_err(path.span, &msg)
327 .span_label(path.span, format!("not {} {}", kind.article(), expected))
329 // Use dummy syntax extensions for unexpected macro kinds for better recovery.
330 (self.dummy_ext(kind), Res::Err)
336 pub fn resolve_macro_path(
339 kind: Option<MacroKind>,
340 parent_scope: &ParentScope<'a>,
343 ) -> Result<(Option<Lrc<SyntaxExtension>>, Res), Determinacy> {
344 let path_span = path.span;
345 let mut path = Segment::from_path(path);
347 // Possibly apply the macro helper hack
348 if kind == Some(MacroKind::Bang) && path.len() == 1 &&
349 path[0].ident.span.ctxt().outer_expn_info()
350 .map_or(false, |info| info.local_inner_macros) {
351 let root = Ident::new(kw::DollarCrate, path[0].ident.span);
352 path.insert(0, Segment::from_ident(root));
355 let res = if path.len() > 1 {
356 let res = match self.resolve_path(&path, Some(MacroNS), parent_scope,
357 false, path_span, CrateLint::No) {
358 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
359 Ok(path_res.base_res())
361 PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
362 PathResult::NonModule(..)
363 | PathResult::Indeterminate
364 | PathResult::Failed { .. } => Err(Determinacy::Determined),
365 PathResult::Module(..) => unreachable!(),
369 let kind = kind.expect("macro kind must be specified if tracing is enabled");
370 parent_scope.module.multi_segment_macro_resolutions.borrow_mut()
371 .push((path, path_span, kind, parent_scope.clone(), res.ok()));
374 self.prohibit_imported_non_macro_attrs(None, res.ok(), path_span);
377 let scope_set = kind.map_or(ScopeSet::All(MacroNS, false), ScopeSet::Macro);
378 let binding = self.early_resolve_ident_in_lexical_scope(
379 path[0].ident, scope_set, parent_scope, false, force, path_span
381 if let Err(Determinacy::Undetermined) = binding {
382 return Err(Determinacy::Undetermined);
386 let kind = kind.expect("macro kind must be specified if tracing is enabled");
387 parent_scope.module.single_segment_macro_resolutions.borrow_mut()
388 .push((path[0].ident, kind, parent_scope.clone(), binding.ok()));
391 let res = binding.map(|binding| binding.res());
392 self.prohibit_imported_non_macro_attrs(binding.ok(), res.ok(), path_span);
396 res.map(|res| (self.get_macro(res), res))
399 // Resolve an identifier in lexical scope.
400 // This is a variation of `fn resolve_ident_in_lexical_scope` that can be run during
401 // expansion and import resolution (perhaps they can be merged in the future).
402 // The function is used for resolving initial segments of macro paths (e.g., `foo` in
403 // `foo::bar!(); or `foo!();`) and also for import paths on 2018 edition.
404 crate fn early_resolve_ident_in_lexical_scope(
408 parent_scope: &ParentScope<'a>,
412 ) -> Result<&'a NameBinding<'a>, Determinacy> {
413 bitflags::bitflags! {
415 const MACRO_RULES = 1 << 0;
416 const MODULE = 1 << 1;
417 const PRELUDE = 1 << 2;
418 const MISC_SUGGEST_CRATE = 1 << 3;
419 const MISC_SUGGEST_SELF = 1 << 4;
420 const MISC_FROM_PRELUDE = 1 << 5;
424 assert!(force || !record_used); // `record_used` implies `force`
426 // Make sure `self`, `super` etc produce an error when passed to here.
427 if orig_ident.is_path_segment_keyword() {
428 return Err(Determinacy::Determined);
431 let (ns, macro_kind, is_import) = match scope_set {
432 ScopeSet::All(ns, is_import) => (ns, None, is_import),
433 ScopeSet::AbsolutePath(ns) => (ns, None, false),
434 ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind), false),
437 // This is *the* result, resolution from the scope closest to the resolved identifier.
438 // However, sometimes this result is "weak" because it comes from a glob import or
439 // a macro expansion, and in this case it cannot shadow names from outer scopes, e.g.
440 // mod m { ... } // solution in outer scope
442 // use prefix::*; // imports another `m` - innermost solution
443 // // weak, cannot shadow the outer `m`, need to report ambiguity error
446 // So we have to save the innermost solution and continue searching in outer scopes
447 // to detect potential ambiguities.
448 let mut innermost_result: Option<(&NameBinding<'_>, Flags)> = None;
449 let mut determinacy = Determinacy::Determined;
451 // Go through all the scopes and try to resolve the name.
452 let break_result = self.visit_scopes(scope_set, parent_scope, orig_ident,
453 |this, scope, use_prelude, ident| {
454 let result = match scope {
455 Scope::DeriveHelpers => {
456 let mut result = Err(Determinacy::Determined);
457 for derive in &parent_scope.derives {
458 let parent_scope = &ParentScope { derives: Vec::new(), ..*parent_scope };
459 match this.resolve_macro_path(derive, Some(MacroKind::Derive),
460 parent_scope, true, force) {
461 Ok((Some(ext), _)) => if ext.helper_attrs.contains(&ident.name) {
462 let binding = (Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper),
463 ty::Visibility::Public, derive.span, ExpnId::root())
464 .to_name_binding(this.arenas);
465 result = Ok((binding, Flags::empty()));
468 Ok(_) | Err(Determinacy::Determined) => {}
469 Err(Determinacy::Undetermined) =>
470 result = Err(Determinacy::Undetermined),
475 Scope::MacroRules(legacy_scope) => match legacy_scope {
476 LegacyScope::Binding(legacy_binding) if ident == legacy_binding.ident =>
477 Ok((legacy_binding.binding, Flags::MACRO_RULES)),
478 LegacyScope::Invocation(invoc) if invoc.output_legacy_scope.get().is_none() =>
479 Err(Determinacy::Undetermined),
480 _ => Err(Determinacy::Determined),
482 Scope::CrateRoot => {
483 let root_ident = Ident::new(kw::PathRoot, ident.span);
484 let root_module = this.resolve_crate_root(root_ident);
485 let binding = this.resolve_ident_in_module_ext(
486 ModuleOrUniformRoot::Module(root_module),
494 Ok(binding) => Ok((binding, Flags::MODULE | Flags::MISC_SUGGEST_CRATE)),
495 Err((Determinacy::Undetermined, Weak::No)) =>
496 return Some(Err(Determinacy::determined(force))),
497 Err((Determinacy::Undetermined, Weak::Yes)) =>
498 Err(Determinacy::Undetermined),
499 Err((Determinacy::Determined, _)) => Err(Determinacy::Determined),
502 Scope::Module(module) => {
503 let adjusted_parent_scope = &ParentScope { module, ..parent_scope.clone() };
504 let binding = this.resolve_ident_in_module_unadjusted_ext(
505 ModuleOrUniformRoot::Module(module),
508 adjusted_parent_scope,
515 let misc_flags = if ptr::eq(module, this.graph_root) {
516 Flags::MISC_SUGGEST_CRATE
517 } else if module.is_normal() {
518 Flags::MISC_SUGGEST_SELF
522 Ok((binding, Flags::MODULE | misc_flags))
524 Err((Determinacy::Undetermined, Weak::No)) =>
525 return Some(Err(Determinacy::determined(force))),
526 Err((Determinacy::Undetermined, Weak::Yes)) =>
527 Err(Determinacy::Undetermined),
528 Err((Determinacy::Determined, _)) => Err(Determinacy::Determined),
531 Scope::MacroUsePrelude => match this.macro_use_prelude.get(&ident.name).cloned() {
532 Some(binding) => Ok((binding, Flags::PRELUDE | Flags::MISC_FROM_PRELUDE)),
533 None => Err(Determinacy::determined(
534 this.graph_root.unresolved_invocations.borrow().is_empty()
537 Scope::BuiltinAttrs => if is_builtin_attr_name(ident.name) {
538 let binding = (Res::NonMacroAttr(NonMacroAttrKind::Builtin),
539 ty::Visibility::Public, DUMMY_SP, ExpnId::root())
540 .to_name_binding(this.arenas);
541 Ok((binding, Flags::PRELUDE))
543 Err(Determinacy::Determined)
545 Scope::LegacyPluginHelpers => if this.session.plugin_attributes.borrow().iter()
546 .any(|(name, _)| ident.name == *name) {
547 let binding = (Res::NonMacroAttr(NonMacroAttrKind::LegacyPluginHelper),
548 ty::Visibility::Public, DUMMY_SP, ExpnId::root())
549 .to_name_binding(this.arenas);
550 Ok((binding, Flags::PRELUDE))
552 Err(Determinacy::Determined)
554 Scope::ExternPrelude => match this.extern_prelude_get(ident, !record_used) {
555 Some(binding) => Ok((binding, Flags::PRELUDE)),
556 None => Err(Determinacy::determined(
557 this.graph_root.unresolved_invocations.borrow().is_empty()
560 Scope::ToolPrelude => if KNOWN_TOOLS.contains(&ident.name) {
561 let binding = (Res::ToolMod, ty::Visibility::Public, DUMMY_SP, ExpnId::root())
562 .to_name_binding(this.arenas);
563 Ok((binding, Flags::PRELUDE))
565 Err(Determinacy::Determined)
567 Scope::StdLibPrelude => {
568 let mut result = Err(Determinacy::Determined);
569 if let Some(prelude) = this.prelude {
570 if let Ok(binding) = this.resolve_ident_in_module_unadjusted(
571 ModuleOrUniformRoot::Module(prelude),
578 if use_prelude || this.is_builtin_macro(binding.res().opt_def_id()) {
579 result = Ok((binding, Flags::PRELUDE | Flags::MISC_FROM_PRELUDE));
585 Scope::BuiltinTypes => match this.primitive_type_table.primitive_types
586 .get(&ident.name).cloned() {
588 let binding = (Res::PrimTy(prim_ty), ty::Visibility::Public,
589 DUMMY_SP, ExpnId::root()).to_name_binding(this.arenas);
590 Ok((binding, Flags::PRELUDE))
592 None => Err(Determinacy::Determined)
597 Ok((binding, flags)) if sub_namespace_match(binding.macro_kind(), macro_kind) => {
599 return Some(Ok(binding));
602 if let Some((innermost_binding, innermost_flags)) = innermost_result {
603 // Found another solution, if the first one was "weak", report an error.
604 let (res, innermost_res) = (binding.res(), innermost_binding.res());
605 if res != innermost_res {
606 let builtin = Res::NonMacroAttr(NonMacroAttrKind::Builtin);
607 let derive_helper = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
609 Res::NonMacroAttr(NonMacroAttrKind::LegacyPluginHelper);
611 let ambiguity_error_kind = if is_import {
612 Some(AmbiguityKind::Import)
613 } else if innermost_res == builtin || res == builtin {
614 Some(AmbiguityKind::BuiltinAttr)
615 } else if innermost_res == derive_helper || res == derive_helper {
616 Some(AmbiguityKind::DeriveHelper)
617 } else if innermost_res == legacy_helper &&
618 flags.contains(Flags::PRELUDE) ||
619 res == legacy_helper &&
620 innermost_flags.contains(Flags::PRELUDE) {
621 Some(AmbiguityKind::LegacyHelperVsPrelude)
622 } else if innermost_flags.contains(Flags::MACRO_RULES) &&
623 flags.contains(Flags::MODULE) &&
624 !this.disambiguate_legacy_vs_modern(innermost_binding,
626 flags.contains(Flags::MACRO_RULES) &&
627 innermost_flags.contains(Flags::MODULE) &&
628 !this.disambiguate_legacy_vs_modern(binding,
630 Some(AmbiguityKind::LegacyVsModern)
631 } else if innermost_binding.is_glob_import() {
632 Some(AmbiguityKind::GlobVsOuter)
633 } else if innermost_binding.may_appear_after(parent_scope.expansion,
635 Some(AmbiguityKind::MoreExpandedVsOuter)
639 if let Some(kind) = ambiguity_error_kind {
640 let misc = |f: Flags| if f.contains(Flags::MISC_SUGGEST_CRATE) {
641 AmbiguityErrorMisc::SuggestCrate
642 } else if f.contains(Flags::MISC_SUGGEST_SELF) {
643 AmbiguityErrorMisc::SuggestSelf
644 } else if f.contains(Flags::MISC_FROM_PRELUDE) {
645 AmbiguityErrorMisc::FromPrelude
647 AmbiguityErrorMisc::None
649 this.ambiguity_errors.push(AmbiguityError {
652 b1: innermost_binding,
654 misc1: misc(innermost_flags),
657 return Some(Ok(innermost_binding));
661 // Found the first solution.
662 innermost_result = Some((binding, flags));
665 Ok(..) | Err(Determinacy::Determined) => {}
666 Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined
672 if let Some(break_result) = break_result {
676 // The first found solution was the only one, return it.
677 if let Some((binding, _)) = innermost_result {
681 let determinacy = Determinacy::determined(determinacy == Determinacy::Determined || force);
682 if determinacy == Determinacy::Determined && macro_kind == Some(MacroKind::Attr) &&
683 self.session.features_untracked().custom_attribute {
684 // For single-segment attributes interpret determinate "no resolution" as a custom
685 // attribute. (Lexical resolution implies the first segment and attr kind should imply
686 // the last segment, so we are certainly working with a single-segment attribute here.)
687 assert!(ns == MacroNS);
688 let binding = (Res::NonMacroAttr(NonMacroAttrKind::Custom),
689 ty::Visibility::Public, orig_ident.span, ExpnId::root())
690 .to_name_binding(self.arenas);
697 pub fn finalize_current_module_macro_resolutions(&mut self, module: Module<'a>) {
698 let check_consistency = |this: &mut Self, path: &[Segment], span, kind: MacroKind,
699 initial_res: Option<Res>, res: Res| {
700 if let Some(initial_res) = initial_res {
701 if res != initial_res && res != Res::Err && this.ambiguity_errors.is_empty() {
702 // Make sure compilation does not succeed if preferred macro resolution
703 // has changed after the macro had been expanded. In theory all such
704 // situations should be reported as ambiguity errors, so this is a bug.
705 if initial_res == Res::NonMacroAttr(NonMacroAttrKind::Custom) {
706 // Yeah, legacy custom attributes are implemented using forced resolution
707 // (which is a best effort error recovery tool, basically), so we can't
708 // promise their resolution won't change later.
709 let msg = format!("inconsistent resolution for a macro: first {}, then {}",
710 initial_res.descr(), res.descr());
711 this.session.span_err(span, &msg);
713 span_bug!(span, "inconsistent resolution for a macro");
717 // It's possible that the macro was unresolved (indeterminate) and silently
718 // expanded into a dummy fragment for recovery during expansion.
719 // Now, post-expansion, the resolution may succeed, but we can't change the
720 // past and need to report an error.
721 // However, non-speculative `resolve_path` can successfully return private items
722 // even if speculative `resolve_path` returned nothing previously, so we skip this
723 // less informative error if the privacy error is reported elsewhere.
724 if this.privacy_errors.is_empty() {
725 let msg = format!("cannot determine resolution for the {} `{}`",
726 kind.descr(), Segment::names_to_string(path));
727 let msg_note = "import resolution is stuck, try simplifying macro imports";
728 this.session.struct_span_err(span, &msg).note(msg_note).emit();
733 let macro_resolutions =
734 mem::take(&mut *module.multi_segment_macro_resolutions.borrow_mut());
735 for (mut path, path_span, kind, parent_scope, initial_res) in macro_resolutions {
736 // FIXME: Path resolution will ICE if segment IDs present.
737 for seg in &mut path { seg.id = None; }
738 match self.resolve_path(
739 &path, Some(MacroNS), &parent_scope, true, path_span, CrateLint::No
741 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
742 let res = path_res.base_res();
743 check_consistency(self, &path, path_span, kind, initial_res, res);
745 path_res @ PathResult::NonModule(..) | path_res @ PathResult::Failed { .. } => {
746 let (span, label) = if let PathResult::Failed { span, label, .. } = path_res {
749 (path_span, format!("partially resolved path in {} {}",
750 kind.article(), kind.descr()))
752 self.report_error(span, ResolutionError::FailedToResolve {
757 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
761 let macro_resolutions =
762 mem::take(&mut *module.single_segment_macro_resolutions.borrow_mut());
763 for (ident, kind, parent_scope, initial_binding) in macro_resolutions {
764 match self.early_resolve_ident_in_lexical_scope(ident, ScopeSet::Macro(kind),
765 &parent_scope, true, true, ident.span) {
767 let initial_res = initial_binding.map(|initial_binding| {
768 self.record_use(ident, MacroNS, initial_binding, false);
769 initial_binding.res()
771 let res = binding.res();
772 let seg = Segment::from_ident(ident);
773 check_consistency(self, &[seg], ident.span, kind, initial_res, res);
776 assert!(initial_binding.is_none());
777 let bang = if kind == MacroKind::Bang { "!" } else { "" };
779 format!("cannot find {} `{}{}` in this scope", kind.descr(), ident, bang);
780 let mut err = self.session.struct_span_err(ident.span, &msg);
781 self.unresolved_macro_suggestions(&mut err, kind, &parent_scope, ident);
787 let builtin_attrs = mem::take(&mut *module.builtin_attrs.borrow_mut());
788 for (ident, parent_scope) in builtin_attrs {
789 let _ = self.early_resolve_ident_in_lexical_scope(
790 ident, ScopeSet::Macro(MacroKind::Attr), &parent_scope, true, true, ident.span
795 fn check_stability_and_deprecation(&self, ext: &SyntaxExtension, path: &ast::Path) {
796 let span = path.span;
797 if let Some(stability) = &ext.stability {
798 if let StabilityLevel::Unstable { reason, issue } = stability.level {
799 let feature = stability.feature;
800 if !self.active_features.contains(&feature) && !span.allows_unstable(feature) {
801 stability::report_unstable(self.session, feature, reason, issue, span);
804 if let Some(depr) = &stability.rustc_depr {
805 let (message, lint) = stability::rustc_deprecation_message(depr, &path.to_string());
806 stability::early_report_deprecation(
807 self.session, &message, depr.suggestion, lint, span
811 if let Some(depr) = &ext.deprecation {
812 let (message, lint) = stability::deprecation_message(depr, &path.to_string());
813 stability::early_report_deprecation(self.session, &message, None, lint, span);
817 fn prohibit_imported_non_macro_attrs(&self, binding: Option<&'a NameBinding<'a>>,
818 res: Option<Res>, span: Span) {
819 if let Some(Res::NonMacroAttr(kind)) = res {
820 if kind != NonMacroAttrKind::Tool && binding.map_or(true, |b| b.is_import()) {
821 let msg = format!("cannot use a {} through an import", kind.descr());
822 let mut err = self.session.struct_span_err(span, &msg);
823 if let Some(binding) = binding {
824 err.span_note(binding.span, &format!("the {} imported here", kind.descr()));
831 crate fn check_reserved_macro_name(&mut self, ident: Ident, res: Res) {
832 // Reserve some names that are not quite covered by the general check
833 // performed on `Resolver::builtin_attrs`.
834 if ident.name == sym::cfg || ident.name == sym::cfg_attr || ident.name == sym::derive {
835 let macro_kind = self.get_macro(res).map(|ext| ext.macro_kind());
836 if macro_kind.is_some() && sub_namespace_match(macro_kind, Some(MacroKind::Attr)) {
837 self.session.span_err(
838 ident.span, &format!("name `{}` is reserved in attribute namespace", ident)
844 /// Compile the macro into a `SyntaxExtension` and possibly replace it with a pre-defined
845 /// extension partially or entirely for built-in macros and legacy plugin macros.
846 crate fn compile_macro(&mut self, item: &ast::Item, edition: Edition) -> Lrc<SyntaxExtension> {
847 let mut result = macro_rules::compile(
848 &self.session.parse_sess, self.session.features_untracked(), item, edition
851 if result.is_builtin {
852 // The macro was marked with `#[rustc_builtin_macro]`.
853 if let Some(ext) = self.builtin_macros.remove(&item.ident.name) {
855 // The macro is a built-in, replace only the expander function.
856 result.kind = ext.kind;
858 // The macro is from a plugin, the in-source definition is dummy,
859 // take all the data from the resolver.
863 let msg = format!("cannot find a built-in macro with name `{}`", item.ident);
864 self.session.span_err(item.span, &msg);