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, TypeNS, MacroNS};
15 use build_reduced_graph::{BuildReducedGraphVisitor, IsMacroExport};
16 use resolve_imports::ImportResolver;
17 use rustc::hir::def_id::{DefId, BUILTIN_MACROS_CRATE, CRATE_DEF_INDEX, DefIndex,
18 DefIndexAddressSpace};
19 use rustc::hir::def::{Def, NonMacroAttrKind};
20 use rustc::hir::map::{self, DefCollector};
21 use rustc::{ty, lint};
22 use rustc::middle::cstore::CrateStore;
23 use syntax::ast::{self, Name, Ident};
25 use syntax::errors::DiagnosticBuilder;
26 use syntax::ext::base::{self, Determinacy, MultiModifier, MultiDecorator};
27 use syntax::ext::base::{MacroKind, SyntaxExtension, Resolver as SyntaxResolver};
28 use syntax::ext::expand::{AstFragment, Invocation, InvocationKind};
29 use syntax::ext::hygiene::{self, Mark};
30 use syntax::ext::tt::macro_rules;
31 use syntax::feature_gate::{self, feature_err, emit_feature_err, is_builtin_attr_name, GateIssue};
32 use syntax::feature_gate::EXPLAIN_DERIVE_UNDERSCORE;
33 use syntax::fold::{self, Folder};
34 use syntax::parse::parser::PathStyle;
35 use syntax::parse::token::{self, Token};
37 use syntax::symbol::{Symbol, keywords};
38 use syntax::tokenstream::{TokenStream, TokenTree, Delimited, DelimSpan};
39 use syntax::util::lev_distance::find_best_match_for_name;
40 use syntax_pos::{Span, DUMMY_SP};
41 use errors::Applicability;
45 use rustc_data_structures::sync::Lrc;
46 use rustc_data_structures::small_vec::ExpectOne;
48 #[derive(Clone, Copy)]
49 crate struct FromPrelude(bool);
52 pub struct InvocationData<'a> {
54 /// Module in which the macro was invoked.
55 crate module: Cell<Module<'a>>,
56 /// Legacy scope in which the macro was invoked.
57 /// The invocation path is resolved in this scope.
58 crate parent_legacy_scope: Cell<LegacyScope<'a>>,
59 /// Legacy scope *produced* by expanding this macro invocation,
60 /// includes all the macro_rules items, other invocations, etc generated by it.
61 /// Set to the parent scope if the macro is not expanded yet (as if the macro produced nothing).
62 crate output_legacy_scope: Cell<LegacyScope<'a>>,
65 impl<'a> InvocationData<'a> {
66 pub fn root(graph_root: Module<'a>) -> Self {
68 module: Cell::new(graph_root),
69 def_index: CRATE_DEF_INDEX,
70 parent_legacy_scope: Cell::new(LegacyScope::Empty),
71 output_legacy_scope: Cell::new(LegacyScope::Empty),
76 /// Binding produced by a `macro_rules` item.
77 /// Not modularized, can shadow previous legacy bindings, etc.
78 pub struct LegacyBinding<'a> {
79 binding: &'a NameBinding<'a>,
80 /// Legacy scope into which the `macro_rules` item was planted.
81 parent_legacy_scope: LegacyScope<'a>,
85 /// Scope introduced by a `macro_rules!` macro.
86 /// Starts at the macro's definition and ends at the end of the macro's parent module
87 /// (named or unnamed), or even further if it escapes with `#[macro_use]`.
88 /// Some macro invocations need to introduce legacy scopes too because they
89 /// potentially can expand into macro definitions.
90 #[derive(Copy, Clone)]
91 pub enum LegacyScope<'a> {
92 /// Created when invocation data is allocated in the arena,
93 /// must be replaced with a proper scope later.
95 /// Empty "root" scope at the crate start containing no names.
97 /// Scope introduced by a `macro_rules!` macro definition.
98 Binding(&'a LegacyBinding<'a>),
99 /// Scope introduced by a macro invocation that can potentially
100 /// create a `macro_rules!` macro definition.
101 Invocation(&'a InvocationData<'a>),
104 /// Everything you need to resolve a macro path.
106 pub struct ParentScope<'a> {
107 crate module: Module<'a>,
108 crate expansion: Mark,
109 crate legacy: LegacyScope<'a>,
110 crate derives: Vec<ast::Path>,
113 pub struct ProcMacError {
118 warn_msg: &'static str,
121 // For compatibility bang macros are skipped when resolving potentially built-in attributes.
122 fn macro_kind_mismatch(name: Name, requirement: Option<MacroKind>, candidate: Option<MacroKind>)
124 requirement == Some(MacroKind::Attr) && candidate == Some(MacroKind::Bang) &&
125 (name == "test" || name == "bench" || is_builtin_attr_name(name))
128 impl<'a, 'crateloader: 'a> base::Resolver for Resolver<'a, 'crateloader> {
129 fn next_node_id(&mut self) -> ast::NodeId {
130 self.session.next_node_id()
133 fn get_module_scope(&mut self, id: ast::NodeId) -> Mark {
134 let mark = Mark::fresh(Mark::root());
135 let module = self.module_map[&self.definitions.local_def_id(id)];
136 self.invocations.insert(mark, self.arenas.alloc_invocation_data(InvocationData {
137 module: Cell::new(module),
138 def_index: module.def_id().unwrap().index,
139 parent_legacy_scope: Cell::new(LegacyScope::Empty),
140 output_legacy_scope: Cell::new(LegacyScope::Empty),
145 fn eliminate_crate_var(&mut self, item: P<ast::Item>) -> P<ast::Item> {
146 struct EliminateCrateVar<'b, 'a: 'b, 'crateloader: 'a>(
147 &'b mut Resolver<'a, 'crateloader>, Span
150 impl<'a, 'b, 'crateloader> Folder for EliminateCrateVar<'a, 'b, 'crateloader> {
151 fn fold_path(&mut self, path: ast::Path) -> ast::Path {
152 match self.fold_qpath(None, path) {
153 (None, path) => path,
158 fn fold_qpath(&mut self, mut qself: Option<ast::QSelf>, mut path: ast::Path)
159 -> (Option<ast::QSelf>, ast::Path) {
160 qself = qself.map(|ast::QSelf { ty, path_span, position }| {
162 ty: self.fold_ty(ty),
163 path_span: self.new_span(path_span),
168 if path.segments[0].ident.name == keywords::DollarCrate.name() {
169 let module = self.0.resolve_crate_root(path.segments[0].ident);
170 path.segments[0].ident.name = keywords::CrateRoot.name();
171 if !module.is_local() {
172 let span = path.segments[0].ident.span;
173 path.segments.insert(1, match module.kind {
174 ModuleKind::Def(_, name) => ast::PathSegment::from_ident(
175 ast::Ident::with_empty_ctxt(name).with_span_pos(span)
179 if let Some(qself) = &mut qself {
187 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
188 fold::noop_fold_mac(mac, self)
192 EliminateCrateVar(self, item.span).fold_item(item).expect_one("")
195 fn is_whitelisted_legacy_custom_derive(&self, name: Name) -> bool {
196 self.whitelisted_legacy_custom_derives.contains(&name)
199 fn visit_ast_fragment_with_placeholders(&mut self, mark: Mark, fragment: &AstFragment,
201 let invocation = self.invocations[&mark];
202 self.collect_def_ids(mark, invocation, fragment);
204 self.current_module = invocation.module.get();
205 self.current_module.unresolved_invocations.borrow_mut().remove(&mark);
206 self.current_module.unresolved_invocations.borrow_mut().extend(derives);
207 for &derive in derives {
208 self.invocations.insert(derive, invocation);
210 let mut visitor = BuildReducedGraphVisitor {
212 current_legacy_scope: invocation.parent_legacy_scope.get(),
215 fragment.visit_with(&mut visitor);
216 invocation.output_legacy_scope.set(visitor.current_legacy_scope);
219 fn add_builtin(&mut self, ident: ast::Ident, ext: Lrc<SyntaxExtension>) {
221 krate: BUILTIN_MACROS_CRATE,
222 index: DefIndex::from_array_index(self.macro_map.len(),
223 DefIndexAddressSpace::Low),
225 let kind = ext.kind();
226 self.macro_map.insert(def_id, ext);
227 let binding = self.arenas.alloc_name_binding(NameBinding {
228 kind: NameBindingKind::Def(Def::Macro(def_id, kind), false),
230 vis: ty::Visibility::Invisible,
231 expansion: Mark::root(),
233 if self.builtin_macros.insert(ident.name, binding).is_some() {
234 self.session.span_err(ident.span,
235 &format!("built-in macro `{}` was already defined", ident));
239 fn resolve_imports(&mut self) {
240 ImportResolver { resolver: self }.resolve_imports()
243 // Resolves attribute and derive legacy macros from `#![plugin(..)]`.
244 fn find_legacy_attr_invoc(&mut self, attrs: &mut Vec<ast::Attribute>, allow_derive: bool)
245 -> Option<ast::Attribute> {
246 for i in 0..attrs.len() {
247 let name = attrs[i].name();
249 if self.session.plugin_attributes.borrow().iter()
250 .any(|&(ref attr_nm, _)| name == &**attr_nm) {
251 attr::mark_known(&attrs[i]);
254 match self.builtin_macros.get(&name).cloned() {
255 Some(binding) => match *binding.get_macro(self) {
256 MultiModifier(..) | MultiDecorator(..) | SyntaxExtension::AttrProcMacro(..) => {
257 return Some(attrs.remove(i))
265 if !allow_derive { return None }
267 // Check for legacy derives
268 for i in 0..attrs.len() {
269 let name = attrs[i].name();
271 if name == "derive" {
272 let result = attrs[i].parse_list(&self.session.parse_sess, |parser| {
273 parser.parse_path_allowing_meta(PathStyle::Mod)
276 let mut traits = match result {
277 Ok(traits) => traits,
284 for j in 0..traits.len() {
285 if traits[j].segments.len() > 1 {
288 let trait_name = traits[j].segments[0].ident.name;
289 let legacy_name = Symbol::intern(&format!("derive_{}", trait_name));
290 if !self.builtin_macros.contains_key(&legacy_name) {
293 let span = traits.remove(j).span;
294 self.gate_legacy_custom_derive(legacy_name, span);
295 if traits.is_empty() {
298 let mut tokens = Vec::new();
299 for (j, path) in traits.iter().enumerate() {
301 tokens.push(TokenTree::Token(attrs[i].span, Token::Comma).into());
303 for (k, segment) in path.segments.iter().enumerate() {
305 tokens.push(TokenTree::Token(path.span, Token::ModSep).into());
307 let tok = Token::from_ast_ident(segment.ident);
308 tokens.push(TokenTree::Token(path.span, tok).into());
311 let delim_span = DelimSpan::from_single(attrs[i].span);
312 attrs[i].tokens = TokenTree::Delimited(delim_span, Delimited {
314 tts: TokenStream::concat(tokens).into(),
317 return Some(ast::Attribute {
318 path: ast::Path::from_ident(Ident::new(legacy_name, span)),
319 tokens: TokenStream::empty(),
320 id: attr::mk_attr_id(),
321 style: ast::AttrStyle::Outer,
322 is_sugared_doc: false,
332 fn resolve_macro_invocation(&mut self, invoc: &Invocation, invoc_id: Mark, force: bool)
333 -> Result<Option<Lrc<SyntaxExtension>>, Determinacy> {
334 let (path, kind, derives_in_scope) = match invoc.kind {
335 InvocationKind::Attr { attr: None, .. } =>
337 InvocationKind::Attr { attr: Some(ref attr), ref traits, .. } =>
338 (&attr.path, MacroKind::Attr, traits.clone()),
339 InvocationKind::Bang { ref mac, .. } =>
340 (&mac.node.path, MacroKind::Bang, Vec::new()),
341 InvocationKind::Derive { ref path, .. } =>
342 (path, MacroKind::Derive, Vec::new()),
345 let parent_scope = self.invoc_parent_scope(invoc_id, derives_in_scope);
346 let (def, ext) = self.resolve_macro_to_def(path, kind, &parent_scope, force)?;
348 if let Def::Macro(def_id, _) = def {
349 self.macro_defs.insert(invoc.expansion_data.mark, def_id);
350 let normal_module_def_id =
351 self.macro_def_scope(invoc.expansion_data.mark).normal_ancestor_id;
352 self.definitions.add_parent_module_of_macro_def(invoc.expansion_data.mark,
353 normal_module_def_id);
354 invoc.expansion_data.mark.set_default_transparency(ext.default_transparency());
355 invoc.expansion_data.mark.set_is_builtin(def_id.krate == BUILTIN_MACROS_CRATE);
361 fn resolve_macro_path(&mut self, path: &ast::Path, kind: MacroKind, invoc_id: Mark,
362 derives_in_scope: Vec<ast::Path>, force: bool)
363 -> Result<Lrc<SyntaxExtension>, Determinacy> {
364 let parent_scope = self.invoc_parent_scope(invoc_id, derives_in_scope);
365 Ok(self.resolve_macro_to_def(path, kind, &parent_scope, force)?.1)
368 fn check_unused_macros(&self) {
369 for did in self.unused_macros.iter() {
370 let id_span = match *self.macro_map[did] {
371 SyntaxExtension::NormalTT { def_info, .. } |
372 SyntaxExtension::DeclMacro { def_info, .. } => def_info,
375 if let Some((id, span)) = id_span {
376 let lint = lint::builtin::UNUSED_MACROS;
377 let msg = "unused macro definition";
378 self.session.buffer_lint(lint, id, span, msg);
380 bug!("attempted to create unused macro error, but span not available");
386 impl<'a, 'cl> Resolver<'a, 'cl> {
387 pub fn dummy_parent_scope(&mut self) -> ParentScope<'a> {
388 self.invoc_parent_scope(Mark::root(), Vec::new())
391 fn invoc_parent_scope(&mut self, invoc_id: Mark, derives: Vec<ast::Path>) -> ParentScope<'a> {
392 let invoc = self.invocations[&invoc_id];
394 module: invoc.module.get().nearest_item_scope(),
395 expansion: invoc_id.parent(),
396 legacy: invoc.parent_legacy_scope.get(),
401 fn resolve_macro_to_def(
405 parent_scope: &ParentScope<'a>,
407 ) -> Result<(Def, Lrc<SyntaxExtension>), Determinacy> {
408 let def = self.resolve_macro_to_def_inner(path, kind, parent_scope, force);
410 // Report errors and enforce feature gates for the resolved macro.
411 if def != Err(Determinacy::Undetermined) {
412 // Do not report duplicated errors on every undetermined resolution.
413 for segment in &path.segments {
414 if let Some(args) = &segment.args {
415 self.session.span_err(args.span(), "generic arguments in macro path");
423 Def::Macro(def_id, macro_kind) => {
424 self.unused_macros.remove(&def_id);
425 if macro_kind == MacroKind::ProcMacroStub {
426 let msg = "can't use a procedural macro from the same crate that defines it";
427 self.session.span_err(path.span, msg);
428 return Err(Determinacy::Determined);
431 Def::NonMacroAttr(attr_kind) => {
432 if kind == MacroKind::Attr {
433 let features = self.session.features_untracked();
434 if attr_kind == NonMacroAttrKind::Custom {
435 assert!(path.segments.len() == 1);
436 let name = path.segments[0].ident.name.as_str();
437 if name.starts_with("rustc_") {
438 if !features.rustc_attrs {
439 let msg = "unless otherwise specified, attributes with the prefix \
440 `rustc_` are reserved for internal compiler diagnostics";
441 feature_err(&self.session.parse_sess, "rustc_attrs", path.span,
442 GateIssue::Language, &msg).emit();
444 } else if name.starts_with("derive_") {
445 if !features.custom_derive {
446 feature_err(&self.session.parse_sess, "custom_derive", path.span,
447 GateIssue::Language, EXPLAIN_DERIVE_UNDERSCORE).emit();
449 } else if !features.custom_attribute {
450 let msg = format!("The attribute `{}` is currently unknown to the \
451 compiler and may have meaning added to it in the \
453 feature_err(&self.session.parse_sess, "custom_attribute", path.span,
454 GateIssue::Language, &msg).emit();
458 // Not only attributes, but anything in macro namespace can result in
459 // `Def::NonMacroAttr` definition (e.g. `inline!()`), so we must report
460 // an error for those cases.
461 let msg = format!("expected a macro, found {}", def.kind_name());
462 self.session.span_err(path.span, &msg);
463 return Err(Determinacy::Determined);
466 _ => panic!("expected `Def::Macro` or `Def::NonMacroAttr`"),
469 Ok((def, self.get_macro(def)))
472 pub fn resolve_macro_to_def_inner(
476 parent_scope: &ParentScope<'a>,
478 ) -> Result<Def, Determinacy> {
479 let ast::Path { ref segments, span } = *path;
480 let mut path: Vec<_> = segments.iter().map(|seg| seg.ident).collect();
482 // Possibly apply the macro helper hack
483 if kind == MacroKind::Bang && path.len() == 1 &&
484 path[0].span.ctxt().outer().expn_info().map_or(false, |info| info.local_inner_macros) {
485 let root = Ident::new(keywords::DollarCrate.name(), path[0].span);
486 path.insert(0, root);
490 let def = match self.resolve_path_with_parent_scope(None, &path, Some(MacroNS),
491 parent_scope, false, span,
493 PathResult::NonModule(path_res) => match path_res.base_def() {
494 Def::Err => Err(Determinacy::Determined),
496 if path_res.unresolved_segments() > 0 {
497 self.found_unresolved_macro = true;
498 self.session.span_err(span, "fail to resolve non-ident macro path");
499 Err(Determinacy::Determined)
505 PathResult::Module(..) => unreachable!(),
506 PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
508 self.found_unresolved_macro = true;
509 Err(Determinacy::Determined)
512 parent_scope.module.macro_resolutions.borrow_mut()
513 .push((path.into_boxed_slice(), span));
517 let result = if let Some(legacy_binding) = self.resolve_legacy_scope(path[0], Some(kind),
518 parent_scope, false) {
519 Ok(legacy_binding.def())
521 match self.resolve_lexical_macro_path_segment(path[0], MacroNS, Some(kind),
522 parent_scope, false, force, span) {
523 Ok((binding, _)) => Ok(binding.def_ignoring_ambiguity()),
524 Err(Determinacy::Undetermined) => return Err(Determinacy::Undetermined),
525 Err(Determinacy::Determined) => {
526 self.found_unresolved_macro = true;
527 Err(Determinacy::Determined)
532 parent_scope.module.legacy_macro_resolutions.borrow_mut()
533 .push((path[0], kind, parent_scope.clone(), result.ok()));
538 // Resolve the initial segment of a non-global macro path
539 // (e.g. `foo` in `foo::bar!(); or `foo!();`).
540 // This is a variation of `fn resolve_ident_in_lexical_scope` that can be run during
541 // expansion and import resolution (perhaps they can be merged in the future).
542 crate fn resolve_lexical_macro_path_segment(
546 kind: Option<MacroKind>,
547 parent_scope: &ParentScope<'a>,
551 ) -> Result<(&'a NameBinding<'a>, FromPrelude), Determinacy> {
552 // General principles:
553 // 1. Not controlled (user-defined) names should have higher priority than controlled names
554 // built into the language or standard library. This way we can add new names into the
555 // language or standard library without breaking user code.
556 // 2. "Closed set" below means new names can appear after the current resolution attempt.
557 // Places to search (in order of decreasing priority):
559 // 1. FIXME: Ribs (type parameters), there's no necessary infrastructure yet
560 // (open set, not controlled).
561 // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
562 // (open, not controlled).
563 // 3. Extern prelude (closed, not controlled).
564 // 4. Tool modules (closed, controlled right now, but not in the future).
565 // 5. Standard library prelude (de-facto closed, controlled).
566 // 6. Language prelude (closed, controlled).
568 // 1. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
569 // (open, not controlled).
570 // 2. `macro_use` prelude (open, the open part is from macro expansions, not controlled).
571 // 2a. User-defined prelude from macro-use
572 // (open, the open part is from macro expansions, not controlled).
573 // 2b. Standard library prelude is currently implemented as `macro-use` (closed, controlled)
574 // 3. Language prelude: builtin macros (closed, controlled, except for legacy plugins).
575 // 4. Language prelude: builtin attributes (closed, controlled).
576 // N (unordered). Derive helpers (open, not controlled). All ambiguities with other names
577 // are currently reported as errors. They should be higher in priority than preludes
578 // and maybe even names in modules according to the "general principles" above. They
579 // also should be subject to restricted shadowing because are effectively produced by
580 // derives (you need to resolve the derive first to add helpers into scope), but they
581 // should be available before the derive is expanded for compatibility.
582 // It's mess in general, so we are being conservative for now.
584 assert!(ns == TypeNS || ns == MacroNS);
585 assert!(force || !record_used); // `record_used` implies `force`
586 ident = ident.modern();
588 // This is *the* result, resolution from the scope closest to the resolved identifier.
589 // However, sometimes this result is "weak" because it comes from a glob import or
590 // a macro expansion, and in this case it cannot shadow names from outer scopes, e.g.
591 // mod m { ... } // solution in outer scope
593 // use prefix::*; // imports another `m` - innermost solution
594 // // weak, cannot shadow the outer `m`, need to report ambiguity error
597 // So we have to save the innermost solution and continue searching in outer scopes
598 // to detect potential ambiguities.
599 let mut innermost_result: Option<(&NameBinding, FromPrelude)> = None;
601 enum WhereToResolve<'a> {
613 // Go through all the scopes and try to resolve the name.
614 let mut where_to_resolve = WhereToResolve::Module(parent_scope.module);
615 let mut use_prelude = !parent_scope.module.no_implicit_prelude;
617 let result = match where_to_resolve {
618 WhereToResolve::Module(module) => {
619 let orig_current_module = mem::replace(&mut self.current_module, module);
620 let binding = self.resolve_ident_in_module_unadjusted(
621 ModuleOrUniformRoot::Module(module),
628 self.current_module = orig_current_module;
629 binding.map(|binding| (binding, FromPrelude(false)))
631 WhereToResolve::MacroUsePrelude => {
632 match self.macro_use_prelude.get(&ident.name).cloned() {
633 Some(binding) => Ok((binding, FromPrelude(true))),
634 None => Err(Determinacy::Determined),
637 WhereToResolve::BuiltinMacros => {
638 match self.builtin_macros.get(&ident.name).cloned() {
639 Some(binding) => Ok((binding, FromPrelude(true))),
640 None => Err(Determinacy::Determined),
643 WhereToResolve::BuiltinAttrs => {
644 // FIXME: Only built-in attributes are not considered as candidates for
645 // non-attributes to fight off regressions on stable channel (#53205).
646 // We need to come up with some more principled approach instead.
647 if kind == Some(MacroKind::Attr) && is_builtin_attr_name(ident.name) {
648 let binding = (Def::NonMacroAttr(NonMacroAttrKind::Builtin),
649 ty::Visibility::Public, ident.span, Mark::root())
650 .to_name_binding(self.arenas);
651 Ok((binding, FromPrelude(true)))
653 Err(Determinacy::Determined)
656 WhereToResolve::DeriveHelpers => {
657 let mut result = Err(Determinacy::Determined);
658 for derive in &parent_scope.derives {
659 let parent_scope = ParentScope { derives: Vec::new(), ..*parent_scope };
660 if let Ok((_, ext)) = self.resolve_macro_to_def(derive, MacroKind::Derive,
661 &parent_scope, force) {
662 if let SyntaxExtension::ProcMacroDerive(_, helper_attrs, _) = &*ext {
663 if helper_attrs.contains(&ident.name) {
665 (Def::NonMacroAttr(NonMacroAttrKind::DeriveHelper),
666 ty::Visibility::Public, derive.span, Mark::root())
667 .to_name_binding(self.arenas);
668 result = Ok((binding, FromPrelude(false)));
676 WhereToResolve::ExternPrelude => {
677 if use_prelude && self.extern_prelude.contains(&ident.name) {
678 if !self.session.features_untracked().extern_prelude &&
679 !self.ignore_extern_prelude_feature {
680 feature_err(&self.session.parse_sess, "extern_prelude",
681 ident.span, GateIssue::Language,
682 "access to extern crates through prelude is experimental")
687 self.crate_loader.process_path_extern(ident.name, ident.span);
689 self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
690 self.populate_module_if_necessary(crate_root);
692 let binding = (crate_root, ty::Visibility::Public,
693 ident.span, Mark::root()).to_name_binding(self.arenas);
694 Ok((binding, FromPrelude(true)))
696 Err(Determinacy::Determined)
699 WhereToResolve::ToolPrelude => {
700 if use_prelude && is_known_tool(ident.name) {
701 let binding = (Def::ToolMod, ty::Visibility::Public,
702 ident.span, Mark::root()).to_name_binding(self.arenas);
703 Ok((binding, FromPrelude(true)))
705 Err(Determinacy::Determined)
708 WhereToResolve::StdLibPrelude => {
709 let mut result = Err(Determinacy::Determined);
711 if let Some(prelude) = self.prelude {
712 if let Ok(binding) = self.resolve_ident_in_module_unadjusted(
713 ModuleOrUniformRoot::Module(prelude),
720 result = Ok((binding, FromPrelude(true)));
726 WhereToResolve::BuiltinTypes => {
727 if let Some(prim_ty) =
728 self.primitive_type_table.primitive_types.get(&ident.name).cloned() {
729 let binding = (Def::PrimTy(prim_ty), ty::Visibility::Public,
730 ident.span, Mark::root()).to_name_binding(self.arenas);
731 Ok((binding, FromPrelude(true)))
733 Err(Determinacy::Determined)
738 macro_rules! continue_search { () => {
739 where_to_resolve = match where_to_resolve {
740 WhereToResolve::Module(module) => {
741 match self.hygienic_lexical_parent(module, &mut ident.span) {
742 Some(parent_module) => WhereToResolve::Module(parent_module),
744 use_prelude = !module.no_implicit_prelude;
746 WhereToResolve::MacroUsePrelude
748 WhereToResolve::ExternPrelude
753 WhereToResolve::MacroUsePrelude => WhereToResolve::BuiltinMacros,
754 WhereToResolve::BuiltinMacros => WhereToResolve::BuiltinAttrs,
755 WhereToResolve::BuiltinAttrs => WhereToResolve::DeriveHelpers,
756 WhereToResolve::DeriveHelpers => break, // nowhere else to search
757 WhereToResolve::ExternPrelude => WhereToResolve::ToolPrelude,
758 WhereToResolve::ToolPrelude => WhereToResolve::StdLibPrelude,
759 WhereToResolve::StdLibPrelude => WhereToResolve::BuiltinTypes,
760 WhereToResolve::BuiltinTypes => break, // nowhere else to search
768 if macro_kind_mismatch(ident.name, kind, result.0.macro_kind()) {
776 if let Some(innermost_result) = innermost_result {
777 // Found another solution, if the first one was "weak", report an error.
778 let (def, innermost_def) = (result.0.def(), innermost_result.0.def());
779 if def != innermost_def &&
780 (innermost_result.0.is_glob_import() ||
781 innermost_result.0.may_appear_after(parent_scope.expansion, result.0) ||
782 innermost_def == Def::NonMacroAttr(NonMacroAttrKind::DeriveHelper) ||
783 def == Def::NonMacroAttr(NonMacroAttrKind::DeriveHelper)) {
784 self.ambiguity_errors.push(AmbiguityError {
786 b1: innermost_result.0,
789 return Ok(innermost_result);
792 // Found the first solution.
793 innermost_result = Some(result);
798 Err(Determinacy::Determined) => {
801 Err(Determinacy::Undetermined) => return Err(Determinacy::determined(force)),
805 // The first found solution was the only one, return it.
806 if let Some(innermost_result) = innermost_result {
807 return Ok(innermost_result);
810 let determinacy = Determinacy::determined(force);
811 if determinacy == Determinacy::Determined && kind == Some(MacroKind::Attr) {
812 // For single-segment attributes interpret determinate "no resolution" as a custom
813 // attribute. (Lexical resolution implies the first segment and attr kind should imply
814 // the last segment, so we are certainly working with a single-segment attribute here.)
815 assert!(ns == MacroNS);
816 let binding = (Def::NonMacroAttr(NonMacroAttrKind::Custom),
817 ty::Visibility::Public, ident.span, Mark::root())
818 .to_name_binding(self.arenas);
819 Ok((binding, FromPrelude(true)))
825 fn resolve_legacy_scope(
828 kind: Option<MacroKind>,
829 parent_scope: &ParentScope<'a>,
831 ) -> Option<&'a NameBinding<'a>> {
832 if macro_kind_mismatch(ident.name, kind, Some(MacroKind::Bang)) {
836 let ident = ident.modern();
838 // This is *the* result, resolution from the scope closest to the resolved identifier.
839 // However, sometimes this result is "weak" because it comes from a macro expansion,
840 // and in this case it cannot shadow names from outer scopes, e.g.
841 // macro_rules! m { ... } // solution in outer scope
843 // define_m!(); // generates another `macro_rules! m` - innermost solution
844 // // weak, cannot shadow the outer `m`, need to report ambiguity error
847 // So we have to save the innermost solution and continue searching in outer scopes
848 // to detect potential ambiguities.
849 let mut innermost_result: Option<&NameBinding> = None;
851 // Go through all the scopes and try to resolve the name.
852 let mut where_to_resolve = parent_scope.legacy;
854 let result = match where_to_resolve {
855 LegacyScope::Binding(legacy_binding) if ident == legacy_binding.ident =>
856 Some(legacy_binding.binding),
860 macro_rules! continue_search { () => {
861 where_to_resolve = match where_to_resolve {
862 LegacyScope::Empty => break, // nowhere else to search
863 LegacyScope::Binding(binding) => binding.parent_legacy_scope,
864 LegacyScope::Invocation(invocation) => invocation.output_legacy_scope.get(),
865 LegacyScope::Uninitialized => unreachable!(),
877 if let Some(innermost_result) = innermost_result {
878 // Found another solution, if the first one was "weak", report an error.
879 if result.def() != innermost_result.def() &&
880 innermost_result.may_appear_after(parent_scope.expansion, result) {
881 self.ambiguity_errors.push(AmbiguityError {
883 b1: innermost_result,
886 return Some(innermost_result);
889 // Found the first solution.
890 innermost_result = Some(result);
901 // The first found solution was the only one (or there was no solution at all), return it.
905 pub fn finalize_current_module_macro_resolutions(&mut self) {
906 let module = self.current_module;
907 for &(ref path, span) in module.macro_resolutions.borrow().iter() {
908 match self.resolve_path(None, &path, Some(MacroNS), true, span, CrateLint::No) {
909 PathResult::NonModule(_) => {},
910 PathResult::Failed(span, msg, _) => {
911 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
917 let legacy_macro_resolutions =
918 mem::replace(&mut *module.legacy_macro_resolutions.borrow_mut(), Vec::new());
919 for (ident, kind, parent_scope, def) in legacy_macro_resolutions {
920 let span = ident.span;
921 let legacy_resolution = self.resolve_legacy_scope(
922 ident, Some(kind), &parent_scope, true
924 let resolution = self.resolve_lexical_macro_path_segment(
925 ident, MacroNS, Some(kind), &parent_scope, true, true, span
928 let check_consistency = |this: &Self, new_def: Def| {
929 if let Some(def) = def {
930 if this.ambiguity_errors.is_empty() && new_def != def && new_def != Def::Err {
931 // Make sure compilation does not succeed if preferred macro resolution
932 // has changed after the macro had been expanded. In theory all such
933 // situations should be reported as ambiguity errors, so this is span-bug.
934 span_bug!(span, "inconsistent resolution for a macro");
937 // It's possible that the macro was unresolved (indeterminate) and silently
938 // expanded into a dummy fragment for recovery during expansion.
939 // Now, post-expansion, the resolution may succeed, but we can't change the
940 // past and need to report an error.
942 format!("cannot determine resolution for the {} `{}`", kind.descr(), ident);
943 let msg_note = "import resolution is stuck, try simplifying macro imports";
944 this.session.struct_span_err(span, &msg).note(msg_note).emit();
948 match (legacy_resolution, resolution) {
950 assert!(def.is_none());
951 let bang = if kind == MacroKind::Bang { "!" } else { "" };
953 format!("cannot find {} `{}{}` in this scope", kind.descr(), ident, bang);
954 let mut err = self.session.struct_span_err(span, &msg);
955 self.suggest_macro_name(&ident.as_str(), kind, &mut err, span);
958 (Some(legacy_binding), Ok((binding, FromPrelude(from_prelude))))
959 if legacy_binding.def() != binding.def_ignoring_ambiguity() &&
961 legacy_binding.may_appear_after(parent_scope.expansion, binding)) => {
962 self.report_ambiguity_error(ident, legacy_binding, binding);
964 // OK, non-macro-expanded legacy wins over prelude even if defs are different
965 // Also, legacy and modern can co-exist if their defs are same
966 (Some(legacy_binding), Ok(_)) |
967 // OK, unambiguous resolution
968 (Some(legacy_binding), Err(_)) => {
969 check_consistency(self, legacy_binding.def());
971 // OK, unambiguous resolution
972 (None, Ok((binding, FromPrelude(from_prelude)))) => {
973 check_consistency(self, binding.def_ignoring_ambiguity());
975 self.record_use(ident, MacroNS, binding);
976 self.err_if_macro_use_proc_macro(ident.name, span, binding);
982 let builtin_attrs = mem::replace(&mut *module.builtin_attrs.borrow_mut(), Vec::new());
983 for (ident, parent_scope) in builtin_attrs {
984 let resolve_legacy = |this: &mut Self| this.resolve_legacy_scope(
985 ident, Some(MacroKind::Attr), &parent_scope, true
987 let resolve_modern = |this: &mut Self| this.resolve_lexical_macro_path_segment(
988 ident, MacroNS, Some(MacroKind::Attr), &parent_scope, true, true, ident.span
989 ).map(|(binding, _)| binding).ok();
991 if let Some(binding) = resolve_legacy(self).or_else(|| resolve_modern(self)) {
992 if binding.def_ignoring_ambiguity() !=
993 Def::NonMacroAttr(NonMacroAttrKind::Builtin) {
994 let builtin_binding = (Def::NonMacroAttr(NonMacroAttrKind::Builtin),
995 ty::Visibility::Public, ident.span, Mark::root())
996 .to_name_binding(self.arenas);
997 self.report_ambiguity_error(ident, binding, builtin_binding);
1003 fn suggest_macro_name(&mut self, name: &str, kind: MacroKind,
1004 err: &mut DiagnosticBuilder<'a>, span: Span) {
1005 // First check if this is a locally-defined bang macro.
1006 let suggestion = if let MacroKind::Bang = kind {
1007 find_best_match_for_name(self.macro_names.iter().map(|ident| &ident.name), name, None)
1010 // Then check global macros.
1012 let names = self.builtin_macros.iter().chain(self.macro_use_prelude.iter())
1013 .filter_map(|(name, binding)| {
1014 if binding.macro_kind() == Some(kind) { Some(name) } else { None }
1016 find_best_match_for_name(names, name, None)
1017 // Then check modules.
1019 let is_macro = |def| {
1020 if let Def::Macro(_, def_kind) = def {
1026 let ident = Ident::new(Symbol::intern(name), span);
1027 self.lookup_typo_candidate(&[ident], MacroNS, is_macro, span)
1030 if let Some(suggestion) = suggestion {
1031 if suggestion != name {
1032 if let MacroKind::Bang = kind {
1033 err.span_suggestion_with_applicability(
1035 "you could try the macro",
1036 suggestion.to_string(),
1037 Applicability::MaybeIncorrect
1040 err.span_suggestion_with_applicability(
1043 suggestion.to_string(),
1044 Applicability::MaybeIncorrect
1048 err.help("have you added the `#[macro_use]` on the module/import?");
1053 fn collect_def_ids(&mut self,
1055 invocation: &'a InvocationData<'a>,
1056 fragment: &AstFragment) {
1057 let Resolver { ref mut invocations, arenas, graph_root, .. } = *self;
1058 let InvocationData { def_index, .. } = *invocation;
1060 let visit_macro_invoc = &mut |invoc: map::MacroInvocationData| {
1061 invocations.entry(invoc.mark).or_insert_with(|| {
1062 arenas.alloc_invocation_data(InvocationData {
1063 def_index: invoc.def_index,
1064 module: Cell::new(graph_root),
1065 parent_legacy_scope: Cell::new(LegacyScope::Uninitialized),
1066 output_legacy_scope: Cell::new(LegacyScope::Uninitialized),
1071 let mut def_collector = DefCollector::new(&mut self.definitions, mark);
1072 def_collector.visit_macro_invoc = Some(visit_macro_invoc);
1073 def_collector.with_parent(def_index, |def_collector| {
1074 fragment.visit_with(def_collector)
1078 pub fn define_macro(&mut self,
1081 current_legacy_scope: &mut LegacyScope<'a>) {
1082 self.local_macro_def_scopes.insert(item.id, self.current_module);
1083 let ident = item.ident;
1084 if ident.name == "macro_rules" {
1085 self.session.span_err(item.span, "user-defined macros may not be named `macro_rules`");
1088 let def_id = self.definitions.local_def_id(item.id);
1089 let ext = Lrc::new(macro_rules::compile(&self.session.parse_sess,
1090 &self.session.features_untracked(),
1091 item, hygiene::default_edition()));
1092 self.macro_map.insert(def_id, ext);
1094 let def = match item.node { ast::ItemKind::MacroDef(ref def) => def, _ => unreachable!() };
1096 let ident = ident.modern();
1097 self.macro_names.insert(ident);
1098 let def = Def::Macro(def_id, MacroKind::Bang);
1099 let vis = ty::Visibility::Invisible; // Doesn't matter for legacy bindings
1100 let binding = (def, vis, item.span, expansion).to_name_binding(self.arenas);
1101 let legacy_binding = self.arenas.alloc_legacy_binding(LegacyBinding {
1102 parent_legacy_scope: *current_legacy_scope, binding, ident
1104 *current_legacy_scope = LegacyScope::Binding(legacy_binding);
1105 self.all_macros.insert(ident.name, def);
1106 if attr::contains_name(&item.attrs, "macro_export") {
1107 let module = self.graph_root;
1108 let vis = ty::Visibility::Public;
1109 self.define(module, ident, MacroNS,
1110 (def, vis, item.span, expansion, IsMacroExport));
1112 if !attr::contains_name(&item.attrs, "rustc_doc_only_macro") {
1113 self.check_reserved_macro_name(ident, MacroNS);
1115 self.unused_macros.insert(def_id);
1118 let module = self.current_module;
1119 let def = Def::Macro(def_id, MacroKind::Bang);
1120 let vis = self.resolve_visibility(&item.vis);
1121 if vis != ty::Visibility::Public {
1122 self.unused_macros.insert(def_id);
1124 self.define(module, ident, MacroNS, (def, vis, item.span, expansion));
1128 /// Error if `ext` is a Macros 1.1 procedural macro being imported by `#[macro_use]`
1129 fn err_if_macro_use_proc_macro(&mut self, name: Name, use_span: Span,
1130 binding: &NameBinding<'a>) {
1131 let krate = match binding.def() {
1132 Def::NonMacroAttr(..) | Def::Err => return,
1133 Def::Macro(def_id, _) => def_id.krate,
1134 _ => unreachable!(),
1137 // Plugin-based syntax extensions are exempt from this check
1138 if krate == BUILTIN_MACROS_CRATE { return; }
1140 let ext = binding.get_macro(self);
1143 // If `ext` is a procedural macro, check if we've already warned about it
1144 SyntaxExtension::AttrProcMacro(..) | SyntaxExtension::ProcMacro { .. } =>
1145 if !self.warned_proc_macros.insert(name) { return; },
1149 let warn_msg = match *ext {
1150 SyntaxExtension::AttrProcMacro(..) =>
1151 "attribute procedural macros cannot be imported with `#[macro_use]`",
1152 SyntaxExtension::ProcMacro { .. } =>
1153 "procedural macros cannot be imported with `#[macro_use]`",
1157 let def_id = self.current_module.normal_ancestor_id;
1158 let node_id = self.definitions.as_local_node_id(def_id).unwrap();
1160 self.proc_mac_errors.push(ProcMacError {
1161 crate_name: self.cstore.crate_name_untracked(krate),
1169 pub fn report_proc_macro_import(&mut self, krate: &ast::Crate) {
1170 for err in self.proc_mac_errors.drain(..) {
1171 let (span, found_use) = ::UsePlacementFinder::check(krate, err.module);
1173 if let Some(span) = span {
1174 let found_use = if found_use { "" } else { "\n" };
1175 self.session.struct_span_err(err.use_span, err.warn_msg)
1176 .span_suggestion_with_applicability(
1178 "instead, import the procedural macro like any other item",
1179 format!("use {}::{};{}", err.crate_name, err.name, found_use),
1180 Applicability::MachineApplicable
1183 self.session.struct_span_err(err.use_span, err.warn_msg)
1184 .help(&format!("instead, import the procedural macro like any other item: \
1185 `use {}::{};`", err.crate_name, err.name))
1191 fn gate_legacy_custom_derive(&mut self, name: Symbol, span: Span) {
1192 if !self.session.features_untracked().custom_derive {
1193 let sess = &self.session.parse_sess;
1194 let explain = feature_gate::EXPLAIN_CUSTOM_DERIVE;
1195 emit_feature_err(sess, "custom_derive", span, GateIssue::Language, explain);
1196 } else if !self.is_whitelisted_legacy_custom_derive(name) {
1197 self.session.span_warn(span, feature_gate::EXPLAIN_DEPR_CUSTOM_DERIVE);