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