rust/src/librustc_resolve/macros.rs

1040 lines
50 KiB
Rust
Raw Normal View History

use crate::{AmbiguityError, AmbiguityKind, AmbiguityErrorMisc, Determinacy};
use crate::{CrateLint, Resolver, ResolutionError, Scope, ScopeSet, ParentScope, Weak};
2019-02-06 17:15:23 +00:00
use crate::{Module, ModuleKind, NameBinding, NameBindingKind, PathResult, Segment, ToNameBinding};
use crate::{is_known_tool, resolve_error};
use crate::ModuleOrUniformRoot;
use crate::Namespace::*;
use crate::build_reduced_graph::{BuildReducedGraphVisitor, IsMacroExport};
use crate::resolve_imports::ImportResolver;
2019-05-08 19:07:12 +00:00
use rustc::hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX};
use rustc::hir::def::{self, DefKind, NonMacroAttrKind};
use rustc::hir::map::DefCollector;
use rustc::middle::stability;
use rustc::{ty, lint, span_bug};
use syntax::ast::{self, Ident, ItemKind};
use syntax::attr::{self, StabilityLevel};
use syntax::ext::base::{self, Indeterminate};
use syntax::ext::base::{MacroKind, SyntaxExtension};
use syntax::ext::expand::{AstFragment, Invocation, InvocationKind};
use syntax::ext::hygiene::{self, Mark, ExpnInfo, ExpnKind};
use syntax::ext::tt::macro_rules;
use syntax::feature_gate::{emit_feature_err, is_builtin_attr_name};
use syntax::feature_gate::GateIssue;
2019-05-11 14:41:37 +00:00
use syntax::symbol::{Symbol, kw, sym};
use syntax_pos::{Span, DUMMY_SP};
use std::cell::Cell;
use std::{mem, ptr};
2018-02-27 16:11:14 +00:00
use rustc_data_structures::sync::Lrc;
type Res = def::Res<ast::NodeId>;
2019-04-03 07:07:45 +00:00
// FIXME: Merge this with `ParentScope`.
#[derive(Clone, Debug)]
pub struct InvocationData<'a> {
2019-02-08 13:53:55 +00:00
/// The module in which the macro was invoked.
crate module: Module<'a>,
2019-02-08 13:53:55 +00:00
/// The legacy scope in which the macro was invoked.
/// The invocation path is resolved in this scope.
crate parent_legacy_scope: LegacyScope<'a>,
2019-02-08 13:53:55 +00:00
/// The legacy scope *produced* by expanding this macro invocation,
/// includes all the macro_rules items, other invocations, etc generated by it.
/// `None` if the macro is not expanded yet.
crate output_legacy_scope: Cell<Option<LegacyScope<'a>>>,
}
impl<'a> InvocationData<'a> {
pub fn root(graph_root: Module<'a>) -> Self {
InvocationData {
module: graph_root,
parent_legacy_scope: LegacyScope::Empty,
output_legacy_scope: Cell::new(None),
}
}
}
/// Binding produced by a `macro_rules` item.
/// Not modularized, can shadow previous legacy bindings, etc.
#[derive(Debug)]
pub struct LegacyBinding<'a> {
binding: &'a NameBinding<'a>,
/// Legacy scope into which the `macro_rules` item was planted.
parent_legacy_scope: LegacyScope<'a>,
ident: Ident,
}
2019-02-08 13:53:55 +00:00
/// The scope introduced by a `macro_rules!` macro.
/// This starts at the macro's definition and ends at the end of the macro's parent
/// module (named or unnamed), or even further if it escapes with `#[macro_use]`.
/// Some macro invocations need to introduce legacy scopes too because they
2019-02-08 13:53:55 +00:00
/// can potentially expand into macro definitions.
#[derive(Copy, Clone, Debug)]
2016-10-06 08:04:30 +00:00
pub enum LegacyScope<'a> {
/// Empty "root" scope at the crate start containing no names.
2016-10-06 08:04:30 +00:00
Empty,
2019-02-08 13:53:55 +00:00
/// The scope introduced by a `macro_rules!` macro definition.
2016-10-06 08:04:30 +00:00
Binding(&'a LegacyBinding<'a>),
2019-02-08 13:53:55 +00:00
/// The scope introduced by a macro invocation that can potentially
/// create a `macro_rules!` macro definition.
Invocation(&'a InvocationData<'a>),
}
// Macro namespace is separated into two sub-namespaces, one for bang macros and
// one for attribute-like macros (attributes, derives).
// We ignore resolutions from one sub-namespace when searching names in scope for another.
fn sub_namespace_match(candidate: Option<MacroKind>, requirement: Option<MacroKind>) -> bool {
#[derive(PartialEq)]
enum SubNS { Bang, AttrLike }
let sub_ns = |kind| match kind {
MacroKind::Bang => SubNS::Bang,
MacroKind::Attr | MacroKind::Derive => SubNS::AttrLike,
};
let candidate = candidate.map(sub_ns);
let requirement = requirement.map(sub_ns);
// "No specific sub-namespace" means "matches anything" for both requirements and candidates.
candidate.is_none() || requirement.is_none() || candidate == requirement
}
// We don't want to format a path using pretty-printing,
// `format!("{}", path)`, because that tries to insert
// line-breaks and is slow.
fn fast_print_path(path: &ast::Path) -> Symbol {
if path.segments.len() == 1 {
return path.segments[0].ident.name
} else {
let mut path_str = String::with_capacity(64);
for (i, segment) in path.segments.iter().enumerate() {
if i != 0 {
path_str.push_str("::");
}
if segment.ident.name != kw::PathRoot {
path_str.push_str(&segment.ident.as_str())
}
}
Symbol::intern(&path_str)
}
}
fn proc_macro_stub(item: &ast::Item) -> Option<(MacroKind, Ident, Span)> {
if attr::contains_name(&item.attrs, sym::proc_macro) {
return Some((MacroKind::Bang, item.ident, item.span));
} else if attr::contains_name(&item.attrs, sym::proc_macro_attribute) {
return Some((MacroKind::Attr, item.ident, item.span));
} else if let Some(attr) = attr::find_by_name(&item.attrs, sym::proc_macro_derive) {
if let Some(nested_meta) = attr.meta_item_list().and_then(|list| list.get(0).cloned()) {
if let Some(ident) = nested_meta.ident() {
return Some((MacroKind::Derive, ident, ident.span));
}
}
}
None
}
2018-12-10 04:37:10 +00:00
impl<'a> base::Resolver for Resolver<'a> {
fn next_node_id(&mut self) -> ast::NodeId {
self.session.next_node_id()
}
fn get_module_scope(&mut self, id: ast::NodeId) -> Mark {
let span = DUMMY_SP.fresh_expansion(Mark::root(), ExpnInfo::default(
ExpnKind::Macro(MacroKind::Attr, sym::test_case), DUMMY_SP, self.session.edition()
));
let mark = span.ctxt().outer();
let module = self.module_map[&self.definitions.local_def_id(id)];
self.definitions.set_invocation_parent(mark, module.def_id().unwrap().index);
self.invocations.insert(mark, self.arenas.alloc_invocation_data(InvocationData {
module,
parent_legacy_scope: LegacyScope::Empty,
output_legacy_scope: Cell::new(None),
2016-09-16 08:50:34 +00:00
}));
mark
}
fn resolve_dollar_crates(&mut self) {
hygiene::update_dollar_crate_names(|ctxt| {
let ident = Ident::new(kw::DollarCrate, DUMMY_SP.with_ctxt(ctxt));
match self.resolve_crate_root(ident).kind {
ModuleKind::Def(.., name) if name != kw::Invalid => name,
_ => kw::Crate,
}
});
}
fn visit_ast_fragment_with_placeholders(&mut self, mark: Mark, fragment: &AstFragment,
derives: &[Mark]) {
fragment.visit_with(&mut DefCollector::new(&mut self.definitions, mark));
2016-10-06 08:04:30 +00:00
let invocation = self.invocations[&mark];
self.current_module = invocation.module;
self.current_module.unresolved_invocations.borrow_mut().remove(&mark);
self.current_module.unresolved_invocations.borrow_mut().extend(derives);
let parent_def = self.definitions.invocation_parent(mark);
for &derive_invoc_id in derives {
self.definitions.set_invocation_parent(derive_invoc_id, parent_def);
}
2018-10-17 09:36:19 +00:00
self.invocations.extend(derives.iter().map(|&derive| (derive, invocation)));
2016-10-06 08:04:30 +00:00
let mut visitor = BuildReducedGraphVisitor {
resolver: self,
current_legacy_scope: invocation.parent_legacy_scope,
expansion: mark,
2016-10-06 08:04:30 +00:00
};
fragment.visit_with(&mut visitor);
invocation.output_legacy_scope.set(Some(visitor.current_legacy_scope));
}
2018-02-27 16:11:14 +00:00
fn add_builtin(&mut self, ident: ast::Ident, ext: Lrc<SyntaxExtension>) {
2016-10-28 06:52:45 +00:00
let def_id = DefId {
krate: CrateNum::BuiltinMacros,
index: DefIndex::from(self.macro_map.len()),
2016-10-28 06:52:45 +00:00
};
let kind = ext.macro_kind();
2016-10-28 06:52:45 +00:00
self.macro_map.insert(def_id, ext);
let binding = self.arenas.alloc_name_binding(NameBinding {
kind: NameBindingKind::Res(Res::Def(DefKind::Macro(kind), def_id), false),
ambiguity: None,
span: DUMMY_SP,
vis: ty::Visibility::Public,
expansion: Mark::root(),
});
if self.builtin_macros.insert(ident.name, binding).is_some() {
self.session.span_err(ident.span,
&format!("built-in macro `{}` was already defined", ident));
}
}
2016-11-10 10:11:25 +00:00
fn resolve_imports(&mut self) {
ImportResolver { resolver: self }.resolve_imports()
}
fn resolve_macro_invocation(&mut self, invoc: &Invocation, invoc_id: Mark, force: bool)
-> Result<Option<Lrc<SyntaxExtension>>, Indeterminate> {
let (path, kind, derives_in_scope, after_derive) = match invoc.kind {
InvocationKind::Attr { ref attr, ref derives, after_derive, .. } =>
(&attr.path, MacroKind::Attr, derives.clone(), after_derive),
InvocationKind::Bang { ref mac, .. } =>
(&mac.node.path, MacroKind::Bang, Vec::new(), false),
InvocationKind::Derive { ref path, .. } =>
(path, MacroKind::Derive, Vec::new(), false),
InvocationKind::DeriveContainer { .. } =>
return Ok(None),
};
let parent_scope = self.invoc_parent_scope(invoc_id, derives_in_scope);
let (ext, res) = self.smart_resolve_macro_path(path, kind, &parent_scope, true, force)?;
let span = invoc.span();
invoc.expansion_data.mark.set_expn_info(ext.expn_info(span, fast_print_path(path)));
if let Res::Def(_, def_id) = res {
if after_derive {
self.session.span_err(span, "macro attributes must be placed before `#[derive]`");
}
self.macro_defs.insert(invoc.expansion_data.mark, def_id);
let normal_module_def_id =
self.macro_def_scope(invoc.expansion_data.mark).normal_ancestor_id;
self.definitions.add_parent_module_of_macro_def(invoc.expansion_data.mark,
normal_module_def_id);
}
2017-03-22 08:39:51 +00:00
Ok(Some(ext))
}
2017-05-11 08:26:07 +00:00
fn check_unused_macros(&self) {
for (&node_id, &span) in self.unused_macros.iter() {
self.session.buffer_lint(
lint::builtin::UNUSED_MACROS, node_id, span, "unused macro definition"
);
2017-05-11 08:26:07 +00:00
}
}
}
2018-12-10 04:37:10 +00:00
impl<'a> Resolver<'a> {
pub fn dummy_parent_scope(&self) -> ParentScope<'a> {
self.invoc_parent_scope(Mark::root(), Vec::new())
}
fn invoc_parent_scope(&self, invoc_id: Mark, derives: Vec<ast::Path>) -> ParentScope<'a> {
let invoc = self.invocations[&invoc_id];
ParentScope {
module: invoc.module.nearest_item_scope(),
expansion: invoc_id.parent(),
legacy: invoc.parent_legacy_scope,
derives,
}
}
/// Resolve macro path with error reporting and recovery.
fn smart_resolve_macro_path(
&mut self,
path: &ast::Path,
kind: MacroKind,
parent_scope: &ParentScope<'a>,
trace: bool,
force: bool,
) -> Result<(Lrc<SyntaxExtension>, Res), Indeterminate> {
let (ext, res) = match self.resolve_macro_path(path, kind, parent_scope, trace, force) {
Ok((Some(ext), res)) => (ext, res),
// Use dummy syntax extensions for unresolved macros for better recovery.
Ok((None, res)) => (self.dummy_ext(kind), res),
Err(Determinacy::Determined) => (self.dummy_ext(kind), Res::Err),
Err(Determinacy::Undetermined) => return Err(Indeterminate),
};
// Report errors and enforce feature gates for the resolved macro.
2019-06-30 10:00:45 +00:00
let features = self.session.features_untracked();
for segment in &path.segments {
if let Some(args) = &segment.args {
self.session.span_err(args.span(), "generic arguments in macro path");
}
if kind == MacroKind::Attr && !features.rustc_attrs &&
segment.ident.as_str().starts_with("rustc") {
let msg =
"attributes starting with `rustc` are reserved for use by the `rustc` compiler";
emit_feature_err(
&self.session.parse_sess,
sym::rustc_attrs,
segment.ident.span,
GateIssue::Language,
msg,
);
}
}
match res {
Res::Def(DefKind::Macro(_), def_id) => {
if let Some(node_id) = self.definitions.as_local_node_id(def_id) {
self.unused_macros.remove(&node_id);
if self.proc_macro_stubs.contains(&node_id) {
self.session.span_err(
path.span,
"can't use a procedural macro from the same crate that defines it",
);
}
}
}
Res::NonMacroAttr(attr_kind) => {
if attr_kind == NonMacroAttrKind::Custom {
assert!(path.segments.len() == 1);
if !features.custom_attribute {
let msg = format!("The attribute `{}` is currently unknown to the \
compiler and may have meaning added to it in the \
future", path);
self.report_unknown_attribute(
path.span,
&path.segments[0].ident.as_str(),
&msg,
sym::custom_attribute,
);
}
}
rustc: Tweak custom attribute capabilities This commit starts to lay some groundwork for the stabilization of custom attribute invocations and general procedural macros. It applies a number of changes discussed on [internals] as well as a [recent issue][issue], namely: * The path used to specify a custom attribute must be of length one and cannot be a global path. This'll help future-proof us against any ambiguities and give us more time to settle the precise syntax. In the meantime though a bare identifier can be used and imported to invoke a custom attribute macro. A new feature gate, `proc_macro_path_invoc`, was added to gate multi-segment paths and absolute paths. * The set of items which can be annotated by a custom procedural attribute has been restricted. Statements, expressions, and modules are disallowed behind two new feature gates: `proc_macro_expr` and `proc_macro_mod`. * The input to procedural macro attributes has been restricted and adjusted. Today an invocation like `#[foo(bar)]` will receive `(bar)` as the input token stream, but after this PR it will only receive `bar` (the delimiters were removed). Invocations like `#[foo]` are still allowed and will be invoked in the same way as `#[foo()]`. This is a **breaking change** for all nightly users as the syntax coming in to procedural macros will be tweaked slightly. * Procedural macros (`foo!()` style) can only be expanded to item-like items by default. A separate feature gate, `proc_macro_non_items`, is required to expand to items like expressions, statements, etc. Closes #50038 [internals]: https://internals.rust-lang.org/t/help-stabilize-a-subset-of-macros-2-0/7252 [issue]: https://github.com/rust-lang/rust/issues/50038
2018-04-20 14:50:39 +00:00
}
Res::Err => {}
_ => panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"),
};
self.check_stability_and_deprecation(&ext, path);
Ok(if ext.macro_kind() != kind {
let expected = if kind == MacroKind::Attr { "attribute" } else { kind.descr() };
let msg = format!("expected {}, found {} `{}`", expected, res.descr(), path);
self.session.struct_span_err(path.span, &msg)
.span_label(path.span, format!("not {} {}", kind.article(), expected))
.emit();
// Use dummy syntax extensions for unexpected macro kinds for better recovery.
(self.dummy_ext(kind), Res::Err)
} else {
(ext, res)
})
}
pub fn resolve_macro_path(
&mut self,
path: &ast::Path,
kind: MacroKind,
parent_scope: &ParentScope<'a>,
trace: bool,
force: bool,
) -> Result<(Option<Lrc<SyntaxExtension>>, Res), Determinacy> {
let path_span = path.span;
let mut path = Segment::from_path(path);
2016-11-27 10:58:46 +00:00
// Possibly apply the macro helper hack
2018-05-14 00:22:52 +00:00
if kind == MacroKind::Bang && path.len() == 1 &&
path[0].ident.span.ctxt().outer_expn_info()
.map_or(false, |info| info.local_inner_macros) {
2019-05-11 14:41:37 +00:00
let root = Ident::new(kw::DollarCrate, path[0].ident.span);
path.insert(0, Segment::from_ident(root));
}
let res = if path.len() > 1 {
let res = match self.resolve_path(&path, Some(MacroNS), parent_scope,
false, path_span, CrateLint::No) {
PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
Ok(path_res.base_res())
}
2016-11-27 10:58:46 +00:00
PathResult::Indeterminate if !force => return Err(Determinacy::Undetermined),
2019-01-16 20:30:41 +00:00
PathResult::NonModule(..)
| PathResult::Indeterminate
| PathResult::Failed { .. } => Err(Determinacy::Determined),
PathResult::Module(..) => unreachable!(),
2016-11-27 10:58:46 +00:00
};
if trace {
parent_scope.module.multi_segment_macro_resolutions.borrow_mut()
.push((path, path_span, kind, parent_scope.clone(), res.ok()));
}
2016-11-27 10:58:46 +00:00
self.prohibit_imported_non_macro_attrs(None, res.ok(), path_span);
res
} else {
let binding = self.early_resolve_ident_in_lexical_scope(
path[0].ident, ScopeSet::Macro(kind), parent_scope, false, force, path_span
);
if let Err(Determinacy::Undetermined) = binding {
return Err(Determinacy::Undetermined);
}
2016-11-10 10:29:36 +00:00
if trace {
parent_scope.module.single_segment_macro_resolutions.borrow_mut()
.push((path[0].ident, kind, parent_scope.clone(), binding.ok()));
}
let res = binding.map(|binding| binding.res());
self.prohibit_imported_non_macro_attrs(binding.ok(), res.ok(), path_span);
res
};
res.map(|res| (self.get_macro(res), res))
}
2016-09-26 03:17:05 +00:00
// Resolve an identifier in lexical scope.
// This is a variation of `fn resolve_ident_in_lexical_scope` that can be run during
// expansion and import resolution (perhaps they can be merged in the future).
// The function is used for resolving initial segments of macro paths (e.g., `foo` in
// `foo::bar!(); or `foo!();`) and also for import paths on 2018 edition.
crate fn early_resolve_ident_in_lexical_scope(
&mut self,
orig_ident: Ident,
scope_set: ScopeSet,
parent_scope: &ParentScope<'a>,
record_used: bool,
force: bool,
path_span: Span,
) -> Result<&'a NameBinding<'a>, Determinacy> {
// General principles:
// 1. Not controlled (user-defined) names should have higher priority than controlled names
// built into the language or standard library. This way we can add new names into the
// language or standard library without breaking user code.
// 2. "Closed set" below means new names cannot appear after the current resolution attempt.
// Places to search (in order of decreasing priority):
// (Type NS)
// 1. FIXME: Ribs (type parameters), there's no necessary infrastructure yet
// (open set, not controlled).
// 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
// (open, not controlled).
// 3. Extern prelude (closed, not controlled).
// 4. Tool modules (closed, controlled right now, but not in the future).
// 5. Standard library prelude (de-facto closed, controlled).
// 6. Language prelude (closed, controlled).
// (Value NS)
// 1. FIXME: Ribs (local variables), there's no necessary infrastructure yet
// (open set, not controlled).
// 2. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
// (open, not controlled).
// 3. Standard library prelude (de-facto closed, controlled).
// (Macro NS)
// 1-3. Derive helpers (open, not controlled). All ambiguities with other names
// are currently reported as errors. They should be higher in priority than preludes
// and probably even names in modules according to the "general principles" above. They
// also should be subject to restricted shadowing because are effectively produced by
// derives (you need to resolve the derive first to add helpers into scope), but they
// should be available before the derive is expanded for compatibility.
// It's mess in general, so we are being conservative for now.
// 1-3. `macro_rules` (open, not controlled), loop through legacy scopes. Have higher
// priority than prelude macros, but create ambiguities with macros in modules.
// 1-3. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents
// (open, not controlled). Have higher priority than prelude macros, but create
// ambiguities with `macro_rules`.
// 4. `macro_use` prelude (open, the open part is from macro expansions, not controlled).
// 4a. User-defined prelude from macro-use
// (open, the open part is from macro expansions, not controlled).
// 4b. Standard library prelude is currently implemented as `macro-use` (closed, controlled)
// 5. Language prelude: builtin macros (closed, controlled, except for legacy plugins).
// 6. Language prelude: builtin attributes (closed, controlled).
// 4-6. Legacy plugin helpers (open, not controlled). Similar to derive helpers,
// but introduced by legacy plugins using `register_attribute`. Priority is somewhere
// in prelude, not sure where exactly (creates ambiguities with any other prelude names).
2019-02-06 17:15:23 +00:00
bitflags::bitflags! {
struct Flags: u8 {
const MACRO_RULES = 1 << 0;
const MODULE = 1 << 1;
const PRELUDE = 1 << 2;
const MISC_SUGGEST_CRATE = 1 << 3;
const MISC_SUGGEST_SELF = 1 << 4;
const MISC_FROM_PRELUDE = 1 << 5;
}
}
assert!(force || !record_used); // `record_used` implies `force`
let mut ident = orig_ident.modern();
// Make sure `self`, `super` etc produce an error when passed to here.
if ident.is_path_segment_keyword() {
return Err(Determinacy::Determined);
}
// This is *the* result, resolution from the scope closest to the resolved identifier.
// However, sometimes this result is "weak" because it comes from a glob import or
// a macro expansion, and in this case it cannot shadow names from outer scopes, e.g.
// mod m { ... } // solution in outer scope
// {
// use prefix::*; // imports another `m` - innermost solution
// // weak, cannot shadow the outer `m`, need to report ambiguity error
// m::mac!();
// }
// So we have to save the innermost solution and continue searching in outer scopes
// to detect potential ambiguities.
2019-02-06 17:15:23 +00:00
let mut innermost_result: Option<(&NameBinding<'_>, Flags)> = None;
// Go through all the scopes and try to resolve the name.
let rust_2015 = orig_ident.span.rust_2015();
let (ns, macro_kind, is_import, is_absolute_path) = match scope_set {
ScopeSet::Import(ns) => (ns, None, true, false),
ScopeSet::AbsolutePath(ns) => (ns, None, false, true),
ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind), false, false),
ScopeSet::Module => (TypeNS, None, false, false),
};
let mut where_to_resolve = match ns {
_ if is_absolute_path => Scope::CrateRoot,
TypeNS | ValueNS => Scope::Module(parent_scope.module),
MacroNS => Scope::DeriveHelpers,
};
let mut use_prelude = !parent_scope.module.no_implicit_prelude;
let mut determinacy = Determinacy::Determined;
2016-11-10 10:29:36 +00:00
loop {
let result = match where_to_resolve {
Scope::DeriveHelpers => {
let mut result = Err(Determinacy::Determined);
for derive in &parent_scope.derives {
let parent_scope = ParentScope { derives: Vec::new(), ..*parent_scope };
match self.resolve_macro_path(derive, MacroKind::Derive,
&parent_scope, true, force) {
Ok((Some(ext), _)) => if ext.helper_attrs.contains(&ident.name) {
let binding = (Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper),
ty::Visibility::Public, derive.span, Mark::root())
.to_name_binding(self.arenas);
result = Ok((binding, Flags::empty()));
break;
}
Ok(_) | Err(Determinacy::Determined) => {}
Err(Determinacy::Undetermined) =>
result = Err(Determinacy::Undetermined),
}
}
result
}
Scope::MacroRules(legacy_scope) => match legacy_scope {
LegacyScope::Binding(legacy_binding) if ident == legacy_binding.ident =>
Ok((legacy_binding.binding, Flags::MACRO_RULES)),
LegacyScope::Invocation(invoc) if invoc.output_legacy_scope.get().is_none() =>
Err(Determinacy::Undetermined),
_ => Err(Determinacy::Determined),
}
Scope::CrateRoot => {
2019-05-11 14:41:37 +00:00
let root_ident = Ident::new(kw::PathRoot, orig_ident.span);
let root_module = self.resolve_crate_root(root_ident);
let binding = self.resolve_ident_in_module_ext(
ModuleOrUniformRoot::Module(root_module),
orig_ident,
ns,
None,
record_used,
path_span,
);
match binding {
Ok(binding) => Ok((binding, Flags::MODULE | Flags::MISC_SUGGEST_CRATE)),
Err((Determinacy::Undetermined, Weak::No)) =>
return Err(Determinacy::determined(force)),
Err((Determinacy::Undetermined, Weak::Yes)) =>
Err(Determinacy::Undetermined),
Err((Determinacy::Determined, _)) => Err(Determinacy::Determined),
}
}
Scope::Module(module) => {
let orig_current_module = mem::replace(&mut self.current_module, module);
let binding = self.resolve_ident_in_module_unadjusted_ext(
ModuleOrUniformRoot::Module(module),
ident,
ns,
None,
true,
record_used,
path_span,
);
self.current_module = orig_current_module;
match binding {
Ok(binding) => {
let misc_flags = if ptr::eq(module, self.graph_root) {
Flags::MISC_SUGGEST_CRATE
} else if module.is_normal() {
Flags::MISC_SUGGEST_SELF
} else {
Flags::empty()
};
Ok((binding, Flags::MODULE | misc_flags))
}
Err((Determinacy::Undetermined, Weak::No)) =>
return Err(Determinacy::determined(force)),
Err((Determinacy::Undetermined, Weak::Yes)) =>
Err(Determinacy::Undetermined),
Err((Determinacy::Determined, _)) => Err(Determinacy::Determined),
}
}
Scope::MacroUsePrelude => {
if use_prelude || rust_2015 {
match self.macro_use_prelude.get(&ident.name).cloned() {
Some(binding) =>
Ok((binding, Flags::PRELUDE | Flags::MISC_FROM_PRELUDE)),
None => Err(Determinacy::determined(
self.graph_root.unresolved_invocations.borrow().is_empty()
))
}
} else {
Err(Determinacy::Determined)
}
}
Scope::BuiltinMacros => {
match self.builtin_macros.get(&ident.name).cloned() {
Some(binding) => Ok((binding, Flags::PRELUDE)),
None => Err(Determinacy::Determined),
}
}
Scope::BuiltinAttrs => {
if is_builtin_attr_name(ident.name) {
let binding = (Res::NonMacroAttr(NonMacroAttrKind::Builtin),
ty::Visibility::Public, DUMMY_SP, Mark::root())
.to_name_binding(self.arenas);
Ok((binding, Flags::PRELUDE))
} else {
Err(Determinacy::Determined)
}
}
Scope::LegacyPluginHelpers => {
if (use_prelude || rust_2015) &&
self.session.plugin_attributes.borrow().iter()
.any(|(name, _)| ident.name == *name) {
let binding = (Res::NonMacroAttr(NonMacroAttrKind::LegacyPluginHelper),
ty::Visibility::Public, DUMMY_SP, Mark::root())
.to_name_binding(self.arenas);
Ok((binding, Flags::PRELUDE))
} else {
Err(Determinacy::Determined)
}
}
Scope::ExternPrelude => {
if use_prelude || is_absolute_path {
2018-11-17 18:08:00 +00:00
match self.extern_prelude_get(ident, !record_used) {
Some(binding) => Ok((binding, Flags::PRELUDE)),
None => Err(Determinacy::determined(
self.graph_root.unresolved_invocations.borrow().is_empty()
)),
}
} else {
Err(Determinacy::Determined)
}
}
Scope::ToolPrelude => {
if use_prelude && is_known_tool(ident.name) {
let binding = (Res::ToolMod, ty::Visibility::Public,
DUMMY_SP, Mark::root()).to_name_binding(self.arenas);
Ok((binding, Flags::PRELUDE))
} else {
Err(Determinacy::Determined)
}
}
Scope::StdLibPrelude => {
let mut result = Err(Determinacy::Determined);
if use_prelude {
if let Some(prelude) = self.prelude {
if let Ok(binding) = self.resolve_ident_in_module_unadjusted(
ModuleOrUniformRoot::Module(prelude),
ident,
ns,
false,
path_span,
) {
result = Ok((binding, Flags::PRELUDE | Flags::MISC_FROM_PRELUDE));
}
}
}
result
}
Scope::BuiltinTypes => {
match self.primitive_type_table.primitive_types.get(&ident.name).cloned() {
Some(prim_ty) => {
let binding = (Res::PrimTy(prim_ty), ty::Visibility::Public,
DUMMY_SP, Mark::root()).to_name_binding(self.arenas);
Ok((binding, Flags::PRELUDE))
}
None => Err(Determinacy::Determined)
}
}
};
match result {
Ok((binding, flags)) if sub_namespace_match(binding.macro_kind(), macro_kind) => {
if !record_used {
return Ok(binding);
}
if let Some((innermost_binding, innermost_flags)) = innermost_result {
// Found another solution, if the first one was "weak", report an error.
let (res, innermost_res) = (binding.res(), innermost_binding.res());
if res != innermost_res {
let builtin = Res::NonMacroAttr(NonMacroAttrKind::Builtin);
let derive_helper = Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper);
let legacy_helper =
Res::NonMacroAttr(NonMacroAttrKind::LegacyPluginHelper);
let ambiguity_error_kind = if is_import {
Some(AmbiguityKind::Import)
} else if innermost_res == builtin || res == builtin {
Some(AmbiguityKind::BuiltinAttr)
} else if innermost_res == derive_helper || res == derive_helper {
Some(AmbiguityKind::DeriveHelper)
} else if innermost_res == legacy_helper &&
flags.contains(Flags::PRELUDE) ||
res == legacy_helper &&
innermost_flags.contains(Flags::PRELUDE) {
Some(AmbiguityKind::LegacyHelperVsPrelude)
} else if innermost_flags.contains(Flags::MACRO_RULES) &&
flags.contains(Flags::MODULE) &&
!self.disambiguate_legacy_vs_modern(innermost_binding,
binding) ||
flags.contains(Flags::MACRO_RULES) &&
innermost_flags.contains(Flags::MODULE) &&
!self.disambiguate_legacy_vs_modern(binding,
innermost_binding) {
Some(AmbiguityKind::LegacyVsModern)
} else if innermost_binding.is_glob_import() {
Some(AmbiguityKind::GlobVsOuter)
} else if innermost_binding.may_appear_after(parent_scope.expansion,
binding) {
Some(AmbiguityKind::MoreExpandedVsOuter)
} else {
None
};
if let Some(kind) = ambiguity_error_kind {
let misc = |f: Flags| if f.contains(Flags::MISC_SUGGEST_CRATE) {
AmbiguityErrorMisc::SuggestCrate
} else if f.contains(Flags::MISC_SUGGEST_SELF) {
AmbiguityErrorMisc::SuggestSelf
} else if f.contains(Flags::MISC_FROM_PRELUDE) {
AmbiguityErrorMisc::FromPrelude
} else {
AmbiguityErrorMisc::None
};
self.ambiguity_errors.push(AmbiguityError {
kind,
ident: orig_ident,
b1: innermost_binding,
b2: binding,
misc1: misc(innermost_flags),
misc2: misc(flags),
});
return Ok(innermost_binding);
}
2016-11-27 10:58:46 +00:00
}
} else {
// Found the first solution.
innermost_result = Some((binding, flags));
}
}
Ok(..) | Err(Determinacy::Determined) => {}
Err(Determinacy::Undetermined) => determinacy = Determinacy::Undetermined
2016-11-10 10:29:36 +00:00
}
where_to_resolve = match where_to_resolve {
Scope::DeriveHelpers =>
Scope::MacroRules(parent_scope.legacy),
Scope::MacroRules(legacy_scope) => match legacy_scope {
LegacyScope::Binding(binding) => Scope::MacroRules(
binding.parent_legacy_scope
),
LegacyScope::Invocation(invoc) => Scope::MacroRules(
invoc.output_legacy_scope.get().unwrap_or(invoc.parent_legacy_scope)
),
LegacyScope::Empty => Scope::Module(parent_scope.module),
}
Scope::CrateRoot => match ns {
TypeNS => {
ident.span.adjust(Mark::root());
Scope::ExternPrelude
}
ValueNS | MacroNS => break,
}
Scope::Module(module) => {
match self.hygienic_lexical_parent(module, &mut ident.span) {
Some(parent_module) => Scope::Module(parent_module),
None => {
ident.span.adjust(Mark::root());
use_prelude = !module.no_implicit_prelude;
match ns {
TypeNS => Scope::ExternPrelude,
ValueNS => Scope::StdLibPrelude,
MacroNS => Scope::MacroUsePrelude,
}
}
}
}
Scope::MacroUsePrelude => Scope::StdLibPrelude,
Scope::BuiltinMacros => Scope::BuiltinAttrs,
Scope::BuiltinAttrs => Scope::LegacyPluginHelpers,
Scope::LegacyPluginHelpers => break, // nowhere else to search
Scope::ExternPrelude if is_absolute_path => break,
Scope::ExternPrelude => Scope::ToolPrelude,
Scope::ToolPrelude => Scope::StdLibPrelude,
Scope::StdLibPrelude => match ns {
TypeNS => Scope::BuiltinTypes,
ValueNS => break, // nowhere else to search
MacroNS => Scope::BuiltinMacros,
}
Scope::BuiltinTypes => break, // nowhere else to search
};
continue;
}
2016-11-10 10:29:36 +00:00
// The first found solution was the only one, return it.
if let Some((binding, _)) = innermost_result {
return Ok(binding);
2016-11-10 10:29:36 +00:00
}
let determinacy = Determinacy::determined(determinacy == Determinacy::Determined || force);
if determinacy == Determinacy::Determined && macro_kind == Some(MacroKind::Attr) {
// For single-segment attributes interpret determinate "no resolution" as a custom
// attribute. (Lexical resolution implies the first segment and attr kind should imply
// the last segment, so we are certainly working with a single-segment attribute here.)
assert!(ns == MacroNS);
let binding = (Res::NonMacroAttr(NonMacroAttrKind::Custom),
ty::Visibility::Public, ident.span, Mark::root())
.to_name_binding(self.arenas);
Ok(binding)
} else {
Err(determinacy)
}
2016-11-10 10:29:36 +00:00
}
pub fn finalize_current_module_macro_resolutions(&mut self) {
let module = self.current_module;
let check_consistency = |this: &mut Self, path: &[Segment], span, kind: MacroKind,
initial_res: Option<Res>, res: Res| {
if let Some(initial_res) = initial_res {
if res != initial_res && res != Res::Err && this.ambiguity_errors.is_empty() {
// Make sure compilation does not succeed if preferred macro resolution
// has changed after the macro had been expanded. In theory all such
// situations should be reported as ambiguity errors, so this is a bug.
if initial_res == Res::NonMacroAttr(NonMacroAttrKind::Custom) {
// Yeah, legacy custom attributes are implemented using forced resolution
// (which is a best effort error recovery tool, basically), so we can't
// promise their resolution won't change later.
let msg = format!("inconsistent resolution for a macro: first {}, then {}",
initial_res.descr(), res.descr());
this.session.span_err(span, &msg);
} else {
span_bug!(span, "inconsistent resolution for a macro");
}
}
} else {
// It's possible that the macro was unresolved (indeterminate) and silently
// expanded into a dummy fragment for recovery during expansion.
// Now, post-expansion, the resolution may succeed, but we can't change the
// past and need to report an error.
// However, non-speculative `resolve_path` can successfully return private items
// even if speculative `resolve_path` returned nothing previously, so we skip this
// less informative error if the privacy error is reported elsewhere.
if this.privacy_errors.is_empty() {
let msg = format!("cannot determine resolution for the {} `{}`",
2018-11-18 11:41:06 +00:00
kind.descr(), Segment::names_to_string(path));
let msg_note = "import resolution is stuck, try simplifying macro imports";
this.session.struct_span_err(span, &msg).note(msg_note).emit();
}
}
};
let macro_resolutions =
2019-06-30 18:30:01 +00:00
mem::take(&mut *module.multi_segment_macro_resolutions.borrow_mut());
for (mut path, path_span, kind, parent_scope, initial_res) in macro_resolutions {
// FIXME: Path resolution will ICE if segment IDs present.
for seg in &mut path { seg.id = None; }
match self.resolve_path(&path, Some(MacroNS), &parent_scope,
true, path_span, CrateLint::No) {
PathResult::NonModule(path_res) if path_res.unresolved_segments() == 0 => {
let res = path_res.base_res();
check_consistency(self, &path, path_span, kind, initial_res, res);
}
2019-01-16 20:30:41 +00:00
path_res @ PathResult::NonModule(..) | path_res @ PathResult::Failed { .. } => {
let (span, label) = if let PathResult::Failed { span, label, .. } = path_res {
(span, label)
} else {
(path_span, format!("partially resolved path in {} {}",
kind.article(), kind.descr()))
};
2019-01-16 20:30:41 +00:00
resolve_error(self, span, ResolutionError::FailedToResolve {
label,
suggestion: None
});
2016-11-27 10:58:46 +00:00
}
PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
2016-11-27 10:58:46 +00:00
}
}
let macro_resolutions =
2019-06-30 18:30:01 +00:00
mem::take(&mut *module.single_segment_macro_resolutions.borrow_mut());
for (ident, kind, parent_scope, initial_binding) in macro_resolutions {
match self.early_resolve_ident_in_lexical_scope(ident, ScopeSet::Macro(kind),
&parent_scope, true, true, ident.span) {
Ok(binding) => {
let initial_res = initial_binding.map(|initial_binding| {
self.record_use(ident, MacroNS, initial_binding, false);
initial_binding.res()
});
let res = binding.res();
2018-11-18 11:41:06 +00:00
let seg = Segment::from_ident(ident);
check_consistency(self, &[seg], ident.span, kind, initial_res, res);
}
Err(..) => {
assert!(initial_binding.is_none());
let bang = if kind == MacroKind::Bang { "!" } else { "" };
let msg =
format!("cannot find {} `{}{}` in this scope", kind.descr(), ident, bang);
let mut err = self.session.struct_span_err(ident.span, &msg);
self.suggest_macro_name(ident.name, kind, &mut err, ident.span);
err.emit();
}
}
2016-10-31 22:17:15 +00:00
}
2019-06-30 18:30:01 +00:00
let builtin_attrs = mem::take(&mut *module.builtin_attrs.borrow_mut());
for (ident, parent_scope) in builtin_attrs {
let _ = self.early_resolve_ident_in_lexical_scope(
ident, ScopeSet::Macro(MacroKind::Attr), &parent_scope, true, true, ident.span
);
}
}
fn check_stability_and_deprecation(&self, ext: &SyntaxExtension, path: &ast::Path) {
let span = path.span;
if let Some(stability) = &ext.stability {
if let StabilityLevel::Unstable { reason, issue } = stability.level {
let feature = stability.feature;
if !self.active_features.contains(&feature) && !span.allows_unstable(feature) {
stability::report_unstable(self.session, feature, reason, issue, span);
}
}
if let Some(depr) = &stability.rustc_depr {
let (message, lint) = stability::rustc_deprecation_message(depr, &path.to_string());
stability::early_report_deprecation(
self.session, &message, depr.suggestion, lint, span
);
}
}
if let Some(depr) = &ext.deprecation {
let (message, lint) = stability::deprecation_message(depr, &path.to_string());
stability::early_report_deprecation(self.session, &message, None, lint, span);
}
}
fn prohibit_imported_non_macro_attrs(&self, binding: Option<&'a NameBinding<'a>>,
res: Option<Res>, span: Span) {
if let Some(Res::NonMacroAttr(kind)) = res {
if kind != NonMacroAttrKind::Tool && binding.map_or(true, |b| b.is_import()) {
let msg = format!("cannot use a {} through an import", kind.descr());
let mut err = self.session.struct_span_err(span, &msg);
if let Some(binding) = binding {
err.span_note(binding.span, &format!("the {} imported here", kind.descr()));
}
err.emit();
}
}
}
crate fn check_reserved_macro_name(&mut self, ident: Ident, res: Res) {
// Reserve some names that are not quite covered by the general check
// performed on `Resolver::builtin_attrs`.
if ident.name == sym::cfg || ident.name == sym::cfg_attr || ident.name == sym::derive {
let macro_kind = self.get_macro(res).map(|ext| ext.macro_kind());
if macro_kind.is_some() && sub_namespace_match(macro_kind, Some(MacroKind::Attr)) {
self.session.span_err(
ident.span, &format!("name `{}` is reserved in attribute namespace", ident)
);
}
}
}
pub fn define_macro(&mut self,
item: &ast::Item,
expansion: Mark,
current_legacy_scope: &mut LegacyScope<'a>) {
let (ext, ident, span, is_legacy) = match &item.node {
ItemKind::MacroDef(def) => {
let ext = Lrc::new(macro_rules::compile(
&self.session.parse_sess,
&self.session.features_untracked(),
item,
self.session.edition(),
));
(ext, item.ident, item.span, def.legacy)
}
ItemKind::Fn(..) => match proc_macro_stub(item) {
Some((macro_kind, ident, span)) => {
self.proc_macro_stubs.insert(item.id);
(self.dummy_ext(macro_kind), ident, span, false)
}
None => return,
}
_ => unreachable!(),
};
let def_id = self.definitions.local_def_id(item.id);
let res = Res::Def(DefKind::Macro(ext.macro_kind()), def_id);
self.macro_map.insert(def_id, ext);
self.local_macro_def_scopes.insert(item.id, self.current_module);
if is_legacy {
2017-03-22 08:39:51 +00:00
let ident = ident.modern();
self.macro_names.insert(ident);
let is_macro_export = attr::contains_name(&item.attrs, sym::macro_export);
let vis = if is_macro_export {
ty::Visibility::Public
} else {
ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))
};
let binding = (res, vis, span, expansion).to_name_binding(self.arenas);
self.set_binding_parent_module(binding, self.current_module);
let legacy_binding = self.arenas.alloc_legacy_binding(LegacyBinding {
parent_legacy_scope: *current_legacy_scope, binding, ident
});
*current_legacy_scope = LegacyScope::Binding(legacy_binding);
self.all_macros.insert(ident.name, res);
if is_macro_export {
2018-05-14 00:22:52 +00:00
let module = self.graph_root;
self.define(module, ident, MacroNS,
(res, vis, span, expansion, IsMacroExport));
} else {
self.check_reserved_macro_name(ident, res);
self.unused_macros.insert(item.id, span);
}
2017-05-11 08:26:07 +00:00
} else {
let module = self.current_module;
let vis = self.resolve_visibility(&item.vis);
if vis != ty::Visibility::Public {
self.unused_macros.insert(item.id, span);
}
self.define(module, ident, MacroNS, (res, vis, span, expansion));
}
}
}