]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_resolve/src/macros.rs
Auto merge of #95656 - cjgillot:no-id-hashing-mode, r=Aaron1011
[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_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};
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     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>,
46     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 crate fn sub_namespace_match(candidate: Option<MacroKind>, requirement: Option<MacroKind>) -> bool {
77     #[derive(PartialEq)]
78     enum SubNS {
79         Bang,
80         AttrLike,
81     }
82     let sub_ns = |kind| match kind {
83         MacroKind::Bang => SubNS::Bang,
84         MacroKind::Attr | MacroKind::Derive => SubNS::AttrLike,
85     };
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
90 }
91
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
98     } else {
99         let mut path_str = String::with_capacity(64);
100         for (i, segment) in path.segments.iter().enumerate() {
101             if i != 0 {
102                 path_str.push_str("::");
103             }
104             if segment.ident.name != kw::PathRoot {
105                 path_str.push_str(segment.ident.as_str())
106             }
107         }
108         Symbol::intern(&path_str)
109     }
110 }
111
112 /// The code common between processing `#![register_tool]` and `#![register_attr]`.
113 fn registered_idents(
114     sess: &Session,
115     attrs: &[ast::Attribute],
116     attr_name: Symbol,
117     descr: &str,
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() {
123                 Some(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")
128                             .emit();
129                     }
130                 }
131                 None => {
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();
135                 }
136             }
137         }
138     }
139     registered
140 }
141
142 crate fn registered_attrs_and_tools(
143     sess: &Session,
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)
153 }
154
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[..] {
158         // `#![test]`
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 {
165                         return true;
166                     }
167                 }
168             }
169         }
170         _ => {}
171     }
172     false
173 }
174
175 impl<'a> ResolverExpand for Resolver<'a> {
176     fn next_node_id(&mut self) -> NodeId {
177         self.next_node_id()
178     }
179
180     fn invocation_parent(&self, id: LocalExpnId) -> LocalDefId {
181         self.invocation_parents[&id].0
182     }
183
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,
189                 _ => kw::Crate,
190             }
191         });
192     }
193
194     fn visit_ast_fragment_with_placeholders(
195         &mut self,
196         expansion: LocalExpnId,
197         fragment: &AstFragment,
198     ) {
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);
204
205         parent_scope.module.unexpanded_invocations.borrow_mut().remove(&expansion);
206     }
207
208     fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind) {
209         if self.builtin_macros.insert(name, BuiltinMacroState::NotYetSeen(ext)).is_some() {
210             self.session
211                 .diagnostic()
212                 .bug(&format!("built-in macro `{}` was already registered", name));
213         }
214     }
215
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(
219         &mut self,
220         call_site: Span,
221         pass: AstPass,
222         features: &[Symbol],
223         parent_module_id: Option<NodeId>,
224     ) -> LocalExpnId {
225         let parent_module =
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),
230                 call_site,
231                 self.session.edition(),
232                 features.into(),
233                 None,
234                 parent_module,
235             ),
236             self.create_stable_hashing_context(),
237         );
238
239         let parent_scope =
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);
242
243         expn_id
244     }
245
246     fn resolve_imports(&mut self) {
247         ImportResolver { r: self }.resolve_imports()
248     }
249
250     fn resolve_macro_invocation(
251         &mut self,
252         invoc: &Invocation,
253         eager_expansion_root: LocalExpnId,
254         force: bool,
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,
259             None => {
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);
268                 parent_scope
269             }
270         };
271
272         let (path, kind, inner_attr, derives) = match invoc.kind {
273             InvocationKind::Attr { ref attr, ref derives, .. } => (
274                 &attr.get_normal_item().path,
275                 MacroKind::Attr,
276                 attr.style == ast::AttrStyle::Inner,
277                 self.arenas.alloc_ast_paths(derives),
278             ),
279             InvocationKind::Bang { ref mac, .. } => (&mac.path, MacroKind::Bang, false, &[][..]),
280             InvocationKind::Derive { ref path, .. } => (path, MacroKind::Derive, false, &[][..]),
281         };
282
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(
288             path,
289             kind,
290             supports_macro_expansion,
291             inner_attr,
292             parent_scope,
293             node_id,
294             force,
295             soft_custom_inner_attributes_gate(path, invoc),
296         )?;
297
298         let span = invoc.span();
299         let def_id = res.opt_def_id();
300         invoc_id.set_expn_data(
301             ext.expn_data(
302                 parent_scope.expansion,
303                 span,
304                 fast_print_path(path),
305                 def_id,
306                 def_id.map(|def_id| self.macro_def_scope(def_id).nearest_parent_mod()),
307             ),
308             self.create_stable_hashing_context(),
309         );
310
311         Ok(ext)
312     }
313
314     fn check_unused_macros(&mut self) {
315         for (_, &(node_id, ident)) in self.unused_macros.iter() {
316             self.lint_buffer.buffer_lint(
317                 UNUSED_MACROS,
318                 node_id,
319                 ident.span,
320                 &format!("unused macro definition: `{}`", ident.as_str()),
321             );
322         }
323     }
324
325     fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool {
326         self.containers_deriving_copy.contains(&expn_id)
327     }
328
329     fn resolve_derives(
330         &mut self,
331         expn_id: LocalExpnId,
332         force: bool,
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,
347         });
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() {
351                 *opt_ext = Some(
352                     match self.resolve_macro_path(
353                         &path,
354                         Some(MacroKind::Derive),
355                         &parent_scope,
356                         true,
357                         force,
358                     ) {
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(
364                                     ext.helper_attrs
365                                         .iter()
366                                         .map(|name| (i, Ident::new(*name, span))),
367                                 );
368                             }
369                             entry.has_derive_copy |= ext.builtin_name == Some(sym::Copy);
370                             ext
371                         }
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);
377                         }
378                     },
379                 );
380             }
381         }
382         // Sort helpers in a stable way independent from the derive resolution order.
383         entry.helper_attrs.sort_by_key(|(i, _)| *i);
384         self.helper_attrs
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);
390         }
391         assert!(self.derive_data.is_empty());
392         self.derive_data = derive_data;
393         Ok(())
394     }
395
396     fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<DeriveResolutions> {
397         self.derive_data.remove(&expn_id).map(|data| data.resolutions)
398     }
399
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.
404     fn cfg_accessible(
405         &mut self,
406         expn_id: LocalExpnId,
407         path: &ast::Path,
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];
412
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 => {
418                     return Ok(true);
419                 }
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"),
426             }
427         }
428
429         if indeterminate {
430             return Err(Indeterminate);
431         }
432
433         self.session
434             .struct_span_err(span, "not sure whether the path is accessible or not")
435             .span_note(span, "`cfg_accessible` is not fully implemented")
436             .emit();
437         Ok(false)
438     }
439
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)
442     }
443
444     fn declare_proc_macro(&mut self, id: NodeId) {
445         self.proc_macros.push(id)
446     }
447
448     fn registered_tools(&self) -> &RegisteredTools {
449         &self.registered_tools
450     }
451 }
452
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(
458         &mut self,
459         path: &ast::Path,
460         kind: MacroKind,
461         supports_macro_expansion: SupportsMacroExpansion,
462         inner_attr: bool,
463         parent_scope: &ParentScope<'a>,
464         node_id: NodeId,
465         force: bool,
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)
469         {
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),
474         };
475
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");
480             }
481             if kind == MacroKind::Attr && segment.ident.as_str().starts_with("rustc") {
482                 self.session.span_err(
483                     segment.ident.span,
484                     "attributes starting with `rustc` are reserved for use by the `rustc` compiler",
485                 );
486             }
487         }
488
489         match res {
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(
495                             path.span,
496                             "can't use a procedural macro from the same crate that defines it",
497                         );
498                     }
499                 }
500             }
501             Res::NonMacroAttr(..) | Res::Err => {}
502             _ => panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"),
503         };
504
505         self.check_stability_and_deprecation(&ext, path, node_id);
506
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"))
515                     } else {
516                         None
517                     }
518                 }
519             }
520         } else {
521             None
522         };
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);
526             self.session
527                 .struct_span_err(path.span, &msg)
528                 .span_label(path.span, format!("not {} {}", article, expected))
529                 .emit();
530             return Ok((self.dummy_ext(kind), Res::Err));
531         }
532
533         // We are trying to avoid reporting this error if other related errors were reported.
534         if res != Res::Err
535             && inner_attr
536             && !self.session.features_untracked().custom_inner_attributes
537         {
538             let msg = match res {
539                 Res::Def(..) => "inner macro attributes are unstable",
540                 Res::NonMacroAttr(..) => "custom inner attributes are unstable",
541                 _ => unreachable!(),
542             };
543             if soft_custom_inner_attributes_gate {
544                 self.session.parse_sess.buffer_lint(SOFT_UNSTABLE, path.span, node_id, msg);
545             } else {
546                 feature_err(&self.session.parse_sess, sym::custom_inner_attributes, path.span, msg)
547                     .emit();
548             }
549         }
550
551         Ok((ext, res))
552     }
553
554     pub fn resolve_macro_path(
555         &mut self,
556         path: &ast::Path,
557         kind: Option<MacroKind>,
558         parent_scope: &ParentScope<'a>,
559         trace: bool,
560         force: bool,
561     ) -> Result<(Option<Lrc<SyntaxExtension>>, Res), Determinacy> {
562         let path_span = path.span;
563         let mut path = Segment::from_path(path);
564
565         // Possibly apply the macro helper hack
566         if kind == Some(MacroKind::Bang)
567             && path.len() == 1
568             && path[0].ident.span.ctxt().outer_expn_data().local_inner_macros
569         {
570             let root = Ident::new(kw::DollarCrate, path[0].ident.span);
571             path.insert(0, Segment::from_ident(root));
572         }
573
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())
578                 }
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!(),
584             };
585
586             if trace {
587                 let kind = kind.expect("macro kind must be specified if tracing is enabled");
588                 self.multi_segment_macro_resolutions.push((
589                     path,
590                     path_span,
591                     kind,
592                     *parent_scope,
593                     res.ok(),
594                 ));
595             }
596
597             self.prohibit_imported_non_macro_attrs(None, res.ok(), path_span);
598             res
599         } else {
600             let scope_set = kind.map_or(ScopeSet::All(MacroNS, false), ScopeSet::Macro);
601             let binding = self.early_resolve_ident_in_lexical_scope(
602                 path[0].ident,
603                 scope_set,
604                 parent_scope,
605                 None,
606                 force,
607                 false,
608                 None,
609             );
610             if let Err(Determinacy::Undetermined) = binding {
611                 return Err(Determinacy::Undetermined);
612             }
613
614             if trace {
615                 let kind = kind.expect("macro kind must be specified if tracing is enabled");
616                 self.single_segment_macro_resolutions.push((
617                     path[0].ident,
618                     kind,
619                     *parent_scope,
620                     binding.ok(),
621                 ));
622             }
623
624             let res = binding.map(|binding| binding.res());
625             self.prohibit_imported_non_macro_attrs(binding.ok(), res.ok(), path_span);
626             res
627         };
628
629         res.map(|res| (self.get_macro(res), res))
630     }
631
632     crate fn finalize_macro_resolutions(&mut self) {
633         let check_consistency = |this: &mut Self,
634                                  path: &[Segment],
635                                  span,
636                                  kind: MacroKind,
637                                  initial_res: Option<Res>,
638                                  res: 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");
645                 }
646             } else {
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() {
655                     let msg = format!(
656                         "cannot determine resolution for the {} `{}`",
657                         kind.descr(),
658                         Segment::names_to_string(path)
659                     );
660                     let msg_note = "import resolution is stuck, try simplifying macro imports";
661                     this.session.struct_span_err(span, &msg).note(msg_note).emit();
662                 }
663             }
664         };
665
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 {
670                 seg.id = None;
671             }
672             match self.resolve_path(
673                 &path,
674                 Some(MacroNS),
675                 &parent_scope,
676                 Finalize::SimplePath(ast::CRATE_NODE_ID, path_span),
677                 None,
678             ) {
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);
682                 }
683                 path_res @ PathResult::NonModule(..) | path_res @ PathResult::Failed { .. } => {
684                     let (span, label) = if let PathResult::Failed { span, label, .. } = path_res {
685                         (span, label)
686                     } else {
687                         (
688                             path_span,
689                             format!(
690                                 "partially resolved path in {} {}",
691                                 kind.article(),
692                                 kind.descr()
693                             ),
694                         )
695                     };
696                     self.report_error(
697                         span,
698                         ResolutionError::FailedToResolve { label, suggestion: None },
699                     );
700                 }
701                 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
702             }
703         }
704
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(
708                 ident,
709                 ScopeSet::Macro(kind),
710                 &parent_scope,
711                 Some(ident.span),
712                 true,
713                 false,
714                 None,
715             ) {
716                 Ok(binding) => {
717                     let initial_res = initial_binding.map(|initial_binding| {
718                         self.record_use(ident, initial_binding, false);
719                         initial_binding.res()
720                     });
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) {
725                         let node_id = self
726                             .invocation_parents
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,
731                             node_id,
732                             ident.span,
733                             "derive helper attribute is used before it is introduced",
734                             BuiltinLintDiagnostics::LegacyDeriveHelpers(binding.span),
735                         );
736                     }
737                 }
738                 Err(..) => {
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);
743                     err.emit();
744                 }
745             }
746         }
747
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(
751                 ident,
752                 ScopeSet::Macro(MacroKind::Attr),
753                 &parent_scope,
754                 Some(ident.span),
755                 true,
756                 false,
757                 None,
758             );
759         }
760     }
761
762     fn check_stability_and_deprecation(
763         &mut self,
764         ext: &SyntaxExtension,
765         path: &ast::Path,
766         node_id: NodeId,
767     ) {
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;
774                     let soft_handler =
775                         |lint, span, msg: &_| lint_buffer.buffer_lint(lint, node_id, span, msg);
776                     stability::report_unstable(
777                         self.session,
778                         feature,
779                         reason,
780                         issue,
781                         None,
782                         is_soft,
783                         span,
784                         soft_handler,
785                     );
786                 }
787             }
788         }
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,
794                 &message,
795                 depr.suggestion,
796                 lint,
797                 span,
798                 node_id,
799             );
800         }
801     }
802
803     fn prohibit_imported_non_macro_attrs(
804         &self,
805         binding: Option<&'a NameBinding<'a>>,
806         res: Option<Res>,
807         span: Span,
808     ) {
809         if let Some(Res::NonMacroAttr(kind)) = res {
810             if kind != NonMacroAttrKind::Tool && binding.map_or(true, |b| b.is_import()) {
811                 let msg =
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()));
816                 }
817                 err.emit();
818             }
819         }
820     }
821
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(
829                     ident.span,
830                     &format!("name `{}` is reserved in attribute namespace", ident),
831                 );
832             }
833         }
834     }
835
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(
840             &self.session,
841             self.session.features_untracked(),
842             item,
843             edition,
844         );
845
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) => {
854                         result.kind = 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());
858                         }
859                     }
860                     BuiltinMacroState::AlreadySeen(span) => {
861                         struct_span_err!(
862                             self.session,
863                             item.span,
864                             E0773,
865                             "attempted to define built-in macro more than once"
866                         )
867                         .span_note(span, "previously defined here")
868                         .emit();
869                     }
870                 }
871             } else {
872                 let msg = format!("cannot find a built-in macro with name `{}`", item.ident);
873                 self.session.span_err(item.span, &msg);
874             }
875         }
876
877         result
878     }
879 }