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