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