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