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;
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 /// The code common between processing `#![register_tool]` and `#![register_attr]`.
116 fn registered_idents(
118 attrs: &[ast::Attribute],
121 ) -> FxHashSet<Ident> {
122 let mut registered = FxHashSet::default();
123 for attr in sess.filter_by_name(attrs, attr_name) {
124 for nested_meta in attr.meta_item_list().unwrap_or_default() {
125 match nested_meta.ident() {
127 if let Some(old_ident) = registered.replace(ident) {
128 let msg = format!("{} `{}` was already registered", descr, ident);
129 sess.struct_span_err(ident.span, &msg)
130 .span_label(old_ident.span, "already registered here")
135 let msg = format!("`{}` only accepts identifiers", attr_name);
136 let span = nested_meta.span();
137 sess.struct_span_err(span, &msg).span_label(span, "not an identifier").emit();
145 pub(crate) fn registered_attrs_and_tools(
147 attrs: &[ast::Attribute],
148 ) -> (FxHashSet<Ident>, FxHashSet<Ident>) {
149 let registered_attrs = registered_idents(sess, attrs, sym::register_attr, "attribute");
150 let mut registered_tools = registered_idents(sess, attrs, sym::register_tool, "tool");
151 // We implicitly add `rustfmt` and `clippy` to known tools,
152 // but it's not an error to register them explicitly.
153 let predefined_tools = [sym::clippy, sym::rustfmt];
154 registered_tools.extend(predefined_tools.iter().cloned().map(Ident::with_dummy_span));
155 (registered_attrs, registered_tools)
158 // Some feature gates for inner attributes are reported as lints for backward compatibility.
159 fn soft_custom_inner_attributes_gate(path: &ast::Path, invoc: &Invocation) -> bool {
160 match &path.segments[..] {
162 [seg] if seg.ident.name == sym::test => return true,
163 // `#![rustfmt::skip]` on out-of-line modules
164 [seg1, seg2] if seg1.ident.name == sym::rustfmt && seg2.ident.name == sym::skip => {
165 if let InvocationKind::Attr { item, .. } = &invoc.kind {
166 if let Annotatable::Item(item) = item {
167 if let ItemKind::Mod(_, ModKind::Loaded(_, Inline::No, _)) = item.kind {
178 impl<'a> ResolverExpand for Resolver<'a> {
179 fn next_node_id(&mut self) -> NodeId {
183 fn invocation_parent(&self, id: LocalExpnId) -> LocalDefId {
184 self.invocation_parents[&id].0
187 fn resolve_dollar_crates(&mut self) {
188 hygiene::update_dollar_crate_names(|ctxt| {
189 let ident = Ident::new(kw::DollarCrate, DUMMY_SP.with_ctxt(ctxt));
190 match self.resolve_crate_root(ident).kind {
191 ModuleKind::Def(.., name) if name != kw::Empty => name,
197 fn visit_ast_fragment_with_placeholders(
199 expansion: LocalExpnId,
200 fragment: &AstFragment,
202 // Integrate the new AST fragment into all the definition and module structures.
203 // We are inside the `expansion` now, but other parent scope components are still the same.
204 let parent_scope = ParentScope { expansion, ..self.invocation_parent_scopes[&expansion] };
205 let output_macro_rules_scope = self.build_reduced_graph(fragment, parent_scope);
206 self.output_macro_rules_scopes.insert(expansion, output_macro_rules_scope);
208 parent_scope.module.unexpanded_invocations.borrow_mut().remove(&expansion);
211 fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind) {
212 if self.builtin_macros.insert(name, BuiltinMacroState::NotYetSeen(ext)).is_some() {
215 .bug(&format!("built-in macro `{}` was already registered", name));
219 // Create a new Expansion with a definition site of the provided module, or
220 // a fake empty `#[no_implicit_prelude]` module if no module is provided.
221 fn expansion_for_ast_pass(
226 parent_module_id: Option<NodeId>,
229 parent_module_id.map(|module_id| self.local_def_id(module_id).to_def_id());
230 let expn_id = LocalExpnId::fresh(
231 ExpnData::allow_unstable(
232 ExpnKind::AstPass(pass),
234 self.session.edition(),
239 self.create_stable_hashing_context(),
243 parent_module.map_or(self.empty_module, |def_id| self.expect_module(def_id));
244 self.ast_transform_scopes.insert(expn_id, parent_scope);
249 fn resolve_imports(&mut self) {
250 ImportResolver { r: self }.resolve_imports()
253 fn resolve_macro_invocation(
256 eager_expansion_root: LocalExpnId,
258 ) -> Result<Lrc<SyntaxExtension>, Indeterminate> {
259 let invoc_id = invoc.expansion_data.id;
260 let parent_scope = match self.invocation_parent_scopes.get(&invoc_id) {
261 Some(parent_scope) => *parent_scope,
263 // If there's no entry in the table, then we are resolving an eagerly expanded
264 // macro, which should inherit its parent scope from its eager expansion root -
265 // the macro that requested this eager expansion.
266 let parent_scope = *self
267 .invocation_parent_scopes
268 .get(&eager_expansion_root)
269 .expect("non-eager expansion without a parent scope");
270 self.invocation_parent_scopes.insert(invoc_id, parent_scope);
275 let (path, kind, inner_attr, derives) = match invoc.kind {
276 InvocationKind::Attr { ref attr, ref derives, .. } => (
277 &attr.get_normal_item().path,
279 attr.style == ast::AttrStyle::Inner,
280 self.arenas.alloc_ast_paths(derives),
282 InvocationKind::Bang { ref mac, .. } => (&mac.path, MacroKind::Bang, false, &[][..]),
283 InvocationKind::Derive { ref path, .. } => (path, MacroKind::Derive, false, &[][..]),
286 // Derives are not included when `invocations` are collected, so we have to add them here.
287 let parent_scope = &ParentScope { derives, ..parent_scope };
288 let supports_macro_expansion = invoc.fragment_kind.supports_macro_expansion();
289 let node_id = invoc.expansion_data.lint_node_id;
290 let (ext, res) = self.smart_resolve_macro_path(
293 supports_macro_expansion,
298 soft_custom_inner_attributes_gate(path, invoc),
301 let span = invoc.span();
302 let def_id = res.opt_def_id();
303 invoc_id.set_expn_data(
305 parent_scope.expansion,
307 fast_print_path(path),
309 def_id.map(|def_id| self.macro_def_scope(def_id).nearest_parent_mod()),
311 self.create_stable_hashing_context(),
317 fn record_macro_rule_usage(&mut self, id: NodeId, rule_i: usize) {
318 let did = self.local_def_id(id);
319 self.unused_macro_rules.remove(&(did, rule_i));
322 fn check_unused_macros(&mut self) {
323 for (_, &(node_id, ident)) in self.unused_macros.iter() {
324 self.lint_buffer.buffer_lint(
328 &format!("unused macro definition: `{}`", ident.name),
331 for (&(def_id, arm_i), &(ident, rule_span)) in self.unused_macro_rules.iter() {
332 if self.unused_macros.contains_key(&def_id) {
333 // We already lint the entire macro as unused
336 let node_id = self.def_id_to_node_id[def_id];
337 self.lint_buffer.buffer_lint(
342 "{} rule of macro `{}` is never used",
343 crate::diagnostics::ordinalize(arm_i + 1),
350 fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool {
351 self.containers_deriving_copy.contains(&expn_id)
356 expn_id: LocalExpnId,
358 derive_paths: &dyn Fn() -> DeriveResolutions,
359 ) -> Result<(), Indeterminate> {
360 // Block expansion of the container until we resolve all derives in it.
361 // This is required for two reasons:
362 // - Derive helper attributes are in scope for the item to which the `#[derive]`
363 // is applied, so they have to be produced by the container's expansion rather
364 // than by individual derives.
365 // - Derives in the container need to know whether one of them is a built-in `Copy`.
366 // Temporarily take the data to avoid borrow checker conflicts.
367 let mut derive_data = mem::take(&mut self.derive_data);
368 let entry = derive_data.entry(expn_id).or_insert_with(|| DeriveData {
369 resolutions: derive_paths(),
370 helper_attrs: Vec::new(),
371 has_derive_copy: false,
373 let parent_scope = self.invocation_parent_scopes[&expn_id];
374 for (i, (path, _, opt_ext)) in entry.resolutions.iter_mut().enumerate() {
375 if opt_ext.is_none() {
377 match self.resolve_macro_path(
379 Some(MacroKind::Derive),
384 Ok((Some(ext), _)) => {
385 if !ext.helper_attrs.is_empty() {
386 let last_seg = path.segments.last().unwrap();
387 let span = last_seg.ident.span.normalize_to_macros_2_0();
388 entry.helper_attrs.extend(
391 .map(|name| (i, Ident::new(*name, span))),
394 entry.has_derive_copy |= ext.builtin_name == Some(sym::Copy);
397 Ok(_) | Err(Determinacy::Determined) => self.dummy_ext(MacroKind::Derive),
398 Err(Determinacy::Undetermined) => {
399 assert!(self.derive_data.is_empty());
400 self.derive_data = derive_data;
401 return Err(Indeterminate);
407 // Sort helpers in a stable way independent from the derive resolution order.
408 entry.helper_attrs.sort_by_key(|(i, _)| *i);
410 .insert(expn_id, entry.helper_attrs.iter().map(|(_, ident)| *ident).collect());
411 // Mark this derive as having `Copy` either if it has `Copy` itself or if its parent derive
412 // has `Copy`, to support cases like `#[derive(Clone, Copy)] #[derive(Debug)]`.
413 if entry.has_derive_copy || self.has_derive_copy(parent_scope.expansion) {
414 self.containers_deriving_copy.insert(expn_id);
416 assert!(self.derive_data.is_empty());
417 self.derive_data = derive_data;
421 fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<DeriveResolutions> {
422 self.derive_data.remove(&expn_id).map(|data| data.resolutions)
425 // The function that implements the resolution logic of `#[cfg_accessible(path)]`.
426 // Returns true if the path can certainly be resolved in one of three namespaces,
427 // returns false if the path certainly cannot be resolved in any of the three namespaces.
428 // Returns `Indeterminate` if we cannot give a certain answer yet.
431 expn_id: LocalExpnId,
433 ) -> Result<bool, Indeterminate> {
434 let span = path.span;
435 let path = &Segment::from_path(path);
436 let parent_scope = self.invocation_parent_scopes[&expn_id];
438 let mut indeterminate = false;
439 for ns in [TypeNS, ValueNS, MacroNS].iter().copied() {
440 match self.maybe_resolve_path(path, Some(ns), &parent_scope) {
441 PathResult::Module(ModuleOrUniformRoot::Module(_)) => return Ok(true),
442 PathResult::NonModule(partial_res) if partial_res.unresolved_segments() == 0 => {
445 PathResult::NonModule(..) |
446 // HACK(Urgau): This shouldn't be necessary
447 PathResult::Failed { is_error_from_last_segment: false, .. } => {
449 .struct_span_err(span, "not sure whether the path is accessible or not")
450 .note("the type may have associated items, but we are currently not checking them")
453 // If we get a partially resolved NonModule in one namespace, we should get the
454 // same result in any other namespaces, so we can return early.
457 PathResult::Indeterminate => indeterminate = true,
458 // We can only be sure that a path doesn't exist after having tested all the
459 // posibilities, only at that time we can return false.
460 PathResult::Failed { .. } => {}
461 PathResult::Module(_) => panic!("unexpected path resolution"),
466 return Err(Indeterminate);
472 fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span {
473 self.crate_loader.cstore().get_proc_macro_quoted_span_untracked(krate, id, self.session)
476 fn declare_proc_macro(&mut self, id: NodeId) {
477 self.proc_macros.push(id)
480 fn registered_tools(&self) -> &RegisteredTools {
481 &self.registered_tools
485 impl<'a> Resolver<'a> {
486 /// Resolve macro path with error reporting and recovery.
487 /// Uses dummy syntax extensions for unresolved macros or macros with unexpected resolutions
488 /// for better error recovery.
489 fn smart_resolve_macro_path(
493 supports_macro_expansion: SupportsMacroExpansion,
495 parent_scope: &ParentScope<'a>,
498 soft_custom_inner_attributes_gate: bool,
499 ) -> Result<(Lrc<SyntaxExtension>, Res), Indeterminate> {
500 let (ext, res) = match self.resolve_macro_path(path, Some(kind), parent_scope, true, force)
502 Ok((Some(ext), res)) => (ext, res),
503 Ok((None, res)) => (self.dummy_ext(kind), res),
504 Err(Determinacy::Determined) => (self.dummy_ext(kind), Res::Err),
505 Err(Determinacy::Undetermined) => return Err(Indeterminate),
508 // Report errors for the resolved macro.
509 for segment in &path.segments {
510 if let Some(args) = &segment.args {
511 self.session.span_err(args.span(), "generic arguments in macro path");
513 if kind == MacroKind::Attr && segment.ident.as_str().starts_with("rustc") {
514 self.session.span_err(
516 "attributes starting with `rustc` are reserved for use by the `rustc` compiler",
522 Res::Def(DefKind::Macro(_), def_id) => {
523 if let Some(def_id) = def_id.as_local() {
524 self.unused_macros.remove(&def_id);
525 if self.proc_macro_stubs.contains(&def_id) {
526 self.session.span_err(
528 "can't use a procedural macro from the same crate that defines it",
533 Res::NonMacroAttr(..) | Res::Err => {}
534 _ => panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"),
537 self.check_stability_and_deprecation(&ext, path, node_id);
539 let unexpected_res = if ext.macro_kind() != kind {
540 Some((kind.article(), kind.descr_expected()))
541 } else if matches!(res, Res::Def(..)) {
542 match supports_macro_expansion {
543 SupportsMacroExpansion::No => Some(("a", "non-macro attribute")),
544 SupportsMacroExpansion::Yes { supports_inner_attrs } => {
545 if inner_attr && !supports_inner_attrs {
546 Some(("a", "non-macro inner attribute"))
555 if let Some((article, expected)) = unexpected_res {
556 let path_str = pprust::path_to_string(path);
557 let msg = format!("expected {}, found {} `{}`", expected, res.descr(), path_str);
559 .struct_span_err(path.span, &msg)
560 .span_label(path.span, format!("not {} {}", article, expected))
562 return Ok((self.dummy_ext(kind), Res::Err));
565 // We are trying to avoid reporting this error if other related errors were reported.
568 && !self.session.features_untracked().custom_inner_attributes
570 let msg = match res {
571 Res::Def(..) => "inner macro attributes are unstable",
572 Res::NonMacroAttr(..) => "custom inner attributes are unstable",
575 if soft_custom_inner_attributes_gate {
576 self.session.parse_sess.buffer_lint(SOFT_UNSTABLE, path.span, node_id, msg);
578 feature_err(&self.session.parse_sess, sym::custom_inner_attributes, path.span, msg)
586 pub fn resolve_macro_path(
589 kind: Option<MacroKind>,
590 parent_scope: &ParentScope<'a>,
593 ) -> Result<(Option<Lrc<SyntaxExtension>>, Res), Determinacy> {
594 let path_span = path.span;
595 let mut path = Segment::from_path(path);
597 // Possibly apply the macro helper hack
598 if kind == Some(MacroKind::Bang)
600 && path[0].ident.span.ctxt().outer_expn_data().local_inner_macros
602 let root = Ident::new(kw::DollarCrate, path[0].ident.span);
603 path.insert(0, Segment::from_ident(root));
606 let res = if path.len() > 1 {
607 let res = match self.maybe_resolve_path(&path, Some(MacroNS), parent_scope) {
608 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
609 Ok(path_res.base_res())
611 PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
612 PathResult::NonModule(..)
613 | PathResult::Indeterminate
614 | PathResult::Failed { .. } => Err(Determinacy::Determined),
615 PathResult::Module(..) => unreachable!(),
619 let kind = kind.expect("macro kind must be specified if tracing is enabled");
620 self.multi_segment_macro_resolutions.push((
629 self.prohibit_imported_non_macro_attrs(None, res.ok(), path_span);
632 let scope_set = kind.map_or(ScopeSet::All(MacroNS, false), ScopeSet::Macro);
633 let binding = self.early_resolve_ident_in_lexical_scope(
641 if let Err(Determinacy::Undetermined) = binding {
642 return Err(Determinacy::Undetermined);
646 let kind = kind.expect("macro kind must be specified if tracing is enabled");
647 self.single_segment_macro_resolutions.push((
655 let res = binding.map(|binding| binding.res());
656 self.prohibit_imported_non_macro_attrs(binding.ok(), res.ok(), path_span);
660 res.map(|res| (self.get_macro(res).map(|macro_data| macro_data.ext), res))
663 pub(crate) fn finalize_macro_resolutions(&mut self) {
664 let check_consistency = |this: &mut Self,
668 initial_res: Option<Res>,
670 if let Some(initial_res) = initial_res {
671 if res != initial_res {
672 // Make sure compilation does not succeed if preferred macro resolution
673 // has changed after the macro had been expanded. In theory all such
674 // situations should be reported as errors, so this is a bug.
675 this.session.delay_span_bug(span, "inconsistent resolution for a macro");
678 // It's possible that the macro was unresolved (indeterminate) and silently
679 // expanded into a dummy fragment for recovery during expansion.
680 // Now, post-expansion, the resolution may succeed, but we can't change the
681 // past and need to report an error.
682 // However, non-speculative `resolve_path` can successfully return private items
683 // even if speculative `resolve_path` returned nothing previously, so we skip this
684 // less informative error if the privacy error is reported elsewhere.
685 if this.privacy_errors.is_empty() {
687 "cannot determine resolution for the {} `{}`",
689 Segment::names_to_string(path)
691 let msg_note = "import resolution is stuck, try simplifying macro imports";
692 this.session.struct_span_err(span, &msg).note(msg_note).emit();
697 let macro_resolutions = mem::take(&mut self.multi_segment_macro_resolutions);
698 for (mut path, path_span, kind, parent_scope, initial_res) in macro_resolutions {
699 // FIXME: Path resolution will ICE if segment IDs present.
700 for seg in &mut path {
703 match self.resolve_path(
707 Some(Finalize::new(ast::CRATE_NODE_ID, path_span)),
710 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
711 let res = path_res.base_res();
712 check_consistency(self, &path, path_span, kind, initial_res, res);
714 path_res @ PathResult::NonModule(..) | path_res @ PathResult::Failed { .. } => {
715 let (span, label) = if let PathResult::Failed { span, label, .. } = path_res {
721 "partially resolved path in {} {}",
729 ResolutionError::FailedToResolve { label, suggestion: None },
732 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
736 let macro_resolutions = mem::take(&mut self.single_segment_macro_resolutions);
737 for (ident, kind, parent_scope, initial_binding) in macro_resolutions {
738 match self.early_resolve_ident_in_lexical_scope(
740 ScopeSet::Macro(kind),
742 Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)),
747 let initial_res = initial_binding.map(|initial_binding| {
748 self.record_use(ident, initial_binding, false);
749 initial_binding.res()
751 let res = binding.res();
752 let seg = Segment::from_ident(ident);
753 check_consistency(self, &[seg], ident.span, kind, initial_res, res);
754 if res == Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat) {
757 .get(&parent_scope.expansion)
758 .map_or(ast::CRATE_NODE_ID, |id| self.def_id_to_node_id[id.0]);
759 self.lint_buffer.buffer_lint_with_diagnostic(
760 LEGACY_DERIVE_HELPERS,
763 "derive helper attribute is used before it is introduced",
764 BuiltinLintDiagnostics::LegacyDeriveHelpers(binding.span),
769 let expected = kind.descr_expected();
770 let msg = format!("cannot find {} `{}` in this scope", expected, ident);
771 let mut err = self.session.struct_span_err(ident.span, &msg);
772 self.unresolved_macro_suggestions(&mut err, kind, &parent_scope, ident);
778 let builtin_attrs = mem::take(&mut self.builtin_attrs);
779 for (ident, parent_scope) in builtin_attrs {
780 let _ = self.early_resolve_ident_in_lexical_scope(
782 ScopeSet::Macro(MacroKind::Attr),
784 Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)),
791 fn check_stability_and_deprecation(
793 ext: &SyntaxExtension,
797 let span = path.span;
798 if let Some(stability) = &ext.stability {
799 if let StabilityLevel::Unstable { reason, issue, is_soft, implied_by } = stability.level
801 let feature = stability.feature;
803 let is_allowed = |feature| {
804 self.active_features.contains(&feature) || span.allows_unstable(feature)
806 let allowed_by_implication =
807 implied_by.map(|feature| is_allowed(feature)).unwrap_or(false);
808 if !is_allowed(feature) && !allowed_by_implication {
809 let lint_buffer = &mut self.lint_buffer;
811 |lint, span, msg: &_| lint_buffer.buffer_lint(lint, node_id, span, msg);
812 stability::report_unstable(
815 reason.to_opt_reason(),
825 if let Some(depr) = &ext.deprecation {
826 let path = pprust::path_to_string(&path);
827 let (message, lint) = stability::deprecation_message_and_lint(depr, "macro", &path);
828 stability::early_report_deprecation(
829 &mut self.lint_buffer,
839 fn prohibit_imported_non_macro_attrs(
841 binding: Option<&'a NameBinding<'a>>,
845 if let Some(Res::NonMacroAttr(kind)) = res {
846 if kind != NonMacroAttrKind::Tool && binding.map_or(true, |b| b.is_import()) {
848 format!("cannot use {} {} through an import", kind.article(), kind.descr());
849 let mut err = self.session.struct_span_err(span, &msg);
850 if let Some(binding) = binding {
851 err.span_note(binding.span, &format!("the {} imported here", kind.descr()));
858 pub(crate) fn check_reserved_macro_name(&mut self, ident: Ident, res: Res) {
859 // Reserve some names that are not quite covered by the general check
860 // performed on `Resolver::builtin_attrs`.
861 if ident.name == sym::cfg || ident.name == sym::cfg_attr {
862 let macro_kind = self.get_macro(res).map(|macro_data| macro_data.ext.macro_kind());
863 if macro_kind.is_some() && sub_namespace_match(macro_kind, Some(MacroKind::Attr)) {
864 self.session.span_err(
866 &format!("name `{}` is reserved in attribute namespace", ident),
872 /// Compile the macro into a `SyntaxExtension` and its rule spans.
874 /// Possibly replace its expander to a pre-defined one for built-in macros.
875 pub(crate) fn compile_macro(
879 ) -> (SyntaxExtension, Vec<(usize, Span)>) {
880 let (mut result, mut rule_spans) = compile_declarative_macro(
882 self.session.features_untracked(),
887 if let Some(builtin_name) = result.builtin_name {
888 // The macro was marked with `#[rustc_builtin_macro]`.
889 if let Some(builtin_macro) = self.builtin_macros.get_mut(&builtin_name) {
890 // The macro is a built-in, replace its expander function
891 // while still taking everything else from the source code.
892 // If we already loaded this builtin macro, give a better error message than 'no such builtin macro'.
893 match mem::replace(builtin_macro, BuiltinMacroState::AlreadySeen(item.span)) {
894 BuiltinMacroState::NotYetSeen(ext) => {
896 rule_spans = Vec::new();
897 if item.id != ast::DUMMY_NODE_ID {
898 self.builtin_macro_kinds
899 .insert(self.local_def_id(item.id), result.macro_kind());
902 BuiltinMacroState::AlreadySeen(span) => {
907 "attempted to define built-in macro more than once"
909 .span_note(span, "previously defined here")
914 let msg = format!("cannot find a built-in macro with name `{}`", item.ident);
915 self.session.span_err(item.span, &msg);