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