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_lowering::ResolverAstLowering;
11 use rustc_ast_pretty::pprust;
12 use rustc_attr::StabilityLevel;
13 use rustc_data_structures::fx::FxHashSet;
14 use rustc_data_structures::intern::Interned;
15 use rustc_data_structures::sync::Lrc;
16 use rustc_errors::struct_span_err;
17 use rustc_expand::base::{Annotatable, DeriveResolutions, Indeterminate, ResolverExpand};
18 use rustc_expand::base::{SyntaxExtension, SyntaxExtensionKind};
19 use rustc_expand::compile_declarative_macro;
20 use rustc_expand::expand::{AstFragment, Invocation, InvocationKind, SupportsMacroExpansion};
21 use rustc_hir::def::{self, DefKind, NonMacroAttrKind};
22 use rustc_hir::def_id::{CrateNum, LocalDefId};
23 use rustc_middle::middle::stability;
24 use rustc_middle::ty::RegisteredTools;
25 use rustc_session::lint::builtin::{LEGACY_DERIVE_HELPERS, SOFT_UNSTABLE, UNUSED_MACROS};
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 crate binding: &'a NameBinding<'a>,
44 /// `macro_rules` scope into which the `macro_rules` item was planted.
45 crate parent_macro_rules_scope: MacroRulesScopeRef<'a>,
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 crate fn sub_namespace_match(candidate: Option<MacroKind>, requirement: Option<MacroKind>) -> bool {
82 let sub_ns = |kind| match kind {
83 MacroKind::Bang => SubNS::Bang,
84 MacroKind::Attr | MacroKind::Derive => SubNS::AttrLike,
86 let candidate = candidate.map(sub_ns);
87 let requirement = requirement.map(sub_ns);
88 // "No specific sub-namespace" means "matches anything" for both requirements and candidates.
89 candidate.is_none() || requirement.is_none() || candidate == requirement
92 // We don't want to format a path using pretty-printing,
93 // `format!("{}", path)`, because that tries to insert
94 // line-breaks and is slow.
95 fn fast_print_path(path: &ast::Path) -> Symbol {
96 if path.segments.len() == 1 {
97 path.segments[0].ident.name
99 let mut path_str = String::with_capacity(64);
100 for (i, segment) in path.segments.iter().enumerate() {
102 path_str.push_str("::");
104 if segment.ident.name != kw::PathRoot {
105 path_str.push_str(segment.ident.as_str())
108 Symbol::intern(&path_str)
112 /// The code common between processing `#![register_tool]` and `#![register_attr]`.
113 fn registered_idents(
115 attrs: &[ast::Attribute],
118 ) -> FxHashSet<Ident> {
119 let mut registered = FxHashSet::default();
120 for attr in sess.filter_by_name(attrs, attr_name) {
121 for nested_meta in attr.meta_item_list().unwrap_or_default() {
122 match nested_meta.ident() {
124 if let Some(old_ident) = registered.replace(ident) {
125 let msg = format!("{} `{}` was already registered", descr, ident);
126 sess.struct_span_err(ident.span, &msg)
127 .span_label(old_ident.span, "already registered here")
132 let msg = format!("`{}` only accepts identifiers", attr_name);
133 let span = nested_meta.span();
134 sess.struct_span_err(span, &msg).span_label(span, "not an identifier").emit();
142 crate fn registered_attrs_and_tools(
144 attrs: &[ast::Attribute],
145 ) -> (FxHashSet<Ident>, FxHashSet<Ident>) {
146 let registered_attrs = registered_idents(sess, attrs, sym::register_attr, "attribute");
147 let mut registered_tools = registered_idents(sess, attrs, sym::register_tool, "tool");
148 // We implicitly add `rustfmt` and `clippy` to known tools,
149 // but it's not an error to register them explicitly.
150 let predefined_tools = [sym::clippy, sym::rustfmt];
151 registered_tools.extend(predefined_tools.iter().cloned().map(Ident::with_dummy_span));
152 (registered_attrs, registered_tools)
155 // Some feature gates for inner attributes are reported as lints for backward compatibility.
156 fn soft_custom_inner_attributes_gate(path: &ast::Path, invoc: &Invocation) -> bool {
157 match &path.segments[..] {
159 [seg] if seg.ident.name == sym::test => return true,
160 // `#![rustfmt::skip]` on out-of-line modules
161 [seg1, seg2] if seg1.ident.name == sym::rustfmt && seg2.ident.name == sym::skip => {
162 if let InvocationKind::Attr { item, .. } = &invoc.kind {
163 if let Annotatable::Item(item) = item {
164 if let ItemKind::Mod(_, ModKind::Loaded(_, Inline::No, _)) = item.kind {
175 impl<'a> ResolverExpand for Resolver<'a> {
176 fn next_node_id(&mut self) -> NodeId {
180 fn invocation_parent(&self, id: LocalExpnId) -> LocalDefId {
181 self.invocation_parents[&id].0
184 fn resolve_dollar_crates(&mut self) {
185 hygiene::update_dollar_crate_names(|ctxt| {
186 let ident = Ident::new(kw::DollarCrate, DUMMY_SP.with_ctxt(ctxt));
187 match self.resolve_crate_root(ident).kind {
188 ModuleKind::Def(.., name) if name != kw::Empty => name,
194 fn visit_ast_fragment_with_placeholders(
196 expansion: LocalExpnId,
197 fragment: &AstFragment,
199 // Integrate the new AST fragment into all the definition and module structures.
200 // We are inside the `expansion` now, but other parent scope components are still the same.
201 let parent_scope = ParentScope { expansion, ..self.invocation_parent_scopes[&expansion] };
202 let output_macro_rules_scope = self.build_reduced_graph(fragment, parent_scope);
203 self.output_macro_rules_scopes.insert(expansion, output_macro_rules_scope);
205 parent_scope.module.unexpanded_invocations.borrow_mut().remove(&expansion);
208 fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind) {
209 if self.builtin_macros.insert(name, BuiltinMacroState::NotYetSeen(ext)).is_some() {
212 .bug(&format!("built-in macro `{}` was already registered", name));
216 // Create a new Expansion with a definition site of the provided module, or
217 // a fake empty `#[no_implicit_prelude]` module if no module is provided.
218 fn expansion_for_ast_pass(
223 parent_module_id: Option<NodeId>,
226 parent_module_id.map(|module_id| self.local_def_id(module_id).to_def_id());
227 let expn_id = LocalExpnId::fresh(
228 ExpnData::allow_unstable(
229 ExpnKind::AstPass(pass),
231 self.session.edition(),
236 self.create_stable_hashing_context(),
240 parent_module.map_or(self.empty_module, |def_id| self.expect_module(def_id));
241 self.ast_transform_scopes.insert(expn_id, parent_scope);
246 fn resolve_imports(&mut self) {
247 ImportResolver { r: self }.resolve_imports()
250 fn resolve_macro_invocation(
253 eager_expansion_root: LocalExpnId,
255 ) -> Result<Lrc<SyntaxExtension>, Indeterminate> {
256 let invoc_id = invoc.expansion_data.id;
257 let parent_scope = match self.invocation_parent_scopes.get(&invoc_id) {
258 Some(parent_scope) => *parent_scope,
260 // If there's no entry in the table, then we are resolving an eagerly expanded
261 // macro, which should inherit its parent scope from its eager expansion root -
262 // the macro that requested this eager expansion.
263 let parent_scope = *self
264 .invocation_parent_scopes
265 .get(&eager_expansion_root)
266 .expect("non-eager expansion without a parent scope");
267 self.invocation_parent_scopes.insert(invoc_id, parent_scope);
272 let (path, kind, inner_attr, derives) = match invoc.kind {
273 InvocationKind::Attr { ref attr, ref derives, .. } => (
274 &attr.get_normal_item().path,
276 attr.style == ast::AttrStyle::Inner,
277 self.arenas.alloc_ast_paths(derives),
279 InvocationKind::Bang { ref mac, .. } => (&mac.path, MacroKind::Bang, false, &[][..]),
280 InvocationKind::Derive { ref path, .. } => (path, MacroKind::Derive, false, &[][..]),
283 // Derives are not included when `invocations` are collected, so we have to add them here.
284 let parent_scope = &ParentScope { derives, ..parent_scope };
285 let supports_macro_expansion = invoc.fragment_kind.supports_macro_expansion();
286 let node_id = invoc.expansion_data.lint_node_id;
287 let (ext, res) = self.smart_resolve_macro_path(
290 supports_macro_expansion,
295 soft_custom_inner_attributes_gate(path, invoc),
298 let span = invoc.span();
299 let def_id = res.opt_def_id();
300 invoc_id.set_expn_data(
302 parent_scope.expansion,
304 fast_print_path(path),
306 def_id.map(|def_id| self.macro_def_scope(def_id).nearest_parent_mod()),
308 self.create_stable_hashing_context(),
314 fn check_unused_macros(&mut self) {
315 for (_, &(node_id, ident)) in self.unused_macros.iter() {
316 self.lint_buffer.buffer_lint(
320 &format!("unused macro definition: `{}`", ident.as_str()),
325 fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool {
326 self.containers_deriving_copy.contains(&expn_id)
331 expn_id: LocalExpnId,
333 derive_paths: &dyn Fn() -> DeriveResolutions,
334 ) -> Result<(), Indeterminate> {
335 // Block expansion of the container until we resolve all derives in it.
336 // This is required for two reasons:
337 // - Derive helper attributes are in scope for the item to which the `#[derive]`
338 // is applied, so they have to be produced by the container's expansion rather
339 // than by individual derives.
340 // - Derives in the container need to know whether one of them is a built-in `Copy`.
341 // Temporarily take the data to avoid borrow checker conflicts.
342 let mut derive_data = mem::take(&mut self.derive_data);
343 let entry = derive_data.entry(expn_id).or_insert_with(|| DeriveData {
344 resolutions: derive_paths(),
345 helper_attrs: Vec::new(),
346 has_derive_copy: false,
348 let parent_scope = self.invocation_parent_scopes[&expn_id];
349 for (i, (path, _, opt_ext)) in entry.resolutions.iter_mut().enumerate() {
350 if opt_ext.is_none() {
352 match self.resolve_macro_path(
354 Some(MacroKind::Derive),
359 Ok((Some(ext), _)) => {
360 if !ext.helper_attrs.is_empty() {
361 let last_seg = path.segments.last().unwrap();
362 let span = last_seg.ident.span.normalize_to_macros_2_0();
363 entry.helper_attrs.extend(
366 .map(|name| (i, Ident::new(*name, span))),
369 entry.has_derive_copy |= ext.builtin_name == Some(sym::Copy);
372 Ok(_) | Err(Determinacy::Determined) => self.dummy_ext(MacroKind::Derive),
373 Err(Determinacy::Undetermined) => {
374 assert!(self.derive_data.is_empty());
375 self.derive_data = derive_data;
376 return Err(Indeterminate);
382 // Sort helpers in a stable way independent from the derive resolution order.
383 entry.helper_attrs.sort_by_key(|(i, _)| *i);
385 .insert(expn_id, entry.helper_attrs.iter().map(|(_, ident)| *ident).collect());
386 // Mark this derive as having `Copy` either if it has `Copy` itself or if its parent derive
387 // has `Copy`, to support cases like `#[derive(Clone, Copy)] #[derive(Debug)]`.
388 if entry.has_derive_copy || self.has_derive_copy(parent_scope.expansion) {
389 self.containers_deriving_copy.insert(expn_id);
391 assert!(self.derive_data.is_empty());
392 self.derive_data = derive_data;
396 fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<DeriveResolutions> {
397 self.derive_data.remove(&expn_id).map(|data| data.resolutions)
400 // The function that implements the resolution logic of `#[cfg_accessible(path)]`.
401 // Returns true if the path can certainly be resolved in one of three namespaces,
402 // returns false if the path certainly cannot be resolved in any of the three namespaces.
403 // Returns `Indeterminate` if we cannot give a certain answer yet.
406 expn_id: LocalExpnId,
408 ) -> Result<bool, Indeterminate> {
409 let span = path.span;
410 let path = &Segment::from_path(path);
411 let parent_scope = self.invocation_parent_scopes[&expn_id];
413 let mut indeterminate = false;
414 for ns in [TypeNS, ValueNS, MacroNS].iter().copied() {
415 match self.maybe_resolve_path(path, Some(ns), &parent_scope) {
416 PathResult::Module(ModuleOrUniformRoot::Module(_)) => return Ok(true),
417 PathResult::NonModule(partial_res) if partial_res.unresolved_segments() == 0 => {
420 PathResult::Indeterminate => indeterminate = true,
421 // FIXME: `resolve_path` is not ready to report partially resolved paths
422 // correctly, so we just report an error if the path was reported as unresolved.
423 // This needs to be fixed for `cfg_accessible` to be useful.
424 PathResult::NonModule(..) | PathResult::Failed { .. } => {}
425 PathResult::Module(_) => panic!("unexpected path resolution"),
430 return Err(Indeterminate);
434 .struct_span_err(span, "not sure whether the path is accessible or not")
435 .span_note(span, "`cfg_accessible` is not fully implemented")
440 fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span {
441 self.crate_loader.cstore().get_proc_macro_quoted_span_untracked(krate, id, self.session)
444 fn declare_proc_macro(&mut self, id: NodeId) {
445 self.proc_macros.push(id)
448 fn registered_tools(&self) -> &RegisteredTools {
449 &self.registered_tools
453 impl<'a> Resolver<'a> {
454 /// Resolve macro path with error reporting and recovery.
455 /// Uses dummy syntax extensions for unresolved macros or macros with unexpected resolutions
456 /// for better error recovery.
457 fn smart_resolve_macro_path(
461 supports_macro_expansion: SupportsMacroExpansion,
463 parent_scope: &ParentScope<'a>,
466 soft_custom_inner_attributes_gate: bool,
467 ) -> Result<(Lrc<SyntaxExtension>, Res), Indeterminate> {
468 let (ext, res) = match self.resolve_macro_path(path, Some(kind), parent_scope, true, force)
470 Ok((Some(ext), res)) => (ext, res),
471 Ok((None, res)) => (self.dummy_ext(kind), res),
472 Err(Determinacy::Determined) => (self.dummy_ext(kind), Res::Err),
473 Err(Determinacy::Undetermined) => return Err(Indeterminate),
476 // Report errors for the resolved macro.
477 for segment in &path.segments {
478 if let Some(args) = &segment.args {
479 self.session.span_err(args.span(), "generic arguments in macro path");
481 if kind == MacroKind::Attr && segment.ident.as_str().starts_with("rustc") {
482 self.session.span_err(
484 "attributes starting with `rustc` are reserved for use by the `rustc` compiler",
490 Res::Def(DefKind::Macro(_), def_id) => {
491 if let Some(def_id) = def_id.as_local() {
492 self.unused_macros.remove(&def_id);
493 if self.proc_macro_stubs.contains(&def_id) {
494 self.session.span_err(
496 "can't use a procedural macro from the same crate that defines it",
501 Res::NonMacroAttr(..) | Res::Err => {}
502 _ => panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"),
505 self.check_stability_and_deprecation(&ext, path, node_id);
507 let unexpected_res = if ext.macro_kind() != kind {
508 Some((kind.article(), kind.descr_expected()))
509 } else if matches!(res, Res::Def(..)) {
510 match supports_macro_expansion {
511 SupportsMacroExpansion::No => Some(("a", "non-macro attribute")),
512 SupportsMacroExpansion::Yes { supports_inner_attrs } => {
513 if inner_attr && !supports_inner_attrs {
514 Some(("a", "non-macro inner attribute"))
523 if let Some((article, expected)) = unexpected_res {
524 let path_str = pprust::path_to_string(path);
525 let msg = format!("expected {}, found {} `{}`", expected, res.descr(), path_str);
527 .struct_span_err(path.span, &msg)
528 .span_label(path.span, format!("not {} {}", article, expected))
530 return Ok((self.dummy_ext(kind), Res::Err));
533 // We are trying to avoid reporting this error if other related errors were reported.
536 && !self.session.features_untracked().custom_inner_attributes
538 let msg = match res {
539 Res::Def(..) => "inner macro attributes are unstable",
540 Res::NonMacroAttr(..) => "custom inner attributes are unstable",
543 if soft_custom_inner_attributes_gate {
544 self.session.parse_sess.buffer_lint(SOFT_UNSTABLE, path.span, node_id, msg);
546 feature_err(&self.session.parse_sess, sym::custom_inner_attributes, path.span, msg)
554 pub fn resolve_macro_path(
557 kind: Option<MacroKind>,
558 parent_scope: &ParentScope<'a>,
561 ) -> Result<(Option<Lrc<SyntaxExtension>>, Res), Determinacy> {
562 let path_span = path.span;
563 let mut path = Segment::from_path(path);
565 // Possibly apply the macro helper hack
566 if kind == Some(MacroKind::Bang)
568 && path[0].ident.span.ctxt().outer_expn_data().local_inner_macros
570 let root = Ident::new(kw::DollarCrate, path[0].ident.span);
571 path.insert(0, Segment::from_ident(root));
574 let res = if path.len() > 1 {
575 let res = match self.maybe_resolve_path(&path, Some(MacroNS), parent_scope) {
576 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
577 Ok(path_res.base_res())
579 PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
580 PathResult::NonModule(..)
581 | PathResult::Indeterminate
582 | PathResult::Failed { .. } => Err(Determinacy::Determined),
583 PathResult::Module(..) => unreachable!(),
587 let kind = kind.expect("macro kind must be specified if tracing is enabled");
588 self.multi_segment_macro_resolutions.push((
597 self.prohibit_imported_non_macro_attrs(None, res.ok(), path_span);
600 let scope_set = kind.map_or(ScopeSet::All(MacroNS, false), ScopeSet::Macro);
601 let binding = self.early_resolve_ident_in_lexical_scope(
610 if let Err(Determinacy::Undetermined) = binding {
611 return Err(Determinacy::Undetermined);
615 let kind = kind.expect("macro kind must be specified if tracing is enabled");
616 self.single_segment_macro_resolutions.push((
624 let res = binding.map(|binding| binding.res());
625 self.prohibit_imported_non_macro_attrs(binding.ok(), res.ok(), path_span);
629 res.map(|res| (self.get_macro(res), res))
632 crate fn finalize_macro_resolutions(&mut self) {
633 let check_consistency = |this: &mut Self,
637 initial_res: Option<Res>,
639 if let Some(initial_res) = initial_res {
640 if res != initial_res {
641 // Make sure compilation does not succeed if preferred macro resolution
642 // has changed after the macro had been expanded. In theory all such
643 // situations should be reported as errors, so this is a bug.
644 this.session.delay_span_bug(span, "inconsistent resolution for a macro");
647 // It's possible that the macro was unresolved (indeterminate) and silently
648 // expanded into a dummy fragment for recovery during expansion.
649 // Now, post-expansion, the resolution may succeed, but we can't change the
650 // past and need to report an error.
651 // However, non-speculative `resolve_path` can successfully return private items
652 // even if speculative `resolve_path` returned nothing previously, so we skip this
653 // less informative error if the privacy error is reported elsewhere.
654 if this.privacy_errors.is_empty() {
656 "cannot determine resolution for the {} `{}`",
658 Segment::names_to_string(path)
660 let msg_note = "import resolution is stuck, try simplifying macro imports";
661 this.session.struct_span_err(span, &msg).note(msg_note).emit();
666 let macro_resolutions = mem::take(&mut self.multi_segment_macro_resolutions);
667 for (mut path, path_span, kind, parent_scope, initial_res) in macro_resolutions {
668 // FIXME: Path resolution will ICE if segment IDs present.
669 for seg in &mut path {
672 match self.resolve_path(
676 Finalize::SimplePath(ast::CRATE_NODE_ID, path_span),
679 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
680 let res = path_res.base_res();
681 check_consistency(self, &path, path_span, kind, initial_res, res);
683 path_res @ PathResult::NonModule(..) | path_res @ PathResult::Failed { .. } => {
684 let (span, label) = if let PathResult::Failed { span, label, .. } = path_res {
690 "partially resolved path in {} {}",
698 ResolutionError::FailedToResolve { label, suggestion: None },
701 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
705 let macro_resolutions = mem::take(&mut self.single_segment_macro_resolutions);
706 for (ident, kind, parent_scope, initial_binding) in macro_resolutions {
707 match self.early_resolve_ident_in_lexical_scope(
709 ScopeSet::Macro(kind),
717 let initial_res = initial_binding.map(|initial_binding| {
718 self.record_use(ident, initial_binding, false);
719 initial_binding.res()
721 let res = binding.res();
722 let seg = Segment::from_ident(ident);
723 check_consistency(self, &[seg], ident.span, kind, initial_res, res);
724 if res == Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat) {
727 .get(&parent_scope.expansion)
728 .map_or(ast::CRATE_NODE_ID, |id| self.def_id_to_node_id[id.0]);
729 self.lint_buffer.buffer_lint_with_diagnostic(
730 LEGACY_DERIVE_HELPERS,
733 "derive helper attribute is used before it is introduced",
734 BuiltinLintDiagnostics::LegacyDeriveHelpers(binding.span),
739 let expected = kind.descr_expected();
740 let msg = format!("cannot find {} `{}` in this scope", expected, ident);
741 let mut err = self.session.struct_span_err(ident.span, &msg);
742 self.unresolved_macro_suggestions(&mut err, kind, &parent_scope, ident);
748 let builtin_attrs = mem::take(&mut self.builtin_attrs);
749 for (ident, parent_scope) in builtin_attrs {
750 let _ = self.early_resolve_ident_in_lexical_scope(
752 ScopeSet::Macro(MacroKind::Attr),
762 fn check_stability_and_deprecation(
764 ext: &SyntaxExtension,
768 let span = path.span;
769 if let Some(stability) = &ext.stability {
770 if let StabilityLevel::Unstable { reason, issue, is_soft } = stability.level {
771 let feature = stability.feature;
772 if !self.active_features.contains(&feature) && !span.allows_unstable(feature) {
773 let lint_buffer = &mut self.lint_buffer;
775 |lint, span, msg: &_| lint_buffer.buffer_lint(lint, node_id, span, msg);
776 stability::report_unstable(
789 if let Some(depr) = &ext.deprecation {
790 let path = pprust::path_to_string(&path);
791 let (message, lint) = stability::deprecation_message_and_lint(depr, "macro", &path);
792 stability::early_report_deprecation(
793 &mut self.lint_buffer,
803 fn prohibit_imported_non_macro_attrs(
805 binding: Option<&'a NameBinding<'a>>,
809 if let Some(Res::NonMacroAttr(kind)) = res {
810 if kind != NonMacroAttrKind::Tool && binding.map_or(true, |b| b.is_import()) {
812 format!("cannot use {} {} through an import", kind.article(), kind.descr());
813 let mut err = self.session.struct_span_err(span, &msg);
814 if let Some(binding) = binding {
815 err.span_note(binding.span, &format!("the {} imported here", kind.descr()));
822 crate fn check_reserved_macro_name(&mut self, ident: Ident, res: Res) {
823 // Reserve some names that are not quite covered by the general check
824 // performed on `Resolver::builtin_attrs`.
825 if ident.name == sym::cfg || ident.name == sym::cfg_attr {
826 let macro_kind = self.get_macro(res).map(|ext| ext.macro_kind());
827 if macro_kind.is_some() && sub_namespace_match(macro_kind, Some(MacroKind::Attr)) {
828 self.session.span_err(
830 &format!("name `{}` is reserved in attribute namespace", ident),
836 /// Compile the macro into a `SyntaxExtension` and possibly replace
837 /// its expander to a pre-defined one for built-in macros.
838 crate fn compile_macro(&mut self, item: &ast::Item, edition: Edition) -> SyntaxExtension {
839 let mut result = compile_declarative_macro(
841 self.session.features_untracked(),
846 if let Some(builtin_name) = result.builtin_name {
847 // The macro was marked with `#[rustc_builtin_macro]`.
848 if let Some(builtin_macro) = self.builtin_macros.get_mut(&builtin_name) {
849 // The macro is a built-in, replace its expander function
850 // while still taking everything else from the source code.
851 // If we already loaded this builtin macro, give a better error message than 'no such builtin macro'.
852 match mem::replace(builtin_macro, BuiltinMacroState::AlreadySeen(item.span)) {
853 BuiltinMacroState::NotYetSeen(ext) => {
855 if item.id != ast::DUMMY_NODE_ID {
856 self.builtin_macro_kinds
857 .insert(self.local_def_id(item.id), result.macro_kind());
860 BuiltinMacroState::AlreadySeen(span) => {
865 "attempted to define built-in macro more than once"
867 .span_note(span, "previously defined here")
872 let msg = format!("cannot find a built-in macro with name `{}`", item.ident);
873 self.session.span_err(item.span, &msg);