1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use {AmbiguityError, CrateLint, Resolver, ResolutionError, is_known_tool, resolve_error};
12 use {Module, ModuleKind, NameBinding, NameBindingKind, PathResult, ToNameBinding};
13 use ModuleOrUniformRoot;
14 use Namespace::{self, *};
15 use build_reduced_graph::{BuildReducedGraphVisitor, IsMacroExport};
16 use resolve_imports::ImportResolver;
17 use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX, DefIndex,
18 CrateNum, DefIndexAddressSpace};
19 use rustc::hir::def::{Def, NonMacroAttrKind};
20 use rustc::hir::map::{self, DefCollector};
21 use rustc::{ty, lint};
22 use syntax::ast::{self, Name, Ident};
24 use syntax::errors::DiagnosticBuilder;
25 use syntax::ext::base::{self, Determinacy};
26 use syntax::ext::base::{MacroKind, SyntaxExtension, Resolver as SyntaxResolver};
27 use syntax::ext::expand::{AstFragment, Invocation, InvocationKind};
28 use syntax::ext::hygiene::{self, Mark};
29 use syntax::ext::tt::macro_rules;
30 use syntax::feature_gate::{self, feature_err, emit_feature_err, is_builtin_attr_name, GateIssue};
31 use syntax::feature_gate::EXPLAIN_DERIVE_UNDERSCORE;
32 use syntax::fold::{self, Folder};
33 use syntax::parse::parser::PathStyle;
34 use syntax::parse::token::{self, Token};
36 use syntax::symbol::{Symbol, keywords};
37 use syntax::tokenstream::{TokenStream, TokenTree, Delimited, DelimSpan};
38 use syntax::util::lev_distance::find_best_match_for_name;
39 use syntax_pos::{Span, DUMMY_SP};
40 use errors::Applicability;
44 use rustc_data_structures::sync::Lrc;
47 pub struct InvocationData<'a> {
49 /// Module in which the macro was invoked.
50 crate module: Cell<Module<'a>>,
51 /// Legacy scope in which the macro was invoked.
52 /// The invocation path is resolved in this scope.
53 crate parent_legacy_scope: Cell<LegacyScope<'a>>,
54 /// Legacy scope *produced* by expanding this macro invocation,
55 /// includes all the macro_rules items, other invocations, etc generated by it.
56 /// Set to the parent scope if the macro is not expanded yet (as if the macro produced nothing).
57 crate output_legacy_scope: Cell<LegacyScope<'a>>,
60 impl<'a> InvocationData<'a> {
61 pub fn root(graph_root: Module<'a>) -> Self {
63 module: Cell::new(graph_root),
64 def_index: CRATE_DEF_INDEX,
65 parent_legacy_scope: Cell::new(LegacyScope::Empty),
66 output_legacy_scope: Cell::new(LegacyScope::Empty),
71 /// Binding produced by a `macro_rules` item.
72 /// Not modularized, can shadow previous legacy bindings, etc.
73 pub struct LegacyBinding<'a> {
74 binding: &'a NameBinding<'a>,
75 /// Legacy scope into which the `macro_rules` item was planted.
76 parent_legacy_scope: LegacyScope<'a>,
80 /// Scope introduced by a `macro_rules!` macro.
81 /// Starts at the macro's definition and ends at the end of the macro's parent module
82 /// (named or unnamed), or even further if it escapes with `#[macro_use]`.
83 /// Some macro invocations need to introduce legacy scopes too because they
84 /// potentially can expand into macro definitions.
85 #[derive(Copy, Clone)]
86 pub enum LegacyScope<'a> {
87 /// Created when invocation data is allocated in the arena,
88 /// must be replaced with a proper scope later.
90 /// Empty "root" scope at the crate start containing no names.
92 /// Scope introduced by a `macro_rules!` macro definition.
93 Binding(&'a LegacyBinding<'a>),
94 /// Scope introduced by a macro invocation that can potentially
95 /// create a `macro_rules!` macro definition.
96 Invocation(&'a InvocationData<'a>),
99 /// Everything you need to resolve a macro path.
101 pub struct ParentScope<'a> {
102 crate module: Module<'a>,
103 crate expansion: Mark,
104 crate legacy: LegacyScope<'a>,
105 crate derives: Vec<ast::Path>,
108 // Macro namespace is separated into two sub-namespaces, one for bang macros and
109 // one for attribute-like macros (attributes, derives).
110 // We ignore resolutions from one sub-namespace when searching names in scope for another.
111 fn sub_namespace_mismatch(requirement: Option<MacroKind>, candidate: Option<MacroKind>) -> bool {
113 enum SubNS { Bang, AttrLike }
114 let sub_ns = |kind| match kind {
115 MacroKind::Bang => Some(SubNS::Bang),
116 MacroKind::Attr | MacroKind::Derive => Some(SubNS::AttrLike),
117 MacroKind::ProcMacroStub => None,
119 let requirement = requirement.and_then(|kind| sub_ns(kind));
120 let candidate = candidate.and_then(|kind| sub_ns(kind));
121 // "No specific sub-namespace" means "matches anything" for both requirements and candidates.
122 candidate.is_some() && requirement.is_some() && candidate != requirement
125 impl<'a, 'crateloader: 'a> base::Resolver for Resolver<'a, 'crateloader> {
126 fn next_node_id(&mut self) -> ast::NodeId {
127 self.session.next_node_id()
130 fn get_module_scope(&mut self, id: ast::NodeId) -> Mark {
131 let mark = Mark::fresh(Mark::root());
132 let module = self.module_map[&self.definitions.local_def_id(id)];
133 self.invocations.insert(mark, self.arenas.alloc_invocation_data(InvocationData {
134 module: Cell::new(module),
135 def_index: module.def_id().unwrap().index,
136 parent_legacy_scope: Cell::new(LegacyScope::Empty),
137 output_legacy_scope: Cell::new(LegacyScope::Empty),
142 fn eliminate_crate_var(&mut self, item: P<ast::Item>) -> P<ast::Item> {
143 struct EliminateCrateVar<'b, 'a: 'b, 'crateloader: 'a>(
144 &'b mut Resolver<'a, 'crateloader>, Span
147 impl<'a, 'b, 'crateloader> Folder for EliminateCrateVar<'a, 'b, 'crateloader> {
148 fn fold_path(&mut self, path: ast::Path) -> ast::Path {
149 match self.fold_qpath(None, path) {
150 (None, path) => path,
155 fn fold_qpath(&mut self, mut qself: Option<ast::QSelf>, mut path: ast::Path)
156 -> (Option<ast::QSelf>, ast::Path) {
157 qself = qself.map(|ast::QSelf { ty, path_span, position }| {
159 ty: self.fold_ty(ty),
160 path_span: self.new_span(path_span),
165 if path.segments[0].ident.name == keywords::DollarCrate.name() {
166 let module = self.0.resolve_crate_root(path.segments[0].ident);
167 path.segments[0].ident.name = keywords::CrateRoot.name();
168 if !module.is_local() {
169 let span = path.segments[0].ident.span;
170 path.segments.insert(1, match module.kind {
171 ModuleKind::Def(_, name) => ast::PathSegment::from_ident(
172 ast::Ident::with_empty_ctxt(name).with_span_pos(span)
176 if let Some(qself) = &mut qself {
184 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
185 fold::noop_fold_mac(mac, self)
189 let ret = EliminateCrateVar(self, item.span).fold_item(item);
190 assert!(ret.len() == 1);
191 ret.into_iter().next().unwrap()
194 fn is_whitelisted_legacy_custom_derive(&self, name: Name) -> bool {
195 self.whitelisted_legacy_custom_derives.contains(&name)
198 fn visit_ast_fragment_with_placeholders(&mut self, mark: Mark, fragment: &AstFragment,
200 let invocation = self.invocations[&mark];
201 self.collect_def_ids(mark, invocation, fragment);
203 self.current_module = invocation.module.get();
204 self.current_module.unresolved_invocations.borrow_mut().remove(&mark);
205 self.current_module.unresolved_invocations.borrow_mut().extend(derives);
206 for &derive in derives {
207 self.invocations.insert(derive, invocation);
209 let mut visitor = BuildReducedGraphVisitor {
211 current_legacy_scope: invocation.parent_legacy_scope.get(),
214 fragment.visit_with(&mut visitor);
215 invocation.output_legacy_scope.set(visitor.current_legacy_scope);
218 fn add_builtin(&mut self, ident: ast::Ident, ext: Lrc<SyntaxExtension>) {
220 krate: CrateNum::BuiltinMacros,
221 index: DefIndex::from_array_index(self.macro_map.len(),
222 DefIndexAddressSpace::Low),
224 let kind = ext.kind();
225 self.macro_map.insert(def_id, ext);
226 let binding = self.arenas.alloc_name_binding(NameBinding {
227 kind: NameBindingKind::Def(Def::Macro(def_id, kind), false),
229 vis: ty::Visibility::Invisible,
230 expansion: Mark::root(),
232 if self.builtin_macros.insert(ident.name, binding).is_some() {
233 self.session.span_err(ident.span,
234 &format!("built-in macro `{}` was already defined", ident));
238 fn resolve_imports(&mut self) {
239 ImportResolver { resolver: self }.resolve_imports()
242 // Resolves attribute and derive legacy macros from `#![plugin(..)]`.
243 fn find_legacy_attr_invoc(&mut self, attrs: &mut Vec<ast::Attribute>, allow_derive: bool)
244 -> Option<ast::Attribute> {
249 // Check for legacy derives
250 for i in 0..attrs.len() {
251 let name = attrs[i].name();
253 if name == "derive" {
254 let result = attrs[i].parse_list(&self.session.parse_sess, |parser| {
255 parser.parse_path_allowing_meta(PathStyle::Mod)
258 let mut traits = match result {
259 Ok(traits) => traits,
266 for j in 0..traits.len() {
267 if traits[j].segments.len() > 1 {
270 let trait_name = traits[j].segments[0].ident.name;
271 let legacy_name = Symbol::intern(&format!("derive_{}", trait_name));
272 if !self.builtin_macros.contains_key(&legacy_name) {
275 let span = traits.remove(j).span;
276 self.gate_legacy_custom_derive(legacy_name, span);
277 if traits.is_empty() {
280 let mut tokens = Vec::new();
281 for (j, path) in traits.iter().enumerate() {
283 tokens.push(TokenTree::Token(attrs[i].span, Token::Comma).into());
285 for (k, segment) in path.segments.iter().enumerate() {
287 tokens.push(TokenTree::Token(path.span, Token::ModSep).into());
289 let tok = Token::from_ast_ident(segment.ident);
290 tokens.push(TokenTree::Token(path.span, tok).into());
293 let delim_span = DelimSpan::from_single(attrs[i].span);
294 attrs[i].tokens = TokenTree::Delimited(delim_span, Delimited {
296 tts: TokenStream::concat(tokens).into(),
299 return Some(ast::Attribute {
300 path: ast::Path::from_ident(Ident::new(legacy_name, span)),
301 tokens: TokenStream::empty(),
302 id: attr::mk_attr_id(),
303 style: ast::AttrStyle::Outer,
304 is_sugared_doc: false,
314 fn resolve_macro_invocation(&mut self, invoc: &Invocation, invoc_id: Mark, force: bool)
315 -> Result<Option<Lrc<SyntaxExtension>>, Determinacy> {
316 let (path, kind, derives_in_scope, after_derive) = match invoc.kind {
317 InvocationKind::Attr { attr: None, .. } =>
319 InvocationKind::Attr { attr: Some(ref attr), ref traits, after_derive, .. } =>
320 (&attr.path, MacroKind::Attr, traits.clone(), after_derive),
321 InvocationKind::Bang { ref mac, .. } =>
322 (&mac.node.path, MacroKind::Bang, Vec::new(), false),
323 InvocationKind::Derive { ref path, .. } =>
324 (path, MacroKind::Derive, Vec::new(), false),
327 let parent_scope = self.invoc_parent_scope(invoc_id, derives_in_scope);
328 let (def, ext) = self.resolve_macro_to_def(path, kind, &parent_scope, force)?;
330 if let Def::Macro(def_id, _) = def {
332 self.session.span_err(invoc.span(),
333 "macro attributes must be placed before `#[derive]`");
335 self.macro_defs.insert(invoc.expansion_data.mark, def_id);
336 let normal_module_def_id =
337 self.macro_def_scope(invoc.expansion_data.mark).normal_ancestor_id;
338 self.definitions.add_parent_module_of_macro_def(invoc.expansion_data.mark,
339 normal_module_def_id);
340 invoc.expansion_data.mark.set_default_transparency(ext.default_transparency());
341 invoc.expansion_data.mark.set_is_builtin(def_id.krate == CrateNum::BuiltinMacros);
347 fn resolve_macro_path(&mut self, path: &ast::Path, kind: MacroKind, invoc_id: Mark,
348 derives_in_scope: Vec<ast::Path>, force: bool)
349 -> Result<Lrc<SyntaxExtension>, Determinacy> {
350 let parent_scope = self.invoc_parent_scope(invoc_id, derives_in_scope);
351 Ok(self.resolve_macro_to_def(path, kind, &parent_scope, force)?.1)
354 fn check_unused_macros(&self) {
355 for did in self.unused_macros.iter() {
356 let id_span = match *self.macro_map[did] {
357 SyntaxExtension::NormalTT { def_info, .. } |
358 SyntaxExtension::DeclMacro { def_info, .. } => def_info,
361 if let Some((id, span)) = id_span {
362 let lint = lint::builtin::UNUSED_MACROS;
363 let msg = "unused macro definition";
364 self.session.buffer_lint(lint, id, span, msg);
366 bug!("attempted to create unused macro error, but span not available");
372 impl<'a, 'cl> Resolver<'a, 'cl> {
373 pub fn dummy_parent_scope(&mut self) -> ParentScope<'a> {
374 self.invoc_parent_scope(Mark::root(), Vec::new())
377 fn invoc_parent_scope(&mut self, invoc_id: Mark, derives: Vec<ast::Path>) -> ParentScope<'a> {
378 let invoc = self.invocations[&invoc_id];
380 module: invoc.module.get().nearest_item_scope(),
381 expansion: invoc_id.parent(),
382 legacy: invoc.parent_legacy_scope.get(),
387 fn resolve_macro_to_def(
391 parent_scope: &ParentScope<'a>,
393 ) -> Result<(Def, Lrc<SyntaxExtension>), Determinacy> {
394 let def = self.resolve_macro_to_def_inner(path, kind, parent_scope, force);
396 // Report errors and enforce feature gates for the resolved macro.
397 if def != Err(Determinacy::Undetermined) {
398 // Do not report duplicated errors on every undetermined resolution.
399 for segment in &path.segments {
400 if let Some(args) = &segment.args {
401 self.session.span_err(args.span(), "generic arguments in macro path");
409 Def::Macro(def_id, macro_kind) => {
410 self.unused_macros.remove(&def_id);
411 if macro_kind == MacroKind::ProcMacroStub {
412 let msg = "can't use a procedural macro from the same crate that defines it";
413 self.session.span_err(path.span, msg);
414 return Err(Determinacy::Determined);
417 Def::NonMacroAttr(attr_kind) => {
418 if kind == MacroKind::Attr {
419 let features = self.session.features_untracked();
420 if attr_kind == NonMacroAttrKind::Custom {
421 assert!(path.segments.len() == 1);
422 let name = path.segments[0].ident.name.as_str();
423 if name.starts_with("rustc_") {
424 if !features.rustc_attrs {
425 let msg = "unless otherwise specified, attributes with the prefix \
426 `rustc_` are reserved for internal compiler diagnostics";
427 feature_err(&self.session.parse_sess, "rustc_attrs", path.span,
428 GateIssue::Language, &msg).emit();
430 } else if name.starts_with("derive_") {
431 if !features.custom_derive {
432 feature_err(&self.session.parse_sess, "custom_derive", path.span,
433 GateIssue::Language, EXPLAIN_DERIVE_UNDERSCORE).emit();
435 } else if !features.custom_attribute {
436 let msg = format!("The attribute `{}` is currently unknown to the \
437 compiler and may have meaning added to it in the \
439 feature_err(&self.session.parse_sess, "custom_attribute", path.span,
440 GateIssue::Language, &msg).emit();
444 // Not only attributes, but anything in macro namespace can result in
445 // `Def::NonMacroAttr` definition (e.g. `inline!()`), so we must report
446 // an error for those cases.
447 let msg = format!("expected a macro, found {}", def.kind_name());
448 self.session.span_err(path.span, &msg);
449 return Err(Determinacy::Determined);
452 _ => panic!("expected `Def::Macro` or `Def::NonMacroAttr`"),
455 Ok((def, self.get_macro(def)))
458 pub fn resolve_macro_to_def_inner(
462 parent_scope: &ParentScope<'a>,
464 ) -> Result<Def, Determinacy> {
465 let ast::Path { ref segments, span } = *path;
466 let mut path: Vec<_> = segments.iter().map(|seg| seg.ident).collect();
468 // Possibly apply the macro helper hack
469 if kind == MacroKind::Bang && path.len() == 1 &&
470 path[0].span.ctxt().outer().expn_info().map_or(false, |info| info.local_inner_macros) {
471 let root = Ident::new(keywords::DollarCrate.name(), path[0].span);
472 path.insert(0, root);
476 let def = match self.resolve_path_with_parent_scope(None, &path, Some(MacroNS),
477 parent_scope, false, span,
479 PathResult::NonModule(path_res) => match path_res.base_def() {
480 Def::Err => Err(Determinacy::Determined),
482 if path_res.unresolved_segments() > 0 {
483 self.found_unresolved_macro = true;
484 self.session.span_err(span, "fail to resolve non-ident macro path");
485 Err(Determinacy::Determined)
491 PathResult::Module(..) => unreachable!(),
492 PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
494 self.found_unresolved_macro = true;
495 Err(Determinacy::Determined)
499 parent_scope.module.macro_resolutions.borrow_mut()
500 .push((path.into_boxed_slice(), span));
504 let binding = self.early_resolve_ident_in_lexical_scope(
505 path[0], MacroNS, Some(kind), parent_scope, false, force, span
509 Err(Determinacy::Determined) => self.found_unresolved_macro = true,
510 Err(Determinacy::Undetermined) => return Err(Determinacy::Undetermined),
513 parent_scope.module.legacy_macro_resolutions.borrow_mut()
514 .push((path[0], kind, parent_scope.clone(), binding.ok()));
516 binding.map(|binding| binding.def_ignoring_ambiguity())
520 // Resolve an identifier in lexical scope.
521 // This is a variation of `fn resolve_ident_in_lexical_scope` that can be run during
522 // expansion and import resolution (perhaps they can be merged in the future).
523 // The function is used for resolving initial segments of macro paths (e.g. `foo` in
524 // `foo::bar!(); or `foo!();`) and can be used for "uniform path" imports in the future.
525 crate fn early_resolve_ident_in_lexical_scope(
529 kind: Option<MacroKind>,
530 parent_scope: &ParentScope<'a>,
534 ) -> Result<&'a NameBinding<'a>, Determinacy> {
535 // General principles:
536 // 1. Not controlled (user-defined) names should have higher priority than controlled names
537 // built into the language or standard library. This way we can add new names into the
538 // language or standard library without breaking user code.
539 // 2. "Closed set" below means new names cannot appear after the current resolution attempt.
540 // Places to search (in order of decreasing priority):
542 // 1. FIXME: Ribs (type parameters), there's no necessary infrastructure yet
543 // (open set, not controlled).
544 // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
545 // (open, not controlled).
546 // 3. Extern prelude (closed, not controlled).
547 // 4. Tool modules (closed, controlled right now, but not in the future).
548 // 5. Standard library prelude (de-facto closed, controlled).
549 // 6. Language prelude (closed, controlled).
551 // 1. FIXME: Ribs (local variables), there's no necessary infrastructure yet
552 // (open set, not controlled).
553 // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
554 // (open, not controlled).
555 // 3. Standard library prelude (de-facto closed, controlled).
557 // 1-3. Derive helpers (open, not controlled). All ambiguities with other names
558 // are currently reported as errors. They should be higher in priority than preludes
559 // and probably even names in modules according to the "general principles" above. They
560 // also should be subject to restricted shadowing because are effectively produced by
561 // derives (you need to resolve the derive first to add helpers into scope), but they
562 // should be available before the derive is expanded for compatibility.
563 // It's mess in general, so we are being conservative for now.
564 // 1-3. `macro_rules` (open, not controlled), loop through legacy scopes. Have higher
565 // priority than prelude macros, but create ambiguities with macros in modules.
566 // 1-3. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
567 // (open, not controlled). Have higher priority than prelude macros, but create
568 // ambiguities with `macro_rules`.
569 // 4. `macro_use` prelude (open, the open part is from macro expansions, not controlled).
570 // 4a. User-defined prelude from macro-use
571 // (open, the open part is from macro expansions, not controlled).
572 // 4b. Standard library prelude is currently implemented as `macro-use` (closed, controlled)
573 // 5. Language prelude: builtin macros (closed, controlled, except for legacy plugins).
574 // 6. Language prelude: builtin attributes (closed, controlled).
575 // 4-6. Legacy plugin helpers (open, not controlled). Similar to derive helpers,
576 // but introduced by legacy plugins using `register_attribute`. Priority is somewhere
577 // in prelude, not sure where exactly (creates ambiguities with any other prelude names).
579 enum WhereToResolve<'a> {
581 MacroRules(LegacyScope<'a>),
595 const DERIVE_HELPERS = 1 << 0;
596 const MACRO_RULES = 1 << 1;
597 const MODULE = 1 << 2;
598 const PRELUDE = 1 << 3;
602 assert!(force || !record_used); // `record_used` implies `force`
603 ident = ident.modern();
605 // This is *the* result, resolution from the scope closest to the resolved identifier.
606 // However, sometimes this result is "weak" because it comes from a glob import or
607 // a macro expansion, and in this case it cannot shadow names from outer scopes, e.g.
608 // mod m { ... } // solution in outer scope
610 // use prefix::*; // imports another `m` - innermost solution
611 // // weak, cannot shadow the outer `m`, need to report ambiguity error
614 // So we have to save the innermost solution and continue searching in outer scopes
615 // to detect potential ambiguities.
616 let mut innermost_result: Option<(&NameBinding, Flags, /* conflicts with */ Flags)> = None;
618 // Go through all the scopes and try to resolve the name.
619 let mut where_to_resolve = WhereToResolve::DeriveHelpers;
620 let mut use_prelude = !parent_scope.module.no_implicit_prelude;
622 let result = match where_to_resolve {
623 WhereToResolve::DeriveHelpers => {
624 let mut result = Err(Determinacy::Determined);
625 for derive in &parent_scope.derives {
626 let parent_scope = ParentScope { derives: Vec::new(), ..*parent_scope };
627 if let Ok((_, ext)) = self.resolve_macro_to_def(derive, MacroKind::Derive,
628 &parent_scope, force) {
629 if let SyntaxExtension::ProcMacroDerive(_, helper_attrs, _) = &*ext {
630 if helper_attrs.contains(&ident.name) {
632 (Def::NonMacroAttr(NonMacroAttrKind::DeriveHelper),
633 ty::Visibility::Public, derive.span, Mark::root())
634 .to_name_binding(self.arenas);
635 result = Ok((binding, Flags::DERIVE_HELPERS, Flags::all()));
643 WhereToResolve::MacroRules(legacy_scope) => match legacy_scope {
644 LegacyScope::Binding(legacy_binding) if ident == legacy_binding.ident =>
645 Ok((legacy_binding.binding, Flags::MACRO_RULES, Flags::empty())),
646 _ => Err(Determinacy::Determined),
648 WhereToResolve::Module(module) => {
649 let orig_current_module = mem::replace(&mut self.current_module, module);
650 let binding = self.resolve_ident_in_module_unadjusted(
651 ModuleOrUniformRoot::Module(module),
658 self.current_module = orig_current_module;
659 binding.map(|binding| (binding, Flags::MODULE, Flags::empty()))
661 WhereToResolve::MacroUsePrelude => {
662 match self.macro_use_prelude.get(&ident.name).cloned() {
663 Some(binding) => Ok((binding, Flags::PRELUDE, Flags::empty())),
664 None => Err(Determinacy::Determined),
667 WhereToResolve::BuiltinMacros => {
668 match self.builtin_macros.get(&ident.name).cloned() {
669 Some(binding) => Ok((binding, Flags::PRELUDE, Flags::empty())),
670 None => Err(Determinacy::Determined),
673 WhereToResolve::BuiltinAttrs => {
674 if is_builtin_attr_name(ident.name) {
675 let binding = (Def::NonMacroAttr(NonMacroAttrKind::Builtin),
676 ty::Visibility::Public, ident.span, Mark::root())
677 .to_name_binding(self.arenas);
678 Ok((binding, Flags::PRELUDE, Flags::empty()))
680 Err(Determinacy::Determined)
683 WhereToResolve::LegacyPluginHelpers => {
684 if self.session.plugin_attributes.borrow().iter()
685 .any(|(name, _)| ident.name == &**name) {
686 let binding = (Def::NonMacroAttr(NonMacroAttrKind::LegacyPluginHelper),
687 ty::Visibility::Public, ident.span, Mark::root())
688 .to_name_binding(self.arenas);
689 Ok((binding, Flags::PRELUDE, Flags::PRELUDE))
691 Err(Determinacy::Determined)
694 WhereToResolve::ExternPrelude => {
695 if use_prelude && self.session.extern_prelude.contains(&ident.name) {
697 self.crate_loader.process_path_extern(ident.name, ident.span);
699 self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
700 self.populate_module_if_necessary(crate_root);
702 let binding = (crate_root, ty::Visibility::Public,
703 ident.span, Mark::root()).to_name_binding(self.arenas);
704 Ok((binding, Flags::PRELUDE, Flags::empty()))
706 Err(Determinacy::Determined)
709 WhereToResolve::ToolPrelude => {
710 if use_prelude && is_known_tool(ident.name) {
711 let binding = (Def::ToolMod, ty::Visibility::Public,
712 ident.span, Mark::root()).to_name_binding(self.arenas);
713 Ok((binding, Flags::PRELUDE, Flags::empty()))
715 Err(Determinacy::Determined)
718 WhereToResolve::StdLibPrelude => {
719 let mut result = Err(Determinacy::Determined);
721 if let Some(prelude) = self.prelude {
722 if let Ok(binding) = self.resolve_ident_in_module_unadjusted(
723 ModuleOrUniformRoot::Module(prelude),
730 result = Ok((binding, Flags::PRELUDE, Flags::empty()));
736 WhereToResolve::BuiltinTypes => {
737 match self.primitive_type_table.primitive_types.get(&ident.name).cloned() {
739 let binding = (Def::PrimTy(prim_ty), ty::Visibility::Public,
740 ident.span, Mark::root()).to_name_binding(self.arenas);
741 Ok((binding, Flags::PRELUDE, Flags::empty()))
743 None => Err(Determinacy::Determined)
748 macro_rules! continue_search { () => {
749 where_to_resolve = match where_to_resolve {
750 WhereToResolve::DeriveHelpers =>
751 WhereToResolve::MacroRules(parent_scope.legacy),
752 WhereToResolve::MacroRules(legacy_scope) => match legacy_scope {
753 LegacyScope::Binding(binding) =>
754 WhereToResolve::MacroRules(binding.parent_legacy_scope),
755 LegacyScope::Invocation(invocation) =>
756 WhereToResolve::MacroRules(invocation.output_legacy_scope.get()),
757 LegacyScope::Empty => WhereToResolve::Module(parent_scope.module),
758 LegacyScope::Uninitialized => unreachable!(),
760 WhereToResolve::Module(module) => {
761 match self.hygienic_lexical_parent(module, &mut ident.span) {
762 Some(parent_module) => WhereToResolve::Module(parent_module),
764 use_prelude = !module.no_implicit_prelude;
766 TypeNS => WhereToResolve::ExternPrelude,
767 ValueNS => WhereToResolve::StdLibPrelude,
768 MacroNS => WhereToResolve::MacroUsePrelude,
773 WhereToResolve::MacroUsePrelude => WhereToResolve::BuiltinMacros,
774 WhereToResolve::BuiltinMacros => WhereToResolve::BuiltinAttrs,
775 WhereToResolve::BuiltinAttrs => WhereToResolve::LegacyPluginHelpers,
776 WhereToResolve::LegacyPluginHelpers => break, // nowhere else to search
777 WhereToResolve::ExternPrelude => WhereToResolve::ToolPrelude,
778 WhereToResolve::ToolPrelude => WhereToResolve::StdLibPrelude,
779 WhereToResolve::StdLibPrelude => match ns {
780 TypeNS => WhereToResolve::BuiltinTypes,
781 ValueNS => break, // nowhere else to search
782 MacroNS => unreachable!(),
784 WhereToResolve::BuiltinTypes => break, // nowhere else to search
791 Ok((binding, flags, ambig_flags)) => {
792 if sub_namespace_mismatch(kind, binding.macro_kind()) {
800 if let Some((innermost_binding, innermost_flags, innermost_ambig_flags))
802 // Found another solution, if the first one was "weak", report an error.
803 if binding.def() != innermost_binding.def() &&
804 (innermost_binding.is_glob_import() ||
805 innermost_binding.may_appear_after(parent_scope.expansion, binding) ||
806 innermost_flags.intersects(ambig_flags) ||
807 flags.intersects(innermost_ambig_flags) ||
808 (innermost_flags.contains(Flags::MACRO_RULES) &&
809 flags.contains(Flags::MODULE) &&
810 !self.disambiguate_legacy_vs_modern(innermost_binding, binding))) {
811 self.ambiguity_errors.push(AmbiguityError {
813 b1: innermost_binding,
816 return Ok(innermost_binding);
819 // Found the first solution.
820 innermost_result = Some((binding, flags, ambig_flags));
825 Err(Determinacy::Determined) => {
828 Err(Determinacy::Undetermined) => return Err(Determinacy::determined(force)),
832 // The first found solution was the only one, return it.
833 if let Some((binding, ..)) = innermost_result {
837 let determinacy = Determinacy::determined(force);
838 if determinacy == Determinacy::Determined && kind == Some(MacroKind::Attr) {
839 // For single-segment attributes interpret determinate "no resolution" as a custom
840 // attribute. (Lexical resolution implies the first segment and attr kind should imply
841 // the last segment, so we are certainly working with a single-segment attribute here.)
842 assert!(ns == MacroNS);
843 let binding = (Def::NonMacroAttr(NonMacroAttrKind::Custom),
844 ty::Visibility::Public, ident.span, Mark::root())
845 .to_name_binding(self.arenas);
852 pub fn finalize_current_module_macro_resolutions(&mut self) {
853 let module = self.current_module;
854 for &(ref path, span) in module.macro_resolutions.borrow().iter() {
855 match self.resolve_path(None, &path, Some(MacroNS), true, span, CrateLint::No) {
856 PathResult::NonModule(_) => {},
857 PathResult::Failed(span, msg, _) => {
858 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
864 let legacy_macro_resolutions =
865 mem::replace(&mut *module.legacy_macro_resolutions.borrow_mut(), Vec::new());
866 for (ident, kind, parent_scope, initial_binding) in legacy_macro_resolutions {
867 let binding = self.early_resolve_ident_in_lexical_scope(
868 ident, MacroNS, Some(kind), &parent_scope, true, true, ident.span
872 let def = binding.def_ignoring_ambiguity();
873 if let Some(initial_binding) = initial_binding {
874 self.record_use(ident, MacroNS, initial_binding);
875 let initial_def = initial_binding.def_ignoring_ambiguity();
876 if self.ambiguity_errors.is_empty() &&
877 def != initial_def && def != Def::Err {
878 // Make sure compilation does not succeed if preferred macro resolution
879 // has changed after the macro had been expanded. In theory all such
880 // situations should be reported as ambiguity errors, so this is a bug.
881 span_bug!(ident.span, "inconsistent resolution for a macro");
884 // It's possible that the macro was unresolved (indeterminate) and silently
885 // expanded into a dummy fragment for recovery during expansion.
886 // Now, post-expansion, the resolution may succeed, but we can't change the
887 // past and need to report an error.
888 let msg = format!("cannot determine resolution for the {} `{}`",
889 kind.descr(), ident);
890 let msg_note = "import resolution is stuck, try simplifying macro imports";
891 self.session.struct_span_err(ident.span, &msg).note(msg_note).emit();
895 assert!(initial_binding.is_none());
896 let bang = if kind == MacroKind::Bang { "!" } else { "" };
898 format!("cannot find {} `{}{}` in this scope", kind.descr(), ident, bang);
899 let mut err = self.session.struct_span_err(ident.span, &msg);
900 self.suggest_macro_name(&ident.as_str(), kind, &mut err, ident.span);
906 let builtin_attrs = mem::replace(&mut *module.builtin_attrs.borrow_mut(), Vec::new());
907 for (ident, parent_scope) in builtin_attrs {
908 let binding = self.early_resolve_ident_in_lexical_scope(
909 ident, MacroNS, Some(MacroKind::Attr), &parent_scope, true, true, ident.span
911 if let Ok(binding) = binding {
912 if binding.def_ignoring_ambiguity() !=
913 Def::NonMacroAttr(NonMacroAttrKind::Builtin) {
914 let builtin_binding = (Def::NonMacroAttr(NonMacroAttrKind::Builtin),
915 ty::Visibility::Public, ident.span, Mark::root())
916 .to_name_binding(self.arenas);
917 self.report_ambiguity_error(ident, binding, builtin_binding);
923 fn suggest_macro_name(&mut self, name: &str, kind: MacroKind,
924 err: &mut DiagnosticBuilder<'a>, span: Span) {
925 // First check if this is a locally-defined bang macro.
926 let suggestion = if let MacroKind::Bang = kind {
927 find_best_match_for_name(self.macro_names.iter().map(|ident| &ident.name), name, None)
930 // Then check global macros.
932 let names = self.builtin_macros.iter().chain(self.macro_use_prelude.iter())
933 .filter_map(|(name, binding)| {
934 if binding.macro_kind() == Some(kind) { Some(name) } else { None }
936 find_best_match_for_name(names, name, None)
937 // Then check modules.
939 let is_macro = |def| {
940 if let Def::Macro(_, def_kind) = def {
946 let ident = Ident::new(Symbol::intern(name), span);
947 self.lookup_typo_candidate(&[ident], MacroNS, is_macro, span)
950 if let Some(suggestion) = suggestion {
951 if suggestion != name {
952 if let MacroKind::Bang = kind {
953 err.span_suggestion_with_applicability(
955 "you could try the macro",
956 suggestion.to_string(),
957 Applicability::MaybeIncorrect
960 err.span_suggestion_with_applicability(
963 suggestion.to_string(),
964 Applicability::MaybeIncorrect
968 err.help("have you added the `#[macro_use]` on the module/import?");
973 fn collect_def_ids(&mut self,
975 invocation: &'a InvocationData<'a>,
976 fragment: &AstFragment) {
977 let Resolver { ref mut invocations, arenas, graph_root, .. } = *self;
978 let InvocationData { def_index, .. } = *invocation;
980 let visit_macro_invoc = &mut |invoc: map::MacroInvocationData| {
981 invocations.entry(invoc.mark).or_insert_with(|| {
982 arenas.alloc_invocation_data(InvocationData {
983 def_index: invoc.def_index,
984 module: Cell::new(graph_root),
985 parent_legacy_scope: Cell::new(LegacyScope::Uninitialized),
986 output_legacy_scope: Cell::new(LegacyScope::Uninitialized),
991 let mut def_collector = DefCollector::new(&mut self.definitions, mark);
992 def_collector.visit_macro_invoc = Some(visit_macro_invoc);
993 def_collector.with_parent(def_index, |def_collector| {
994 fragment.visit_with(def_collector)
998 pub fn define_macro(&mut self,
1001 current_legacy_scope: &mut LegacyScope<'a>) {
1002 self.local_macro_def_scopes.insert(item.id, self.current_module);
1003 let ident = item.ident;
1004 if ident.name == "macro_rules" {
1005 self.session.span_err(item.span, "user-defined macros may not be named `macro_rules`");
1008 let def_id = self.definitions.local_def_id(item.id);
1009 let ext = Lrc::new(macro_rules::compile(&self.session.parse_sess,
1010 &self.session.features_untracked(),
1011 item, hygiene::default_edition()));
1012 self.macro_map.insert(def_id, ext);
1014 let def = match item.node { ast::ItemKind::MacroDef(ref def) => def, _ => unreachable!() };
1016 let ident = ident.modern();
1017 self.macro_names.insert(ident);
1018 let def = Def::Macro(def_id, MacroKind::Bang);
1019 let vis = ty::Visibility::Invisible; // Doesn't matter for legacy bindings
1020 let binding = (def, vis, item.span, expansion).to_name_binding(self.arenas);
1021 self.set_binding_parent_module(binding, self.current_module);
1022 let legacy_binding = self.arenas.alloc_legacy_binding(LegacyBinding {
1023 parent_legacy_scope: *current_legacy_scope, binding, ident
1025 *current_legacy_scope = LegacyScope::Binding(legacy_binding);
1026 self.all_macros.insert(ident.name, def);
1027 if attr::contains_name(&item.attrs, "macro_export") {
1028 let module = self.graph_root;
1029 let vis = ty::Visibility::Public;
1030 self.define(module, ident, MacroNS,
1031 (def, vis, item.span, expansion, IsMacroExport));
1033 if !attr::contains_name(&item.attrs, "rustc_doc_only_macro") {
1034 self.check_reserved_macro_name(ident, MacroNS);
1036 self.unused_macros.insert(def_id);
1039 let module = self.current_module;
1040 let def = Def::Macro(def_id, MacroKind::Bang);
1041 let vis = self.resolve_visibility(&item.vis);
1042 if vis != ty::Visibility::Public {
1043 self.unused_macros.insert(def_id);
1045 self.define(module, ident, MacroNS, (def, vis, item.span, expansion));
1049 fn gate_legacy_custom_derive(&mut self, name: Symbol, span: Span) {
1050 if !self.session.features_untracked().custom_derive {
1051 let sess = &self.session.parse_sess;
1052 let explain = feature_gate::EXPLAIN_CUSTOM_DERIVE;
1053 emit_feature_err(sess, "custom_derive", span, GateIssue::Language, explain);
1054 } else if !self.is_whitelisted_legacy_custom_derive(name) {
1055 self.session.span_warn(span, feature_gate::EXPLAIN_DEPR_CUSTOM_DERIVE);