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