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