]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_resolve/src/macros.rs
Rollup merge of #106739 - WaffleLapkin:astconv, r=estebank
[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, Applicability};
16 use rustc_expand::base::{Annotatable, DeriveResolutions, Indeterminate, ResolverExpand};
17 use rustc_expand::base::{SyntaxExtension, SyntaxExtensionKind};
18 use rustc_expand::compile_declarative_macro;
19 use rustc_expand::expand::{AstFragment, Invocation, InvocationKind, SupportsMacroExpansion};
20 use rustc_hir::def::{self, DefKind, NonMacroAttrKind};
21 use rustc_hir::def_id::{CrateNum, LocalDefId};
22 use rustc_middle::middle::stability;
23 use rustc_middle::ty::RegisteredTools;
24 use rustc_session::lint::builtin::{LEGACY_DERIVE_HELPERS, SOFT_UNSTABLE};
25 use rustc_session::lint::builtin::{UNUSED_MACROS, UNUSED_MACRO_RULES};
26 use rustc_session::lint::BuiltinLintDiagnostics;
27 use rustc_session::parse::feature_err;
28 use rustc_session::Session;
29 use rustc_span::edition::Edition;
30 use rustc_span::hygiene::{self, ExpnData, ExpnKind, LocalExpnId};
31 use rustc_span::hygiene::{AstPass, MacroKind};
32 use rustc_span::symbol::{kw, sym, Ident, Symbol};
33 use rustc_span::{Span, DUMMY_SP};
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 pub(crate) fn registered_tools(sess: &Session, attrs: &[ast::Attribute]) -> FxHashSet<Ident> {
116     let mut registered_tools = FxHashSet::default();
117     for attr in sess.filter_by_name(attrs, sym::register_tool) {
118         for nested_meta in attr.meta_item_list().unwrap_or_default() {
119             match nested_meta.ident() {
120                 Some(ident) => {
121                     if let Some(old_ident) = registered_tools.replace(ident) {
122                         let msg = format!("{} `{}` was already registered", "tool", ident);
123                         sess.struct_span_err(ident.span, &msg)
124                             .span_label(old_ident.span, "already registered here")
125                             .emit();
126                     }
127                 }
128                 None => {
129                     let msg = format!("`{}` only accepts identifiers", sym::register_tool);
130                     let span = nested_meta.span();
131                     sess.struct_span_err(span, &msg).span_label(span, "not an identifier").emit();
132                 }
133             }
134         }
135     }
136     // We implicitly add `rustfmt` and `clippy` to known tools,
137     // but it's not an error to register them explicitly.
138     let predefined_tools = [sym::clippy, sym::rustfmt];
139     registered_tools.extend(predefined_tools.iter().cloned().map(Ident::with_dummy_span));
140     registered_tools
141 }
142
143 // Some feature gates for inner attributes are reported as lints for backward compatibility.
144 fn soft_custom_inner_attributes_gate(path: &ast::Path, invoc: &Invocation) -> bool {
145     match &path.segments[..] {
146         // `#![test]`
147         [seg] if seg.ident.name == sym::test => return true,
148         // `#![rustfmt::skip]` on out-of-line modules
149         [seg1, seg2] if seg1.ident.name == sym::rustfmt && seg2.ident.name == sym::skip => {
150             if let InvocationKind::Attr { item, .. } = &invoc.kind {
151                 if let Annotatable::Item(item) = item {
152                     if let ItemKind::Mod(_, ModKind::Loaded(_, Inline::No, _)) = item.kind {
153                         return true;
154                     }
155                 }
156             }
157         }
158         _ => {}
159     }
160     false
161 }
162
163 impl<'a> ResolverExpand for Resolver<'a> {
164     fn next_node_id(&mut self) -> NodeId {
165         self.next_node_id()
166     }
167
168     fn invocation_parent(&self, id: LocalExpnId) -> LocalDefId {
169         self.invocation_parents[&id].0
170     }
171
172     fn resolve_dollar_crates(&mut self) {
173         hygiene::update_dollar_crate_names(|ctxt| {
174             let ident = Ident::new(kw::DollarCrate, DUMMY_SP.with_ctxt(ctxt));
175             match self.resolve_crate_root(ident).kind {
176                 ModuleKind::Def(.., name) if name != kw::Empty => name,
177                 _ => kw::Crate,
178             }
179         });
180     }
181
182     fn visit_ast_fragment_with_placeholders(
183         &mut self,
184         expansion: LocalExpnId,
185         fragment: &AstFragment,
186     ) {
187         // Integrate the new AST fragment into all the definition and module structures.
188         // We are inside the `expansion` now, but other parent scope components are still the same.
189         let parent_scope = ParentScope { expansion, ..self.invocation_parent_scopes[&expansion] };
190         let output_macro_rules_scope = self.build_reduced_graph(fragment, parent_scope);
191         self.output_macro_rules_scopes.insert(expansion, output_macro_rules_scope);
192
193         parent_scope.module.unexpanded_invocations.borrow_mut().remove(&expansion);
194     }
195
196     fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind) {
197         if self.builtin_macros.insert(name, BuiltinMacroState::NotYetSeen(ext)).is_some() {
198             self.session
199                 .diagnostic()
200                 .bug(&format!("built-in macro `{}` was already registered", name));
201         }
202     }
203
204     // Create a new Expansion with a definition site of the provided module, or
205     // a fake empty `#[no_implicit_prelude]` module if no module is provided.
206     fn expansion_for_ast_pass(
207         &mut self,
208         call_site: Span,
209         pass: AstPass,
210         features: &[Symbol],
211         parent_module_id: Option<NodeId>,
212     ) -> LocalExpnId {
213         let parent_module =
214             parent_module_id.map(|module_id| self.local_def_id(module_id).to_def_id());
215         let expn_id = LocalExpnId::fresh(
216             ExpnData::allow_unstable(
217                 ExpnKind::AstPass(pass),
218                 call_site,
219                 self.session.edition(),
220                 features.into(),
221                 None,
222                 parent_module,
223             ),
224             self.create_stable_hashing_context(),
225         );
226
227         let parent_scope =
228             parent_module.map_or(self.empty_module, |def_id| self.expect_module(def_id));
229         self.ast_transform_scopes.insert(expn_id, parent_scope);
230
231         expn_id
232     }
233
234     fn resolve_imports(&mut self) {
235         ImportResolver { r: self }.resolve_imports()
236     }
237
238     fn resolve_macro_invocation(
239         &mut self,
240         invoc: &Invocation,
241         eager_expansion_root: LocalExpnId,
242         force: bool,
243     ) -> Result<Lrc<SyntaxExtension>, Indeterminate> {
244         let invoc_id = invoc.expansion_data.id;
245         let parent_scope = match self.invocation_parent_scopes.get(&invoc_id) {
246             Some(parent_scope) => *parent_scope,
247             None => {
248                 // If there's no entry in the table, then we are resolving an eagerly expanded
249                 // macro, which should inherit its parent scope from its eager expansion root -
250                 // the macro that requested this eager expansion.
251                 let parent_scope = *self
252                     .invocation_parent_scopes
253                     .get(&eager_expansion_root)
254                     .expect("non-eager expansion without a parent scope");
255                 self.invocation_parent_scopes.insert(invoc_id, parent_scope);
256                 parent_scope
257             }
258         };
259
260         let (path, kind, inner_attr, derives) = match invoc.kind {
261             InvocationKind::Attr { ref attr, ref derives, .. } => (
262                 &attr.get_normal_item().path,
263                 MacroKind::Attr,
264                 attr.style == ast::AttrStyle::Inner,
265                 self.arenas.alloc_ast_paths(derives),
266             ),
267             InvocationKind::Bang { ref mac, .. } => (&mac.path, MacroKind::Bang, false, &[][..]),
268             InvocationKind::Derive { ref path, .. } => (path, MacroKind::Derive, false, &[][..]),
269         };
270
271         // Derives are not included when `invocations` are collected, so we have to add them here.
272         let parent_scope = &ParentScope { derives, ..parent_scope };
273         let supports_macro_expansion = invoc.fragment_kind.supports_macro_expansion();
274         let node_id = invoc.expansion_data.lint_node_id;
275         let (ext, res) = self.smart_resolve_macro_path(
276             path,
277             kind,
278             supports_macro_expansion,
279             inner_attr,
280             parent_scope,
281             node_id,
282             force,
283             soft_custom_inner_attributes_gate(path, invoc),
284         )?;
285
286         let span = invoc.span();
287         let def_id = res.opt_def_id();
288         invoc_id.set_expn_data(
289             ext.expn_data(
290                 parent_scope.expansion,
291                 span,
292                 fast_print_path(path),
293                 def_id,
294                 def_id.map(|def_id| self.macro_def_scope(def_id).nearest_parent_mod()),
295             ),
296             self.create_stable_hashing_context(),
297         );
298
299         Ok(ext)
300     }
301
302     fn record_macro_rule_usage(&mut self, id: NodeId, rule_i: usize) {
303         let did = self.local_def_id(id);
304         self.unused_macro_rules.remove(&(did, rule_i));
305     }
306
307     fn check_unused_macros(&mut self) {
308         for (_, &(node_id, ident)) in self.unused_macros.iter() {
309             self.lint_buffer.buffer_lint(
310                 UNUSED_MACROS,
311                 node_id,
312                 ident.span,
313                 &format!("unused macro definition: `{}`", ident.name),
314             );
315         }
316         for (&(def_id, arm_i), &(ident, rule_span)) in self.unused_macro_rules.iter() {
317             if self.unused_macros.contains_key(&def_id) {
318                 // We already lint the entire macro as unused
319                 continue;
320             }
321             let node_id = self.def_id_to_node_id[def_id];
322             self.lint_buffer.buffer_lint(
323                 UNUSED_MACRO_RULES,
324                 node_id,
325                 rule_span,
326                 &format!(
327                     "{} rule of macro `{}` is never used",
328                     crate::diagnostics::ordinalize(arm_i + 1),
329                     ident.name
330                 ),
331             );
332         }
333     }
334
335     fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool {
336         self.containers_deriving_copy.contains(&expn_id)
337     }
338
339     fn resolve_derives(
340         &mut self,
341         expn_id: LocalExpnId,
342         force: bool,
343         derive_paths: &dyn Fn() -> DeriveResolutions,
344     ) -> Result<(), Indeterminate> {
345         // Block expansion of the container until we resolve all derives in it.
346         // This is required for two reasons:
347         // - Derive helper attributes are in scope for the item to which the `#[derive]`
348         //   is applied, so they have to be produced by the container's expansion rather
349         //   than by individual derives.
350         // - Derives in the container need to know whether one of them is a built-in `Copy`.
351         // Temporarily take the data to avoid borrow checker conflicts.
352         let mut derive_data = mem::take(&mut self.derive_data);
353         let entry = derive_data.entry(expn_id).or_insert_with(|| DeriveData {
354             resolutions: derive_paths(),
355             helper_attrs: Vec::new(),
356             has_derive_copy: false,
357         });
358         let parent_scope = self.invocation_parent_scopes[&expn_id];
359         for (i, (path, _, opt_ext, _)) in entry.resolutions.iter_mut().enumerate() {
360             if opt_ext.is_none() {
361                 *opt_ext = Some(
362                     match self.resolve_macro_path(
363                         &path,
364                         Some(MacroKind::Derive),
365                         &parent_scope,
366                         true,
367                         force,
368                     ) {
369                         Ok((Some(ext), _)) => {
370                             if !ext.helper_attrs.is_empty() {
371                                 let last_seg = path.segments.last().unwrap();
372                                 let span = last_seg.ident.span.normalize_to_macros_2_0();
373                                 entry.helper_attrs.extend(
374                                     ext.helper_attrs
375                                         .iter()
376                                         .map(|name| (i, Ident::new(*name, span))),
377                                 );
378                             }
379                             entry.has_derive_copy |= ext.builtin_name == Some(sym::Copy);
380                             ext
381                         }
382                         Ok(_) | Err(Determinacy::Determined) => self.dummy_ext(MacroKind::Derive),
383                         Err(Determinacy::Undetermined) => {
384                             assert!(self.derive_data.is_empty());
385                             self.derive_data = derive_data;
386                             return Err(Indeterminate);
387                         }
388                     },
389                 );
390             }
391         }
392         // Sort helpers in a stable way independent from the derive resolution order.
393         entry.helper_attrs.sort_by_key(|(i, _)| *i);
394         self.helper_attrs
395             .insert(expn_id, entry.helper_attrs.iter().map(|(_, ident)| *ident).collect());
396         // Mark this derive as having `Copy` either if it has `Copy` itself or if its parent derive
397         // has `Copy`, to support cases like `#[derive(Clone, Copy)] #[derive(Debug)]`.
398         if entry.has_derive_copy || self.has_derive_copy(parent_scope.expansion) {
399             self.containers_deriving_copy.insert(expn_id);
400         }
401         assert!(self.derive_data.is_empty());
402         self.derive_data = derive_data;
403         Ok(())
404     }
405
406     fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option<DeriveResolutions> {
407         self.derive_data.remove(&expn_id).map(|data| data.resolutions)
408     }
409
410     // The function that implements the resolution logic of `#[cfg_accessible(path)]`.
411     // Returns true if the path can certainly be resolved in one of three namespaces,
412     // returns false if the path certainly cannot be resolved in any of the three namespaces.
413     // Returns `Indeterminate` if we cannot give a certain answer yet.
414     fn cfg_accessible(
415         &mut self,
416         expn_id: LocalExpnId,
417         path: &ast::Path,
418     ) -> Result<bool, Indeterminate> {
419         let span = path.span;
420         let path = &Segment::from_path(path);
421         let parent_scope = self.invocation_parent_scopes[&expn_id];
422
423         let mut indeterminate = false;
424         for ns in [TypeNS, ValueNS, MacroNS].iter().copied() {
425             match self.maybe_resolve_path(path, Some(ns), &parent_scope) {
426                 PathResult::Module(ModuleOrUniformRoot::Module(_)) => return Ok(true),
427                 PathResult::NonModule(partial_res) if partial_res.unresolved_segments() == 0 => {
428                     return Ok(true);
429                 }
430                 PathResult::NonModule(..) |
431                 // HACK(Urgau): This shouldn't be necessary
432                 PathResult::Failed { is_error_from_last_segment: false, .. } => {
433                     self.session
434                         .struct_span_err(span, "not sure whether the path is accessible or not")
435                         .note("the type may have associated items, but we are currently not checking them")
436                         .emit();
437
438                     // If we get a partially resolved NonModule in one namespace, we should get the
439                     // same result in any other namespaces, so we can return early.
440                     return Ok(false);
441                 }
442                 PathResult::Indeterminate => indeterminate = true,
443                 // We can only be sure that a path doesn't exist after having tested all the
444                 // possibilities, only at that time we can return false.
445                 PathResult::Failed { .. } => {}
446                 PathResult::Module(_) => panic!("unexpected path resolution"),
447             }
448         }
449
450         if indeterminate {
451             return Err(Indeterminate);
452         }
453
454         Ok(false)
455     }
456
457     fn get_proc_macro_quoted_span(&self, krate: CrateNum, id: usize) -> Span {
458         self.cstore().get_proc_macro_quoted_span_untracked(krate, id, self.session)
459     }
460
461     fn declare_proc_macro(&mut self, id: NodeId) {
462         self.proc_macros.push(id)
463     }
464
465     fn registered_tools(&self) -> &RegisteredTools {
466         &self.registered_tools
467     }
468 }
469
470 impl<'a> Resolver<'a> {
471     /// Resolve macro path with error reporting and recovery.
472     /// Uses dummy syntax extensions for unresolved macros or macros with unexpected resolutions
473     /// for better error recovery.
474     fn smart_resolve_macro_path(
475         &mut self,
476         path: &ast::Path,
477         kind: MacroKind,
478         supports_macro_expansion: SupportsMacroExpansion,
479         inner_attr: bool,
480         parent_scope: &ParentScope<'a>,
481         node_id: NodeId,
482         force: bool,
483         soft_custom_inner_attributes_gate: bool,
484     ) -> Result<(Lrc<SyntaxExtension>, Res), Indeterminate> {
485         let (ext, res) = match self.resolve_macro_path(path, Some(kind), parent_scope, true, force)
486         {
487             Ok((Some(ext), res)) => (ext, res),
488             Ok((None, res)) => (self.dummy_ext(kind), res),
489             Err(Determinacy::Determined) => (self.dummy_ext(kind), Res::Err),
490             Err(Determinacy::Undetermined) => return Err(Indeterminate),
491         };
492
493         // Report errors for the resolved macro.
494         for segment in &path.segments {
495             if let Some(args) = &segment.args {
496                 self.session.span_err(args.span(), "generic arguments in macro path");
497             }
498             if kind == MacroKind::Attr && segment.ident.as_str().starts_with("rustc") {
499                 self.session.span_err(
500                     segment.ident.span,
501                     "attributes starting with `rustc` are reserved for use by the `rustc` compiler",
502                 );
503             }
504         }
505
506         match res {
507             Res::Def(DefKind::Macro(_), def_id) => {
508                 if let Some(def_id) = def_id.as_local() {
509                     self.unused_macros.remove(&def_id);
510                     if self.proc_macro_stubs.contains(&def_id) {
511                         self.session.span_err(
512                             path.span,
513                             "can't use a procedural macro from the same crate that defines it",
514                         );
515                     }
516                 }
517             }
518             Res::NonMacroAttr(..) | Res::Err => {}
519             _ => panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"),
520         };
521
522         self.check_stability_and_deprecation(&ext, path, node_id);
523
524         let unexpected_res = if ext.macro_kind() != kind {
525             Some((kind.article(), kind.descr_expected()))
526         } else if matches!(res, Res::Def(..)) {
527             match supports_macro_expansion {
528                 SupportsMacroExpansion::No => Some(("a", "non-macro attribute")),
529                 SupportsMacroExpansion::Yes { supports_inner_attrs } => {
530                     if inner_attr && !supports_inner_attrs {
531                         Some(("a", "non-macro inner attribute"))
532                     } else {
533                         None
534                     }
535                 }
536             }
537         } else {
538             None
539         };
540         if let Some((article, expected)) = unexpected_res {
541             let path_str = pprust::path_to_string(path);
542             let msg = format!("expected {}, found {} `{}`", expected, res.descr(), path_str);
543             self.session
544                 .struct_span_err(path.span, &msg)
545                 .span_label(path.span, format!("not {} {}", article, expected))
546                 .emit();
547             return Ok((self.dummy_ext(kind), Res::Err));
548         }
549
550         // We are trying to avoid reporting this error if other related errors were reported.
551         if res != Res::Err
552             && inner_attr
553             && !self.session.features_untracked().custom_inner_attributes
554         {
555             let msg = match res {
556                 Res::Def(..) => "inner macro attributes are unstable",
557                 Res::NonMacroAttr(..) => "custom inner attributes are unstable",
558                 _ => unreachable!(),
559             };
560             if soft_custom_inner_attributes_gate {
561                 self.session.parse_sess.buffer_lint(SOFT_UNSTABLE, path.span, node_id, msg);
562             } else {
563                 feature_err(&self.session.parse_sess, sym::custom_inner_attributes, path.span, msg)
564                     .emit();
565             }
566         }
567
568         Ok((ext, res))
569     }
570
571     pub fn resolve_macro_path(
572         &mut self,
573         path: &ast::Path,
574         kind: Option<MacroKind>,
575         parent_scope: &ParentScope<'a>,
576         trace: bool,
577         force: bool,
578     ) -> Result<(Option<Lrc<SyntaxExtension>>, Res), Determinacy> {
579         let path_span = path.span;
580         let mut path = Segment::from_path(path);
581
582         // Possibly apply the macro helper hack
583         if kind == Some(MacroKind::Bang)
584             && path.len() == 1
585             && path[0].ident.span.ctxt().outer_expn_data().local_inner_macros
586         {
587             let root = Ident::new(kw::DollarCrate, path[0].ident.span);
588             path.insert(0, Segment::from_ident(root));
589         }
590
591         let res = if path.len() > 1 {
592             let res = match self.maybe_resolve_path(&path, Some(MacroNS), parent_scope) {
593                 PathResult::NonModule(path_res) if let Some(res) = path_res.full_res() => Ok(res),
594                 PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
595                 PathResult::NonModule(..)
596                 | PathResult::Indeterminate
597                 | PathResult::Failed { .. } => Err(Determinacy::Determined),
598                 PathResult::Module(..) => unreachable!(),
599             };
600
601             if trace {
602                 let kind = kind.expect("macro kind must be specified if tracing is enabled");
603                 self.multi_segment_macro_resolutions.push((
604                     path,
605                     path_span,
606                     kind,
607                     *parent_scope,
608                     res.ok(),
609                 ));
610             }
611
612             self.prohibit_imported_non_macro_attrs(None, res.ok(), path_span);
613             res
614         } else {
615             let scope_set = kind.map_or(ScopeSet::All(MacroNS, false), ScopeSet::Macro);
616             let binding = self.early_resolve_ident_in_lexical_scope(
617                 path[0].ident,
618                 scope_set,
619                 parent_scope,
620                 None,
621                 force,
622                 None,
623             );
624             if let Err(Determinacy::Undetermined) = binding {
625                 return Err(Determinacy::Undetermined);
626             }
627
628             if trace {
629                 let kind = kind.expect("macro kind must be specified if tracing is enabled");
630                 self.single_segment_macro_resolutions.push((
631                     path[0].ident,
632                     kind,
633                     *parent_scope,
634                     binding.ok(),
635                 ));
636             }
637
638             let res = binding.map(|binding| binding.res());
639             self.prohibit_imported_non_macro_attrs(binding.ok(), res.ok(), path_span);
640             res
641         };
642
643         res.map(|res| (self.get_macro(res).map(|macro_data| macro_data.ext), res))
644     }
645
646     pub(crate) fn finalize_macro_resolutions(&mut self) {
647         let check_consistency = |this: &mut Self,
648                                  path: &[Segment],
649                                  span,
650                                  kind: MacroKind,
651                                  initial_res: Option<Res>,
652                                  res: Res| {
653             if let Some(initial_res) = initial_res {
654                 if res != initial_res {
655                     // Make sure compilation does not succeed if preferred macro resolution
656                     // has changed after the macro had been expanded. In theory all such
657                     // situations should be reported as errors, so this is a bug.
658                     this.session.delay_span_bug(span, "inconsistent resolution for a macro");
659                 }
660             } else {
661                 // It's possible that the macro was unresolved (indeterminate) and silently
662                 // expanded into a dummy fragment for recovery during expansion.
663                 // Now, post-expansion, the resolution may succeed, but we can't change the
664                 // past and need to report an error.
665                 // However, non-speculative `resolve_path` can successfully return private items
666                 // even if speculative `resolve_path` returned nothing previously, so we skip this
667                 // less informative error if the privacy error is reported elsewhere.
668                 if this.privacy_errors.is_empty() {
669                     let msg = format!(
670                         "cannot determine resolution for the {} `{}`",
671                         kind.descr(),
672                         Segment::names_to_string(path)
673                     );
674                     let msg_note = "import resolution is stuck, try simplifying macro imports";
675                     this.session.struct_span_err(span, &msg).note(msg_note).emit();
676                 }
677             }
678         };
679
680         let macro_resolutions = mem::take(&mut self.multi_segment_macro_resolutions);
681         for (mut path, path_span, kind, parent_scope, initial_res) in macro_resolutions {
682             // FIXME: Path resolution will ICE if segment IDs present.
683             for seg in &mut path {
684                 seg.id = None;
685             }
686             match self.resolve_path(
687                 &path,
688                 Some(MacroNS),
689                 &parent_scope,
690                 Some(Finalize::new(ast::CRATE_NODE_ID, path_span)),
691                 None,
692             ) {
693                 PathResult::NonModule(path_res) if let Some(res) = path_res.full_res() => {
694                     check_consistency(self, &path, path_span, kind, initial_res, res)
695                 }
696                 path_res @ PathResult::NonModule(..) | path_res @ PathResult::Failed { .. } => {
697                     let mut suggestion = None;
698                     let (span, label) = if let PathResult::Failed { span, label, .. } = path_res {
699                         // try to suggest if it's not a macro, maybe a function
700                         if let PathResult::NonModule(partial_res) = self.maybe_resolve_path(&path, Some(ValueNS), &parent_scope)
701                             && partial_res.unresolved_segments() == 0 {
702                             let sm = self.session.source_map();
703                             let exclamation_span = sm.next_point(span);
704                             suggestion = Some((
705                                 vec![(exclamation_span, "".to_string())],
706                                     format!("{} is not a macro, but a {}, try to remove `!`", Segment::names_to_string(&path), partial_res.base_res().descr()),
707                                     Applicability::MaybeIncorrect
708                                 ));
709                         }
710                         (span, label)
711                     } else {
712                         (
713                             path_span,
714                             format!(
715                                 "partially resolved path in {} {}",
716                                 kind.article(),
717                                 kind.descr()
718                             ),
719                         )
720                     };
721                     self.report_error(
722                         span,
723                         ResolutionError::FailedToResolve { label, suggestion },
724                     );
725                 }
726                 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
727             }
728         }
729
730         let macro_resolutions = mem::take(&mut self.single_segment_macro_resolutions);
731         for (ident, kind, parent_scope, initial_binding) in macro_resolutions {
732             match self.early_resolve_ident_in_lexical_scope(
733                 ident,
734                 ScopeSet::Macro(kind),
735                 &parent_scope,
736                 Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)),
737                 true,
738                 None,
739             ) {
740                 Ok(binding) => {
741                     let initial_res = initial_binding.map(|initial_binding| {
742                         self.record_use(ident, initial_binding, false);
743                         initial_binding.res()
744                     });
745                     let res = binding.res();
746                     let seg = Segment::from_ident(ident);
747                     check_consistency(self, &[seg], ident.span, kind, initial_res, res);
748                     if res == Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat) {
749                         let node_id = self
750                             .invocation_parents
751                             .get(&parent_scope.expansion)
752                             .map_or(ast::CRATE_NODE_ID, |id| self.def_id_to_node_id[id.0]);
753                         self.lint_buffer.buffer_lint_with_diagnostic(
754                             LEGACY_DERIVE_HELPERS,
755                             node_id,
756                             ident.span,
757                             "derive helper attribute is used before it is introduced",
758                             BuiltinLintDiagnostics::LegacyDeriveHelpers(binding.span),
759                         );
760                     }
761                 }
762                 Err(..) => {
763                     let expected = kind.descr_expected();
764                     let msg = format!("cannot find {} `{}` in this scope", expected, ident);
765                     let mut err = self.session.struct_span_err(ident.span, &msg);
766                     self.unresolved_macro_suggestions(&mut err, kind, &parent_scope, ident);
767                     err.emit();
768                 }
769             }
770         }
771
772         let builtin_attrs = mem::take(&mut self.builtin_attrs);
773         for (ident, parent_scope) in builtin_attrs {
774             let _ = self.early_resolve_ident_in_lexical_scope(
775                 ident,
776                 ScopeSet::Macro(MacroKind::Attr),
777                 &parent_scope,
778                 Some(Finalize::new(ast::CRATE_NODE_ID, ident.span)),
779                 true,
780                 None,
781             );
782         }
783     }
784
785     fn check_stability_and_deprecation(
786         &mut self,
787         ext: &SyntaxExtension,
788         path: &ast::Path,
789         node_id: NodeId,
790     ) {
791         let span = path.span;
792         if let Some(stability) = &ext.stability {
793             if let StabilityLevel::Unstable { reason, issue, is_soft, implied_by } = stability.level
794             {
795                 let feature = stability.feature;
796
797                 let is_allowed = |feature| {
798                     self.active_features.contains(&feature) || span.allows_unstable(feature)
799                 };
800                 let allowed_by_implication =
801                     implied_by.map(|feature| is_allowed(feature)).unwrap_or(false);
802                 if !is_allowed(feature) && !allowed_by_implication {
803                     let lint_buffer = &mut self.lint_buffer;
804                     let soft_handler =
805                         |lint, span, msg: &_| lint_buffer.buffer_lint(lint, node_id, span, msg);
806                     stability::report_unstable(
807                         self.session,
808                         feature,
809                         reason.to_opt_reason(),
810                         issue,
811                         None,
812                         is_soft,
813                         span,
814                         soft_handler,
815                     );
816                 }
817             }
818         }
819         if let Some(depr) = &ext.deprecation {
820             let path = pprust::path_to_string(&path);
821             let (message, lint) = stability::deprecation_message_and_lint(depr, "macro", &path);
822             stability::early_report_deprecation(
823                 &mut self.lint_buffer,
824                 &message,
825                 depr.suggestion,
826                 lint,
827                 span,
828                 node_id,
829             );
830         }
831     }
832
833     fn prohibit_imported_non_macro_attrs(
834         &self,
835         binding: Option<&'a NameBinding<'a>>,
836         res: Option<Res>,
837         span: Span,
838     ) {
839         if let Some(Res::NonMacroAttr(kind)) = res {
840             if kind != NonMacroAttrKind::Tool && binding.map_or(true, |b| b.is_import()) {
841                 let msg =
842                     format!("cannot use {} {} through an import", kind.article(), kind.descr());
843                 let mut err = self.session.struct_span_err(span, &msg);
844                 if let Some(binding) = binding {
845                     err.span_note(binding.span, &format!("the {} imported here", kind.descr()));
846                 }
847                 err.emit();
848             }
849         }
850     }
851
852     pub(crate) fn check_reserved_macro_name(&mut self, ident: Ident, res: Res) {
853         // Reserve some names that are not quite covered by the general check
854         // performed on `Resolver::builtin_attrs`.
855         if ident.name == sym::cfg || ident.name == sym::cfg_attr {
856             let macro_kind = self.get_macro(res).map(|macro_data| macro_data.ext.macro_kind());
857             if macro_kind.is_some() && sub_namespace_match(macro_kind, Some(MacroKind::Attr)) {
858                 self.session.span_err(
859                     ident.span,
860                     &format!("name `{}` is reserved in attribute namespace", ident),
861                 );
862             }
863         }
864     }
865
866     /// Compile the macro into a `SyntaxExtension` and its rule spans.
867     ///
868     /// Possibly replace its expander to a pre-defined one for built-in macros.
869     pub(crate) fn compile_macro(
870         &mut self,
871         item: &ast::Item,
872         edition: Edition,
873     ) -> (SyntaxExtension, Vec<(usize, Span)>) {
874         let (mut result, mut rule_spans) = compile_declarative_macro(
875             &self.session,
876             self.session.features_untracked(),
877             item,
878             edition,
879         );
880
881         if let Some(builtin_name) = result.builtin_name {
882             // The macro was marked with `#[rustc_builtin_macro]`.
883             if let Some(builtin_macro) = self.builtin_macros.get_mut(&builtin_name) {
884                 // The macro is a built-in, replace its expander function
885                 // while still taking everything else from the source code.
886                 // If we already loaded this builtin macro, give a better error message than 'no such builtin macro'.
887                 match mem::replace(builtin_macro, BuiltinMacroState::AlreadySeen(item.span)) {
888                     BuiltinMacroState::NotYetSeen(ext) => {
889                         result.kind = ext;
890                         rule_spans = Vec::new();
891                         if item.id != ast::DUMMY_NODE_ID {
892                             self.builtin_macro_kinds
893                                 .insert(self.local_def_id(item.id), result.macro_kind());
894                         }
895                     }
896                     BuiltinMacroState::AlreadySeen(span) => {
897                         struct_span_err!(
898                             self.session,
899                             item.span,
900                             E0773,
901                             "attempted to define built-in macro more than once"
902                         )
903                         .span_note(span, "previously defined here")
904                         .emit();
905                     }
906                 }
907             } else {
908                 let msg = format!("cannot find a built-in macro with name `{}`", item.ident);
909                 self.session.span_err(item.span, &msg);
910             }
911         }
912
913         (result, rule_spans)
914     }
915 }