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