]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_resolve/src/macros.rs
Rollup merge of #81526 - ojeda:btree-use-unwrap_unchecked, r=scottmcm
[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::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, BuiltinMacroState, Determinacy};
7 use crate::{CrateLint, ParentScope, ResolutionError, Resolver, Scope, ScopeSet, Weak};
8 use crate::{ModuleKind, ModuleOrUniformRoot, NameBinding, PathResult, Segment, ToNameBinding};
9 use rustc_ast::{self as ast, 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::ptr_key::PtrKey;
15 use rustc_data_structures::sync::Lrc;
16 use rustc_errors::struct_span_err;
17 use rustc_expand::base::{Indeterminate, InvocationRes, ResolverExpand};
18 use rustc_expand::base::{SyntaxExtension, SyntaxExtensionKind};
19 use rustc_expand::compile_declarative_macro;
20 use rustc_expand::expand::{AstFragment, Invocation, InvocationKind};
21 use rustc_feature::is_builtin_attr_name;
22 use rustc_hir::def::{self, DefKind, NonMacroAttrKind};
23 use rustc_hir::def_id;
24 use rustc_hir::PrimTy;
25 use rustc_middle::middle::stability;
26 use rustc_middle::ty;
27 use rustc_session::lint::builtin::{SOFT_UNSTABLE, UNUSED_MACROS};
28 use rustc_session::parse::feature_err;
29 use rustc_session::Session;
30 use rustc_span::edition::Edition;
31 use rustc_span::hygiene::{self, ExpnData, ExpnId, ExpnKind};
32 use rustc_span::hygiene::{AstPass, MacroKind};
33 use rustc_span::symbol::{kw, sym, Ident, Symbol};
34 use rustc_span::{Span, DUMMY_SP};
35 use std::cell::Cell;
36 use std::{mem, ptr};
37
38 type Res = def::Res<NodeId>;
39
40 /// Binding produced by a `macro_rules` item.
41 /// Not modularized, can shadow previous `macro_rules` bindings, etc.
42 #[derive(Debug)]
43 pub struct MacroRulesBinding<'a> {
44     crate binding: &'a NameBinding<'a>,
45     /// `macro_rules` scope into which the `macro_rules` item was planted.
46     crate parent_macro_rules_scope: MacroRulesScopeRef<'a>,
47     crate ident: Ident,
48 }
49
50 /// The scope introduced by a `macro_rules!` macro.
51 /// This starts at the macro's definition and ends at the end of the macro's parent
52 /// module (named or unnamed), or even further if it escapes with `#[macro_use]`.
53 /// Some macro invocations need to introduce `macro_rules` scopes too because they
54 /// can potentially expand into macro definitions.
55 #[derive(Copy, Clone, Debug)]
56 pub enum MacroRulesScope<'a> {
57     /// Empty "root" scope at the crate start containing no names.
58     Empty,
59     /// The scope introduced by a `macro_rules!` macro definition.
60     Binding(&'a MacroRulesBinding<'a>),
61     /// The scope introduced by a macro invocation that can potentially
62     /// create a `macro_rules!` macro definition.
63     Invocation(ExpnId),
64 }
65
66 /// `macro_rules!` scopes are always kept by reference and inside a cell.
67 /// The reason is that we update scopes with value `MacroRulesScope::Invocation(invoc_id)`
68 /// in-place after `invoc_id` gets expanded.
69 /// This helps to avoid uncontrollable growth of `macro_rules!` scope chains,
70 /// which usually grow lineraly with the number of macro invocations
71 /// in a module (including derives) and hurt performance.
72 pub(crate) type MacroRulesScopeRef<'a> = PtrKey<'a, Cell<MacroRulesScope<'a>>>;
73
74 // Macro namespace is separated into two sub-namespaces, one for bang macros and
75 // one for attribute-like macros (attributes, derives).
76 // We ignore resolutions from one sub-namespace when searching names in scope for another.
77 fn sub_namespace_match(candidate: Option<MacroKind>, requirement: Option<MacroKind>) -> bool {
78     #[derive(PartialEq)]
79     enum SubNS {
80         Bang,
81         AttrLike,
82     }
83     let sub_ns = |kind| match kind {
84         MacroKind::Bang => SubNS::Bang,
85         MacroKind::Attr | MacroKind::Derive => SubNS::AttrLike,
86     };
87     let candidate = candidate.map(sub_ns);
88     let requirement = requirement.map(sub_ns);
89     // "No specific sub-namespace" means "matches anything" for both requirements and candidates.
90     candidate.is_none() || requirement.is_none() || candidate == requirement
91 }
92
93 // We don't want to format a path using pretty-printing,
94 // `format!("{}", path)`, because that tries to insert
95 // line-breaks and is slow.
96 fn fast_print_path(path: &ast::Path) -> Symbol {
97     if path.segments.len() == 1 {
98         path.segments[0].ident.name
99     } else {
100         let mut path_str = String::with_capacity(64);
101         for (i, segment) in path.segments.iter().enumerate() {
102             if i != 0 {
103                 path_str.push_str("::");
104             }
105             if segment.ident.name != kw::PathRoot {
106                 path_str.push_str(&segment.ident.as_str())
107             }
108         }
109         Symbol::intern(&path_str)
110     }
111 }
112
113 /// The code common between processing `#![register_tool]` and `#![register_attr]`.
114 fn registered_idents(
115     sess: &Session,
116     attrs: &[ast::Attribute],
117     attr_name: Symbol,
118     descr: &str,
119 ) -> FxHashSet<Ident> {
120     let mut registered = FxHashSet::default();
121     for attr in sess.filter_by_name(attrs, attr_name) {
122         for nested_meta in attr.meta_item_list().unwrap_or_default() {
123             match nested_meta.ident() {
124                 Some(ident) => {
125                     if let Some(old_ident) = registered.replace(ident) {
126                         let msg = format!("{} `{}` was already registered", descr, ident);
127                         sess.struct_span_err(ident.span, &msg)
128                             .span_label(old_ident.span, "already registered here")
129                             .emit();
130                     }
131                 }
132                 None => {
133                     let msg = format!("`{}` only accepts identifiers", attr_name);
134                     let span = nested_meta.span();
135                     sess.struct_span_err(span, &msg).span_label(span, "not an identifier").emit();
136                 }
137             }
138         }
139     }
140     registered
141 }
142
143 crate fn registered_attrs_and_tools(
144     sess: &Session,
145     attrs: &[ast::Attribute],
146 ) -> (FxHashSet<Ident>, FxHashSet<Ident>) {
147     let registered_attrs = registered_idents(sess, attrs, sym::register_attr, "attribute");
148     let mut registered_tools = registered_idents(sess, attrs, sym::register_tool, "tool");
149     // We implicitly add `rustfmt` and `clippy` to known tools,
150     // but it's not an error to register them explicitly.
151     let predefined_tools = [sym::clippy, sym::rustfmt];
152     registered_tools.extend(predefined_tools.iter().cloned().map(Ident::with_dummy_span));
153     (registered_attrs, registered_tools)
154 }
155
156 impl<'a> ResolverExpand for Resolver<'a> {
157     fn next_node_id(&mut self) -> NodeId {
158         self.next_node_id()
159     }
160
161     fn resolve_dollar_crates(&mut self) {
162         hygiene::update_dollar_crate_names(|ctxt| {
163             let ident = Ident::new(kw::DollarCrate, DUMMY_SP.with_ctxt(ctxt));
164             match self.resolve_crate_root(ident).kind {
165                 ModuleKind::Def(.., name) if name != kw::Empty => name,
166                 _ => kw::Crate,
167             }
168         });
169     }
170
171     fn visit_ast_fragment_with_placeholders(&mut self, expansion: ExpnId, fragment: &AstFragment) {
172         // Integrate the new AST fragment into all the definition and module structures.
173         // We are inside the `expansion` now, but other parent scope components are still the same.
174         let parent_scope = ParentScope { expansion, ..self.invocation_parent_scopes[&expansion] };
175         let output_macro_rules_scope = self.build_reduced_graph(fragment, parent_scope);
176         self.output_macro_rules_scopes.insert(expansion, output_macro_rules_scope);
177
178         parent_scope.module.unexpanded_invocations.borrow_mut().remove(&expansion);
179     }
180
181     fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind) {
182         if self.builtin_macros.insert(name, BuiltinMacroState::NotYetSeen(ext)).is_some() {
183             self.session
184                 .diagnostic()
185                 .bug(&format!("built-in macro `{}` was already registered", name));
186         }
187     }
188
189     // Create a new Expansion with a definition site of the provided module, or
190     // a fake empty `#[no_implicit_prelude]` module if no module is provided.
191     fn expansion_for_ast_pass(
192         &mut self,
193         call_site: Span,
194         pass: AstPass,
195         features: &[Symbol],
196         parent_module_id: Option<NodeId>,
197     ) -> ExpnId {
198         let expn_id = ExpnId::fresh(Some(ExpnData::allow_unstable(
199             ExpnKind::AstPass(pass),
200             call_site,
201             self.session.edition(),
202             features.into(),
203             None,
204         )));
205
206         let parent_scope = if let Some(module_id) = parent_module_id {
207             let parent_def_id = self.local_def_id(module_id);
208             self.definitions.add_parent_module_of_macro_def(expn_id, parent_def_id.to_def_id());
209             self.module_map[&parent_def_id]
210         } else {
211             self.definitions.add_parent_module_of_macro_def(
212                 expn_id,
213                 def_id::DefId::local(def_id::CRATE_DEF_INDEX),
214             );
215             self.empty_module
216         };
217         self.ast_transform_scopes.insert(expn_id, parent_scope);
218         expn_id
219     }
220
221     fn resolve_imports(&mut self) {
222         ImportResolver { r: self }.resolve_imports()
223     }
224
225     fn resolve_macro_invocation(
226         &mut self,
227         invoc: &Invocation,
228         eager_expansion_root: ExpnId,
229         force: bool,
230     ) -> Result<InvocationRes, Indeterminate> {
231         let invoc_id = invoc.expansion_data.id;
232         let parent_scope = match self.invocation_parent_scopes.get(&invoc_id) {
233             Some(parent_scope) => *parent_scope,
234             None => {
235                 // If there's no entry in the table, then we are resolving an eagerly expanded
236                 // macro, which should inherit its parent scope from its eager expansion root -
237                 // the macro that requested this eager expansion.
238                 let parent_scope = *self
239                     .invocation_parent_scopes
240                     .get(&eager_expansion_root)
241                     .expect("non-eager expansion without a parent scope");
242                 self.invocation_parent_scopes.insert(invoc_id, parent_scope);
243                 parent_scope
244             }
245         };
246
247         let (path, kind, inner_attr, derives, after_derive) = match invoc.kind {
248             InvocationKind::Attr { ref attr, ref derives, after_derive, .. } => (
249                 &attr.get_normal_item().path,
250                 MacroKind::Attr,
251                 attr.style == ast::AttrStyle::Inner,
252                 self.arenas.alloc_ast_paths(derives),
253                 after_derive,
254             ),
255             InvocationKind::Bang { ref mac, .. } => {
256                 (&mac.path, MacroKind::Bang, false, &[][..], false)
257             }
258             InvocationKind::Derive { ref path, .. } => {
259                 (path, MacroKind::Derive, false, &[][..], false)
260             }
261             InvocationKind::DeriveContainer { ref derives, .. } => {
262                 // Block expansion of the container until we resolve all derives in it.
263                 // This is required for two reasons:
264                 // - Derive helper attributes are in scope for the item to which the `#[derive]`
265                 //   is applied, so they have to be produced by the container's expansion rather
266                 //   than by individual derives.
267                 // - Derives in the container need to know whether one of them is a built-in `Copy`.
268                 // FIXME: Try to avoid repeated resolutions for derives here and in expansion.
269                 let mut exts = Vec::new();
270                 let mut helper_attrs = Vec::new();
271                 for path in derives {
272                     exts.push(
273                         match self.resolve_macro_path(
274                             path,
275                             Some(MacroKind::Derive),
276                             &parent_scope,
277                             true,
278                             force,
279                         ) {
280                             Ok((Some(ext), _)) => {
281                                 let span = path
282                                     .segments
283                                     .last()
284                                     .unwrap()
285                                     .ident
286                                     .span
287                                     .normalize_to_macros_2_0();
288                                 helper_attrs.extend(
289                                     ext.helper_attrs.iter().map(|name| Ident::new(*name, span)),
290                                 );
291                                 if ext.builtin_name == Some(sym::Copy) {
292                                     self.containers_deriving_copy.insert(invoc_id);
293                                 }
294                                 ext
295                             }
296                             Ok(_) | Err(Determinacy::Determined) => {
297                                 self.dummy_ext(MacroKind::Derive)
298                             }
299                             Err(Determinacy::Undetermined) => return Err(Indeterminate),
300                         },
301                     )
302                 }
303                 self.helper_attrs.insert(invoc_id, helper_attrs);
304                 return Ok(InvocationRes::DeriveContainer(exts));
305             }
306         };
307
308         // Derives are not included when `invocations` are collected, so we have to add them here.
309         let parent_scope = &ParentScope { derives, ..parent_scope };
310         let require_inert = !invoc.fragment_kind.supports_macro_expansion();
311         let node_id = self.lint_node_id(eager_expansion_root);
312         let (ext, res) = self.smart_resolve_macro_path(
313             path,
314             kind,
315             require_inert,
316             inner_attr,
317             parent_scope,
318             node_id,
319             force,
320         )?;
321
322         let span = invoc.span();
323         invoc_id.set_expn_data(ext.expn_data(
324             parent_scope.expansion,
325             span,
326             fast_print_path(path),
327             res.opt_def_id(),
328         ));
329
330         if let Res::Def(_, _) = res {
331             if after_derive {
332                 self.session.span_err(span, "macro attributes must be placed before `#[derive]`");
333             }
334             let normal_module_def_id = self.macro_def_scope(invoc_id).nearest_parent_mod;
335             self.definitions.add_parent_module_of_macro_def(invoc_id, normal_module_def_id);
336         }
337
338         Ok(InvocationRes::Single(ext))
339     }
340
341     fn check_unused_macros(&mut self) {
342         for (_, &(node_id, span)) in self.unused_macros.iter() {
343             self.lint_buffer.buffer_lint(UNUSED_MACROS, node_id, span, "unused macro definition");
344         }
345     }
346
347     fn lint_node_id(&mut self, expn_id: ExpnId) -> NodeId {
348         // FIXME - make this more precise. This currently returns the NodeId of the
349         // nearest closing item - we should try to return the closest parent of the ExpnId
350         self.invocation_parents
351             .get(&expn_id)
352             .map_or(ast::CRATE_NODE_ID, |id| self.def_id_to_node_id[*id])
353     }
354
355     fn has_derive_copy(&self, expn_id: ExpnId) -> bool {
356         self.containers_deriving_copy.contains(&expn_id)
357     }
358
359     // The function that implements the resolution logic of `#[cfg_accessible(path)]`.
360     // Returns true if the path can certainly be resolved in one of three namespaces,
361     // returns false if the path certainly cannot be resolved in any of the three namespaces.
362     // Returns `Indeterminate` if we cannot give a certain answer yet.
363     fn cfg_accessible(&mut self, expn_id: ExpnId, path: &ast::Path) -> Result<bool, Indeterminate> {
364         let span = path.span;
365         let path = &Segment::from_path(path);
366         let parent_scope = self.invocation_parent_scopes[&expn_id];
367
368         let mut indeterminate = false;
369         for ns in [TypeNS, ValueNS, MacroNS].iter().copied() {
370             match self.resolve_path(path, Some(ns), &parent_scope, false, span, CrateLint::No) {
371                 PathResult::Module(ModuleOrUniformRoot::Module(_)) => return Ok(true),
372                 PathResult::NonModule(partial_res) if partial_res.unresolved_segments() == 0 => {
373                     return Ok(true);
374                 }
375                 PathResult::Indeterminate => indeterminate = true,
376                 // FIXME: `resolve_path` is not ready to report partially resolved paths
377                 // correctly, so we just report an error if the path was reported as unresolved.
378                 // This needs to be fixed for `cfg_accessible` to be useful.
379                 PathResult::NonModule(..) | PathResult::Failed { .. } => {}
380                 PathResult::Module(_) => panic!("unexpected path resolution"),
381             }
382         }
383
384         if indeterminate {
385             return Err(Indeterminate);
386         }
387
388         self.session
389             .struct_span_err(span, "not sure whether the path is accessible or not")
390             .span_note(span, "`cfg_accessible` is not fully implemented")
391             .emit();
392         Ok(false)
393     }
394 }
395
396 impl<'a> Resolver<'a> {
397     /// Resolve macro path with error reporting and recovery.
398     /// Uses dummy syntax extensions for unresolved macros or macros with unexpected resolutions
399     /// for better error recovery.
400     fn smart_resolve_macro_path(
401         &mut self,
402         path: &ast::Path,
403         kind: MacroKind,
404         require_inert: bool,
405         inner_attr: bool,
406         parent_scope: &ParentScope<'a>,
407         node_id: NodeId,
408         force: bool,
409     ) -> Result<(Lrc<SyntaxExtension>, Res), Indeterminate> {
410         let (ext, res) = match self.resolve_macro_path(path, Some(kind), parent_scope, true, force)
411         {
412             Ok((Some(ext), res)) => (ext, res),
413             Ok((None, res)) => (self.dummy_ext(kind), res),
414             Err(Determinacy::Determined) => (self.dummy_ext(kind), Res::Err),
415             Err(Determinacy::Undetermined) => return Err(Indeterminate),
416         };
417
418         // Report errors for the resolved macro.
419         for segment in &path.segments {
420             if let Some(args) = &segment.args {
421                 self.session.span_err(args.span(), "generic arguments in macro path");
422             }
423             if kind == MacroKind::Attr && segment.ident.as_str().starts_with("rustc") {
424                 self.session.span_err(
425                     segment.ident.span,
426                     "attributes starting with `rustc` are reserved for use by the `rustc` compiler",
427                 );
428             }
429         }
430
431         match res {
432             Res::Def(DefKind::Macro(_), def_id) => {
433                 if let Some(def_id) = def_id.as_local() {
434                     self.unused_macros.remove(&def_id);
435                     if self.proc_macro_stubs.contains(&def_id) {
436                         self.session.span_err(
437                             path.span,
438                             "can't use a procedural macro from the same crate that defines it",
439                         );
440                     }
441                 }
442             }
443             Res::NonMacroAttr(..) | Res::Err => {}
444             _ => panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"),
445         };
446
447         self.check_stability_and_deprecation(&ext, path, node_id);
448
449         let unexpected_res = if ext.macro_kind() != kind {
450             Some((kind.article(), kind.descr_expected()))
451         } else if require_inert && matches!(res, Res::Def(..)) {
452             Some(("a", "non-macro attribute"))
453         } else {
454             None
455         };
456         if let Some((article, expected)) = unexpected_res {
457             let path_str = pprust::path_to_string(path);
458             let msg = format!("expected {}, found {} `{}`", expected, res.descr(), path_str);
459             self.session
460                 .struct_span_err(path.span, &msg)
461                 .span_label(path.span, format!("not {} {}", article, expected))
462                 .emit();
463             return Ok((self.dummy_ext(kind), Res::Err));
464         }
465
466         // We are trying to avoid reporting this error if other related errors were reported.
467         if res != Res::Err
468             && inner_attr
469             && !self.session.features_untracked().custom_inner_attributes
470         {
471             let msg = match res {
472                 Res::Def(..) => "inner macro attributes are unstable",
473                 Res::NonMacroAttr(..) => "custom inner attributes are unstable",
474                 _ => unreachable!(),
475             };
476             if path == &sym::test {
477                 self.session.parse_sess.buffer_lint(SOFT_UNSTABLE, path.span, node_id, msg);
478             } else {
479                 feature_err(&self.session.parse_sess, sym::custom_inner_attributes, path.span, msg)
480                     .emit();
481             }
482         }
483
484         Ok((ext, res))
485     }
486
487     pub fn resolve_macro_path(
488         &mut self,
489         path: &ast::Path,
490         kind: Option<MacroKind>,
491         parent_scope: &ParentScope<'a>,
492         trace: bool,
493         force: bool,
494     ) -> Result<(Option<Lrc<SyntaxExtension>>, Res), Determinacy> {
495         let path_span = path.span;
496         let mut path = Segment::from_path(path);
497
498         // Possibly apply the macro helper hack
499         if kind == Some(MacroKind::Bang)
500             && path.len() == 1
501             && path[0].ident.span.ctxt().outer_expn_data().local_inner_macros
502         {
503             let root = Ident::new(kw::DollarCrate, path[0].ident.span);
504             path.insert(0, Segment::from_ident(root));
505         }
506
507         let res = if path.len() > 1 {
508             let res = match self.resolve_path(
509                 &path,
510                 Some(MacroNS),
511                 parent_scope,
512                 false,
513                 path_span,
514                 CrateLint::No,
515             ) {
516                 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
517                     Ok(path_res.base_res())
518                 }
519                 PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
520                 PathResult::NonModule(..)
521                 | PathResult::Indeterminate
522                 | PathResult::Failed { .. } => Err(Determinacy::Determined),
523                 PathResult::Module(..) => unreachable!(),
524             };
525
526             if trace {
527                 let kind = kind.expect("macro kind must be specified if tracing is enabled");
528                 self.multi_segment_macro_resolutions.push((
529                     path,
530                     path_span,
531                     kind,
532                     *parent_scope,
533                     res.ok(),
534                 ));
535             }
536
537             self.prohibit_imported_non_macro_attrs(None, res.ok(), path_span);
538             res
539         } else {
540             let scope_set = kind.map_or(ScopeSet::All(MacroNS, false), ScopeSet::Macro);
541             let binding = self.early_resolve_ident_in_lexical_scope(
542                 path[0].ident,
543                 scope_set,
544                 parent_scope,
545                 false,
546                 force,
547                 path_span,
548             );
549             if let Err(Determinacy::Undetermined) = binding {
550                 return Err(Determinacy::Undetermined);
551             }
552
553             if trace {
554                 let kind = kind.expect("macro kind must be specified if tracing is enabled");
555                 self.single_segment_macro_resolutions.push((
556                     path[0].ident,
557                     kind,
558                     *parent_scope,
559                     binding.ok(),
560                 ));
561             }
562
563             let res = binding.map(|binding| binding.res());
564             self.prohibit_imported_non_macro_attrs(binding.ok(), res.ok(), path_span);
565             res
566         };
567
568         res.map(|res| (self.get_macro(res), res))
569     }
570
571     // Resolve an identifier in lexical scope.
572     // This is a variation of `fn resolve_ident_in_lexical_scope` that can be run during
573     // expansion and import resolution (perhaps they can be merged in the future).
574     // The function is used for resolving initial segments of macro paths (e.g., `foo` in
575     // `foo::bar!(); or `foo!();`) and also for import paths on 2018 edition.
576     crate fn early_resolve_ident_in_lexical_scope(
577         &mut self,
578         orig_ident: Ident,
579         scope_set: ScopeSet,
580         parent_scope: &ParentScope<'a>,
581         record_used: bool,
582         force: bool,
583         path_span: Span,
584     ) -> Result<&'a NameBinding<'a>, Determinacy> {
585         bitflags::bitflags! {
586             struct Flags: u8 {
587                 const MACRO_RULES          = 1 << 0;
588                 const MODULE               = 1 << 1;
589                 const MISC_SUGGEST_CRATE   = 1 << 2;
590                 const MISC_SUGGEST_SELF    = 1 << 3;
591                 const MISC_FROM_PRELUDE    = 1 << 4;
592             }
593         }
594
595         assert!(force || !record_used); // `record_used` implies `force`
596
597         // Make sure `self`, `super` etc produce an error when passed to here.
598         if orig_ident.is_path_segment_keyword() {
599             return Err(Determinacy::Determined);
600         }
601
602         let (ns, macro_kind, is_import) = match scope_set {
603             ScopeSet::All(ns, is_import) => (ns, None, is_import),
604             ScopeSet::AbsolutePath(ns) => (ns, None, false),
605             ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind), false),
606         };
607
608         // This is *the* result, resolution from the scope closest to the resolved identifier.
609         // However, sometimes this result is "weak" because it comes from a glob import or
610         // a macro expansion, and in this case it cannot shadow names from outer scopes, e.g.
611         // mod m { ... } // solution in outer scope
612         // {
613         //     use prefix::*; // imports another `m` - innermost solution
614         //                    // weak, cannot shadow the outer `m`, need to report ambiguity error
615         //     m::mac!();
616         // }
617         // So we have to save the innermost solution and continue searching in outer scopes
618         // to detect potential ambiguities.
619         let mut innermost_result: Option<(&NameBinding<'_>, Flags)> = None;
620         let mut determinacy = Determinacy::Determined;
621
622         // Go through all the scopes and try to resolve the name.
623         let break_result = self.visit_scopes(
624             scope_set,
625             parent_scope,
626             orig_ident.span.ctxt(),
627             |this, scope, use_prelude, ctxt| {
628                 let ident = Ident::new(orig_ident.name, orig_ident.span.with_ctxt(ctxt));
629                 let ok = |res, span, arenas| {
630                     Ok((
631                         (res, ty::Visibility::Public, span, ExpnId::root()).to_name_binding(arenas),
632                         Flags::empty(),
633                     ))
634                 };
635                 let result = match scope {
636                     Scope::DeriveHelpers(expn_id) => {
637                         if let Some(attr) = this
638                             .helper_attrs
639                             .get(&expn_id)
640                             .and_then(|attrs| attrs.iter().rfind(|i| ident == **i))
641                         {
642                             let binding = (
643                                 Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper),
644                                 ty::Visibility::Public,
645                                 attr.span,
646                                 expn_id,
647                             )
648                                 .to_name_binding(this.arenas);
649                             Ok((binding, Flags::empty()))
650                         } else {
651                             Err(Determinacy::Determined)
652                         }
653                     }
654                     Scope::DeriveHelpersCompat => {
655                         let mut result = Err(Determinacy::Determined);
656                         for derive in parent_scope.derives {
657                             let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
658                             match this.resolve_macro_path(
659                                 derive,
660                                 Some(MacroKind::Derive),
661                                 parent_scope,
662                                 true,
663                                 force,
664                             ) {
665                                 Ok((Some(ext), _)) => {
666                                     if ext.helper_attrs.contains(&ident.name) {
667                                         result = ok(
668                                             Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat),
669                                             derive.span,
670                                             this.arenas,
671                                         );
672                                         break;
673                                     }
674                                 }
675                                 Ok(_) | Err(Determinacy::Determined) => {}
676                                 Err(Determinacy::Undetermined) => {
677                                     result = Err(Determinacy::Undetermined)
678                                 }
679                             }
680                         }
681                         result
682                     }
683                     Scope::MacroRules(macro_rules_scope) => match macro_rules_scope.get() {
684                         MacroRulesScope::Binding(macro_rules_binding)
685                             if ident == macro_rules_binding.ident =>
686                         {
687                             Ok((macro_rules_binding.binding, Flags::MACRO_RULES))
688                         }
689                         MacroRulesScope::Invocation(_) => Err(Determinacy::Undetermined),
690                         _ => Err(Determinacy::Determined),
691                     },
692                     Scope::CrateRoot => {
693                         let root_ident = Ident::new(kw::PathRoot, ident.span);
694                         let root_module = this.resolve_crate_root(root_ident);
695                         let binding = this.resolve_ident_in_module_ext(
696                             ModuleOrUniformRoot::Module(root_module),
697                             ident,
698                             ns,
699                             parent_scope,
700                             record_used,
701                             path_span,
702                         );
703                         match binding {
704                             Ok(binding) => Ok((binding, Flags::MODULE | Flags::MISC_SUGGEST_CRATE)),
705                             Err((Determinacy::Undetermined, Weak::No)) => {
706                                 return Some(Err(Determinacy::determined(force)));
707                             }
708                             Err((Determinacy::Undetermined, Weak::Yes)) => {
709                                 Err(Determinacy::Undetermined)
710                             }
711                             Err((Determinacy::Determined, _)) => Err(Determinacy::Determined),
712                         }
713                     }
714                     Scope::Module(module) => {
715                         let adjusted_parent_scope = &ParentScope { module, ..*parent_scope };
716                         let binding = this.resolve_ident_in_module_unadjusted_ext(
717                             ModuleOrUniformRoot::Module(module),
718                             ident,
719                             ns,
720                             adjusted_parent_scope,
721                             true,
722                             record_used,
723                             path_span,
724                         );
725                         match binding {
726                             Ok(binding) => {
727                                 let misc_flags = if ptr::eq(module, this.graph_root) {
728                                     Flags::MISC_SUGGEST_CRATE
729                                 } else if module.is_normal() {
730                                     Flags::MISC_SUGGEST_SELF
731                                 } else {
732                                     Flags::empty()
733                                 };
734                                 Ok((binding, Flags::MODULE | misc_flags))
735                             }
736                             Err((Determinacy::Undetermined, Weak::No)) => {
737                                 return Some(Err(Determinacy::determined(force)));
738                             }
739                             Err((Determinacy::Undetermined, Weak::Yes)) => {
740                                 Err(Determinacy::Undetermined)
741                             }
742                             Err((Determinacy::Determined, _)) => Err(Determinacy::Determined),
743                         }
744                     }
745                     Scope::RegisteredAttrs => match this.registered_attrs.get(&ident).cloned() {
746                         Some(ident) => ok(
747                             Res::NonMacroAttr(NonMacroAttrKind::Registered),
748                             ident.span,
749                             this.arenas,
750                         ),
751                         None => Err(Determinacy::Determined),
752                     },
753                     Scope::MacroUsePrelude => {
754                         match this.macro_use_prelude.get(&ident.name).cloned() {
755                             Some(binding) => Ok((binding, Flags::MISC_FROM_PRELUDE)),
756                             None => Err(Determinacy::determined(
757                                 this.graph_root.unexpanded_invocations.borrow().is_empty(),
758                             )),
759                         }
760                     }
761                     Scope::BuiltinAttrs => {
762                         if is_builtin_attr_name(ident.name) {
763                             ok(
764                                 Res::NonMacroAttr(NonMacroAttrKind::Builtin(ident.name)),
765                                 DUMMY_SP,
766                                 this.arenas,
767                             )
768                         } else {
769                             Err(Determinacy::Determined)
770                         }
771                     }
772                     Scope::ExternPrelude => match this.extern_prelude_get(ident, !record_used) {
773                         Some(binding) => Ok((binding, Flags::empty())),
774                         None => Err(Determinacy::determined(
775                             this.graph_root.unexpanded_invocations.borrow().is_empty(),
776                         )),
777                     },
778                     Scope::ToolPrelude => match this.registered_tools.get(&ident).cloned() {
779                         Some(ident) => ok(Res::ToolMod, ident.span, this.arenas),
780                         None => Err(Determinacy::Determined),
781                     },
782                     Scope::StdLibPrelude => {
783                         let mut result = Err(Determinacy::Determined);
784                         if let Some(prelude) = this.prelude {
785                             if let Ok(binding) = this.resolve_ident_in_module_unadjusted(
786                                 ModuleOrUniformRoot::Module(prelude),
787                                 ident,
788                                 ns,
789                                 parent_scope,
790                                 false,
791                                 path_span,
792                             ) {
793                                 if use_prelude || this.is_builtin_macro(binding.res()) {
794                                     result = Ok((binding, Flags::MISC_FROM_PRELUDE));
795                                 }
796                             }
797                         }
798                         result
799                     }
800                     Scope::BuiltinTypes => match PrimTy::from_name(ident.name) {
801                         Some(prim_ty) => ok(Res::PrimTy(prim_ty), DUMMY_SP, this.arenas),
802                         None => Err(Determinacy::Determined),
803                     },
804                 };
805
806                 match result {
807                     Ok((binding, flags))
808                         if sub_namespace_match(binding.macro_kind(), macro_kind) =>
809                     {
810                         if !record_used {
811                             return Some(Ok(binding));
812                         }
813
814                         if let Some((innermost_binding, innermost_flags)) = innermost_result {
815                             // Found another solution, if the first one was "weak", report an error.
816                             let (res, innermost_res) = (binding.res(), innermost_binding.res());
817                             if res != innermost_res {
818                                 let is_builtin = |res| {
819                                     matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Builtin(..)))
820                                 };
821                                 let derive_helper_compat =
822                                     Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat);
823
824                                 let ambiguity_error_kind = if is_import {
825                                     Some(AmbiguityKind::Import)
826                                 } else if is_builtin(innermost_res) || is_builtin(res) {
827                                     Some(AmbiguityKind::BuiltinAttr)
828                                 } else if innermost_res == derive_helper_compat
829                                     || res == derive_helper_compat
830                                 {
831                                     Some(AmbiguityKind::DeriveHelper)
832                                 } else if innermost_flags.contains(Flags::MACRO_RULES)
833                                     && flags.contains(Flags::MODULE)
834                                     && !this.disambiguate_macro_rules_vs_modularized(
835                                         innermost_binding,
836                                         binding,
837                                     )
838                                     || flags.contains(Flags::MACRO_RULES)
839                                         && innermost_flags.contains(Flags::MODULE)
840                                         && !this.disambiguate_macro_rules_vs_modularized(
841                                             binding,
842                                             innermost_binding,
843                                         )
844                                 {
845                                     Some(AmbiguityKind::MacroRulesVsModularized)
846                                 } else if innermost_binding.is_glob_import() {
847                                     Some(AmbiguityKind::GlobVsOuter)
848                                 } else if innermost_binding
849                                     .may_appear_after(parent_scope.expansion, binding)
850                                 {
851                                     Some(AmbiguityKind::MoreExpandedVsOuter)
852                                 } else {
853                                     None
854                                 };
855                                 if let Some(kind) = ambiguity_error_kind {
856                                     let misc = |f: Flags| {
857                                         if f.contains(Flags::MISC_SUGGEST_CRATE) {
858                                             AmbiguityErrorMisc::SuggestCrate
859                                         } else if f.contains(Flags::MISC_SUGGEST_SELF) {
860                                             AmbiguityErrorMisc::SuggestSelf
861                                         } else if f.contains(Flags::MISC_FROM_PRELUDE) {
862                                             AmbiguityErrorMisc::FromPrelude
863                                         } else {
864                                             AmbiguityErrorMisc::None
865                                         }
866                                     };
867                                     this.ambiguity_errors.push(AmbiguityError {
868                                         kind,
869                                         ident: orig_ident,
870                                         b1: innermost_binding,
871                                         b2: binding,
872                                         misc1: misc(innermost_flags),
873                                         misc2: misc(flags),
874                                     });
875                                     return Some(Ok(innermost_binding));
876                                 }
877                             }
878                         } else {
879                             // Found the first solution.
880                             innermost_result = Some((binding, flags));
881                         }
882                     }
883                     Ok(..) | Err(Determinacy::Determined) => {}
884                     Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined,
885                 }
886
887                 None
888             },
889         );
890
891         if let Some(break_result) = break_result {
892             return break_result;
893         }
894
895         // The first found solution was the only one, return it.
896         if let Some((binding, _)) = innermost_result {
897             return Ok(binding);
898         }
899
900         Err(Determinacy::determined(determinacy == Determinacy::Determined || force))
901     }
902
903     crate fn finalize_macro_resolutions(&mut self) {
904         let check_consistency = |this: &mut Self,
905                                  path: &[Segment],
906                                  span,
907                                  kind: MacroKind,
908                                  initial_res: Option<Res>,
909                                  res: Res| {
910             if let Some(initial_res) = initial_res {
911                 if res != initial_res {
912                     // Make sure compilation does not succeed if preferred macro resolution
913                     // has changed after the macro had been expanded. In theory all such
914                     // situations should be reported as errors, so this is a bug.
915                     this.session.delay_span_bug(span, "inconsistent resolution for a macro");
916                 }
917             } else {
918                 // It's possible that the macro was unresolved (indeterminate) and silently
919                 // expanded into a dummy fragment for recovery during expansion.
920                 // Now, post-expansion, the resolution may succeed, but we can't change the
921                 // past and need to report an error.
922                 // However, non-speculative `resolve_path` can successfully return private items
923                 // even if speculative `resolve_path` returned nothing previously, so we skip this
924                 // less informative error if the privacy error is reported elsewhere.
925                 if this.privacy_errors.is_empty() {
926                     let msg = format!(
927                         "cannot determine resolution for the {} `{}`",
928                         kind.descr(),
929                         Segment::names_to_string(path)
930                     );
931                     let msg_note = "import resolution is stuck, try simplifying macro imports";
932                     this.session.struct_span_err(span, &msg).note(msg_note).emit();
933                 }
934             }
935         };
936
937         let macro_resolutions = mem::take(&mut self.multi_segment_macro_resolutions);
938         for (mut path, path_span, kind, parent_scope, initial_res) in macro_resolutions {
939             // FIXME: Path resolution will ICE if segment IDs present.
940             for seg in &mut path {
941                 seg.id = None;
942             }
943             match self.resolve_path(
944                 &path,
945                 Some(MacroNS),
946                 &parent_scope,
947                 true,
948                 path_span,
949                 CrateLint::No,
950             ) {
951                 PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
952                     let res = path_res.base_res();
953                     check_consistency(self, &path, path_span, kind, initial_res, res);
954                 }
955                 path_res @ PathResult::NonModule(..) | path_res @ PathResult::Failed { .. } => {
956                     let (span, label) = if let PathResult::Failed { span, label, .. } = path_res {
957                         (span, label)
958                     } else {
959                         (
960                             path_span,
961                             format!(
962                                 "partially resolved path in {} {}",
963                                 kind.article(),
964                                 kind.descr()
965                             ),
966                         )
967                     };
968                     self.report_error(
969                         span,
970                         ResolutionError::FailedToResolve { label, suggestion: None },
971                     );
972                 }
973                 PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
974             }
975         }
976
977         let macro_resolutions = mem::take(&mut self.single_segment_macro_resolutions);
978         for (ident, kind, parent_scope, initial_binding) in macro_resolutions {
979             match self.early_resolve_ident_in_lexical_scope(
980                 ident,
981                 ScopeSet::Macro(kind),
982                 &parent_scope,
983                 true,
984                 true,
985                 ident.span,
986             ) {
987                 Ok(binding) => {
988                     let initial_res = initial_binding.map(|initial_binding| {
989                         self.record_use(ident, MacroNS, initial_binding, false);
990                         initial_binding.res()
991                     });
992                     let res = binding.res();
993                     let seg = Segment::from_ident(ident);
994                     check_consistency(self, &[seg], ident.span, kind, initial_res, res);
995                 }
996                 Err(..) => {
997                     let expected = kind.descr_expected();
998                     let msg = format!("cannot find {} `{}` in this scope", expected, ident);
999                     let mut err = self.session.struct_span_err(ident.span, &msg);
1000                     self.unresolved_macro_suggestions(&mut err, kind, &parent_scope, ident);
1001                     err.emit();
1002                 }
1003             }
1004         }
1005
1006         let builtin_attrs = mem::take(&mut self.builtin_attrs);
1007         for (ident, parent_scope) in builtin_attrs {
1008             let _ = self.early_resolve_ident_in_lexical_scope(
1009                 ident,
1010                 ScopeSet::Macro(MacroKind::Attr),
1011                 &parent_scope,
1012                 true,
1013                 true,
1014                 ident.span,
1015             );
1016         }
1017     }
1018
1019     fn check_stability_and_deprecation(
1020         &mut self,
1021         ext: &SyntaxExtension,
1022         path: &ast::Path,
1023         node_id: NodeId,
1024     ) {
1025         let span = path.span;
1026         if let Some(stability) = &ext.stability {
1027             if let StabilityLevel::Unstable { reason, issue, is_soft } = stability.level {
1028                 let feature = stability.feature;
1029                 if !self.active_features.contains(&feature) && !span.allows_unstable(feature) {
1030                     let lint_buffer = &mut self.lint_buffer;
1031                     let soft_handler =
1032                         |lint, span, msg: &_| lint_buffer.buffer_lint(lint, node_id, span, msg);
1033                     stability::report_unstable(
1034                         self.session,
1035                         feature,
1036                         reason,
1037                         issue,
1038                         is_soft,
1039                         span,
1040                         soft_handler,
1041                     );
1042                 }
1043             }
1044         }
1045         if let Some(depr) = &ext.deprecation {
1046             let path = pprust::path_to_string(&path);
1047             let (message, lint) = stability::deprecation_message(depr, "macro", &path);
1048             stability::early_report_deprecation(
1049                 &mut self.lint_buffer,
1050                 &message,
1051                 depr.suggestion,
1052                 lint,
1053                 span,
1054                 node_id,
1055             );
1056         }
1057     }
1058
1059     fn prohibit_imported_non_macro_attrs(
1060         &self,
1061         binding: Option<&'a NameBinding<'a>>,
1062         res: Option<Res>,
1063         span: Span,
1064     ) {
1065         if let Some(Res::NonMacroAttr(kind)) = res {
1066             if kind != NonMacroAttrKind::Tool && binding.map_or(true, |b| b.is_import()) {
1067                 let msg =
1068                     format!("cannot use {} {} through an import", kind.article(), kind.descr());
1069                 let mut err = self.session.struct_span_err(span, &msg);
1070                 if let Some(binding) = binding {
1071                     err.span_note(binding.span, &format!("the {} imported here", kind.descr()));
1072                 }
1073                 err.emit();
1074             }
1075         }
1076     }
1077
1078     crate fn check_reserved_macro_name(&mut self, ident: Ident, res: Res) {
1079         // Reserve some names that are not quite covered by the general check
1080         // performed on `Resolver::builtin_attrs`.
1081         if ident.name == sym::cfg || ident.name == sym::cfg_attr || ident.name == sym::derive {
1082             let macro_kind = self.get_macro(res).map(|ext| ext.macro_kind());
1083             if macro_kind.is_some() && sub_namespace_match(macro_kind, Some(MacroKind::Attr)) {
1084                 self.session.span_err(
1085                     ident.span,
1086                     &format!("name `{}` is reserved in attribute namespace", ident),
1087                 );
1088             }
1089         }
1090     }
1091
1092     /// Compile the macro into a `SyntaxExtension` and possibly replace
1093     /// its expander to a pre-defined one for built-in macros.
1094     crate fn compile_macro(&mut self, item: &ast::Item, edition: Edition) -> SyntaxExtension {
1095         let mut result = compile_declarative_macro(
1096             &self.session,
1097             self.session.features_untracked(),
1098             item,
1099             edition,
1100         );
1101
1102         if let Some(builtin_name) = result.builtin_name {
1103             // The macro was marked with `#[rustc_builtin_macro]`.
1104             if let Some(builtin_macro) = self.builtin_macros.get_mut(&builtin_name) {
1105                 // The macro is a built-in, replace its expander function
1106                 // while still taking everything else from the source code.
1107                 // If we already loaded this builtin macro, give a better error message than 'no such builtin macro'.
1108                 match mem::replace(builtin_macro, BuiltinMacroState::AlreadySeen(item.span)) {
1109                     BuiltinMacroState::NotYetSeen(ext) => result.kind = ext,
1110                     BuiltinMacroState::AlreadySeen(span) => {
1111                         struct_span_err!(
1112                             self.session,
1113                             item.span,
1114                             E0773,
1115                             "attempted to define built-in macro more than once"
1116                         )
1117                         .span_note(span, "previously defined here")
1118                         .emit();
1119                     }
1120                 }
1121             } else {
1122                 let msg = format!("cannot find a built-in macro with name `{}`", item.ident);
1123                 self.session.span_err(item.span, &msg);
1124             }
1125         }
1126
1127         result
1128     }
1129 }