]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_resolve/src/macros.rs
Rollup merge of #99508 - TaKO8Ki:avoid-symbol-to-string-conversion-in-BuiltinLintDiag...
[rust.git] / compiler / rustc_resolve / src / macros.rs
1 //! A bunch of methods and structures more or less related to resolving macros and
2 //! interface provided by `Resolver` to macro expander.
3
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};
34 use std::cell::Cell;
35 use std::mem;
36
37 type Res = def::Res<NodeId>;
38
39 /// Binding produced by a `macro_rules` item.
40 /// Not modularized, can shadow previous `macro_rules` bindings, etc.
41 #[derive(Debug)]
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,
47 }
48
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.
57     Empty,
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),
63 }
64
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>>>;
72
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>,
79 ) -> bool {
80     #[derive(PartialEq)]
81     enum SubNS {
82         Bang,
83         AttrLike,
84     }
85     let sub_ns = |kind| match kind {
86         MacroKind::Bang => SubNS::Bang,
87         MacroKind::Attr | MacroKind::Derive => SubNS::AttrLike,
88     };
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
93 }
94
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
101     } else {
102         let mut path_str = String::with_capacity(64);
103         for (i, segment) in path.segments.iter().enumerate() {
104             if i != 0 {
105                 path_str.push_str("::");
106             }
107             if segment.ident.name != kw::PathRoot {
108                 path_str.push_str(segment.ident.as_str())
109             }
110         }
111         Symbol::intern(&path_str)
112     }
113 }
114
115 /// The code common between processing `#![register_tool]` and `#![register_attr]`.
116 fn registered_idents(
117     sess: &Session,
118     attrs: &[ast::Attribute],
119     attr_name: Symbol,
120     descr: &str,
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() {
126                 Some(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")
131                             .emit();
132                     }
133                 }
134                 None => {
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();
138                 }
139             }
140         }
141     }
142     registered
143 }
144
145 pub(crate) fn registered_attrs_and_tools(
146     sess: &Session,
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)
156 }
157
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[..] {
161         // `#![test]`
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 {
168                         return true;
169                     }
170                 }
171             }
172         }
173         _ => {}
174     }
175     false
176 }
177
178 impl<'a> ResolverExpand for Resolver<'a> {
179     fn next_node_id(&mut self) -> NodeId {
180         self.next_node_id()
181     }
182
183     fn invocation_parent(&self, id: LocalExpnId) -> LocalDefId {
184         self.invocation_parents[&id].0
185     }
186
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,
192                 _ => kw::Crate,
193             }
194         });
195     }
196
197     fn visit_ast_fragment_with_placeholders(
198         &mut self,
199         expansion: LocalExpnId,
200         fragment: &AstFragment,
201     ) {
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);
207
208         parent_scope.module.unexpanded_invocations.borrow_mut().remove(&expansion);
209     }
210
211     fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind) {
212         if self.builtin_macros.insert(name, BuiltinMacroState::NotYetSeen(ext)).is_some() {
213             self.session
214                 .diagnostic()
215                 .bug(&format!("built-in macro `{}` was already registered", name));
216         }
217     }
218
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(
222         &mut self,
223         call_site: Span,
224         pass: AstPass,
225         features: &[Symbol],
226         parent_module_id: Option<NodeId>,
227     ) -> LocalExpnId {
228         let parent_module =
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),
233                 call_site,
234                 self.session.edition(),
235                 features.into(),
236                 None,
237                 parent_module,
238             ),
239             self.create_stable_hashing_context(),
240         );
241
242         let parent_scope =
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);
245
246         expn_id
247     }
248
249     fn resolve_imports(&mut self) {
250         ImportResolver { r: self }.resolve_imports()
251     }
252
253     fn resolve_macro_invocation(
254         &mut self,
255         invoc: &Invocation,
256         eager_expansion_root: LocalExpnId,
257         force: bool,
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,
262             None => {
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);
271                 parent_scope
272             }
273         };
274
275         let (path, kind, inner_attr, derives) = match invoc.kind {
276             InvocationKind::Attr { ref attr, ref derives, .. } => (
277                 &attr.get_normal_item().path,
278                 MacroKind::Attr,
279                 attr.style == ast::AttrStyle::Inner,
280                 self.arenas.alloc_ast_paths(derives),
281             ),
282             InvocationKind::Bang { ref mac, .. } => (&mac.path, MacroKind::Bang, false, &[][..]),
283             InvocationKind::Derive { ref path, .. } => (path, MacroKind::Derive, false, &[][..]),
284         };
285
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(
291             path,
292             kind,
293             supports_macro_expansion,
294             inner_attr,
295             parent_scope,
296             node_id,
297             force,
298             soft_custom_inner_attributes_gate(path, invoc),
299         )?;
300
301         let span = invoc.span();
302         let def_id = res.opt_def_id();
303         invoc_id.set_expn_data(
304             ext.expn_data(
305                 parent_scope.expansion,
306                 span,
307                 fast_print_path(path),
308                 def_id,
309                 def_id.map(|def_id| self.macro_def_scope(def_id).nearest_parent_mod()),
310             ),
311             self.create_stable_hashing_context(),
312         );
313
314         Ok(ext)
315     }
316
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));
320     }
321
322     fn check_unused_macros(&mut self) {
323         for (_, &(node_id, ident)) in self.unused_macros.iter() {
324             self.lint_buffer.buffer_lint(
325                 UNUSED_MACROS,
326                 node_id,
327                 ident.span,
328                 &format!("unused macro definition: `{}`", ident.name),
329             );
330         }
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
334                 continue;
335             }
336             let node_id = self.def_id_to_node_id[def_id];
337             self.lint_buffer.buffer_lint(
338                 UNUSED_MACRO_RULES,
339                 node_id,
340                 rule_span,
341                 &format!(
342                     "{} rule of macro `{}` is never used",
343                     crate::diagnostics::ordinalize(arm_i + 1),
344                     ident.name
345                 ),
346             );
347         }
348     }
349
350     fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool {
351         self.containers_deriving_copy.contains(&expn_id)
352     }
353
354     fn resolve_derives(
355         &mut self,
356         expn_id: LocalExpnId,
357         force: bool,
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,
372         });
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() {
376                 *opt_ext = Some(
377                     match self.resolve_macro_path(
378                         &path,
379                         Some(MacroKind::Derive),
380                         &parent_scope,
381                         true,
382                         force,
383                     ) {
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(
389                                     ext.helper_attrs
390                                         .iter()
391                                         .map(|name| (i, Ident::new(*name, span))),
392                                 );
393                             }
394                             entry.has_derive_copy |= ext.builtin_name == Some(sym::Copy);
395                             ext
396                         }
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);
402                         }
403                     },
404                 );
405             }
406         }
407         // Sort helpers in a stable way independent from the derive resolution order.
408         entry.helper_attrs.sort_by_key(|(i, _)| *i);
409         self.helper_attrs
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);
415         }
416         assert!(self.derive_data.is_empty());
417         self.derive_data = derive_data;
418         Ok(())
419     }
420
421     fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<DeriveResolutions> {
422         self.derive_data.remove(&expn_id).map(|data| data.resolutions)
423     }
424
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.
429     fn cfg_accessible(
430         &mut self,
431         expn_id: LocalExpnId,
432         path: &ast::Path,
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];
437
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 => {
443                     return Ok(true);
444                 }
445                 PathResult::NonModule(..) |
446                 // HACK(Urgau): This shouldn't be necessary
447                 PathResult::Failed { is_error_from_last_segment: false, .. } => {
448                     self.session
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")
451                         .emit();
452
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.
455                     return Ok(false);
456                 }
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"),
462             }
463         }
464
465         if indeterminate {
466             return Err(Indeterminate);
467         }
468
469         Ok(false)
470     }
471
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)
474     }
475
476     fn declare_proc_macro(&mut self, id: NodeId) {
477         self.proc_macros.push(id)
478     }
479
480     fn registered_tools(&self) -> &RegisteredTools {
481         &self.registered_tools
482     }
483 }
484
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(
490         &mut self,
491         path: &ast::Path,
492         kind: MacroKind,
493         supports_macro_expansion: SupportsMacroExpansion,
494         inner_attr: bool,
495         parent_scope: &ParentScope<'a>,
496         node_id: NodeId,
497         force: bool,
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)
501         {
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),
506         };
507
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");
512             }
513             if kind == MacroKind::Attr && segment.ident.as_str().starts_with("rustc") {
514                 self.session.span_err(
515                     segment.ident.span,
516                     "attributes starting with `rustc` are reserved for use by the `rustc` compiler",
517                 );
518             }
519         }
520
521         match res {
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(
527                             path.span,
528                             "can't use a procedural macro from the same crate that defines it",
529                         );
530                     }
531                 }
532             }
533             Res::NonMacroAttr(..) | Res::Err => {}
534             _ => panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"),
535         };
536
537         self.check_stability_and_deprecation(&ext, path, node_id);
538
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"))
547                     } else {
548                         None
549                     }
550                 }
551             }
552         } else {
553             None
554         };
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);
558             self.session
559                 .struct_span_err(path.span, &msg)
560                 .span_label(path.span, format!("not {} {}", article, expected))
561                 .emit();
562             return Ok((self.dummy_ext(kind), Res::Err));
563         }
564
565         // We are trying to avoid reporting this error if other related errors were reported.
566         if res != Res::Err
567             && inner_attr
568             && !self.session.features_untracked().custom_inner_attributes
569         {
570             let msg = match res {
571                 Res::Def(..) => "inner macro attributes are unstable",
572                 Res::NonMacroAttr(..) => "custom inner attributes are unstable",
573                 _ => unreachable!(),
574             };
575             if soft_custom_inner_attributes_gate {
576                 self.session.parse_sess.buffer_lint(SOFT_UNSTABLE, path.span, node_id, msg);
577             } else {
578                 feature_err(&self.session.parse_sess, sym::custom_inner_attributes, path.span, msg)
579                     .emit();
580             }
581         }
582
583         Ok((ext, res))
584     }
585
586     pub fn resolve_macro_path(
587         &mut self,
588         path: &ast::Path,
589         kind: Option<MacroKind>,
590         parent_scope: &ParentScope<'a>,
591         trace: bool,
592         force: bool,
593     ) -> Result<(Option<Lrc<SyntaxExtension>>, Res), Determinacy> {
594         let path_span = path.span;
595         let mut path = Segment::from_path(path);
596
597         // Possibly apply the macro helper hack
598         if kind == Some(MacroKind::Bang)
599             && path.len() == 1
600             && path[0].ident.span.ctxt().outer_expn_data().local_inner_macros
601         {
602             let root = Ident::new(kw::DollarCrate, path[0].ident.span);
603             path.insert(0, Segment::from_ident(root));
604         }
605
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())
610                 }
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!(),
616             };
617
618             if trace {
619                 let kind = kind.expect("macro kind must be specified if tracing is enabled");
620                 self.multi_segment_macro_resolutions.push((
621                     path,
622                     path_span,
623                     kind,
624                     *parent_scope,
625                     res.ok(),
626                 ));
627             }
628
629             self.prohibit_imported_non_macro_attrs(None, res.ok(), path_span);
630             res
631         } else {
632             let scope_set = kind.map_or(ScopeSet::All(MacroNS, false), ScopeSet::Macro);
633             let binding = self.early_resolve_ident_in_lexical_scope(
634                 path[0].ident,
635                 scope_set,
636                 parent_scope,
637                 None,
638                 force,
639                 None,
640             );
641             if let Err(Determinacy::Undetermined) = binding {
642                 return Err(Determinacy::Undetermined);
643             }
644
645             if trace {
646                 let kind = kind.expect("macro kind must be specified if tracing is enabled");
647                 self.single_segment_macro_resolutions.push((
648                     path[0].ident,
649                     kind,
650                     *parent_scope,
651                     binding.ok(),
652                 ));
653             }
654
655             let res = binding.map(|binding| binding.res());
656             self.prohibit_imported_non_macro_attrs(binding.ok(), res.ok(), path_span);
657             res
658         };
659
660         res.map(|res| (self.get_macro(res).map(|macro_data| macro_data.ext), res))
661     }
662
663     pub(crate) fn finalize_macro_resolutions(&mut self) {
664         let check_consistency = |this: &mut Self,
665                                  path: &[Segment],
666                                  span,
667                                  kind: MacroKind,
668                                  initial_res: Option<Res>,
669                                  res: 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");
676                 }
677             } else {
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() {
686                     let msg = format!(
687                         "cannot determine resolution for the {} `{}`",
688                         kind.descr(),
689                         Segment::names_to_string(path)
690                     );
691                     let msg_note = "import resolution is stuck, try simplifying macro imports";
692                     this.session.struct_span_err(span, &msg).note(msg_note).emit();
693                 }
694             }
695         };
696
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 {
701                 seg.id = None;
702             }
703             match self.resolve_path(
704                 &path,
705                 Some(MacroNS),
706                 &parent_scope,
707                 Some(Finalize::new(ast::CRATE_NODE_ID, path_span)),
708                 None,
709             ) {
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);
713                 }
714                 path_res @ PathResult::NonModule(..) | path_res @ PathResult::Failed { .. } => {
715                     let (span, label) = if let PathResult::Failed { span, label, .. } = path_res {
716                         (span, label)
717                     } else {
718                         (
719                             path_span,
720                             format!(
721                                 "partially resolved path in {} {}",
722                                 kind.article(),
723                                 kind.descr()
724                             ),
725                         )
726                     };
727                     self.report_error(
728                         span,
729                         ResolutionError::FailedToResolve { label, suggestion: None },
730                     );
731                 }
732                 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
733             }
734         }
735
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(
739                 ident,
740                 ScopeSet::Macro(kind),
741                 &parent_scope,
742                 Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)),
743                 true,
744                 None,
745             ) {
746                 Ok(binding) => {
747                     let initial_res = initial_binding.map(|initial_binding| {
748                         self.record_use(ident, initial_binding, false);
749                         initial_binding.res()
750                     });
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) {
755                         let node_id = self
756                             .invocation_parents
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,
761                             node_id,
762                             ident.span,
763                             "derive helper attribute is used before it is introduced",
764                             BuiltinLintDiagnostics::LegacyDeriveHelpers(binding.span),
765                         );
766                     }
767                 }
768                 Err(..) => {
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);
773                     err.emit();
774                 }
775             }
776         }
777
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(
781                 ident,
782                 ScopeSet::Macro(MacroKind::Attr),
783                 &parent_scope,
784                 Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)),
785                 true,
786                 None,
787             );
788         }
789     }
790
791     fn check_stability_and_deprecation(
792         &mut self,
793         ext: &SyntaxExtension,
794         path: &ast::Path,
795         node_id: NodeId,
796     ) {
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
800             {
801                 let feature = stability.feature;
802
803                 let is_allowed = |feature| {
804                     self.active_features.contains(&feature) || span.allows_unstable(feature)
805                 };
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;
810                     let soft_handler =
811                         |lint, span, msg: &_| lint_buffer.buffer_lint(lint, node_id, span, msg);
812                     stability::report_unstable(
813                         self.session,
814                         feature,
815                         reason,
816                         issue,
817                         None,
818                         is_soft,
819                         span,
820                         soft_handler,
821                     );
822                 }
823             }
824         }
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,
830                 &message,
831                 depr.suggestion,
832                 lint,
833                 span,
834                 node_id,
835             );
836         }
837     }
838
839     fn prohibit_imported_non_macro_attrs(
840         &self,
841         binding: Option<&'a NameBinding<'a>>,
842         res: Option<Res>,
843         span: Span,
844     ) {
845         if let Some(Res::NonMacroAttr(kind)) = res {
846             if kind != NonMacroAttrKind::Tool && binding.map_or(true, |b| b.is_import()) {
847                 let msg =
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()));
852                 }
853                 err.emit();
854             }
855         }
856     }
857
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(
865                     ident.span,
866                     &format!("name `{}` is reserved in attribute namespace", ident),
867                 );
868             }
869         }
870     }
871
872     /// Compile the macro into a `SyntaxExtension` and its rule spans.
873     ///
874     /// Possibly replace its expander to a pre-defined one for built-in macros.
875     pub(crate) fn compile_macro(
876         &mut self,
877         item: &ast::Item,
878         edition: Edition,
879     ) -> (SyntaxExtension, Vec<(usize, Span)>) {
880         let (mut result, mut rule_spans) = compile_declarative_macro(
881             &self.session,
882             self.session.features_untracked(),
883             item,
884             edition,
885         );
886
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) => {
895                         result.kind = 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());
900                         }
901                     }
902                     BuiltinMacroState::AlreadySeen(span) => {
903                         struct_span_err!(
904                             self.session,
905                             item.span,
906                             E0773,
907                             "attempted to define built-in macro more than once"
908                         )
909                         .span_note(span, "previously defined here")
910                         .emit();
911                     }
912                 }
913             } else {
914                 let msg = format!("cannot find a built-in macro with name `{}`", item.ident);
915                 self.session.span_err(item.span, &msg);
916             }
917         }
918
919         (result, rule_spans)
920     }
921 }