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