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