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()));
535 if let Ok(Def::NonMacroAttr(NonMacroAttrKind::Custom)) = result {} else {
539 // At this point we've found that the `attr` is determinately unresolved and thus can be
540 // interpreted as a custom attribute. Normally custom attributes are feature gated, but
541 // it may be a custom attribute whitelisted by a derive macro and they do not require
544 // So here we look through all of the derive annotations in scope and try to resolve them.
545 // If they themselves successfully resolve *and* one of the resolved derive macros
546 // whitelists this attribute's name, then this is a registered attribute and we can convert
547 // it from a "generic custom attrite" into a "known derive helper attribute".
548 assert!(kind == MacroKind::Attr);
549 enum ConvertToDeriveHelper { Yes, No, DontKnow }
550 let mut convert_to_derive_helper = ConvertToDeriveHelper::No;
551 for derive in &parent_scope.derives {
552 match self.resolve_macro_to_def(derive, MacroKind::Derive, parent_scope, force) {
553 Ok((_, ext)) => if let SyntaxExtension::ProcMacroDerive(_, inert_attrs, _) = &*ext {
554 if inert_attrs.contains(&path[0].name) {
555 convert_to_derive_helper = ConvertToDeriveHelper::Yes;
559 Err(Determinacy::Undetermined) =>
560 convert_to_derive_helper = ConvertToDeriveHelper::DontKnow,
561 Err(Determinacy::Determined) => {}
565 match convert_to_derive_helper {
566 ConvertToDeriveHelper::Yes => Ok(Def::NonMacroAttr(NonMacroAttrKind::DeriveHelper)),
567 ConvertToDeriveHelper::No => result,
568 ConvertToDeriveHelper::DontKnow => Err(Determinacy::determined(force)),
572 // Resolve the initial segment of a non-global macro path
573 // (e.g. `foo` in `foo::bar!(); or `foo!();`).
574 // This is a variation of `fn resolve_ident_in_lexical_scope` that can be run during
575 // expansion and import resolution (perhaps they can be merged in the future).
576 crate fn resolve_lexical_macro_path_segment(
580 kind: Option<MacroKind>,
581 parent_scope: &ParentScope<'a>,
585 ) -> Result<(&'a NameBinding<'a>, FromPrelude), Determinacy> {
586 // General principles:
587 // 1. Not controlled (user-defined) names should have higher priority than controlled names
588 // built into the language or standard library. This way we can add new names into the
589 // language or standard library without breaking user code.
590 // 2. "Closed set" below means new names can appear after the current resolution attempt.
591 // Places to search (in order of decreasing priority):
593 // 1. FIXME: Ribs (type parameters), there's no necessary infrastructure yet
594 // (open set, not controlled).
595 // 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
596 // (open, not controlled).
597 // 3. Extern prelude (closed, not controlled).
598 // 4. Tool modules (closed, controlled right now, but not in the future).
599 // 5. Standard library prelude (de-facto closed, controlled).
600 // 6. Language prelude (closed, controlled).
602 // 1. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
603 // (open, not controlled).
604 // 2. `macro_use` prelude (open, the open part is from macro expansions, not controlled).
605 // 2a. User-defined prelude from macro-use
606 // (open, the open part is from macro expansions, not controlled).
607 // 2b. Standard library prelude is currently implemented as `macro-use` (closed, controlled)
608 // 3. Language prelude: builtin macros (closed, controlled, except for legacy plugins).
609 // 4. Language prelude: builtin attributes (closed, controlled).
611 assert!(ns == TypeNS || ns == MacroNS);
612 assert!(force || !record_used); // `record_used` implies `force`
613 ident = ident.modern();
615 // This is *the* result, resolution from the scope closest to the resolved identifier.
616 // However, sometimes this result is "weak" because it comes from a glob import or
617 // a macro expansion, and in this case it cannot shadow names from outer scopes, e.g.
618 // mod m { ... } // solution in outer scope
620 // use prefix::*; // imports another `m` - innermost solution
621 // // weak, cannot shadow the outer `m`, need to report ambiguity error
624 // So we have to save the innermost solution and continue searching in outer scopes
625 // to detect potential ambiguities.
626 let mut innermost_result: Option<(&NameBinding, FromPrelude)> = None;
628 enum WhereToResolve<'a> {
639 // Go through all the scopes and try to resolve the name.
640 let mut where_to_resolve = WhereToResolve::Module(parent_scope.module);
641 let mut use_prelude = !parent_scope.module.no_implicit_prelude;
643 let result = match where_to_resolve {
644 WhereToResolve::Module(module) => {
645 let orig_current_module = mem::replace(&mut self.current_module, module);
646 let binding = self.resolve_ident_in_module_unadjusted(
647 ModuleOrUniformRoot::Module(module),
654 self.current_module = orig_current_module;
655 binding.map(|binding| (binding, FromPrelude(false)))
657 WhereToResolve::MacroUsePrelude => {
658 match self.macro_use_prelude.get(&ident.name).cloned() {
659 Some(binding) => Ok((binding, FromPrelude(true))),
660 None => Err(Determinacy::Determined),
663 WhereToResolve::BuiltinMacros => {
664 match self.builtin_macros.get(&ident.name).cloned() {
665 Some(binding) => Ok((binding, FromPrelude(true))),
666 None => Err(Determinacy::Determined),
669 WhereToResolve::BuiltinAttrs => {
670 // FIXME: Only built-in attributes are not considered as candidates for
671 // non-attributes to fight off regressions on stable channel (#53205).
672 // We need to come up with some more principled approach instead.
673 if kind == Some(MacroKind::Attr) && is_builtin_attr_name(ident.name) {
674 let binding = (Def::NonMacroAttr(NonMacroAttrKind::Builtin),
675 ty::Visibility::Public, ident.span, Mark::root())
676 .to_name_binding(self.arenas);
677 Ok((binding, FromPrelude(true)))
679 Err(Determinacy::Determined)
682 WhereToResolve::ExternPrelude => {
683 if use_prelude && self.extern_prelude.contains(&ident.name) {
684 if !self.session.features_untracked().extern_prelude &&
685 !self.ignore_extern_prelude_feature {
686 feature_err(&self.session.parse_sess, "extern_prelude",
687 ident.span, GateIssue::Language,
688 "access to extern crates through prelude is experimental")
693 self.crate_loader.process_path_extern(ident.name, ident.span);
695 self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX });
696 self.populate_module_if_necessary(crate_root);
698 let binding = (crate_root, ty::Visibility::Public,
699 ident.span, Mark::root()).to_name_binding(self.arenas);
700 Ok((binding, FromPrelude(true)))
702 Err(Determinacy::Determined)
705 WhereToResolve::ToolPrelude => {
706 if use_prelude && is_known_tool(ident.name) {
707 let binding = (Def::ToolMod, ty::Visibility::Public,
708 ident.span, Mark::root()).to_name_binding(self.arenas);
709 Ok((binding, FromPrelude(true)))
711 Err(Determinacy::Determined)
714 WhereToResolve::StdLibPrelude => {
715 let mut result = Err(Determinacy::Determined);
717 if let Some(prelude) = self.prelude {
718 if let Ok(binding) = self.resolve_ident_in_module_unadjusted(
719 ModuleOrUniformRoot::Module(prelude),
726 result = Ok((binding, FromPrelude(true)));
732 WhereToResolve::BuiltinTypes => {
733 if let Some(prim_ty) =
734 self.primitive_type_table.primitive_types.get(&ident.name).cloned() {
735 let binding = (Def::PrimTy(prim_ty), ty::Visibility::Public,
736 ident.span, Mark::root()).to_name_binding(self.arenas);
737 Ok((binding, FromPrelude(true)))
739 Err(Determinacy::Determined)
744 macro_rules! continue_search { () => {
745 where_to_resolve = match where_to_resolve {
746 WhereToResolve::Module(module) => {
747 match self.hygienic_lexical_parent(module, &mut ident.span) {
748 Some(parent_module) => WhereToResolve::Module(parent_module),
750 use_prelude = !module.no_implicit_prelude;
752 WhereToResolve::MacroUsePrelude
754 WhereToResolve::ExternPrelude
759 WhereToResolve::MacroUsePrelude => WhereToResolve::BuiltinMacros,
760 WhereToResolve::BuiltinMacros => WhereToResolve::BuiltinAttrs,
761 WhereToResolve::BuiltinAttrs => break, // nowhere else to search
762 WhereToResolve::ExternPrelude => WhereToResolve::ToolPrelude,
763 WhereToResolve::ToolPrelude => WhereToResolve::StdLibPrelude,
764 WhereToResolve::StdLibPrelude => WhereToResolve::BuiltinTypes,
765 WhereToResolve::BuiltinTypes => break, // nowhere else to search
773 if macro_kind_mismatch(ident.name, kind, result.0.macro_kind()) {
781 if let Some(innermost_result) = innermost_result {
782 // Found another solution, if the first one was "weak", report an error.
783 if result.0.def() != innermost_result.0.def() &&
784 (innermost_result.0.is_glob_import() ||
785 innermost_result.0.may_appear_after(parent_scope.expansion, result.0)) {
786 self.ambiguity_errors.push(AmbiguityError {
788 b1: innermost_result.0,
791 return Ok(innermost_result);
794 // Found the first solution.
795 innermost_result = Some(result);
800 Err(Determinacy::Determined) => {
803 Err(Determinacy::Undetermined) => return Err(Determinacy::determined(force)),
807 // The first found solution was the only one, return it.
808 if let Some(innermost_result) = innermost_result {
809 return Ok(innermost_result);
812 let determinacy = Determinacy::determined(force);
813 if determinacy == Determinacy::Determined && kind == Some(MacroKind::Attr) {
814 // For single-segment attributes interpret determinate "no resolution" as a custom
815 // attribute. (Lexical resolution implies the first segment and attr kind should imply
816 // the last segment, so we are certainly working with a single-segment attribute here.)
817 assert!(ns == MacroNS);
818 let binding = (Def::NonMacroAttr(NonMacroAttrKind::Custom),
819 ty::Visibility::Public, ident.span, Mark::root())
820 .to_name_binding(self.arenas);
821 Ok((binding, FromPrelude(true)))
827 fn resolve_legacy_scope(
830 kind: Option<MacroKind>,
831 parent_scope: &ParentScope<'a>,
833 ) -> Option<&'a NameBinding<'a>> {
834 if macro_kind_mismatch(ident.name, kind, Some(MacroKind::Bang)) {
838 let ident = ident.modern();
840 // This is *the* result, resolution from the scope closest to the resolved identifier.
841 // However, sometimes this result is "weak" because it comes from a macro expansion,
842 // and in this case it cannot shadow names from outer scopes, e.g.
843 // macro_rules! m { ... } // solution in outer scope
845 // define_m!(); // generates another `macro_rules! m` - innermost solution
846 // // weak, cannot shadow the outer `m`, need to report ambiguity error
849 // So we have to save the innermost solution and continue searching in outer scopes
850 // to detect potential ambiguities.
851 let mut innermost_result: Option<&NameBinding> = None;
853 // Go through all the scopes and try to resolve the name.
854 let mut where_to_resolve = parent_scope.legacy;
856 let result = match where_to_resolve {
857 LegacyScope::Binding(legacy_binding) if ident == legacy_binding.ident =>
858 Some(legacy_binding.binding),
862 macro_rules! continue_search { () => {
863 where_to_resolve = match where_to_resolve {
864 LegacyScope::Empty => break, // nowhere else to search
865 LegacyScope::Binding(binding) => binding.parent_legacy_scope,
866 LegacyScope::Invocation(invocation) => invocation.output_legacy_scope.get(),
867 LegacyScope::Uninitialized => unreachable!(),
879 if let Some(innermost_result) = innermost_result {
880 // Found another solution, if the first one was "weak", report an error.
881 if result.def() != innermost_result.def() &&
882 innermost_result.may_appear_after(parent_scope.expansion, result) {
883 self.ambiguity_errors.push(AmbiguityError {
885 b1: innermost_result,
888 return Some(innermost_result);
891 // Found the first solution.
892 innermost_result = Some(result);
903 // The first found solution was the only one (or there was no solution at all), return it.
907 pub fn finalize_current_module_macro_resolutions(&mut self) {
908 let module = self.current_module;
909 for &(ref path, span) in module.macro_resolutions.borrow().iter() {
910 match self.resolve_path(None, &path, Some(MacroNS), true, span, CrateLint::No) {
911 PathResult::NonModule(_) => {},
912 PathResult::Failed(span, msg, _) => {
913 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
919 let legacy_macro_resolutions =
920 mem::replace(&mut *module.legacy_macro_resolutions.borrow_mut(), Vec::new());
921 for (ident, kind, parent_scope, def) in legacy_macro_resolutions {
922 let span = ident.span;
923 let legacy_resolution = self.resolve_legacy_scope(
924 ident, Some(kind), &parent_scope, true
926 let resolution = self.resolve_lexical_macro_path_segment(
927 ident, MacroNS, Some(kind), &parent_scope, true, true, span
930 let check_consistency = |this: &Self, new_def: Def| {
931 if let Some(def) = def {
932 if this.ambiguity_errors.is_empty() && new_def != def && new_def != Def::Err {
933 // Make sure compilation does not succeed if preferred macro resolution
934 // has changed after the macro had been expanded. In theory all such
935 // situations should be reported as ambiguity errors, so this is span-bug.
936 span_bug!(span, "inconsistent resolution for a macro");
939 // It's possible that the macro was unresolved (indeterminate) and silently
940 // expanded into a dummy fragment for recovery during expansion.
941 // Now, post-expansion, the resolution may succeed, but we can't change the
942 // past and need to report an error.
944 format!("cannot determine resolution for the {} `{}`", kind.descr(), ident);
945 let msg_note = "import resolution is stuck, try simplifying macro imports";
946 this.session.struct_span_err(span, &msg).note(msg_note).emit();
950 match (legacy_resolution, resolution) {
952 assert!(def.is_none());
953 let bang = if kind == MacroKind::Bang { "!" } else { "" };
955 format!("cannot find {} `{}{}` in this scope", kind.descr(), ident, bang);
956 let mut err = self.session.struct_span_err(span, &msg);
957 self.suggest_macro_name(&ident.as_str(), kind, &mut err, span);
960 (Some(legacy_binding), Ok((binding, FromPrelude(from_prelude))))
961 if legacy_binding.def() != binding.def_ignoring_ambiguity() &&
963 legacy_binding.may_appear_after(parent_scope.expansion, binding)) => {
964 self.report_ambiguity_error(ident, legacy_binding, binding);
966 // OK, non-macro-expanded legacy wins over prelude even if defs are different
967 // Also, legacy and modern can co-exist if their defs are same
968 (Some(legacy_binding), Ok(_)) |
969 // OK, unambiguous resolution
970 (Some(legacy_binding), Err(_)) => {
971 check_consistency(self, legacy_binding.def());
973 // OK, unambiguous resolution
974 (None, Ok((binding, FromPrelude(from_prelude)))) => {
975 check_consistency(self, binding.def_ignoring_ambiguity());
977 self.record_use(ident, MacroNS, binding);
978 self.err_if_macro_use_proc_macro(ident.name, span, binding);
984 let builtin_attrs = mem::replace(&mut *module.builtin_attrs.borrow_mut(), Vec::new());
985 for (ident, parent_scope) in builtin_attrs {
986 let resolve_legacy = |this: &mut Self| this.resolve_legacy_scope(
987 ident, Some(MacroKind::Attr), &parent_scope, true
989 let resolve_modern = |this: &mut Self| this.resolve_lexical_macro_path_segment(
990 ident, MacroNS, Some(MacroKind::Attr), &parent_scope, true, true, ident.span
991 ).map(|(binding, _)| binding).ok();
993 if let Some(binding) = resolve_legacy(self).or_else(|| resolve_modern(self)) {
994 if binding.def_ignoring_ambiguity() !=
995 Def::NonMacroAttr(NonMacroAttrKind::Builtin) {
996 let builtin_binding = (Def::NonMacroAttr(NonMacroAttrKind::Builtin),
997 ty::Visibility::Public, ident.span, Mark::root())
998 .to_name_binding(self.arenas);
999 self.report_ambiguity_error(ident, binding, builtin_binding);
1005 fn suggest_macro_name(&mut self, name: &str, kind: MacroKind,
1006 err: &mut DiagnosticBuilder<'a>, span: Span) {
1007 // First check if this is a locally-defined bang macro.
1008 let suggestion = if let MacroKind::Bang = kind {
1009 find_best_match_for_name(self.macro_names.iter().map(|ident| &ident.name), name, None)
1012 // Then check global macros.
1014 let names = self.builtin_macros.iter().chain(self.macro_use_prelude.iter())
1015 .filter_map(|(name, binding)| {
1016 if binding.macro_kind() == Some(kind) { Some(name) } else { None }
1018 find_best_match_for_name(names, name, None)
1019 // Then check modules.
1021 let is_macro = |def| {
1022 if let Def::Macro(_, def_kind) = def {
1028 let ident = Ident::new(Symbol::intern(name), span);
1029 self.lookup_typo_candidate(&[ident], MacroNS, is_macro, span)
1032 if let Some(suggestion) = suggestion {
1033 if suggestion != name {
1034 if let MacroKind::Bang = kind {
1035 err.span_suggestion_with_applicability(
1037 "you could try the macro",
1038 suggestion.to_string(),
1039 Applicability::MaybeIncorrect
1042 err.span_suggestion_with_applicability(
1045 suggestion.to_string(),
1046 Applicability::MaybeIncorrect
1050 err.help("have you added the `#[macro_use]` on the module/import?");
1055 fn collect_def_ids(&mut self,
1057 invocation: &'a InvocationData<'a>,
1058 fragment: &AstFragment) {
1059 let Resolver { ref mut invocations, arenas, graph_root, .. } = *self;
1060 let InvocationData { def_index, .. } = *invocation;
1062 let visit_macro_invoc = &mut |invoc: map::MacroInvocationData| {
1063 invocations.entry(invoc.mark).or_insert_with(|| {
1064 arenas.alloc_invocation_data(InvocationData {
1065 def_index: invoc.def_index,
1066 module: Cell::new(graph_root),
1067 parent_legacy_scope: Cell::new(LegacyScope::Uninitialized),
1068 output_legacy_scope: Cell::new(LegacyScope::Uninitialized),
1073 let mut def_collector = DefCollector::new(&mut self.definitions, mark);
1074 def_collector.visit_macro_invoc = Some(visit_macro_invoc);
1075 def_collector.with_parent(def_index, |def_collector| {
1076 fragment.visit_with(def_collector)
1080 pub fn define_macro(&mut self,
1083 current_legacy_scope: &mut LegacyScope<'a>) {
1084 self.local_macro_def_scopes.insert(item.id, self.current_module);
1085 let ident = item.ident;
1086 if ident.name == "macro_rules" {
1087 self.session.span_err(item.span, "user-defined macros may not be named `macro_rules`");
1090 let def_id = self.definitions.local_def_id(item.id);
1091 let ext = Lrc::new(macro_rules::compile(&self.session.parse_sess,
1092 &self.session.features_untracked(),
1093 item, hygiene::default_edition()));
1094 self.macro_map.insert(def_id, ext);
1096 let def = match item.node { ast::ItemKind::MacroDef(ref def) => def, _ => unreachable!() };
1098 let ident = ident.modern();
1099 self.macro_names.insert(ident);
1100 let def = Def::Macro(def_id, MacroKind::Bang);
1101 let vis = ty::Visibility::Invisible; // Doesn't matter for legacy bindings
1102 let binding = (def, vis, item.span, expansion).to_name_binding(self.arenas);
1103 let legacy_binding = self.arenas.alloc_legacy_binding(LegacyBinding {
1104 parent_legacy_scope: *current_legacy_scope, binding, ident
1106 *current_legacy_scope = LegacyScope::Binding(legacy_binding);
1107 self.all_macros.insert(ident.name, def);
1108 if attr::contains_name(&item.attrs, "macro_export") {
1109 let module = self.graph_root;
1110 let vis = ty::Visibility::Public;
1111 self.define(module, ident, MacroNS,
1112 (def, vis, item.span, expansion, IsMacroExport));
1114 if !attr::contains_name(&item.attrs, "rustc_doc_only_macro") {
1115 self.check_reserved_macro_name(ident, MacroNS);
1117 self.unused_macros.insert(def_id);
1120 let module = self.current_module;
1121 let def = Def::Macro(def_id, MacroKind::Bang);
1122 let vis = self.resolve_visibility(&item.vis);
1123 if vis != ty::Visibility::Public {
1124 self.unused_macros.insert(def_id);
1126 self.define(module, ident, MacroNS, (def, vis, item.span, expansion));
1130 /// Error if `ext` is a Macros 1.1 procedural macro being imported by `#[macro_use]`
1131 fn err_if_macro_use_proc_macro(&mut self, name: Name, use_span: Span,
1132 binding: &NameBinding<'a>) {
1133 let krate = match binding.def() {
1134 Def::NonMacroAttr(..) | Def::Err => return,
1135 Def::Macro(def_id, _) => def_id.krate,
1136 _ => unreachable!(),
1139 // Plugin-based syntax extensions are exempt from this check
1140 if krate == BUILTIN_MACROS_CRATE { return; }
1142 let ext = binding.get_macro(self);
1145 // If `ext` is a procedural macro, check if we've already warned about it
1146 SyntaxExtension::AttrProcMacro(..) | SyntaxExtension::ProcMacro { .. } =>
1147 if !self.warned_proc_macros.insert(name) { return; },
1151 let warn_msg = match *ext {
1152 SyntaxExtension::AttrProcMacro(..) =>
1153 "attribute procedural macros cannot be imported with `#[macro_use]`",
1154 SyntaxExtension::ProcMacro { .. } =>
1155 "procedural macros cannot be imported with `#[macro_use]`",
1159 let def_id = self.current_module.normal_ancestor_id;
1160 let node_id = self.definitions.as_local_node_id(def_id).unwrap();
1162 self.proc_mac_errors.push(ProcMacError {
1163 crate_name: self.cstore.crate_name_untracked(krate),
1171 pub fn report_proc_macro_import(&mut self, krate: &ast::Crate) {
1172 for err in self.proc_mac_errors.drain(..) {
1173 let (span, found_use) = ::UsePlacementFinder::check(krate, err.module);
1175 if let Some(span) = span {
1176 let found_use = if found_use { "" } else { "\n" };
1177 self.session.struct_span_err(err.use_span, err.warn_msg)
1178 .span_suggestion_with_applicability(
1180 "instead, import the procedural macro like any other item",
1181 format!("use {}::{};{}", err.crate_name, err.name, found_use),
1182 Applicability::MachineApplicable
1185 self.session.struct_span_err(err.use_span, err.warn_msg)
1186 .help(&format!("instead, import the procedural macro like any other item: \
1187 `use {}::{};`", err.crate_name, err.name))
1193 fn gate_legacy_custom_derive(&mut self, name: Symbol, span: Span) {
1194 if !self.session.features_untracked().custom_derive {
1195 let sess = &self.session.parse_sess;
1196 let explain = feature_gate::EXPLAIN_CUSTOM_DERIVE;
1197 emit_feature_err(sess, "custom_derive", span, GateIssue::Language, explain);
1198 } else if !self.is_whitelisted_legacy_custom_derive(name) {
1199 self.session.span_warn(span, feature_gate::EXPLAIN_DEPR_CUSTOM_DERIVE);