1 //! A bunch of methods and structures more or less related to resolving macros and
2 //! interface provided by `Resolver` to macro expander.
4 use crate::imports::ImportResolver;
5 use crate::Namespace::*;
6 use crate::{BuiltinMacroState, Determinacy};
7 use crate::{DeriveData, Finalize, ParentScope, ResolutionError, Resolver, ScopeSet};
8 use crate::{ModuleKind, ModuleOrUniformRoot, NameBinding, PathResult, Segment};
9 use rustc_ast::{self as ast, Inline, ItemKind, ModKind, NodeId};
10 use rustc_ast_pretty::pprust;
11 use rustc_attr::StabilityLevel;
12 use rustc_data_structures::fx::FxHashSet;
13 use rustc_data_structures::intern::Interned;
14 use rustc_data_structures::sync::Lrc;
15 use rustc_errors::{struct_span_err, Applicability};
16 use rustc_expand::base::{Annotatable, DeriveResolutions, Indeterminate, ResolverExpand};
17 use rustc_expand::base::{SyntaxExtension, SyntaxExtensionKind};
18 use rustc_expand::compile_declarative_macro;
19 use rustc_expand::expand::{AstFragment, Invocation, InvocationKind, SupportsMacroExpansion};
20 use rustc_hir::def::{self, DefKind, NonMacroAttrKind};
21 use rustc_hir::def_id::{CrateNum, LocalDefId};
22 use rustc_middle::middle::stability;
23 use rustc_middle::ty::RegisteredTools;
24 use rustc_session::lint::builtin::{LEGACY_DERIVE_HELPERS, SOFT_UNSTABLE};
25 use rustc_session::lint::builtin::{UNUSED_MACROS, UNUSED_MACRO_RULES};
26 use rustc_session::lint::BuiltinLintDiagnostics;
27 use rustc_session::parse::feature_err;
28 use rustc_session::Session;
29 use rustc_span::edition::Edition;
30 use rustc_span::hygiene::{self, ExpnData, ExpnKind, LocalExpnId};
31 use rustc_span::hygiene::{AstPass, MacroKind};
32 use rustc_span::symbol::{kw, sym, Ident, Symbol};
33 use rustc_span::{Span, DUMMY_SP};
37 type Res = def::Res<NodeId>;
39 /// Binding produced by a `macro_rules` item.
40 /// Not modularized, can shadow previous `macro_rules` bindings, etc.
42 pub struct MacroRulesBinding<'a> {
43 pub(crate) binding: &'a NameBinding<'a>,
44 /// `macro_rules` scope into which the `macro_rules` item was planted.
45 pub(crate) parent_macro_rules_scope: MacroRulesScopeRef<'a>,
46 pub(crate) ident: Ident,
49 /// The scope introduced by a `macro_rules!` macro.
50 /// This starts at the macro's definition and ends at the end of the macro's parent
51 /// module (named or unnamed), or even further if it escapes with `#[macro_use]`.
52 /// Some macro invocations need to introduce `macro_rules` scopes too because they
53 /// can potentially expand into macro definitions.
54 #[derive(Copy, Clone, Debug)]
55 pub enum MacroRulesScope<'a> {
56 /// Empty "root" scope at the crate start containing no names.
58 /// The scope introduced by a `macro_rules!` macro definition.
59 Binding(&'a MacroRulesBinding<'a>),
60 /// The scope introduced by a macro invocation that can potentially
61 /// create a `macro_rules!` macro definition.
62 Invocation(LocalExpnId),
65 /// `macro_rules!` scopes are always kept by reference and inside a cell.
66 /// The reason is that we update scopes with value `MacroRulesScope::Invocation(invoc_id)`
67 /// in-place after `invoc_id` gets expanded.
68 /// This helps to avoid uncontrollable growth of `macro_rules!` scope chains,
69 /// which usually grow linearly with the number of macro invocations
70 /// in a module (including derives) and hurt performance.
71 pub(crate) type MacroRulesScopeRef<'a> = Interned<'a, Cell<MacroRulesScope<'a>>>;
73 /// Macro namespace is separated into two sub-namespaces, one for bang macros and
74 /// one for attribute-like macros (attributes, derives).
75 /// We ignore resolutions from one sub-namespace when searching names in scope for another.
76 pub(crate) fn sub_namespace_match(
77 candidate: Option<MacroKind>,
78 requirement: Option<MacroKind>,
85 let sub_ns = |kind| match kind {
86 MacroKind::Bang => SubNS::Bang,
87 MacroKind::Attr | MacroKind::Derive => SubNS::AttrLike,
89 let candidate = candidate.map(sub_ns);
90 let requirement = requirement.map(sub_ns);
91 // "No specific sub-namespace" means "matches anything" for both requirements and candidates.
92 candidate.is_none() || requirement.is_none() || candidate == requirement
95 // We don't want to format a path using pretty-printing,
96 // `format!("{}", path)`, because that tries to insert
97 // line-breaks and is slow.
98 fn fast_print_path(path: &ast::Path) -> Symbol {
99 if path.segments.len() == 1 {
100 path.segments[0].ident.name
102 let mut path_str = String::with_capacity(64);
103 for (i, segment) in path.segments.iter().enumerate() {
105 path_str.push_str("::");
107 if segment.ident.name != kw::PathRoot {
108 path_str.push_str(segment.ident.as_str())
111 Symbol::intern(&path_str)
115 pub(crate) fn registered_tools(sess: &Session, attrs: &[ast::Attribute]) -> FxHashSet<Ident> {
116 let mut registered_tools = FxHashSet::default();
117 for attr in sess.filter_by_name(attrs, sym::register_tool) {
118 for nested_meta in attr.meta_item_list().unwrap_or_default() {
119 match nested_meta.ident() {
121 if let Some(old_ident) = registered_tools.replace(ident) {
122 let msg = format!("{} `{}` was already registered", "tool", ident);
123 sess.struct_span_err(ident.span, &msg)
124 .span_label(old_ident.span, "already registered here")
129 let msg = format!("`{}` only accepts identifiers", sym::register_tool);
130 let span = nested_meta.span();
131 sess.struct_span_err(span, &msg).span_label(span, "not an identifier").emit();
136 // We implicitly add `rustfmt` and `clippy` to known tools,
137 // but it's not an error to register them explicitly.
138 let predefined_tools = [sym::clippy, sym::rustfmt];
139 registered_tools.extend(predefined_tools.iter().cloned().map(Ident::with_dummy_span));
143 // Some feature gates for inner attributes are reported as lints for backward compatibility.
144 fn soft_custom_inner_attributes_gate(path: &ast::Path, invoc: &Invocation) -> bool {
145 match &path.segments[..] {
147 [seg] if seg.ident.name == sym::test => return true,
148 // `#![rustfmt::skip]` on out-of-line modules
149 [seg1, seg2] if seg1.ident.name == sym::rustfmt && seg2.ident.name == sym::skip => {
150 if let InvocationKind::Attr { item, .. } = &invoc.kind {
151 if let Annotatable::Item(item) = item {
152 if let ItemKind::Mod(_, ModKind::Loaded(_, Inline::No, _)) = item.kind {
163 impl<'a> ResolverExpand for Resolver<'a> {
164 fn next_node_id(&mut self) -> NodeId {
168 fn invocation_parent(&self, id: LocalExpnId) -> LocalDefId {
169 self.invocation_parents[&id].0
172 fn resolve_dollar_crates(&mut self) {
173 hygiene::update_dollar_crate_names(|ctxt| {
174 let ident = Ident::new(kw::DollarCrate, DUMMY_SP.with_ctxt(ctxt));
175 match self.resolve_crate_root(ident).kind {
176 ModuleKind::Def(.., name) if name != kw::Empty => name,
182 fn visit_ast_fragment_with_placeholders(
184 expansion: LocalExpnId,
185 fragment: &AstFragment,
187 // Integrate the new AST fragment into all the definition and module structures.
188 // We are inside the `expansion` now, but other parent scope components are still the same.
189 let parent_scope = ParentScope { expansion, ..self.invocation_parent_scopes[&expansion] };
190 let output_macro_rules_scope = self.build_reduced_graph(fragment, parent_scope);
191 self.output_macro_rules_scopes.insert(expansion, output_macro_rules_scope);
193 parent_scope.module.unexpanded_invocations.borrow_mut().remove(&expansion);
196 fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind) {
197 if self.builtin_macros.insert(name, BuiltinMacroState::NotYetSeen(ext)).is_some() {
200 .bug(&format!("built-in macro `{}` was already registered", name));
204 // Create a new Expansion with a definition site of the provided module, or
205 // a fake empty `#[no_implicit_prelude]` module if no module is provided.
206 fn expansion_for_ast_pass(
211 parent_module_id: Option<NodeId>,
214 parent_module_id.map(|module_id| self.local_def_id(module_id).to_def_id());
215 let expn_id = LocalExpnId::fresh(
216 ExpnData::allow_unstable(
217 ExpnKind::AstPass(pass),
219 self.session.edition(),
224 self.create_stable_hashing_context(),
228 parent_module.map_or(self.empty_module, |def_id| self.expect_module(def_id));
229 self.ast_transform_scopes.insert(expn_id, parent_scope);
234 fn resolve_imports(&mut self) {
235 ImportResolver { r: self }.resolve_imports()
238 fn resolve_macro_invocation(
241 eager_expansion_root: LocalExpnId,
243 ) -> Result<Lrc<SyntaxExtension>, Indeterminate> {
244 let invoc_id = invoc.expansion_data.id;
245 let parent_scope = match self.invocation_parent_scopes.get(&invoc_id) {
246 Some(parent_scope) => *parent_scope,
248 // If there's no entry in the table, then we are resolving an eagerly expanded
249 // macro, which should inherit its parent scope from its eager expansion root -
250 // the macro that requested this eager expansion.
251 let parent_scope = *self
252 .invocation_parent_scopes
253 .get(&eager_expansion_root)
254 .expect("non-eager expansion without a parent scope");
255 self.invocation_parent_scopes.insert(invoc_id, parent_scope);
260 let (path, kind, inner_attr, derives) = match invoc.kind {
261 InvocationKind::Attr { ref attr, ref derives, .. } => (
262 &attr.get_normal_item().path,
264 attr.style == ast::AttrStyle::Inner,
265 self.arenas.alloc_ast_paths(derives),
267 InvocationKind::Bang { ref mac, .. } => (&mac.path, MacroKind::Bang, false, &[][..]),
268 InvocationKind::Derive { ref path, .. } => (path, MacroKind::Derive, false, &[][..]),
271 // Derives are not included when `invocations` are collected, so we have to add them here.
272 let parent_scope = &ParentScope { derives, ..parent_scope };
273 let supports_macro_expansion = invoc.fragment_kind.supports_macro_expansion();
274 let node_id = invoc.expansion_data.lint_node_id;
275 let (ext, res) = self.smart_resolve_macro_path(
278 supports_macro_expansion,
283 soft_custom_inner_attributes_gate(path, invoc),
286 let span = invoc.span();
287 let def_id = res.opt_def_id();
288 invoc_id.set_expn_data(
290 parent_scope.expansion,
292 fast_print_path(path),
294 def_id.map(|def_id| self.macro_def_scope(def_id).nearest_parent_mod()),
296 self.create_stable_hashing_context(),
302 fn record_macro_rule_usage(&mut self, id: NodeId, rule_i: usize) {
303 let did = self.local_def_id(id);
304 self.unused_macro_rules.remove(&(did, rule_i));
307 fn check_unused_macros(&mut self) {
308 for (_, &(node_id, ident)) in self.unused_macros.iter() {
309 self.lint_buffer.buffer_lint(
313 &format!("unused macro definition: `{}`", ident.name),
316 for (&(def_id, arm_i), &(ident, rule_span)) in self.unused_macro_rules.iter() {
317 if self.unused_macros.contains_key(&def_id) {
318 // We already lint the entire macro as unused
321 let node_id = self.def_id_to_node_id[def_id];
322 self.lint_buffer.buffer_lint(
327 "{} rule of macro `{}` is never used",
328 crate::diagnostics::ordinalize(arm_i + 1),
335 fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool {
336 self.containers_deriving_copy.contains(&expn_id)
341 expn_id: LocalExpnId,
343 derive_paths: &dyn Fn() -> DeriveResolutions,
344 ) -> Result<(), Indeterminate> {
345 // Block expansion of the container until we resolve all derives in it.
346 // This is required for two reasons:
347 // - Derive helper attributes are in scope for the item to which the `#[derive]`
348 // is applied, so they have to be produced by the container's expansion rather
349 // than by individual derives.
350 // - Derives in the container need to know whether one of them is a built-in `Copy`.
351 // Temporarily take the data to avoid borrow checker conflicts.
352 let mut derive_data = mem::take(&mut self.derive_data);
353 let entry = derive_data.entry(expn_id).or_insert_with(|| DeriveData {
354 resolutions: derive_paths(),
355 helper_attrs: Vec::new(),
356 has_derive_copy: false,
358 let parent_scope = self.invocation_parent_scopes[&expn_id];
359 for (i, (path, _, opt_ext)) in entry.resolutions.iter_mut().enumerate() {
360 if opt_ext.is_none() {
362 match self.resolve_macro_path(
364 Some(MacroKind::Derive),
369 Ok((Some(ext), _)) => {
370 if !ext.helper_attrs.is_empty() {
371 let last_seg = path.segments.last().unwrap();
372 let span = last_seg.ident.span.normalize_to_macros_2_0();
373 entry.helper_attrs.extend(
376 .map(|name| (i, Ident::new(*name, span))),
379 entry.has_derive_copy |= ext.builtin_name == Some(sym::Copy);
382 Ok(_) | Err(Determinacy::Determined) => self.dummy_ext(MacroKind::Derive),
383 Err(Determinacy::Undetermined) => {
384 assert!(self.derive_data.is_empty());
385 self.derive_data = derive_data;
386 return Err(Indeterminate);
392 // Sort helpers in a stable way independent from the derive resolution order.
393 entry.helper_attrs.sort_by_key(|(i, _)| *i);
395 .insert(expn_id, entry.helper_attrs.iter().map(|(_, ident)| *ident).collect());
396 // Mark this derive as having `Copy` either if it has `Copy` itself or if its parent derive
397 // has `Copy`, to support cases like `#[derive(Clone, Copy)] #[derive(Debug)]`.
398 if entry.has_derive_copy || self.has_derive_copy(parent_scope.expansion) {
399 self.containers_deriving_copy.insert(expn_id);
401 assert!(self.derive_data.is_empty());
402 self.derive_data = derive_data;
406 fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<DeriveResolutions> {
407 self.derive_data.remove(&expn_id).map(|data| data.resolutions)
410 // The function that implements the resolution logic of `#[cfg_accessible(path)]`.
411 // Returns true if the path can certainly be resolved in one of three namespaces,
412 // returns false if the path certainly cannot be resolved in any of the three namespaces.
413 // Returns `Indeterminate` if we cannot give a certain answer yet.
416 expn_id: LocalExpnId,
418 ) -> Result<bool, Indeterminate> {
419 let span = path.span;
420 let path = &Segment::from_path(path);
421 let parent_scope = self.invocation_parent_scopes[&expn_id];
423 let mut indeterminate = false;
424 for ns in [TypeNS, ValueNS, MacroNS].iter().copied() {
425 match self.maybe_resolve_path(path, Some(ns), &parent_scope) {
426 PathResult::Module(ModuleOrUniformRoot::Module(_)) => return Ok(true),
427 PathResult::NonModule(partial_res) if partial_res.unresolved_segments() == 0 => {
430 PathResult::NonModule(..) |
431 // HACK(Urgau): This shouldn't be necessary
432 PathResult::Failed { is_error_from_last_segment: false, .. } => {
434 .struct_span_err(span, "not sure whether the path is accessible or not")
435 .note("the type may have associated items, but we are currently not checking them")
438 // If we get a partially resolved NonModule in one namespace, we should get the
439 // same result in any other namespaces, so we can return early.
442 PathResult::Indeterminate => indeterminate = true,
443 // We can only be sure that a path doesn't exist after having tested all the
444 // possibilities, only at that time we can return false.
445 PathResult::Failed { .. } => {}
446 PathResult::Module(_) => panic!("unexpected path resolution"),
451 return Err(Indeterminate);
457 fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span {
458 self.crate_loader.cstore().get_proc_macro_quoted_span_untracked(krate, id, self.session)
461 fn declare_proc_macro(&mut self, id: NodeId) {
462 self.proc_macros.push(id)
465 fn registered_tools(&self) -> &RegisteredTools {
466 &self.registered_tools
470 impl<'a> Resolver<'a> {
471 /// Resolve macro path with error reporting and recovery.
472 /// Uses dummy syntax extensions for unresolved macros or macros with unexpected resolutions
473 /// for better error recovery.
474 fn smart_resolve_macro_path(
478 supports_macro_expansion: SupportsMacroExpansion,
480 parent_scope: &ParentScope<'a>,
483 soft_custom_inner_attributes_gate: bool,
484 ) -> Result<(Lrc<SyntaxExtension>, Res), Indeterminate> {
485 let (ext, res) = match self.resolve_macro_path(path, Some(kind), parent_scope, true, force)
487 Ok((Some(ext), res)) => (ext, res),
488 Ok((None, res)) => (self.dummy_ext(kind), res),
489 Err(Determinacy::Determined) => (self.dummy_ext(kind), Res::Err),
490 Err(Determinacy::Undetermined) => return Err(Indeterminate),
493 // Report errors for the resolved macro.
494 for segment in &path.segments {
495 if let Some(args) = &segment.args {
496 self.session.span_err(args.span(), "generic arguments in macro path");
498 if kind == MacroKind::Attr && segment.ident.as_str().starts_with("rustc") {
499 self.session.span_err(
501 "attributes starting with `rustc` are reserved for use by the `rustc` compiler",
507 Res::Def(DefKind::Macro(_), def_id) => {
508 if let Some(def_id) = def_id.as_local() {
509 self.unused_macros.remove(&def_id);
510 if self.proc_macro_stubs.contains(&def_id) {
511 self.session.span_err(
513 "can't use a procedural macro from the same crate that defines it",
518 Res::NonMacroAttr(..) | Res::Err => {}
519 _ => panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"),
522 self.check_stability_and_deprecation(&ext, path, node_id);
524 let unexpected_res = if ext.macro_kind() != kind {
525 Some((kind.article(), kind.descr_expected()))
526 } else if matches!(res, Res::Def(..)) {
527 match supports_macro_expansion {
528 SupportsMacroExpansion::No => Some(("a", "non-macro attribute")),
529 SupportsMacroExpansion::Yes { supports_inner_attrs } => {
530 if inner_attr && !supports_inner_attrs {
531 Some(("a", "non-macro inner attribute"))
540 if let Some((article, expected)) = unexpected_res {
541 let path_str = pprust::path_to_string(path);
542 let msg = format!("expected {}, found {} `{}`", expected, res.descr(), path_str);
544 .struct_span_err(path.span, &msg)
545 .span_label(path.span, format!("not {} {}", article, expected))
547 return Ok((self.dummy_ext(kind), Res::Err));
550 // We are trying to avoid reporting this error if other related errors were reported.
553 && !self.session.features_untracked().custom_inner_attributes
555 let msg = match res {
556 Res::Def(..) => "inner macro attributes are unstable",
557 Res::NonMacroAttr(..) => "custom inner attributes are unstable",
560 if soft_custom_inner_attributes_gate {
561 self.session.parse_sess.buffer_lint(SOFT_UNSTABLE, path.span, node_id, msg);
563 feature_err(&self.session.parse_sess, sym::custom_inner_attributes, path.span, msg)
571 pub fn resolve_macro_path(
574 kind: Option<MacroKind>,
575 parent_scope: &ParentScope<'a>,
578 ) -> Result<(Option<Lrc<SyntaxExtension>>, Res), Determinacy> {
579 let path_span = path.span;
580 let mut path = Segment::from_path(path);
582 // Possibly apply the macro helper hack
583 if kind == Some(MacroKind::Bang)
585 && path[0].ident.span.ctxt().outer_expn_data().local_inner_macros
587 let root = Ident::new(kw::DollarCrate, path[0].ident.span);
588 path.insert(0, Segment::from_ident(root));
591 let res = if path.len() > 1 {
592 let res = match self.maybe_resolve_path(&path, Some(MacroNS), parent_scope) {
593 PathResult::NonModule(path_res) if let Some(res) = path_res.full_res() => Ok(res),
594 PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
595 PathResult::NonModule(..)
596 | PathResult::Indeterminate
597 | PathResult::Failed { .. } => Err(Determinacy::Determined),
598 PathResult::Module(..) => unreachable!(),
602 let kind = kind.expect("macro kind must be specified if tracing is enabled");
603 self.multi_segment_macro_resolutions.push((
612 self.prohibit_imported_non_macro_attrs(None, res.ok(), path_span);
615 let scope_set = kind.map_or(ScopeSet::All(MacroNS, false), ScopeSet::Macro);
616 let binding = self.early_resolve_ident_in_lexical_scope(
624 if let Err(Determinacy::Undetermined) = binding {
625 return Err(Determinacy::Undetermined);
629 let kind = kind.expect("macro kind must be specified if tracing is enabled");
630 self.single_segment_macro_resolutions.push((
638 let res = binding.map(|binding| binding.res());
639 self.prohibit_imported_non_macro_attrs(binding.ok(), res.ok(), path_span);
643 res.map(|res| (self.get_macro(res).map(|macro_data| macro_data.ext), res))
646 pub(crate) fn finalize_macro_resolutions(&mut self) {
647 let check_consistency = |this: &mut Self,
651 initial_res: Option<Res>,
653 if let Some(initial_res) = initial_res {
654 if res != initial_res {
655 // Make sure compilation does not succeed if preferred macro resolution
656 // has changed after the macro had been expanded. In theory all such
657 // situations should be reported as errors, so this is a bug.
658 this.session.delay_span_bug(span, "inconsistent resolution for a macro");
661 // It's possible that the macro was unresolved (indeterminate) and silently
662 // expanded into a dummy fragment for recovery during expansion.
663 // Now, post-expansion, the resolution may succeed, but we can't change the
664 // past and need to report an error.
665 // However, non-speculative `resolve_path` can successfully return private items
666 // even if speculative `resolve_path` returned nothing previously, so we skip this
667 // less informative error if the privacy error is reported elsewhere.
668 if this.privacy_errors.is_empty() {
670 "cannot determine resolution for the {} `{}`",
672 Segment::names_to_string(path)
674 let msg_note = "import resolution is stuck, try simplifying macro imports";
675 this.session.struct_span_err(span, &msg).note(msg_note).emit();
680 let macro_resolutions = mem::take(&mut self.multi_segment_macro_resolutions);
681 for (mut path, path_span, kind, parent_scope, initial_res) in macro_resolutions {
682 // FIXME: Path resolution will ICE if segment IDs present.
683 for seg in &mut path {
686 match self.resolve_path(
690 Some(Finalize::new(ast::CRATE_NODE_ID, path_span)),
693 PathResult::NonModule(path_res) if let Some(res) = path_res.full_res() => {
694 check_consistency(self, &path, path_span, kind, initial_res, res)
696 path_res @ PathResult::NonModule(..) | path_res @ PathResult::Failed { .. } => {
697 let mut suggestion = None;
698 let (span, label) = if let PathResult::Failed { span, label, .. } = path_res {
699 // try to suggest if it's not a macro, maybe a function
700 if let PathResult::NonModule(partial_res) = self.maybe_resolve_path(&path, Some(ValueNS), &parent_scope)
701 && partial_res.unresolved_segments() == 0 {
702 let sm = self.session.source_map();
703 let exclamation_span = sm.next_point(span);
705 vec![(exclamation_span, "".to_string())],
706 format!("{} is not a macro, but a {}, try to remove `!`", Segment::names_to_string(&path), partial_res.base_res().descr()),
707 Applicability::MaybeIncorrect
715 "partially resolved path in {} {}",
723 ResolutionError::FailedToResolve { label, suggestion },
726 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
730 let macro_resolutions = mem::take(&mut self.single_segment_macro_resolutions);
731 for (ident, kind, parent_scope, initial_binding) in macro_resolutions {
732 match self.early_resolve_ident_in_lexical_scope(
734 ScopeSet::Macro(kind),
736 Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)),
741 let initial_res = initial_binding.map(|initial_binding| {
742 self.record_use(ident, initial_binding, false);
743 initial_binding.res()
745 let res = binding.res();
746 let seg = Segment::from_ident(ident);
747 check_consistency(self, &[seg], ident.span, kind, initial_res, res);
748 if res == Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat) {
751 .get(&parent_scope.expansion)
752 .map_or(ast::CRATE_NODE_ID, |id| self.def_id_to_node_id[id.0]);
753 self.lint_buffer.buffer_lint_with_diagnostic(
754 LEGACY_DERIVE_HELPERS,
757 "derive helper attribute is used before it is introduced",
758 BuiltinLintDiagnostics::LegacyDeriveHelpers(binding.span),
763 let expected = kind.descr_expected();
764 let msg = format!("cannot find {} `{}` in this scope", expected, ident);
765 let mut err = self.session.struct_span_err(ident.span, &msg);
766 self.unresolved_macro_suggestions(&mut err, kind, &parent_scope, ident);
772 let builtin_attrs = mem::take(&mut self.builtin_attrs);
773 for (ident, parent_scope) in builtin_attrs {
774 let _ = self.early_resolve_ident_in_lexical_scope(
776 ScopeSet::Macro(MacroKind::Attr),
778 Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)),
785 fn check_stability_and_deprecation(
787 ext: &SyntaxExtension,
791 let span = path.span;
792 if let Some(stability) = &ext.stability {
793 if let StabilityLevel::Unstable { reason, issue, is_soft, implied_by } = stability.level
795 let feature = stability.feature;
797 let is_allowed = |feature| {
798 self.active_features.contains(&feature) || span.allows_unstable(feature)
800 let allowed_by_implication =
801 implied_by.map(|feature| is_allowed(feature)).unwrap_or(false);
802 if !is_allowed(feature) && !allowed_by_implication {
803 let lint_buffer = &mut self.lint_buffer;
805 |lint, span, msg: &_| lint_buffer.buffer_lint(lint, node_id, span, msg);
806 stability::report_unstable(
809 reason.to_opt_reason(),
819 if let Some(depr) = &ext.deprecation {
820 let path = pprust::path_to_string(&path);
821 let (message, lint) = stability::deprecation_message_and_lint(depr, "macro", &path);
822 stability::early_report_deprecation(
823 &mut self.lint_buffer,
833 fn prohibit_imported_non_macro_attrs(
835 binding: Option<&'a NameBinding<'a>>,
839 if let Some(Res::NonMacroAttr(kind)) = res {
840 if kind != NonMacroAttrKind::Tool && binding.map_or(true, |b| b.is_import()) {
842 format!("cannot use {} {} through an import", kind.article(), kind.descr());
843 let mut err = self.session.struct_span_err(span, &msg);
844 if let Some(binding) = binding {
845 err.span_note(binding.span, &format!("the {} imported here", kind.descr()));
852 pub(crate) fn check_reserved_macro_name(&mut self, ident: Ident, res: Res) {
853 // Reserve some names that are not quite covered by the general check
854 // performed on `Resolver::builtin_attrs`.
855 if ident.name == sym::cfg || ident.name == sym::cfg_attr {
856 let macro_kind = self.get_macro(res).map(|macro_data| macro_data.ext.macro_kind());
857 if macro_kind.is_some() && sub_namespace_match(macro_kind, Some(MacroKind::Attr)) {
858 self.session.span_err(
860 &format!("name `{}` is reserved in attribute namespace", ident),
866 /// Compile the macro into a `SyntaxExtension` and its rule spans.
868 /// Possibly replace its expander to a pre-defined one for built-in macros.
869 pub(crate) fn compile_macro(
873 ) -> (SyntaxExtension, Vec<(usize, Span)>) {
874 let (mut result, mut rule_spans) = compile_declarative_macro(
876 self.session.features_untracked(),
881 if let Some(builtin_name) = result.builtin_name {
882 // The macro was marked with `#[rustc_builtin_macro]`.
883 if let Some(builtin_macro) = self.builtin_macros.get_mut(&builtin_name) {
884 // The macro is a built-in, replace its expander function
885 // while still taking everything else from the source code.
886 // If we already loaded this builtin macro, give a better error message than 'no such builtin macro'.
887 match mem::replace(builtin_macro, BuiltinMacroState::AlreadySeen(item.span)) {
888 BuiltinMacroState::NotYetSeen(ext) => {
890 rule_spans = Vec::new();
891 if item.id != ast::DUMMY_NODE_ID {
892 self.builtin_macro_kinds
893 .insert(self.local_def_id(item.id), result.macro_kind());
896 BuiltinMacroState::AlreadySeen(span) => {
901 "attempted to define built-in macro more than once"
903 .span_note(span, "previously defined here")
908 let msg = format!("cannot find a built-in macro with name `{}`", item.ident);
909 self.session.span_err(item.span, &msg);