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