Auto merge of #29387 - little-dude:rustfmt_librustc_resolve, r=nrc

Another rustfmt PR.
I ran rustfmt, then split the changes in multiple commits. First commit are the non-problematic changed. The others are all the little weirdness that caught my attention and could be discussed.
This commit is contained in:
bors
2015-11-15 22:07:12 +00:00
6 changed files with 1216 additions and 1186 deletions
+266 -255
View File
@@ -66,7 +66,7 @@ enum DuplicateCheckingMode {
ForbidDuplicateTypesAndModules,
ForbidDuplicateValues,
ForbidDuplicateTypesAndValues,
OverwriteDuplicates
OverwriteDuplicates,
}
#[derive(Copy, Clone, PartialEq)]
@@ -74,19 +74,19 @@ enum NamespaceError {
NoError,
ModuleError,
TypeError,
ValueError
ValueError,
}
fn namespace_error_to_string(ns: NamespaceError) -> &'static str {
match ns {
NoError => "",
NoError => "",
ModuleError | TypeError => "type or module",
ValueError => "value",
ValueError => "value",
}
}
struct GraphBuilder<'a, 'b:'a, 'tcx:'b> {
resolver: &'a mut Resolver<'b, 'tcx>
struct GraphBuilder<'a, 'b: 'a, 'tcx: 'b> {
resolver: &'a mut Resolver<'b, 'tcx>,
}
impl<'a, 'b:'a, 'tcx:'b> Deref for GraphBuilder<'a, 'b, 'tcx> {
@@ -109,7 +109,7 @@ fn build_reduced_graph(self, krate: &hir::Crate) {
let parent = self.graph_root.get_module();
let mut visitor = BuildReducedGraphVisitor {
builder: self,
parent: parent
parent: parent,
};
visit::walk_crate(&mut visitor, krate);
}
@@ -135,9 +135,7 @@ fn add_child(&self,
// child name directly. Otherwise, we create or reuse an anonymous
// module and add the child to that.
self.check_for_conflicts_between_external_crates_and_items(&**parent,
name,
sp);
self.check_for_conflicts_between_external_crates_and_items(&**parent, name, sp);
// Add or reuse the child.
let child = parent.children.borrow().get(&name).cloned();
@@ -194,14 +192,14 @@ fn add_child(&self,
n = Some(TypeNS);
duplicate_type = TypeError;
}
};
}
if child.defined_in_namespace(ValueNS) {
duplicate_type = ValueError;
n = Some(ValueNS);
}
n
}
OverwriteDuplicates => None
OverwriteDuplicates => None,
};
if duplicate_type != NoError {
// Return an error here by looking up the namespace that
@@ -218,7 +216,7 @@ fn add_child(&self,
let r = child.span_for_namespace(ns);
if let Some(sp) = r {
self.session.span_note(sp,
&format!("first definition of {} `{}` here",
&format!("first definition of {} `{}` here",
namespace_error_to_string(duplicate_type),
name));
}
@@ -278,15 +276,20 @@ fn build_reduced_graph_for_item(&mut self, item: &Item, parent: &Rc<Module>) ->
let module_path = match view_path.node {
ViewPathSimple(_, ref full_path) => {
full_path.segments
.split_last().unwrap().1
.iter().map(|seg| seg.identifier.name)
.collect()
.split_last()
.unwrap()
.1
.iter()
.map(|seg| seg.identifier.name)
.collect()
}
ViewPathGlob(ref module_ident_path) |
ViewPathList(ref module_ident_path, _) => {
module_ident_path.segments
.iter().map(|seg| seg.identifier.name).collect()
.iter()
.map(|seg| seg.identifier.name)
.collect()
}
};
@@ -302,8 +305,7 @@ fn build_reduced_graph_for_item(&mut self, item: &Item, parent: &Rc<Module>) ->
match view_path.node {
ViewPathSimple(binding, ref full_path) => {
let source_name =
full_path.segments.last().unwrap().identifier.name;
let source_name = full_path.segments.last().unwrap().identifier.name;
if source_name.as_str() == "mod" || source_name.as_str() == "self" {
resolve_error(self,
view_path.span,
@@ -321,19 +323,21 @@ fn build_reduced_graph_for_item(&mut self, item: &Item, parent: &Rc<Module>) ->
}
ViewPathList(_, ref source_items) => {
// Make sure there's at most one `mod` import in the list.
let mod_spans = source_items.iter().filter_map(|item| match item.node {
PathListMod { .. } => Some(item.span),
_ => None
}).collect::<Vec<Span>>();
let mod_spans = source_items.iter()
.filter_map(|item| {
match item.node {
PathListMod { .. } => Some(item.span),
_ => None,
}
})
.collect::<Vec<Span>>();
if mod_spans.len() > 1 {
resolve_error(
self,
mod_spans[0],
ResolutionError::SelfImportCanOnlyAppearOnceInTheList
);
resolve_error(self,
mod_spans[0],
ResolutionError::SelfImportCanOnlyAppearOnceInTheList);
for other_span in mod_spans.iter().skip(1) {
self.session.span_note(*other_span,
"another `self` import appears here");
self.session
.span_note(*other_span, "another `self` import appears here");
}
}
@@ -359,14 +363,13 @@ fn build_reduced_graph_for_item(&mut self, item: &Item, parent: &Rc<Module>) ->
(module_path.to_vec(), name, rename)
}
};
self.build_import_directive(
&**parent,
module_path,
SingleImport(rename, name),
source_item.span,
source_item.node.id(),
is_public,
shadowable);
self.build_import_directive(&**parent,
module_path,
SingleImport(rename, name),
source_item.span,
source_item.node.id(),
is_public,
shadowable);
}
}
ViewPathGlob(_) => {
@@ -383,9 +386,13 @@ fn build_reduced_graph_for_item(&mut self, item: &Item, parent: &Rc<Module>) ->
}
ItemExternCrate(_) => {
// n.b. we don't need to look at the path option here, because cstore already did
// n.b. we don't need to look at the path option here, because cstore already
// did
if let Some(crate_id) = self.session.cstore.find_extern_mod_stmt_cnum(item.id) {
let def_id = DefId { krate: crate_id, index: CRATE_DEF_INDEX };
let def_id = DefId {
krate: crate_id,
index: CRATE_DEF_INDEX,
};
self.external_exports.insert(def_id);
let parent_link = ModuleParentLink(Rc::downgrade(parent), name);
let external_module = Rc::new(Module::new(parent_link,
@@ -394,9 +401,10 @@ fn build_reduced_graph_for_item(&mut self, item: &Item, parent: &Rc<Module>) ->
false,
true));
debug!("(build reduced graph for item) found extern `{}`",
module_to_string(&*external_module));
module_to_string(&*external_module));
self.check_for_conflicts_between_external_crates(&**parent, name, sp);
parent.external_module_children.borrow_mut()
parent.external_module_children
.borrow_mut()
.insert(name, external_module.clone());
self.build_reduced_graph_for_external_crate(&external_module);
}
@@ -407,20 +415,19 @@ fn build_reduced_graph_for_item(&mut self, item: &Item, parent: &Rc<Module>) ->
let child = parent.children.borrow().get(&name).cloned();
if let Some(child) = child {
// check if there's struct of the same name already defined
if child.defined_in_namespace(TypeNS)
&& child.get_module_if_available().is_none() {
self.session.span_warn(sp, &format!(
"duplicate definition of {} `{}`. \
Defining a module and a struct with \
the same name will be disallowed \
soon.",
namespace_error_to_string(TypeError),
name));
if child.defined_in_namespace(TypeNS) &&
child.get_module_if_available().is_none() {
self.session.span_warn(sp,
&format!("duplicate definition of {} `{}`. \
Defining a module and a struct with \
the same name will be disallowed soon.",
namespace_error_to_string(TypeError),
name));
{
let r = child.span_for_namespace(TypeNS);
if let Some(sp) = r {
self.session.span_note(sp,
&format!("first definition of {} `{}` here",
&format!("first definition of {} `{}` here",
namespace_error_to_string(TypeError),
name));
}
@@ -468,10 +475,13 @@ fn build_reduced_graph_for_item(&mut self, item: &Item, parent: &Rc<Module>) ->
// These items live in the type namespace.
ItemTy(..) => {
let name_bindings =
self.add_child(name, parent, ForbidDuplicateTypesAndModules, sp);
let name_bindings = self.add_child(name,
parent,
ForbidDuplicateTypesAndModules,
sp);
name_bindings.define_type(DefTy(self.ast_map.local_def_id(item.id), false), sp,
name_bindings.define_type(DefTy(self.ast_map.local_def_id(item.id), false),
sp,
modifiers);
let parent_link = self.get_parent_link(parent, name);
@@ -485,8 +495,10 @@ fn build_reduced_graph_for_item(&mut self, item: &Item, parent: &Rc<Module>) ->
}
ItemEnum(ref enum_definition, _) => {
let name_bindings =
self.add_child(name, parent, ForbidDuplicateTypesAndModules, sp);
let name_bindings = self.add_child(name,
parent,
ForbidDuplicateTypesAndModules,
sp);
name_bindings.define_type(DefTy(self.ast_map.local_def_id(item.id), true),
sp,
@@ -504,10 +516,7 @@ fn build_reduced_graph_for_item(&mut self, item: &Item, parent: &Rc<Module>) ->
for variant in &(*enum_definition).variants {
let item_def_id = self.ast_map.local_def_id(item.id);
self.build_reduced_graph_for_variant(
&**variant,
item_def_id,
&module);
self.build_reduced_graph_for_variant(&**variant, item_def_id, &module);
}
parent.clone()
}
@@ -522,20 +531,21 @@ fn build_reduced_graph_for_item(&mut self, item: &Item, parent: &Rc<Module>) ->
if let Some(child) = child {
// check if theres a DefMod
if let Some(DefMod(_)) = child.def_for_namespace(TypeNS) {
self.session.span_warn(sp, &format!(
"duplicate definition of {} `{}`. \
Defining a module and a struct with \
the same name will be disallowed \
soon.",
namespace_error_to_string(TypeError),
name));
self.session.span_warn(sp,
&format!("duplicate definition of {} `{}`. \
Defining a module and a struct \
with the same name will be \
disallowed soon.",
namespace_error_to_string(TypeError),
name));
{
let r = child.span_for_namespace(TypeNS);
if let Some(sp) = r {
self.session.span_note(sp,
&format!("first definition of {} `{}` here",
namespace_error_to_string(TypeError),
name));
self.session
.span_note(sp,
&format!("first definition of {} `{}` here",
namespace_error_to_string(TypeError),
name));
}
}
}
@@ -559,12 +569,15 @@ fn build_reduced_graph_for_item(&mut self, item: &Item, parent: &Rc<Module>) ->
}
// Record the def ID and fields of this struct.
let named_fields = struct_def.fields().iter().filter_map(|f| {
match f.node.kind {
NamedField(name, _) => Some(name),
UnnamedField(_) => None
}
}).collect();
let named_fields = struct_def.fields()
.iter()
.filter_map(|f| {
match f.node.kind {
NamedField(name, _) => Some(name),
UnnamedField(_) => None,
}
})
.collect();
let item_def_id = self.ast_map.local_def_id(item.id);
self.structs.insert(item_def_id, named_fields);
@@ -575,8 +588,10 @@ fn build_reduced_graph_for_item(&mut self, item: &Item, parent: &Rc<Module>) ->
ItemImpl(..) => parent.clone(),
ItemTrait(_, _, _, ref items) => {
let name_bindings =
self.add_child(name, parent, ForbidDuplicateTypesAndModules, sp);
let name_bindings = self.add_child(name,
parent,
ForbidDuplicateTypesAndModules,
sp);
// Add all the items within to a new module.
let parent_link = self.get_parent_link(parent, name);
@@ -593,9 +608,9 @@ fn build_reduced_graph_for_item(&mut self, item: &Item, parent: &Rc<Module>) ->
// Add the names of all the items to the trait info.
for trait_item in items {
let name_bindings = self.add_child(trait_item.name,
&module_parent,
ForbidDuplicateTypesAndValues,
trait_item.span);
&module_parent,
ForbidDuplicateTypesAndValues,
trait_item.span);
match trait_item.node {
hir::ConstTraitItem(..) => {
@@ -642,19 +657,19 @@ fn build_reduced_graph_for_variant(&mut self,
false
};
let child = self.add_child(name, parent,
ForbidDuplicateTypesAndValues,
variant.span);
let child = self.add_child(name, parent, ForbidDuplicateTypesAndValues, variant.span);
// variants are always treated as importable to allow them to be glob
// used
child.define_value(DefVariant(item_id,
self.ast_map.local_def_id(variant.node.data.id()),
is_exported),
variant.span, DefModifiers::PUBLIC | DefModifiers::IMPORTABLE);
variant.span,
DefModifiers::PUBLIC | DefModifiers::IMPORTABLE);
child.define_type(DefVariant(item_id,
self.ast_map.local_def_id(variant.node.data.id()),
is_exported),
variant.span, DefModifiers::PUBLIC | DefModifiers::IMPORTABLE);
variant.span,
DefModifiers::PUBLIC | DefModifiers::IMPORTABLE);
}
/// Constructs the reduced graph for one foreign item.
@@ -668,9 +683,7 @@ fn build_reduced_graph_for_foreign_item(&mut self,
} else {
DefModifiers::empty()
} | DefModifiers::IMPORTABLE;
let name_bindings =
self.add_child(name, parent, ForbidDuplicateValues,
foreign_item.span);
let name_bindings = self.add_child(name, parent, ForbidDuplicateValues, foreign_item.span);
let def = match foreign_item.node {
ForeignItemFn(..) => {
@@ -687,16 +700,15 @@ fn build_reduced_graph_for_block(&mut self, block: &Block, parent: &Rc<Module>)
if self.block_needs_anonymous_module(block) {
let block_id = block.id;
debug!("(building reduced graph for block) creating a new \
anonymous module for block {}",
debug!("(building reduced graph for block) creating a new anonymous module for block \
{}",
block_id);
let new_module = Rc::new(Module::new(
BlockParentLink(Rc::downgrade(parent), block_id),
None,
AnonymousModuleKind,
false,
false));
let new_module = Rc::new(Module::new(BlockParentLink(Rc::downgrade(parent), block_id),
None,
AnonymousModuleKind,
false,
false));
parent.anonymous_children.borrow_mut().insert(block_id, new_module.clone());
new_module
} else {
@@ -711,18 +723,19 @@ fn handle_external_def(&mut self,
final_ident: &str,
name: Name,
new_parent: &Rc<Module>) {
debug!("(building reduced graph for \
external crate) building external def {}, priv {:?}",
final_ident, vis);
debug!("(building reduced graph for external crate) building external def {}, priv {:?}",
final_ident,
vis);
let is_public = vis == hir::Public;
let modifiers = if is_public {
DefModifiers::PUBLIC
} else {
DefModifiers::empty()
} | DefModifiers::IMPORTABLE;
let is_exported = is_public && match new_parent.def_id.get() {
let is_exported = is_public &&
match new_parent.def_id.get() {
None => true,
Some(did) => self.external_exports.contains(&did)
Some(did) => self.external_exports.contains(&did),
};
if is_exported {
self.external_exports.insert(def.def_id());
@@ -731,140 +744,148 @@ fn handle_external_def(&mut self,
let kind = match def {
DefTy(_, true) => EnumModuleKind,
DefTy(_, false) | DefStruct(..) => TypeModuleKind,
_ => NormalModuleKind
_ => NormalModuleKind,
};
match def {
DefMod(def_id) | DefForeignMod(def_id) | DefStruct(def_id) |
DefTy(def_id, _) => {
let type_def = child_name_bindings.type_def.borrow().clone();
match type_def {
Some(TypeNsDef { module_def: Some(module_def), .. }) => {
debug!("(building reduced graph for external crate) \
already created module");
module_def.def_id.set(Some(def_id));
}
Some(_) | None => {
debug!("(building reduced graph for \
external crate) building module \
{} {}", final_ident, is_public);
let parent_link = self.get_parent_link(new_parent, name);
DefMod(def_id) |
DefForeignMod(def_id) |
DefStruct(def_id) |
DefTy(def_id, _) => {
let type_def = child_name_bindings.type_def.borrow().clone();
match type_def {
Some(TypeNsDef { module_def: Some(module_def), .. }) => {
debug!("(building reduced graph for external crate) already created \
module");
module_def.def_id.set(Some(def_id));
}
Some(_) | None => {
debug!("(building reduced graph for external crate) building module {} {}",
final_ident,
is_public);
let parent_link = self.get_parent_link(new_parent, name);
child_name_bindings.define_module(parent_link,
Some(def_id),
kind,
true,
is_public,
DUMMY_SP);
}
child_name_bindings.define_module(parent_link,
Some(def_id),
kind,
true,
is_public,
DUMMY_SP);
}
}
}
}
_ => {}
_ => {}
}
match def {
DefMod(_) | DefForeignMod(_) => {}
DefVariant(_, variant_id, is_struct) => {
debug!("(building reduced graph for external crate) building \
variant {}",
final_ident);
// variants are always treated as importable to allow them to be
// glob used
let modifiers = DefModifiers::PUBLIC | DefModifiers::IMPORTABLE;
if is_struct {
child_name_bindings.define_type(def, DUMMY_SP, modifiers);
// Not adding fields for variants as they are not accessed with a self receiver
self.structs.insert(variant_id, Vec::new());
} else {
child_name_bindings.define_value(def, DUMMY_SP, modifiers);
}
}
DefFn(ctor_id, true) => {
child_name_bindings.define_value(
DefMod(_) | DefForeignMod(_) => {}
DefVariant(_, variant_id, is_struct) => {
debug!("(building reduced graph for external crate) building variant {}",
final_ident);
// variants are always treated as importable to allow them to be
// glob used
let modifiers = DefModifiers::PUBLIC | DefModifiers::IMPORTABLE;
if is_struct {
child_name_bindings.define_type(def, DUMMY_SP, modifiers);
// Not adding fields for variants as they are not accessed with a self receiver
self.structs.insert(variant_id, Vec::new());
} else {
child_name_bindings.define_value(def, DUMMY_SP, modifiers);
}
}
DefFn(ctor_id, true) => {
child_name_bindings.define_value(
csearch::get_tuple_struct_definition_if_ctor(&self.session.cstore, ctor_id)
.map_or(def, |_| DefStruct(ctor_id)), DUMMY_SP, modifiers);
}
DefFn(..) | DefStatic(..) | DefConst(..) | DefAssociatedConst(..) |
DefMethod(..) => {
debug!("(building reduced graph for external \
crate) building value (fn/static) {}", final_ident);
// impl methods have already been defined with the correct importability modifier
let mut modifiers = match *child_name_bindings.value_def.borrow() {
Some(ref def) => (modifiers & !DefModifiers::IMPORTABLE) |
(def.modifiers & DefModifiers::IMPORTABLE),
None => modifiers
};
if new_parent.kind.get() != NormalModuleKind {
modifiers = modifiers & !DefModifiers::IMPORTABLE;
}
child_name_bindings.define_value(def, DUMMY_SP, modifiers);
}
DefTrait(def_id) => {
debug!("(building reduced graph for external \
crate) building type {}", final_ident);
// If this is a trait, add all the trait item names to the trait
// info.
let trait_item_def_ids =
csearch::get_trait_item_def_ids(&self.session.cstore, def_id);
for trait_item_def in &trait_item_def_ids {
let trait_item_name = csearch::get_trait_name(&self.session.cstore,
trait_item_def.def_id());
debug!("(building reduced graph for external crate) ... \
adding trait item '{}'",
trait_item_name);
self.trait_item_map.insert((trait_item_name, def_id),
trait_item_def.def_id());
if is_exported {
self.external_exports.insert(trait_item_def.def_id());
}
}
child_name_bindings.define_type(def, DUMMY_SP, modifiers);
// Define a module if necessary.
let parent_link = self.get_parent_link(new_parent, name);
child_name_bindings.set_module_kind(parent_link,
Some(def_id),
TraitModuleKind,
true,
is_public,
DUMMY_SP)
}
DefTy(..) | DefAssociatedTy(..) => {
debug!("(building reduced graph for external \
crate) building type {}", final_ident);
let modifiers = match new_parent.kind.get() {
NormalModuleKind => modifiers,
_ => modifiers & !DefModifiers::IMPORTABLE
};
child_name_bindings.define_type(def, DUMMY_SP, modifiers);
}
DefStruct(def_id) => {
debug!("(building reduced graph for external \
crate) building type and value for {}",
final_ident);
child_name_bindings.define_type(def, DUMMY_SP, modifiers);
let fields = csearch::get_struct_field_names(&self.session.cstore, def_id);
if fields.is_empty() {
DefFn(..) |
DefStatic(..) |
DefConst(..) |
DefAssociatedConst(..) |
DefMethod(..) => {
debug!("(building reduced graph for external crate) building value (fn/static) {}",
final_ident);
// impl methods have already been defined with the correct importability
// modifier
let mut modifiers = match *child_name_bindings.value_def.borrow() {
Some(ref def) => (modifiers & !DefModifiers::IMPORTABLE) |
(def.modifiers & DefModifiers::IMPORTABLE),
None => modifiers,
};
if new_parent.kind.get() != NormalModuleKind {
modifiers = modifiers & !DefModifiers::IMPORTABLE;
}
child_name_bindings.define_value(def, DUMMY_SP, modifiers);
}
DefTrait(def_id) => {
debug!("(building reduced graph for external crate) building type {}",
final_ident);
// Record the def ID and fields of this struct.
self.structs.insert(def_id, fields);
}
DefLocal(..) | DefPrimTy(..) | DefTyParam(..) |
DefUse(..) | DefUpvar(..) |
DefLabel(..) | DefSelfTy(..) => {
panic!("didn't expect `{:?}`", def);
}
// If this is a trait, add all the trait item names to the trait
// info.
let trait_item_def_ids = csearch::get_trait_item_def_ids(&self.session.cstore,
def_id);
for trait_item_def in &trait_item_def_ids {
let trait_item_name = csearch::get_trait_name(&self.session.cstore,
trait_item_def.def_id());
debug!("(building reduced graph for external crate) ... adding trait item \
'{}'",
trait_item_name);
self.trait_item_map.insert((trait_item_name, def_id), trait_item_def.def_id());
if is_exported {
self.external_exports.insert(trait_item_def.def_id());
}
}
child_name_bindings.define_type(def, DUMMY_SP, modifiers);
// Define a module if necessary.
let parent_link = self.get_parent_link(new_parent, name);
child_name_bindings.set_module_kind(parent_link,
Some(def_id),
TraitModuleKind,
true,
is_public,
DUMMY_SP)
}
DefTy(..) | DefAssociatedTy(..) => {
debug!("(building reduced graph for external crate) building type {}",
final_ident);
let modifiers = match new_parent.kind.get() {
NormalModuleKind => modifiers,
_ => modifiers & !DefModifiers::IMPORTABLE,
};
child_name_bindings.define_type(def, DUMMY_SP, modifiers);
}
DefStruct(def_id) => {
debug!("(building reduced graph for external crate) building type and value for \
{}",
final_ident);
child_name_bindings.define_type(def, DUMMY_SP, modifiers);
let fields = csearch::get_struct_field_names(&self.session.cstore, def_id);
if fields.is_empty() {
child_name_bindings.define_value(def, DUMMY_SP, modifiers);
}
// Record the def ID and fields of this struct.
self.structs.insert(def_id, fields);
}
DefLocal(..) |
DefPrimTy(..) |
DefTyParam(..) |
DefUse(..) |
DefUpvar(..) |
DefLabel(..) |
DefSelfTy(..) => {
panic!("didn't expect `{:?}`", def);
}
}
}
@@ -894,11 +915,10 @@ fn build_reduced_graph_for_external_crate_def(&mut self,
});
}
_ => {
let child_name_bindings =
self.add_child(name,
root,
OverwriteDuplicates,
DUMMY_SP);
let child_name_bindings = self.add_child(name,
root,
OverwriteDuplicates,
DUMMY_SP);
self.handle_external_def(def,
def_visibility,
@@ -910,12 +930,10 @@ fn build_reduced_graph_for_external_crate_def(&mut self,
}
}
DlImpl(_) => {
debug!("(building reduced graph for external crate) \
ignoring impl");
debug!("(building reduced graph for external crate) ignoring impl");
}
DlField => {
debug!("(building reduced graph for external crate) \
ignoring field");
debug!("(building reduced graph for external crate) ignoring field");
}
}
}
@@ -928,7 +946,7 @@ fn populate_external_module(&mut self, module: &Rc<Module>) {
let def_id = match module.def_id.get() {
None => {
debug!("(populating external module) ... no def ID!");
return
return;
}
Some(def_id) => def_id,
};
@@ -936,13 +954,13 @@ fn populate_external_module(&mut self, module: &Rc<Module>) {
csearch::each_child_of_item(&self.session.cstore,
def_id,
|def_like, child_name, visibility| {
debug!("(populating external module) ... found ident: {}",
child_name);
self.build_reduced_graph_for_external_crate_def(module,
def_like,
child_name,
visibility)
});
debug!("(populating external module) ... found ident: {}",
child_name);
self.build_reduced_graph_for_external_crate_def(module,
def_like,
child_name,
visibility)
});
module.populated.set(true)
}
@@ -977,12 +995,9 @@ fn build_import_directive(&mut self,
id: NodeId,
is_public: bool,
shadowable: Shadowable) {
module_.imports.borrow_mut().push(ImportDirective::new(module_path,
subclass,
span,
id,
is_public,
shadowable));
module_.imports
.borrow_mut()
.push(ImportDirective::new(module_path, subclass, span, id, is_public, shadowable));
self.unresolved_imports += 1;
if is_public {
@@ -1030,9 +1045,9 @@ fn build_import_directive(&mut self,
}
}
struct BuildReducedGraphVisitor<'a, 'b:'a, 'tcx:'b> {
struct BuildReducedGraphVisitor<'a, 'b: 'a, 'tcx: 'b> {
builder: GraphBuilder<'a, 'b, 'tcx>,
parent: Rc<Module>
parent: Rc<Module>,
}
impl<'a, 'b, 'v, 'tcx> Visitor<'v> for BuildReducedGraphVisitor<'a, 'b, 'tcx> {
@@ -1056,13 +1071,9 @@ fn visit_block(&mut self, block: &Block) {
}
pub fn build_reduced_graph(resolver: &mut Resolver, krate: &hir::Crate) {
GraphBuilder {
resolver: resolver
}.build_reduced_graph(krate);
GraphBuilder { resolver: resolver }.build_reduced_graph(krate);
}
pub fn populate_module_if_necessary(resolver: &mut Resolver, module: &Rc<Module>) {
GraphBuilder {
resolver: resolver
}.populate_module_if_necessary(module);
GraphBuilder { resolver: resolver }.populate_module_if_necessary(module);
}
+13 -13
View File
@@ -31,8 +31,8 @@
use rustc_front::hir::{ViewPathGlob, ViewPathList, ViewPathSimple};
use rustc_front::visit::{self, Visitor};
struct UnusedImportCheckVisitor<'a, 'b:'a, 'tcx:'b> {
resolver: &'a mut Resolver<'b, 'tcx>
struct UnusedImportCheckVisitor<'a, 'b: 'a, 'tcx: 'b> {
resolver: &'a mut Resolver<'b, 'tcx>,
}
// Deref and DerefMut impls allow treating UnusedImportCheckVisitor as Resolver.
@@ -51,16 +51,16 @@ fn deref_mut<'c>(&'c mut self) -> &'c mut Resolver<'b, 'tcx> {
}
impl<'a, 'b, 'tcx> UnusedImportCheckVisitor<'a, 'b, 'tcx> {
// We have information about whether `use` (import) directives are actually used now.
// If an import is not used at all, we signal a lint error. If an import is only used
// for a single namespace, we remove the other namespace from the recorded privacy
// information. That means in privacy.rs, we will only check imports and namespaces
// which are used. In particular, this means that if an import could name either a
// public or private item, we will check the correct thing, dependent on how the import
// is used.
// We have information about whether `use` (import) directives are actually
// used now. If an import is not used at all, we signal a lint error. If an
// import is only used for a single namespace, we remove the other namespace
// from the recorded privacy information. That means in privacy.rs, we will
// only check imports and namespaces which are used. In particular, this
// means that if an import could name either a public or private item, we
// will check the correct thing, dependent on how the import is used.
fn finalize_import(&mut self, id: ast::NodeId, span: Span) {
debug!("finalizing import uses for {:?}",
self.session.codemap().span_to_snippet(span));
self.session.codemap().span_to_snippet(span));
if !self.used_imports.contains(&(id, TypeNS)) &&
!self.used_imports.contains(&(id, ValueNS)) {
@@ -99,14 +99,14 @@ fn finalize_import(&mut self, id: ast::NodeId, span: Span) {
// we might have two LastPrivates pointing at the same thing. There is no point
// checking both, so lets not check the value one.
(Some(DependsOn(def_v)), Some(DependsOn(def_t))) if def_v == def_t => v_used = Unused,
_ => {},
_ => {}
}
path_res.last_private = LastImport {
value_priv: v_priv,
value_used: v_used,
type_priv: t_priv,
type_used: t_used
type_used: t_used,
};
}
}
@@ -132,7 +132,7 @@ fn visit_item(&mut self, item: &hir::Item) {
"unused extern crate".to_string());
}
}
},
}
hir::ItemUse(ref p) => {
match p.node {
ViewPathSimple(_, _) => {
+3 -3
View File
@@ -10,9 +10,9 @@
#![allow(non_snake_case)]
// Error messages for EXXXX errors.
// Each message should start and end with a new line, and be wrapped to 80 characters.
// In vim you can `:set tw=80` and use `gq` to wrap paragraphs. Use `:set tw=0` to disable.
// Error messages for EXXXX errors. Each message should start and end with a
// new line, and be wrapped to 80 characters. In vim you can `:set tw=80` and
// use `gq` to wrap paragraphs. Use `:set tw=0` to disable.
register_long_diagnostics! {
E0154: r##"
+746 -714
View File
@@ -25,9 +25,13 @@
#![feature(rustc_private)]
#![feature(staged_api)]
#[macro_use] extern crate log;
#[macro_use] extern crate syntax;
#[macro_use] #[no_link] extern crate rustc_bitflags;
#[macro_use]
extern crate log;
#[macro_use]
extern crate syntax;
#[macro_use]
#[no_link]
extern crate rustc_bitflags;
extern crate rustc_front;
extern crate rustc;
@@ -198,208 +202,279 @@ pub enum ResolutionError<'a> {
AttemptToUseNonConstantValueInConstant,
}
fn resolve_error<'b, 'a:'b, 'tcx:'a>(resolver: &'b Resolver<'a, 'tcx>, span: syntax::codemap::Span,
resolution_error: ResolutionError<'b>) {
fn resolve_error<'b, 'a: 'b, 'tcx: 'a>(resolver: &'b Resolver<'a, 'tcx>,
span: syntax::codemap::Span,
resolution_error: ResolutionError<'b>) {
if !resolver.emit_errors {
return;
}
match resolution_error {
ResolutionError::TypeParametersFromOuterFunction => {
span_err!(resolver.session, span, E0401, "can't use type parameters from \
outer function; try using a local \
type parameter instead");
},
span_err!(resolver.session,
span,
E0401,
"can't use type parameters from outer function; try using a local type \
parameter instead");
}
ResolutionError::OuterTypeParameterContext => {
span_err!(resolver.session, span, E0402,
"cannot use an outer type parameter in this context");
},
span_err!(resolver.session,
span,
E0402,
"cannot use an outer type parameter in this context");
}
ResolutionError::NameAlreadyUsedInTypeParameterList(name) => {
span_err!(resolver.session, span, E0403,
"the name `{}` is already used for a type \
parameter in this type parameter list", name);
},
span_err!(resolver.session,
span,
E0403,
"the name `{}` is already used for a type parameter in this type parameter \
list",
name);
}
ResolutionError::IsNotATrait(name) => {
span_err!(resolver.session, span, E0404,
"`{}` is not a trait",
name);
},
span_err!(resolver.session, span, E0404, "`{}` is not a trait", name);
}
ResolutionError::UndeclaredTraitName(name) => {
span_err!(resolver.session, span, E0405,
"use of undeclared trait name `{}`",
name);
},
span_err!(resolver.session,
span,
E0405,
"use of undeclared trait name `{}`",
name);
}
ResolutionError::UndeclaredAssociatedType => {
span_err!(resolver.session, span, E0406, "undeclared associated type");
},
}
ResolutionError::MethodNotMemberOfTrait(method, trait_) => {
span_err!(resolver.session, span, E0407,
"method `{}` is not a member of trait `{}`",
method,
trait_);
},
span_err!(resolver.session,
span,
E0407,
"method `{}` is not a member of trait `{}`",
method,
trait_);
}
ResolutionError::TypeNotMemberOfTrait(type_, trait_) => {
span_err!(resolver.session, span, E0437,
"type `{}` is not a member of trait `{}`",
type_,
trait_);
},
span_err!(resolver.session,
span,
E0437,
"type `{}` is not a member of trait `{}`",
type_,
trait_);
}
ResolutionError::ConstNotMemberOfTrait(const_, trait_) => {
span_err!(resolver.session, span, E0438,
"const `{}` is not a member of trait `{}`",
const_,
trait_);
},
span_err!(resolver.session,
span,
E0438,
"const `{}` is not a member of trait `{}`",
const_,
trait_);
}
ResolutionError::VariableNotBoundInPattern(variable_name, pattern_number) => {
span_err!(resolver.session, span, E0408,
"variable `{}` from pattern #1 is not bound in pattern #{}",
variable_name,
pattern_number);
},
span_err!(resolver.session,
span,
E0408,
"variable `{}` from pattern #1 is not bound in pattern #{}",
variable_name,
pattern_number);
}
ResolutionError::VariableBoundWithDifferentMode(variable_name, pattern_number) => {
span_err!(resolver.session, span, E0409,
"variable `{}` is bound with different \
mode in pattern #{} than in pattern #1",
variable_name,
pattern_number);
},
span_err!(resolver.session,
span,
E0409,
"variable `{}` is bound with different mode in pattern #{} than in pattern \
#1",
variable_name,
pattern_number);
}
ResolutionError::VariableNotBoundInParentPattern(variable_name, pattern_number) => {
span_err!(resolver.session, span, E0410,
"variable `{}` from pattern #{} is not bound in pattern #1",
variable_name,
pattern_number);
},
span_err!(resolver.session,
span,
E0410,
"variable `{}` from pattern #{} is not bound in pattern #1",
variable_name,
pattern_number);
}
ResolutionError::SelfUsedOutsideImplOrTrait => {
span_err!(resolver.session, span, E0411, "use of `Self` outside of an impl or trait");
},
span_err!(resolver.session,
span,
E0411,
"use of `Self` outside of an impl or trait");
}
ResolutionError::UseOfUndeclared(kind, name) => {
span_err!(resolver.session, span, E0412,
"use of undeclared {} `{}`",
kind,
name);
},
span_err!(resolver.session,
span,
E0412,
"use of undeclared {} `{}`",
kind,
name);
}
ResolutionError::DeclarationShadowsEnumVariantOrUnitLikeStruct(name) => {
span_err!(resolver.session, span, E0413,
"declaration of `{}` shadows an enum variant or unit-like struct in \
scope",
name);
},
span_err!(resolver.session,
span,
E0413,
"declaration of `{}` shadows an enum variant or unit-like struct in scope",
name);
}
ResolutionError::OnlyIrrefutablePatternsAllowedHere(did, name) => {
span_err!(resolver.session, span, E0414, "only irrefutable patterns allowed here");
resolver.session.span_note(span, "there already is a constant in scope \
sharing the same name as this pattern");
span_err!(resolver.session,
span,
E0414,
"only irrefutable patterns allowed here");
resolver.session.span_note(span,
"there already is a constant in scope sharing the same \
name as this pattern");
if let Some(sp) = resolver.ast_map.span_if_local(did) {
resolver.session.span_note(sp, "constant defined here");
}
if let Some(directive) = resolver.current_module
.import_resolutions
.borrow().get(&name) {
.borrow()
.get(&name) {
let item = resolver.ast_map.expect_item(directive.value_id);
resolver.session.span_note(item.span, "constant imported here");
}
},
}
ResolutionError::IdentifierBoundMoreThanOnceInParameterList(identifier) => {
span_err!(resolver.session, span, E0415,
"identifier `{}` is bound more than once in this parameter list",
identifier);
},
span_err!(resolver.session,
span,
E0415,
"identifier `{}` is bound more than once in this parameter list",
identifier);
}
ResolutionError::IdentifierBoundMoreThanOnceInSamePattern(identifier) => {
span_err!(resolver.session, span, E0416,
"identifier `{}` is bound more than once in the same pattern",
identifier);
},
span_err!(resolver.session,
span,
E0416,
"identifier `{}` is bound more than once in the same pattern",
identifier);
}
ResolutionError::StaticVariableReference => {
span_err!(resolver.session, span, E0417, "static variables cannot be \
referenced in a pattern, \
use a `const` instead");
},
span_err!(resolver.session,
span,
E0417,
"static variables cannot be referenced in a pattern, use a `const` instead");
}
ResolutionError::NotAnEnumVariantStructOrConst(name) => {
span_err!(resolver.session, span, E0418,
"`{}` is not an enum variant, struct or const",
name);
},
span_err!(resolver.session,
span,
E0418,
"`{}` is not an enum variant, struct or const",
name);
}
ResolutionError::UnresolvedEnumVariantStructOrConst(name) => {
span_err!(resolver.session, span, E0419,
"unresolved enum variant, struct or const `{}`",
name);
},
span_err!(resolver.session,
span,
E0419,
"unresolved enum variant, struct or const `{}`",
name);
}
ResolutionError::NotAnAssociatedConst(name) => {
span_err!(resolver.session, span, E0420,
"`{}` is not an associated const",
name);
},
span_err!(resolver.session,
span,
E0420,
"`{}` is not an associated const",
name);
}
ResolutionError::UnresolvedAssociatedConst(name) => {
span_err!(resolver.session, span, E0421,
"unresolved associated const `{}`",
name);
},
span_err!(resolver.session,
span,
E0421,
"unresolved associated const `{}`",
name);
}
ResolutionError::DoesNotNameAStruct(name) => {
span_err!(resolver.session, span, E0422, "`{}` does not name a structure", name);
},
span_err!(resolver.session,
span,
E0422,
"`{}` does not name a structure",
name);
}
ResolutionError::StructVariantUsedAsFunction(path_name) => {
span_err!(resolver.session, span, E0423,
"`{}` is the name of a struct or struct variant, \
but this expression \
uses it like a function name",
path_name);
},
span_err!(resolver.session,
span,
E0423,
"`{}` is the name of a struct or struct variant, but this expression uses \
it like a function name",
path_name);
}
ResolutionError::SelfNotAvailableInStaticMethod => {
span_err!(resolver.session, span, E0424, "`self` is not available in a static method. \
Maybe a `self` argument is missing?");
},
span_err!(resolver.session,
span,
E0424,
"`self` is not available in a static method. Maybe a `self` argument is \
missing?");
}
ResolutionError::UnresolvedName(path, name) => {
span_err!(resolver.session, span, E0425,
"unresolved name `{}`{}",
path,
name);
},
span_err!(resolver.session,
span,
E0425,
"unresolved name `{}`{}",
path,
name);
}
ResolutionError::UndeclaredLabel(name) => {
span_err!(resolver.session, span, E0426,
"use of undeclared label `{}`",
name);
},
span_err!(resolver.session,
span,
E0426,
"use of undeclared label `{}`",
name);
}
ResolutionError::CannotUseRefBindingModeWith(descr) => {
span_err!(resolver.session, span, E0427,
"cannot use `ref` binding mode with {}",
descr);
},
span_err!(resolver.session,
span,
E0427,
"cannot use `ref` binding mode with {}",
descr);
}
ResolutionError::DuplicateDefinition(namespace, name) => {
span_err!(resolver.session, span, E0428,
"duplicate definition of {} `{}`",
namespace,
name);
},
span_err!(resolver.session,
span,
E0428,
"duplicate definition of {} `{}`",
namespace,
name);
}
ResolutionError::SelfImportsOnlyAllowedWithin => {
span_err!(resolver.session, span, E0429, "{}",
"`self` imports are only allowed within a { } list");
},
span_err!(resolver.session,
span,
E0429,
"{}",
"`self` imports are only allowed within a { } list");
}
ResolutionError::SelfImportCanOnlyAppearOnceInTheList => {
span_err!(resolver.session, span, E0430,
"`self` import can only appear once in the list");
},
span_err!(resolver.session,
span,
E0430,
"`self` import can only appear once in the list");
}
ResolutionError::SelfImportOnlyInImportListWithNonEmptyPrefix => {
span_err!(resolver.session, span, E0431,
"`self` import can only appear in an import list with a \
non-empty prefix");
span_err!(resolver.session,
span,
E0431,
"`self` import can only appear in an import list with a non-empty prefix");
}
ResolutionError::UnresolvedImport(name) => {
let msg = match name {
Some((n, p)) => format!("unresolved import `{}`{}", n, p),
None => "unresolved import".to_owned()
None => "unresolved import".to_owned(),
};
span_err!(resolver.session, span, E0432, "{}", msg);
},
}
ResolutionError::FailedToResolve(msg) => {
span_err!(resolver.session, span, E0433, "failed to resolve. {}", msg);
},
}
ResolutionError::CannotCaptureDynamicEnvironmentInFnItem => {
span_err!(resolver.session, span, E0434, "{}",
"can't capture dynamic environment in a fn item; \
use the || { ... } closure form instead");
},
ResolutionError::AttemptToUseNonConstantValueInConstant =>{
span_err!(resolver.session, span, E0435,
"attempt to use a non-constant value in a constant");
},
span_err!(resolver.session,
span,
E0434,
"{}",
"can't capture dynamic environment in a fn item; use the || { ... } \
closure form instead");
}
ResolutionError::AttemptToUseNonConstantValueInConstant => {
span_err!(resolver.session,
span,
E0435,
"attempt to use a non-constant value in a constant");
}
}
}
@@ -422,7 +497,7 @@ enum PatternBindingMode {
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub enum Namespace {
TypeNS,
ValueNS
ValueNS,
}
/// A NamespaceResult represents the result of resolving an import in
@@ -439,20 +514,20 @@ enum NamespaceResult {
UnboundResult,
/// Means that resolve has determined that the name is bound in the Module
/// argument, and specified by the NameBindings argument.
BoundResult(Rc<Module>, Rc<NameBindings>)
BoundResult(Rc<Module>, Rc<NameBindings>),
}
impl NamespaceResult {
fn is_unknown(&self) -> bool {
match *self {
UnknownResult => true,
_ => false
_ => false,
}
}
fn is_unbound(&self) -> bool {
match *self {
UnboundResult => true,
_ => false
_ => false,
}
}
}
@@ -492,16 +567,19 @@ fn visit_ty(&mut self, ty: &Ty) {
fn visit_generics(&mut self, generics: &Generics) {
self.resolve_generics(generics);
}
fn visit_poly_trait_ref(&mut self,
tref: &hir::PolyTraitRef,
m: &hir::TraitBoundModifier) {
fn visit_poly_trait_ref(&mut self, tref: &hir::PolyTraitRef, m: &hir::TraitBoundModifier) {
match self.resolve_trait_reference(tref.trait_ref.ref_id, &tref.trait_ref.path, 0) {
Ok(def) => self.record_def(tref.trait_ref.ref_id, def),
Err(_) => { /* error already reported */ }
Err(_) => {
// error already reported
}
}
visit::walk_poly_trait_ref(self, tref, m);
}
fn visit_variant(&mut self, variant: &hir::Variant, generics: &Generics, item_id: ast::NodeId) {
fn visit_variant(&mut self,
variant: &hir::Variant,
generics: &Generics,
item_id: ast::NodeId) {
execute_callback!(hir_map::Node::NodeVariant(variant), self);
if let Some(ref dis_expr) = variant.node.disr_expr {
// resolve the discriminator expr as a constant
@@ -511,8 +589,11 @@ fn visit_variant(&mut self, variant: &hir::Variant, generics: &Generics, item_id
}
// `visit::walk_variant` without the discriminant expression.
self.visit_variant_data(&variant.node.data, variant.node.name,
generics, item_id, variant.span);
self.visit_variant_data(&variant.node.data,
variant.node.name,
generics,
item_id,
variant.span);
}
fn visit_foreign_item(&mut self, foreign_item: &hir::ForeignItem) {
execute_callback!(hir_map::Node::NodeForeignItem(foreign_item), self);
@@ -520,7 +601,7 @@ fn visit_foreign_item(&mut self, foreign_item: &hir::ForeignItem) {
ForeignItemFn(_, ref generics) => {
HasTypeParameters(generics, FnSpace, ItemRibKind)
}
ForeignItemStatic(..) => NoTypeParameters
ForeignItemStatic(..) => NoTypeParameters,
};
self.with_type_parameter_rib(type_parameters, |this| {
visit::walk_foreign_item(this, foreign_item);
@@ -542,7 +623,7 @@ fn visit_fn(&mut self,
self.visit_explicit_self(&sig.explicit_self);
MethodRibKind
}
FnKind::Closure(..) => ClosureRibKind(node_id)
FnKind::Closure(..) => ClosureRibKind(node_id),
};
self.resolve_function(rib_kind, declaration, block);
}
@@ -551,14 +632,17 @@ fn visit_fn(&mut self,
type ErrorMessage = Option<(Span, String)>;
enum ResolveResult<T> {
Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
Indeterminate, // Couldn't determine due to unresolved globs.
Success(T) // Successfully resolved the import.
Failed(ErrorMessage), // Failed to resolve the name, optional helpful error message.
Indeterminate, // Couldn't determine due to unresolved globs.
Success(T), // Successfully resolved the import.
}
impl<T> ResolveResult<T> {
fn success(&self) -> bool {
match *self { Success(_) => true, _ => false }
match *self {
Success(_) => true,
_ => false,
}
}
}
@@ -574,16 +658,15 @@ enum FallbackSuggestion {
#[derive(Copy, Clone)]
enum TypeParameters<'a> {
NoTypeParameters,
HasTypeParameters(
// Type parameters.
&'a Generics,
HasTypeParameters(// Type parameters.
&'a Generics,
// Identifies the things that these parameters
// were declared on (type, fn, etc)
ParamSpace,
// Identifies the things that these parameters
// were declared on (type, fn, etc)
ParamSpace,
// The kind of the rib used for type parameters.
RibKind)
// The kind of the rib used for type parameters.
RibKind),
}
// The rib kind controls the translation of local
@@ -607,18 +690,18 @@ enum RibKind {
ItemRibKind,
// We're in a constant item. Can't refer to dynamic stuff.
ConstantItemRibKind
ConstantItemRibKind,
}
#[derive(Copy, Clone)]
enum UseLexicalScopeFlag {
DontUseLexicalScope,
UseLexicalScope
UseLexicalScope,
}
enum ModulePrefixResult {
NoPrefixFound,
PrefixFound(Rc<Module>, usize)
PrefixFound(Rc<Module>, usize),
}
#[derive(Copy, Clone)]
@@ -644,7 +727,7 @@ enum NameSearchType {
enum BareIdentifierPatternResolution {
FoundStructOrEnumVariant(Def, LastPrivate),
FoundConst(Def, LastPrivate, Name),
BareIdentifierPatternUnresolved
BareIdentifierPatternUnresolved,
}
/// One local scope.
@@ -658,7 +741,7 @@ impl Rib {
fn new(kind: RibKind) -> Rib {
Rib {
bindings: HashMap::new(),
kind: kind
kind: kind,
}
}
}
@@ -666,14 +749,14 @@ fn new(kind: RibKind) -> Rib {
/// A definition along with the index of the rib it was found on
struct LocalDef {
ribs: Option<(Namespace, usize)>,
def: Def
def: Def,
}
impl LocalDef {
fn from_def(def: Def) -> Self {
LocalDef {
ribs: None,
def: def
def: def,
}
}
}
@@ -683,7 +766,7 @@ fn from_def(def: Def) -> Self {
enum ParentLink {
NoParentLink,
ModuleParentLink(Weak<Module>, Name),
BlockParentLink(Weak<Module>, NodeId)
BlockParentLink(Weak<Module>, NodeId),
}
/// The type of module this is.
@@ -808,10 +891,15 @@ pub fn dec_pub_glob_count(&self) {
impl fmt::Debug for Module {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}, kind: {:?}, {}",
write!(f,
"{:?}, kind: {:?}, {}",
self.def_id,
self.kind,
if self.is_public { "public" } else { "private" } )
if self.is_public {
"public"
} else {
"private"
})
}
}
@@ -829,7 +917,7 @@ struct TypeNsDef {
modifiers: DefModifiers, // see note in ImportResolution about how to use this
module_def: Option<Rc<Module>>,
type_def: Option<Def>,
type_span: Option<Span>
type_span: Option<Span>,
}
// Records a possibly-private value definition.
@@ -844,8 +932,8 @@ struct ValueNsDef {
// bound to.
#[derive(Debug)]
pub struct NameBindings {
type_def: RefCell<Option<TypeNsDef>>, //< Meaning in type namespace.
value_def: RefCell<Option<ValueNsDef>>, //< Meaning in value namespace.
type_def: RefCell<Option<TypeNsDef>>, // < Meaning in type namespace.
value_def: RefCell<Option<ValueNsDef>>, // < Meaning in value namespace.
}
impl NameBindings {
@@ -870,11 +958,7 @@ fn define_module(&self,
} else {
DefModifiers::empty()
} | DefModifiers::IMPORTABLE;
let module_ = Rc::new(Module::new(parent_link,
def_id,
kind,
external,
is_public));
let module_ = Rc::new(Module::new(parent_link, def_id, kind, external, is_public));
let type_def = self.type_def.borrow().clone();
match type_def {
None => {
@@ -882,7 +966,7 @@ fn define_module(&self,
modifiers: modifiers,
module_def: Some(module_),
type_def: None,
type_span: Some(sp)
type_span: Some(sp),
});
}
Some(type_def) => {
@@ -890,7 +974,7 @@ fn define_module(&self,
modifiers: modifiers,
module_def: Some(module_),
type_span: Some(sp),
type_def: type_def.type_def
type_def: type_def.type_def,
});
}
}
@@ -912,11 +996,7 @@ fn set_module_kind(&self,
let type_def = self.type_def.borrow().clone();
match type_def {
None => {
let module = Module::new(parent_link,
def_id,
kind,
external,
is_public);
let module = Module::new(parent_link, def_id, kind, external, is_public);
*self.type_def.borrow_mut() = Some(TypeNsDef {
modifiers: modifiers,
module_def: Some(Rc::new(module)),
@@ -927,11 +1007,7 @@ fn set_module_kind(&self,
Some(type_def) => {
match type_def.module_def {
None => {
let module = Module::new(parent_link,
def_id,
kind,
external,
is_public);
let module = Module::new(parent_link, def_id, kind, external, is_public);
*self.type_def.borrow_mut() = Some(TypeNsDef {
modifiers: modifiers,
module_def: Some(Rc::new(module)),
@@ -947,7 +1023,9 @@ fn set_module_kind(&self,
/// Records a type definition.
fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
debug!("defining type for def {:?} with modifiers {:?}", def, modifiers);
debug!("defining type for def {:?} with modifiers {:?}",
def,
modifiers);
// Merges the type with the existing type def or creates a new one.
let type_def = self.type_def.borrow().clone();
match type_def {
@@ -972,7 +1050,9 @@ fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) {
/// Records a value definition.
fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
debug!("defining value for def {:?} with modifiers {:?}", def, modifiers);
debug!("defining value for def {:?} with modifiers {:?}",
def,
modifiers);
*self.value_def.borrow_mut() = Some(ValueNsDef {
def: def,
value_span: Some(sp),
@@ -984,7 +1064,7 @@ fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) {
fn get_module_if_available(&self) -> Option<Rc<Module>> {
match *self.type_def.borrow() {
Some(ref type_def) => type_def.module_def.clone(),
None => None
None => None,
}
}
@@ -993,17 +1073,16 @@ fn get_module_if_available(&self) -> Option<Rc<Module>> {
fn get_module(&self) -> Rc<Module> {
match self.get_module_if_available() {
None => {
panic!("get_module called on a node with no module \
definition!")
panic!("get_module called on a node with no module definition!")
}
Some(module_def) => module_def
Some(module_def) => module_def,
}
}
fn defined_in_namespace(&self, namespace: Namespace) -> bool {
match namespace {
TypeNS => return self.type_def.borrow().is_some(),
ValueNS => return self.value_def.borrow().is_some()
TypeNS => return self.type_def.borrow().is_some(),
ValueNS => return self.value_def.borrow().is_some(),
}
}
@@ -1014,11 +1093,13 @@ fn defined_in_public_namespace(&self, namespace: Namespace) -> bool {
fn defined_in_namespace_with(&self, namespace: Namespace, modifiers: DefModifiers) -> bool {
match namespace {
TypeNS => match *self.type_def.borrow() {
Some(ref def) => def.modifiers.contains(modifiers), None => false
Some(ref def) => def.modifiers.contains(modifiers),
None => false,
},
ValueNS => match *self.value_def.borrow() {
Some(ref def) => def.modifiers.contains(modifiers), None => false
}
Some(ref def) => def.modifiers.contains(modifiers),
None => false,
},
}
}
@@ -1048,7 +1129,7 @@ fn def_for_namespace(&self, namespace: Namespace) -> Option<Def> {
ValueNS => {
match *self.value_def.borrow() {
None => None,
Some(value_def) => Some(value_def.def)
Some(value_def) => Some(value_def.def),
}
}
}
@@ -1057,16 +1138,16 @@ fn def_for_namespace(&self, namespace: Namespace) -> Option<Def> {
fn span_for_namespace(&self, namespace: Namespace) -> Option<Span> {
if self.defined_in_namespace(namespace) {
match namespace {
TypeNS => {
TypeNS => {
match *self.type_def.borrow() {
None => None,
Some(ref type_def) => type_def.type_span
Some(ref type_def) => type_def.type_span,
}
}
ValueNS => {
match *self.value_def.borrow() {
None => None,
Some(ref value_def) => value_def.value_span
Some(ref value_def) => value_def.value_span,
}
}
}
@@ -1077,7 +1158,7 @@ fn span_for_namespace(&self, namespace: Namespace) -> Option<Span> {
fn is_public(&self, namespace: Namespace) -> bool {
match namespace {
TypeNS => {
TypeNS => {
let type_def = self.type_def.borrow();
type_def.as_ref().unwrap().modifiers.contains(DefModifiers::PUBLIC)
}
@@ -1096,25 +1177,23 @@ struct PrimitiveTypeTable {
impl PrimitiveTypeTable {
fn new() -> PrimitiveTypeTable {
let mut table = PrimitiveTypeTable {
primitive_types: HashMap::new()
};
let mut table = PrimitiveTypeTable { primitive_types: HashMap::new() };
table.intern("bool", TyBool);
table.intern("char", TyChar);
table.intern("f32", TyFloat(TyF32));
table.intern("f64", TyFloat(TyF64));
table.intern("isize", TyInt(TyIs));
table.intern("i8", TyInt(TyI8));
table.intern("i16", TyInt(TyI16));
table.intern("i32", TyInt(TyI32));
table.intern("i64", TyInt(TyI64));
table.intern("str", TyStr);
table.intern("usize", TyUint(TyUs));
table.intern("u8", TyUint(TyU8));
table.intern("u16", TyUint(TyU16));
table.intern("u32", TyUint(TyU32));
table.intern("u64", TyUint(TyU64));
table.intern("bool", TyBool);
table.intern("char", TyChar);
table.intern("f32", TyFloat(TyF32));
table.intern("f64", TyFloat(TyF64));
table.intern("isize", TyInt(TyIs));
table.intern("i8", TyInt(TyI8));
table.intern("i16", TyInt(TyI16));
table.intern("i32", TyInt(TyI32));
table.intern("i64", TyInt(TyI64));
table.intern("str", TyStr);
table.intern("usize", TyUint(TyUs));
table.intern("u8", TyUint(TyU8));
table.intern("u16", TyUint(TyU16));
table.intern("u32", TyUint(TyU32));
table.intern("u64", TyUint(TyU64));
table
}
@@ -1125,7 +1204,7 @@ fn intern(&mut self, string: &str, primitive_type: PrimTy) {
}
/// The main resolver class.
pub struct Resolver<'a, 'tcx:'a> {
pub struct Resolver<'a, 'tcx: 'a> {
session: &'a Session,
ast_map: &'a hir_map::Map<'tcx>,
@@ -1186,20 +1265,20 @@ pub struct Resolver<'a, 'tcx:'a> {
// The intention is that the callback modifies this flag.
// Once set, the resolver falls out of the walk, preserving the ribs.
resolved: bool,
}
#[derive(PartialEq)]
enum FallbackChecks {
Everything,
OnlyTraitAndStatics
OnlyTraitAndStatics,
}
impl<'a, 'tcx> Resolver<'a, 'tcx> {
fn new(session: &'a Session,
ast_map: &'a hir_map::Map<'tcx>,
crate_span: Span,
make_glob_map: MakeGlobMap) -> Resolver<'a, 'tcx> {
make_glob_map: MakeGlobMap)
-> Resolver<'a, 'tcx> {
let graph_root = NameBindings::new();
let root_def_id = ast_map.local_def_id(CRATE_NODE_ID);
@@ -1219,7 +1298,6 @@ fn new(session: &'a Session,
// The outermost module has def ID 0; this is not reflected in the
// AST.
graph_root: graph_root,
trait_item_map: FnvHashMap(),
@@ -1252,7 +1330,6 @@ fn new(session: &'a Session,
callback: None,
resolved: false,
}
}
@@ -1285,7 +1362,7 @@ fn create_name_bindings_from_module(module: Rc<Module>) -> NameBindings {
modifiers: DefModifiers::IMPORTABLE,
module_def: Some(module),
type_def: None,
type_span: None
type_span: None,
})),
value_def: RefCell::new(None),
}
@@ -1298,10 +1375,11 @@ fn check_for_conflicts_between_external_crates(&self,
name: Name,
span: Span) {
if module.external_module_children.borrow().contains_key(&name) {
span_err!(self.session, span, E0259,
"an external crate named `{}` has already \
been imported into this module",
name);
span_err!(self.session,
span,
E0259,
"an external crate named `{}` has already been imported into this module",
name);
}
}
@@ -1311,11 +1389,12 @@ fn check_for_conflicts_between_external_crates_and_items(&self,
name: Name,
span: Span) {
if module.external_module_children.borrow().contains_key(&name) {
span_err!(self.session, span, E0260,
"the name `{}` conflicts with an external \
crate that has been imported into this \
module",
name);
span_err!(self.session,
span,
E0260,
"the name `{}` conflicts with an external crate that has been imported \
into this module",
name);
}
}
@@ -1327,17 +1406,16 @@ fn resolve_module_path_from_root(&mut self,
span: Span,
name_search_type: NameSearchType,
lp: LastPrivate)
-> ResolveResult<(Rc<Module>, LastPrivate)> {
fn search_parent_externals(needle: Name, module: &Rc<Module>)
-> Option<Rc<Module>> {
-> ResolveResult<(Rc<Module>, LastPrivate)> {
fn search_parent_externals(needle: Name, module: &Rc<Module>) -> Option<Rc<Module>> {
match module.external_module_children.borrow().get(&needle) {
Some(_) => Some(module.clone()),
None => match module.parent_link {
ModuleParentLink(ref parent, _) => {
search_parent_externals(needle, &parent.upgrade().unwrap())
}
_ => None
}
_ => None,
},
}
}
@@ -1363,13 +1441,11 @@ fn search_parent_externals(needle: Name, module: &Rc<Module>)
let msg = if "???" == &module_name[..] {
span.hi = span.lo + Pos::from_usize(segment_name.len());
match search_parent_externals(name,
&self.current_module) {
match search_parent_externals(name, &self.current_module) {
Some(module) => {
let path_str = names_to_string(module_path);
let target_mod_str = module_to_string(&*module);
let current_mod_str =
module_to_string(&*self.current_module);
let current_mod_str = module_to_string(&*self.current_module);
let prefix = if target_mod_str == current_mod_str {
"self::".to_string()
@@ -1378,23 +1454,20 @@ fn search_parent_externals(needle: Name, module: &Rc<Module>)
};
format!("Did you mean `{}{}`?", prefix, path_str)
},
None => format!("Maybe a missing `extern crate {}`?",
segment_name),
}
None => format!("Maybe a missing `extern crate {}`?", segment_name),
}
} else {
format!("Could not find `{}` in `{}`",
segment_name,
module_name)
format!("Could not find `{}` in `{}`", segment_name, module_name)
};
return Failed(Some((span, msg)));
}
Failed(err) => return Failed(err),
Indeterminate => {
debug!("(resolving module path for import) module \
resolution is indeterminate: {}",
name);
debug!("(resolving module path for import) module resolution is \
indeterminate: {}",
name);
return Indeterminate;
}
Success((target, used_proxy)) => {
@@ -1404,8 +1477,7 @@ fn search_parent_externals(needle: Name, module: &Rc<Module>)
Some(ref type_def) => {
match type_def.module_def {
None => {
let msg = format!("Not a module `{}`",
name);
let msg = format!("Not a module `{}`", name);
return Failed(Some((span, msg)));
}
@@ -1430,8 +1502,7 @@ fn search_parent_externals(needle: Name, module: &Rc<Module>)
}
None => {
// There are no type bindings at all.
let msg = format!("Not a module `{}`",
name);
let msg = format!("Not a module `{}`", name);
return Failed(Some((span, msg)));
}
}
@@ -1464,8 +1535,7 @@ fn resolve_module_path(&mut self,
module_to_string(&*module_));
// Resolve the module prefix, if any.
let module_prefix_result = self.resolve_module_prefix(module_.clone(),
module_path);
let module_prefix_result = self.resolve_module_prefix(module_.clone(), module_path);
let search_module;
let start_index;
@@ -1477,21 +1547,20 @@ fn resolve_module_path(&mut self,
match mpath.rfind(':') {
Some(idx) => {
let msg = format!("Could not find `{}` in `{}`",
// idx +- 1 to account for the
// colons on either side
&mpath[idx + 1..],
&mpath[..idx - 1]);
// idx +- 1 to account for the
// colons on either side
&mpath[idx + 1..],
&mpath[..idx - 1]);
return Failed(Some((span, msg)));
},
}
None => {
return Failed(None)
return Failed(None);
}
}
}
Failed(err) => return Failed(err),
Indeterminate => {
debug!("(resolving module path for import) indeterminate; \
bailing");
debug!("(resolving module path for import) indeterminate; bailing");
return Indeterminate;
}
Success(NoPrefixFound) => {
@@ -1510,12 +1579,10 @@ fn resolve_module_path(&mut self,
// This is not a crate-relative path. We resolve the
// first component of the path in the current lexical
// scope and then proceed to resolve below that.
match self.resolve_module_in_lexical_scope(module_,
module_path[0]) {
match self.resolve_module_in_lexical_scope(module_, module_path[0]) {
Failed(err) => return Failed(err),
Indeterminate => {
debug!("(resolving module path for import) \
indeterminate; bailing");
debug!("(resolving module path for import) indeterminate; bailing");
return Indeterminate;
}
Success(containing_module) => {
@@ -1550,9 +1617,8 @@ fn resolve_item_in_lexical_scope(&mut self,
module_: Rc<Module>,
name: Name,
namespace: Namespace)
-> ResolveResult<(Target, bool)> {
debug!("(resolving item in lexical scope) resolving `{}` in \
namespace {:?} in `{}`",
-> ResolveResult<(Target, bool)> {
debug!("(resolving item in lexical scope) resolving `{}` in namespace {:?} in `{}`",
name,
namespace,
module_to_string(&*module_));
@@ -1562,15 +1628,16 @@ fn resolve_item_in_lexical_scope(&mut self,
build_reduced_graph::populate_module_if_necessary(self, &module_);
match module_.children.borrow().get(&name) {
Some(name_bindings)
if name_bindings.defined_in_namespace(namespace) => {
Some(name_bindings) if name_bindings.defined_in_namespace(namespace) => {
debug!("top name bindings succeeded");
return Success((Target::new(module_.clone(),
name_bindings.clone(),
Shadowable::Never),
false));
false));
}
Some(_) | None => {
// Not found; continue.
}
Some(_) | None => { /* Not found; continue. */ }
}
// Now check for its import directives. We don't have to have resolved
@@ -1581,19 +1648,18 @@ fn resolve_item_in_lexical_scope(&mut self,
match (*import_resolution).target_for_namespace(namespace) {
None => {
// Not found; continue.
debug!("(resolving item in lexical scope) found \
import resolution, but not in namespace {:?}",
debug!("(resolving item in lexical scope) found import resolution, but not \
in namespace {:?}",
namespace);
}
Some(target) => {
debug!("(resolving item in lexical scope) using \
import resolution");
debug!("(resolving item in lexical scope) using import resolution");
// track used imports and extern crates as well
let id = import_resolution.id(namespace);
self.used_imports.insert((id, namespace));
self.record_import_use(id, name);
if let Some(DefId{krate: kid, ..}) = target.target_module.def_id.get() {
self.used_crates.insert(kid);
self.used_crates.insert(kid);
}
return Success((target, false));
}
@@ -1605,12 +1671,9 @@ fn resolve_item_in_lexical_scope(&mut self,
// FIXME (21114): In principle unclear `child` *has* to be lifted.
let child = module_.external_module_children.borrow().get(&name).cloned();
if let Some(module) = child {
let name_bindings =
Rc::new(Resolver::create_name_bindings_from_module(module));
let name_bindings = Rc::new(Resolver::create_name_bindings_from_module(module));
debug!("lower name bindings succeeded");
return Success((Target::new(module_,
name_bindings,
Shadowable::Never),
return Success((Target::new(module_, name_bindings, Shadowable::Never),
false));
}
}
@@ -1622,18 +1685,15 @@ fn resolve_item_in_lexical_scope(&mut self,
match search_module.parent_link.clone() {
NoParentLink => {
// No more parents. This module was unresolved.
debug!("(resolving item in lexical scope) unresolved \
module");
debug!("(resolving item in lexical scope) unresolved module");
return Failed(None);
}
ModuleParentLink(parent_module_node, _) => {
match search_module.kind.get() {
NormalModuleKind => {
// We stop the search here.
debug!("(resolving item in lexical \
scope) unresolved module: not \
searching through module \
parents");
debug!("(resolving item in lexical scope) unresolved module: not \
searching through module parents");
return Failed(None);
}
TraitModuleKind |
@@ -1657,20 +1717,18 @@ fn resolve_item_in_lexical_scope(&mut self,
true) {
Failed(Some((span, msg))) => {
resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
},
}
Failed(None) => (), // Continue up the search chain.
Indeterminate => {
// We couldn't see through the higher scope because of an
// unresolved import higher up. Bail.
debug!("(resolving item in lexical scope) indeterminate \
higher scope; bailing");
debug!("(resolving item in lexical scope) indeterminate higher scope; bailing");
return Indeterminate;
}
Success((target, used_reexport)) => {
// We found the module.
debug!("(resolving item in lexical scope) found name \
in module, done");
debug!("(resolving item in lexical scope) found name in module, done");
return Success((target, used_reexport));
}
}
@@ -1681,7 +1739,7 @@ fn resolve_item_in_lexical_scope(&mut self,
fn resolve_module_in_lexical_scope(&mut self,
module_: Rc<Module>,
name: Name)
-> ResolveResult<Rc<Module>> {
-> ResolveResult<Rc<Module>> {
// If this module is an anonymous module, resolve the item in the
// lexical scope. Otherwise, resolve the item from the crate root.
let resolve_result = self.resolve_item_in_lexical_scope(module_, name, TypeNS);
@@ -1692,9 +1750,8 @@ fn resolve_module_in_lexical_scope(&mut self,
Some(ref type_def) => {
match type_def.module_def {
None => {
debug!("!!! (resolving module in lexical \
scope) module wasn't actually a \
module!");
debug!("!!! (resolving module in lexical scope) module wasn't \
actually a module!");
return Failed(None);
}
Some(ref module_def) => {
@@ -1704,14 +1761,14 @@ fn resolve_module_in_lexical_scope(&mut self,
}
None => {
debug!("!!! (resolving module in lexical scope) module
\
wasn't actually a module!");
return Failed(None);
}
}
}
Indeterminate => {
debug!("(resolving module in lexical scope) indeterminate; \
bailing");
debug!("(resolving module in lexical scope) indeterminate; bailing");
return Indeterminate;
}
Failed(err) => {
@@ -1722,8 +1779,7 @@ fn resolve_module_in_lexical_scope(&mut self,
}
/// Returns the nearest normal module parent of the given module.
fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>)
-> Option<Rc<Module>> {
fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>) -> Option<Rc<Module>> {
let mut module_ = module_;
loop {
match module_.parent_link.clone() {
@@ -1745,8 +1801,7 @@ fn get_nearest_normal_module_parent(&mut self, module_: Rc<Module>)
/// Returns the nearest normal module parent of the given module, or the
/// module itself if it is a normal module.
fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>)
-> Rc<Module> {
fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>) -> Rc<Module> {
match module_.kind.get() {
NormalModuleKind => return module_,
TraitModuleKind |
@@ -1755,7 +1810,7 @@ fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>)
AnonymousModuleKind => {
match self.get_nearest_normal_module_parent(module_.clone()) {
None => module_,
Some(new_module) => new_module
Some(new_module) => new_module,
}
}
}
@@ -1767,7 +1822,7 @@ fn get_nearest_normal_module_parent_or_self(&mut self, module_: Rc<Module>)
fn resolve_module_prefix(&mut self,
module_: Rc<Module>,
module_path: &[Name])
-> ResolveResult<ModulePrefixResult> {
-> ResolveResult<ModulePrefixResult> {
// Start at the current module if we see `self` or `super`, or at the
// top of the crate otherwise.
let mut i = match &*module_path[0].as_str() {
@@ -1817,13 +1872,12 @@ fn resolve_name_in_module(&mut self,
build_reduced_graph::populate_module_if_necessary(self, &module_);
match module_.children.borrow().get(&name) {
Some(name_bindings)
if name_bindings.defined_in_namespace(namespace) => {
Some(name_bindings) if name_bindings.defined_in_namespace(namespace) => {
debug!("(resolving name in module) found node as child");
return Success((Target::new(module_.clone(),
name_bindings.clone(),
Shadowable::Never),
false));
false));
}
Some(_) | None => {
// Continue.
@@ -1840,24 +1894,19 @@ fn resolve_name_in_module(&mut self,
// Check the list of resolved imports.
match module_.import_resolutions.borrow().get(&name) {
Some(import_resolution) if allow_private_imports ||
import_resolution.is_public => {
Some(import_resolution) if allow_private_imports || import_resolution.is_public => {
if import_resolution.is_public &&
import_resolution.outstanding_references != 0 {
debug!("(resolving name in module) import \
unresolved; bailing out");
if import_resolution.is_public && import_resolution.outstanding_references != 0 {
debug!("(resolving name in module) import unresolved; bailing out");
return Indeterminate;
}
match import_resolution.target_for_namespace(namespace) {
None => {
debug!("(resolving name in module) name found, \
but not in namespace {:?}",
debug!("(resolving name in module) name found, but not in namespace {:?}",
namespace);
}
Some(target) => {
debug!("(resolving name in module) resolved to \
import");
debug!("(resolving name in module) resolved to import");
// track used imports and extern crates as well
let id = import_resolution.id(namespace);
self.used_imports.insert((id, namespace));
@@ -1877,18 +1926,14 @@ fn resolve_name_in_module(&mut self,
// FIXME (21114): In principle unclear `child` *has* to be lifted.
let child = module_.external_module_children.borrow().get(&name).cloned();
if let Some(module) = child {
let name_bindings =
Rc::new(Resolver::create_name_bindings_from_module(module));
return Success((Target::new(module_,
name_bindings,
Shadowable::Never),
let name_bindings = Rc::new(Resolver::create_name_bindings_from_module(module));
return Success((Target::new(module_, name_bindings, Shadowable::Never),
false));
}
}
// We're out of luck.
debug!("(resolving name in module) failed to resolve `{}`",
name);
debug!("(resolving name in module) failed to resolve `{}`", name);
return Failed(None);
}
@@ -1939,8 +1984,8 @@ fn report_unresolved_imports(&mut self, module_: Rc<Module>) {
// generate a fake "implementation scope" containing all the
// implementations thus found, for compatibility with old resolve pass.
fn with_scope<F>(&mut self, name: Option<Name>, f: F) where
F: FnOnce(&mut Resolver),
fn with_scope<F>(&mut self, name: Option<Name>, f: F)
where F: FnOnce(&mut Resolver)
{
let orig_module = self.current_module.clone();
@@ -1961,8 +2006,7 @@ fn with_scope<F>(&mut self, name: Option<Name>, f: F) where
Some(name_bindings) => {
match (*name_bindings).get_module_if_available() {
None => {
debug!("!!! (with scope) didn't find module \
for `{}` in `{}`",
debug!("!!! (with scope) didn't find module for `{}` in `{}`",
name,
module_to_string(&*orig_module));
}
@@ -1990,12 +2034,12 @@ fn search_label(&self, name: Name) -> Option<DefLike> {
}
_ => {
// Do not resolve labels across function boundary
return None
return None;
}
}
let result = rib.bindings.get(&name).cloned();
if result.is_some() {
return result
return result;
}
}
None
@@ -2009,16 +2053,17 @@ fn resolve_crate(&mut self, krate: &hir::Crate) {
fn check_if_primitive_type_name(&self, name: Name, span: Span) {
if let Some(_) = self.primitive_type_table.primitive_types.get(&name) {
span_err!(self.session, span, E0317,
"user-defined types or type parameters cannot shadow the primitive types");
span_err!(self.session,
span,
E0317,
"user-defined types or type parameters cannot shadow the primitive types");
}
}
fn resolve_item(&mut self, item: &Item) {
let name = item.name;
debug!("(resolving item) resolving {}",
name);
debug!("(resolving item) resolving {}", name);
match item.node {
ItemEnum(_, ref generics) |
@@ -2026,27 +2071,18 @@ fn resolve_item(&mut self, item: &Item) {
ItemStruct(_, ref generics) => {
self.check_if_primitive_type_name(name, item.span);
self.with_type_parameter_rib(HasTypeParameters(generics,
TypeSpace,
ItemRibKind),
self.with_type_parameter_rib(HasTypeParameters(generics, TypeSpace, ItemRibKind),
|this| visit::walk_item(this, item));
}
ItemFn(_, _, _, _, ref generics, _) => {
self.with_type_parameter_rib(HasTypeParameters(generics,
FnSpace,
ItemRibKind),
self.with_type_parameter_rib(HasTypeParameters(generics, FnSpace, ItemRibKind),
|this| visit::walk_item(this, item));
}
ItemDefaultImpl(_, ref trait_ref) => {
self.with_optional_trait_ref(Some(trait_ref), |_, _| {});
}
ItemImpl(_,
_,
ref generics,
ref opt_trait_ref,
ref self_type,
ref impl_items) => {
ItemImpl(_, _, ref generics, ref opt_trait_ref, ref self_type, ref impl_items) => {
self.resolve_implementation(generics,
opt_trait_ref,
&**self_type,
@@ -2142,8 +2178,8 @@ fn resolve_item(&mut self, item: &Item) {
match self.resolve_crate_relative_path(prefix.span,
&prefix.segments,
TypeNS) {
Some((def, lp)) => self.record_def(item.id,
PathResolution::new(def, lp, 0)),
Some((def, lp)) =>
self.record_def(item.id, PathResolution::new(def, lp, 0)),
None => {
resolve_error(self,
prefix.span,
@@ -2163,8 +2199,8 @@ fn resolve_item(&mut self, item: &Item) {
}
}
fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F) where
F: FnOnce(&mut Resolver),
fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F)
where F: FnOnce(&mut Resolver)
{
match type_parameters {
HasTypeParameters(generics, space, rib_kind) => {
@@ -2177,18 +2213,18 @@ fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F)
if seen_bindings.contains(&name) {
resolve_error(self,
type_parameter.span,
ResolutionError::NameAlreadyUsedInTypeParameterList(
name)
);
ResolutionError::NameAlreadyUsedInTypeParameterList(name));
}
seen_bindings.insert(name);
// plain insert (no renaming)
function_type_rib.bindings.insert(name,
DlDef(DefTyParam(space,
index as u32,
self.ast_map.local_def_id(type_parameter.id),
name)));
function_type_rib.bindings
.insert(name,
DlDef(DefTyParam(space,
index as u32,
self.ast_map
.local_def_id(type_parameter.id),
name)));
}
self.type_ribs.push(function_type_rib);
}
@@ -2201,13 +2237,17 @@ fn with_type_parameter_rib<F>(&mut self, type_parameters: TypeParameters, f: F)
f(self);
match type_parameters {
HasTypeParameters(..) => { if !self.resolved { self.type_ribs.pop(); } }
NoTypeParameters => { }
HasTypeParameters(..) => {
if !self.resolved {
self.type_ribs.pop();
}
}
NoTypeParameters => {}
}
}
fn with_label_rib<F>(&mut self, f: F) where
F: FnOnce(&mut Resolver),
fn with_label_rib<F>(&mut self, f: F)
where F: FnOnce(&mut Resolver)
{
self.label_ribs.push(Rib::new(NormalRibKind));
f(self);
@@ -2216,8 +2256,8 @@ fn with_label_rib<F>(&mut self, f: F) where
}
}
fn with_constant_rib<F>(&mut self, f: F) where
F: FnOnce(&mut Resolver),
fn with_constant_rib<F>(&mut self, f: F)
where F: FnOnce(&mut Resolver)
{
self.value_ribs.push(Rib::new(ConstantItemRibKind));
self.type_ribs.push(Rib::new(ConstantItemRibKind));
@@ -2228,10 +2268,7 @@ fn with_constant_rib<F>(&mut self, f: F) where
}
}
fn resolve_function(&mut self,
rib_kind: RibKind,
declaration: &FnDecl,
block: &Block) {
fn resolve_function(&mut self, rib_kind: RibKind, declaration: &FnDecl, block: &Block) {
// Create a value rib for the function.
self.value_ribs.push(Rib::new(rib_kind));
@@ -2241,9 +2278,7 @@ fn resolve_function(&mut self,
// Add each argument to the rib.
let mut bindings_list = HashMap::new();
for argument in &declaration.inputs {
self.resolve_pattern(&*argument.pat,
ArgumentIrrefutableMode,
&mut bindings_list);
self.resolve_pattern(&*argument.pat, ArgumentIrrefutableMode, &mut bindings_list);
self.visit_ty(&*argument.ty);
@@ -2275,22 +2310,20 @@ fn resolve_trait_reference(&mut self,
resolve_error(self,
trait_path.span,
ResolutionError::IsNotATrait(&*path_names_to_string(trait_path,
path_depth))
);
path_depth)));
// If it's a typedef, give a note
if let DefTy(..) = path_res.base_def {
self.session.span_note(trait_path.span,
"`type` aliases cannot be used for traits");
self.session
.span_note(trait_path.span, "`type` aliases cannot be used for traits");
}
Err(())
}
} else {
resolve_error(self,
trait_path.span,
ResolutionError::UndeclaredTraitName(
&*path_names_to_string(trait_path, path_depth))
);
ResolutionError::UndeclaredTraitName(&*path_names_to_string(trait_path,
path_depth)));
Err(())
}
}
@@ -2328,17 +2361,15 @@ fn with_current_self_type<T, F>(&mut self, self_type: &Ty, f: F) -> T
result
}
fn with_optional_trait_ref<T, F>(&mut self,
opt_trait_ref: Option<&TraitRef>,
f: F)
-> T
fn with_optional_trait_ref<T, F>(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T
where F: FnOnce(&mut Resolver, Option<DefId>) -> T
{
let mut new_val = None;
let mut new_id = None;
if let Some(trait_ref) = opt_trait_ref {
if let Ok(path_res) = self.resolve_trait_reference(trait_ref.ref_id,
&trait_ref.path, 0) {
&trait_ref.path,
0) {
assert!(path_res.depth == 0);
self.record_def(trait_ref.ref_id, path_res);
new_val = Some((path_res.base_def.def_id(), trait_ref.clone()));
@@ -2435,14 +2466,14 @@ fn resolve_implementation(&mut self,
}
fn check_trait_item<F>(&self, name: Name, span: Span, err: F)
where F: FnOnce(Name, &str) -> ResolutionError {
// If there is a TraitRef in scope for an impl, then the method must be in the trait.
where F: FnOnce(Name, &str) -> ResolutionError
{
// If there is a TraitRef in scope for an impl, then the method must be in the
// trait.
if let Some((did, ref trait_ref)) = self.current_trait_ref {
if !self.trait_item_map.contains_key(&(name, did)) {
let path_str = path_names_to_string(&trait_ref.path, 0);
resolve_error(self,
span,
err(name, &*path_str));
resolve_error(self, span, err(name, &*path_str));
}
}
}
@@ -2455,9 +2486,7 @@ fn resolve_local(&mut self, local: &Local) {
walk_list!(self, visit_expr, &local.init);
// Resolve the pattern.
self.resolve_pattern(&*local.pat,
LocalIrrefutableMode,
&mut HashMap::new());
self.resolve_pattern(&*local.pat, LocalIrrefutableMode, &mut HashMap::new());
}
// build a map from pattern identifiers to binding-info's.
@@ -2468,10 +2497,11 @@ fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
let mut result = HashMap::new();
pat_bindings_hygienic(&self.def_map, pat, |binding_mode, _id, sp, path1| {
let name = mtwt::resolve(path1.node);
result.insert(name, BindingInfo {
span: sp,
binding_mode: binding_mode
});
result.insert(name,
BindingInfo {
span: sp,
binding_mode: binding_mode,
});
});
return result;
}
@@ -2480,7 +2510,7 @@ fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
// same set of bindings, with the same binding modes for each.
fn check_consistent_bindings(&mut self, arm: &Arm) {
if arm.pats.is_empty() {
return
return;
}
let map_0 = self.binding_mode_map(&*arm.pats[0]);
for (i, p) in arm.pats.iter().enumerate() {
@@ -2488,21 +2518,19 @@ fn check_consistent_bindings(&mut self, arm: &Arm) {
for (&key, &binding_0) in &map_0 {
match map_i.get(&key) {
None => {
resolve_error(self,
p.span,
ResolutionError::VariableNotBoundInPattern(key,
i + 1));
}
Some(binding_i) => {
if binding_0.binding_mode != binding_i.binding_mode {
None => {
resolve_error(self,
binding_i.span,
ResolutionError::VariableBoundWithDifferentMode(key,
i + 1)
);
p.span,
ResolutionError::VariableNotBoundInPattern(key, i + 1));
}
Some(binding_i) => {
if binding_0.binding_mode != binding_i.binding_mode {
resolve_error(self,
binding_i.span,
ResolutionError::VariableBoundWithDifferentMode(key,
i + 1));
}
}
}
}
}
@@ -2510,8 +2538,7 @@ fn check_consistent_bindings(&mut self, arm: &Arm) {
if !map_0.contains_key(&key) {
resolve_error(self,
binding.span,
ResolutionError::VariableNotBoundInParentPattern(key,
i + 1));
ResolutionError::VariableNotBoundInParentPattern(key, i + 1));
}
}
}
@@ -2544,10 +2571,11 @@ fn resolve_block(&mut self, block: &Block) {
// Move down in the graph, if there's an anonymous module rooted here.
let orig_module = self.current_module.clone();
match orig_module.anonymous_children.borrow().get(&block.id) {
None => { /* Nothing to do. */ }
None => {
// Nothing to do.
}
Some(anonymous_module) => {
debug!("(resolving block) found anonymous module, moving \
down");
debug!("(resolving block) found anonymous module, moving down");
self.current_module = anonymous_module.clone();
}
}
@@ -2559,8 +2587,10 @@ fn resolve_block(&mut self, block: &Block) {
if let hir::DeclItem(ref i) = declaration.node {
match i.node {
ItemExternCrate(_) | ItemUse(_) if found_non_item => {
span_err!(self.session, i.span, E0154,
"imports are not allowed after non-item statements");
span_err!(self.session,
i.span,
E0154,
"imports are not allowed after non-item statements");
}
_ => {}
}
@@ -2586,30 +2616,29 @@ fn resolve_block(&mut self, block: &Block) {
fn resolve_type(&mut self, ty: &Ty) {
match ty.node {
TyPath(ref maybe_qself, ref path) => {
let resolution =
match self.resolve_possibly_assoc_item(ty.id,
maybe_qself.as_ref(),
path,
TypeNS,
true) {
// `<T>::a::b::c` is resolved by typeck alone.
TypecheckRequired => {
// Resolve embedded types.
visit::walk_ty(self, ty);
return;
}
ResolveAttempt(resolution) => resolution,
};
let resolution = match self.resolve_possibly_assoc_item(ty.id,
maybe_qself.as_ref(),
path,
TypeNS,
true) {
// `<T>::a::b::c` is resolved by typeck alone.
TypecheckRequired => {
// Resolve embedded types.
visit::walk_ty(self, ty);
return;
}
ResolveAttempt(resolution) => resolution,
};
// This is a path in the type namespace. Walk through scopes
// looking for it.
match resolution {
Some(def) => {
// Write the result into the def map.
debug!("(resolving type) writing resolution for `{}` \
(id {}) = {:?}",
debug!("(resolving type) writing resolution for `{}` (id {}) = {:?}",
path_names_to_string(path, 0),
ty.id, def);
ty.id,
def);
self.record_def(ty.id, def);
}
None => {
@@ -2623,10 +2652,10 @@ fn resolve_type(&mut self, ty: &Ty) {
};
let self_type_name = special_idents::type_self.name;
let is_invalid_self_type_name =
path.segments.len() > 0 &&
maybe_qself.is_none() &&
path.segments[0].identifier.name == self_type_name;
let is_invalid_self_type_name = path.segments.len() > 0 &&
maybe_qself.is_none() &&
path.segments[0].identifier.name ==
self_type_name;
if is_invalid_self_type_name {
resolve_error(self,
ty.span,
@@ -2674,19 +2703,18 @@ fn resolve_pattern(&mut self,
match self.resolve_bare_identifier_pattern(ident.name, pattern.span) {
FoundStructOrEnumVariant(def, lp) if const_ok => {
debug!("(resolving pattern) resolving `{}` to \
struct or enum variant",
debug!("(resolving pattern) resolving `{}` to struct or enum variant",
renamed);
self.enforce_default_binding_mode(
pattern,
binding_mode,
"an enum variant");
self.record_def(pattern.id, PathResolution {
base_def: def,
last_private: lp,
depth: 0
});
self.enforce_default_binding_mode(pattern,
binding_mode,
"an enum variant");
self.record_def(pattern.id,
PathResolution {
base_def: def,
last_private: lp,
depth: 0,
});
}
FoundStructOrEnumVariant(..) => {
resolve_error(
@@ -2697,19 +2725,15 @@ struct or enum variant",
);
}
FoundConst(def, lp, _) if const_ok => {
debug!("(resolving pattern) resolving `{}` to \
constant",
renamed);
debug!("(resolving pattern) resolving `{}` to constant", renamed);
self.enforce_default_binding_mode(
pattern,
binding_mode,
"a constant");
self.record_def(pattern.id, PathResolution {
base_def: def,
last_private: lp,
depth: 0
});
self.enforce_default_binding_mode(pattern, binding_mode, "a constant");
self.record_def(pattern.id,
PathResolution {
base_def: def,
last_private: lp,
depth: 0,
});
}
FoundConst(def, _, name) => {
resolve_error(
@@ -2720,8 +2744,7 @@ struct or enum variant",
);
}
BareIdentifierPatternUnresolved => {
debug!("(resolving pattern) binding `{}`",
renamed);
debug!("(resolving pattern) binding `{}`", renamed);
let def_id = self.ast_map.local_def_id(pattern.id);
let def = DefLocal(def_id, pattern.id);
@@ -2730,11 +2753,12 @@ struct or enum variant",
// will be able to distinguish variants from
// locals in patterns.
self.record_def(pattern.id, PathResolution {
base_def: def,
last_private: LastMod(AllPublic),
depth: 0
});
self.record_def(pattern.id,
PathResolution {
base_def: def,
last_private: LastMod(AllPublic),
depth: 0,
});
// Add the binding to the local ribs, if it
// doesn't already exist in the bindings list. (We
@@ -2747,7 +2771,7 @@ struct or enum variant",
last_rib.bindings.insert(renamed, DlDef(def));
bindings_list.insert(renamed, pat_id);
} else if mode == ArgumentIrrefutableMode &&
bindings_list.contains_key(&renamed) {
bindings_list.contains_key(&renamed) {
// Forbid duplicate bindings in the same
// parameter list.
resolve_error(
@@ -2756,8 +2780,7 @@ struct or enum variant",
ResolutionError::IdentifierBoundMoreThanOnceInParameterList(
&ident.name.as_str())
);
} else if bindings_list.get(&renamed) ==
Some(&pat_id) {
} else if bindings_list.get(&renamed) == Some(&pat_id) {
// Then this is a duplicate variable in the
// same disjunction, which is an error.
resolve_error(
@@ -2775,21 +2798,24 @@ struct or enum variant",
PatEnum(ref path, _) => {
// This must be an enum variant, struct or const.
let resolution =
match self.resolve_possibly_assoc_item(pat_id, None,
path, ValueNS,
false) {
// The below shouldn't happen because all
// qualified paths should be in PatQPath.
TypecheckRequired =>
self.session.span_bug(
path.span,
"resolve_possibly_assoc_item claimed
that a path in PatEnum requires typecheck
to resolve, but qualified paths should be
PatQPath"),
ResolveAttempt(resolution) => resolution,
};
let resolution = match self.resolve_possibly_assoc_item(pat_id,
None,
path,
ValueNS,
false) {
// The below shouldn't happen because all
// qualified paths should be in PatQPath.
TypecheckRequired =>
self.session.span_bug(path.span,
"resolve_possibly_assoc_item claimed
\
that a path in PatEnum requires typecheck
\
to resolve, but qualified paths should be
\
PatQPath"),
ResolveAttempt(resolution) => resolution,
};
if let Some(path_res) = resolution {
match path_res.base_def {
DefVariant(..) | DefStruct(..) | DefConst(..) => {
@@ -2818,8 +2844,11 @@ struct or enum variant",
.as_str())
);
} else {
let const_name = path.segments.last().unwrap()
.identifier.name;
let const_name = path.segments
.last()
.unwrap()
.identifier
.name;
let traits = self.get_traits_containing_item(const_name);
self.trait_map.insert(pattern.id, traits);
self.record_def(pattern.id, path_res);
@@ -2839,23 +2868,27 @@ struct or enum variant",
PatQPath(ref qself, ref path) => {
// Associated constants only.
let resolution =
match self.resolve_possibly_assoc_item(pat_id, Some(qself),
path, ValueNS,
false) {
TypecheckRequired => {
// All `<T>::CONST` should end up here, and will
// require use of the trait map to resolve
// during typechecking.
let const_name = path.segments.last().unwrap()
.identifier.name;
let traits = self.get_traits_containing_item(const_name);
self.trait_map.insert(pattern.id, traits);
visit::walk_pat(self, pattern);
return true;
}
ResolveAttempt(resolution) => resolution,
};
let resolution = match self.resolve_possibly_assoc_item(pat_id,
Some(qself),
path,
ValueNS,
false) {
TypecheckRequired => {
// All `<T>::CONST` should end up here, and will
// require use of the trait map to resolve
// during typechecking.
let const_name = path.segments
.last()
.unwrap()
.identifier
.name;
let traits = self.get_traits_containing_item(const_name);
self.trait_map.insert(pattern.id, traits);
visit::walk_pat(self, pattern);
return true;
}
ResolveAttempt(resolution) => resolution,
};
if let Some(path_res) = resolution {
match path_res.base_def {
// All `<T as Trait>::CONST` should end up here, and
@@ -2874,13 +2907,14 @@ struct or enum variant",
}
}
} else {
resolve_error(
self,
path.span,
ResolutionError::UnresolvedAssociatedConst(
&path.segments.last().unwrap().identifier.name.as_str()
)
);
resolve_error(self,
path.span,
ResolutionError::UnresolvedAssociatedConst(&path.segments
.last()
.unwrap()
.identifier
.name
.as_str()));
}
visit::walk_pat(self, pattern);
}
@@ -2891,8 +2925,7 @@ struct or enum variant",
self.record_def(pattern.id, definition);
}
result => {
debug!("(resolving pattern) didn't find struct \
def: {:?}", result);
debug!("(resolving pattern) didn't find struct def: {:?}", result);
resolve_error(
self,
path.span,
@@ -2916,21 +2949,20 @@ struct or enum variant",
});
}
fn resolve_bare_identifier_pattern(&mut self, name: Name, span: Span)
fn resolve_bare_identifier_pattern(&mut self,
name: Name,
span: Span)
-> BareIdentifierPatternResolution {
let module = self.current_module.clone();
match self.resolve_item_in_lexical_scope(module,
name,
ValueNS) {
match self.resolve_item_in_lexical_scope(module, name, ValueNS) {
Success((target, _)) => {
debug!("(resolve bare identifier pattern) succeeded in \
finding {} at {:?}",
name,
target.bindings.value_def.borrow());
debug!("(resolve bare identifier pattern) succeeded in finding {} at {:?}",
name,
target.bindings.value_def.borrow());
match *target.bindings.value_def.borrow() {
None => {
panic!("resolved name in the value namespace to a \
set of name bindings with no def?!");
panic!("resolved name in the value namespace to a set of name bindings \
with no def?!");
}
Some(def) => {
// For the two success cases, this lookup can be
@@ -2944,9 +2976,7 @@ fn resolve_bare_identifier_pattern(&mut self, name: Name, span: Span)
return FoundConst(def, LastMod(AllPublic), name);
}
DefStatic(..) => {
resolve_error(self,
span,
ResolutionError::StaticVariableReference);
resolve_error(self, span, ResolutionError::StaticVariableReference);
return BareIdentifierPatternUnresolved;
}
_ => {
@@ -2965,11 +2995,10 @@ fn resolve_bare_identifier_pattern(&mut self, name: Name, span: Span)
Some((span, msg)) => {
resolve_error(self, span, ResolutionError::FailedToResolve(&*msg));
}
None => ()
None => (),
}
debug!("(resolve bare identifier pattern) failed to find {}",
name);
debug!("(resolve bare identifier pattern) failed to find {}", name);
return BareIdentifierPatternUnresolved;
}
}
@@ -2982,8 +3011,7 @@ fn resolve_possibly_assoc_item(&mut self,
path: &Path,
namespace: Namespace,
check_ribs: bool)
-> AssocItemResolveResult
{
-> AssocItemResolveResult {
let max_assoc_types;
match maybe_qself {
@@ -3008,8 +3036,7 @@ fn resolve_possibly_assoc_item(&mut self,
break;
}
self.with_no_errors(|this| {
resolution = this.resolve_path(id, path, depth,
TypeNS, true);
resolution = this.resolve_path(id, path, depth, TypeNS, true);
});
}
if let Some(DefMod(_)) = resolution.map(|r| r.base_def) {
@@ -3028,9 +3055,10 @@ pub fn resolve_path(&mut self,
path: &Path,
path_depth: usize,
namespace: Namespace,
check_ribs: bool) -> Option<PathResolution> {
check_ribs: bool)
-> Option<PathResolution> {
let span = path.span;
let segments = &path.segments[..path.segments.len()-path_depth];
let segments = &path.segments[..path.segments.len() - path_depth];
let mk_res = |(def, lp)| PathResolution::new(def, lp, path_depth);
@@ -3040,16 +3068,15 @@ pub fn resolve_path(&mut self,
}
// Try to find a path to an item in a module.
let unqualified_def = self.resolve_identifier(
segments.last().unwrap().identifier,
namespace, check_ribs);
let unqualified_def = self.resolve_identifier(segments.last().unwrap().identifier,
namespace,
check_ribs);
if segments.len() <= 1 {
return unqualified_def
.and_then(|def| self.adjust_local_def(def, span))
.map(|def| {
PathResolution::new(def, LastMod(AllPublic), path_depth)
});
return unqualified_def.and_then(|def| self.adjust_local_def(def, span))
.map(|def| {
PathResolution::new(def, LastMod(AllPublic), path_depth)
});
}
let def = self.resolve_module_relative_path(span, segments, namespace);
@@ -3057,7 +3084,8 @@ pub fn resolve_path(&mut self,
(Some((ref d, _)), Some(ref ud)) if *d == ud.def => {
self.session
.add_lint(lint::builtin::UNUSED_QUALIFICATIONS,
id, span,
id,
span,
"unnecessary qualification".to_string());
}
_ => {}
@@ -3082,8 +3110,7 @@ fn resolve_identifier(&mut self,
}
if check_ribs {
if let Some(def) = self.resolve_identifier_in_local_ribs(identifier,
namespace) {
if let Some(def) = self.resolve_identifier_in_local_ribs(identifier, namespace) {
return Some(def);
}
}
@@ -3095,15 +3122,14 @@ fn resolve_identifier(&mut self,
// Resolve a local definition, potentially adjusting for closures.
fn adjust_local_def(&mut self, local_def: LocalDef, span: Span) -> Option<Def> {
let ribs = match local_def.ribs {
Some((TypeNS, i)) => &self.type_ribs[i+1..],
Some((ValueNS, i)) => &self.value_ribs[i+1..],
_ => &[] as &[_]
Some((TypeNS, i)) => &self.type_ribs[i + 1..],
Some((ValueNS, i)) => &self.value_ribs[i + 1..],
_ => &[] as &[_],
};
let mut def = local_def.def;
match def {
DefUpvar(..) => {
self.session.span_bug(span,
&format!("unexpected {:?} in bindings", def))
self.session.span_bug(span, &format!("unexpected {:?} in bindings", def))
}
DefLocal(_, node_id) => {
for rib in ribs {
@@ -3115,16 +3141,21 @@ fn adjust_local_def(&mut self, local_def: LocalDef, span: Span) -> Option<Def> {
let prev_def = def;
let node_def_id = self.ast_map.local_def_id(node_id);
let seen = self.freevars_seen.entry(function_id)
.or_insert_with(|| NodeMap());
let seen = self.freevars_seen
.entry(function_id)
.or_insert_with(|| NodeMap());
if let Some(&index) = seen.get(&node_id) {
def = DefUpvar(node_def_id, node_id, index, function_id);
continue;
}
let vec = self.freevars.entry(function_id)
.or_insert_with(|| vec![]);
let vec = self.freevars
.entry(function_id)
.or_insert_with(|| vec![]);
let depth = vec.len();
vec.push(Freevar { def: prev_def, span: span });
vec.push(Freevar {
def: prev_def,
span: span,
});
def = DefUpvar(node_def_id, node_id, depth, function_id);
seen.insert(node_id, depth);
@@ -3133,20 +3164,16 @@ fn adjust_local_def(&mut self, local_def: LocalDef, span: Span) -> Option<Def> {
// This was an attempt to access an upvar inside a
// named function item. This is not allowed, so we
// report an error.
resolve_error(
self,
span,
ResolutionError::CannotCaptureDynamicEnvironmentInFnItem
);
resolve_error(self,
span,
ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
return None;
}
ConstantItemRibKind => {
// Still doesn't deal with upvars
resolve_error(
self,
span,
ResolutionError::AttemptToUseNonConstantValueInConstant
);
resolve_error(self,
span,
ResolutionError::AttemptToUseNonConstantValueInConstant);
return None;
}
}
@@ -3195,7 +3222,9 @@ fn resolve_definition_of_name_in_module(&mut self,
Some(def) => {
// Found it. Stop the search here.
let p = child_name_bindings.defined_in_public_namespace(namespace);
let lp = if p {LastMod(AllPublic)} else {
let lp = if p {
LastMod(AllPublic)
} else {
LastMod(DependsOn(def.def_id()))
};
return ChildNameDefinition(def, lp);
@@ -3220,7 +3249,7 @@ fn resolve_definition_of_name_in_module(&mut self,
match target.target_module.def_id.get() {
Some(DefId{krate: kid, ..}) => {
self.used_crates.insert(kid);
},
}
_ => {}
}
return ImportNameDefinition(def, LastMod(AllPublic));
@@ -3237,12 +3266,16 @@ fn resolve_definition_of_name_in_module(&mut self,
// Finally, search through external children.
if namespace == TypeNS {
if let Some(module) = containing_module.external_module_children.borrow()
.get(&name).cloned() {
if let Some(module) = containing_module.external_module_children
.borrow()
.get(&name)
.cloned() {
if let Some(def_id) = module.def_id.get() {
// track used crates
self.used_crates.insert(def_id.krate);
let lp = if module.is_public {LastMod(AllPublic)} else {
let lp = if module.is_public {
LastMod(AllPublic)
} else {
LastMod(DependsOn(def_id))
};
return ChildNameDefinition(DefMod(def_id), lp);
@@ -3259,9 +3292,12 @@ fn resolve_module_relative_path(&mut self,
segments: &[hir::PathSegment],
namespace: Namespace)
-> Option<(Def, LastPrivate)> {
let module_path = segments.split_last().unwrap().1.iter()
.map(|ps| ps.identifier.name)
.collect::<Vec<_>>();
let module_path = segments.split_last()
.unwrap()
.1
.iter()
.map(|ps| ps.identifier.name)
.collect::<Vec<_>>();
let containing_module;
let last_private;
@@ -3315,10 +3351,13 @@ fn resolve_crate_relative_path(&mut self,
span: Span,
segments: &[hir::PathSegment],
namespace: Namespace)
-> Option<(Def, LastPrivate)> {
let module_path = segments.split_last().unwrap().1.iter()
.map(|ps| ps.identifier.name)
.collect::<Vec<_>>();
-> Option<(Def, LastPrivate)> {
let module_path = segments.split_last()
.unwrap()
.1
.iter()
.map(|ps| ps.identifier.name)
.collect::<Vec<_>>();
let root_module = self.graph_root.get_module();
@@ -3355,9 +3394,7 @@ fn resolve_crate_relative_path(&mut self,
}
let name = segments.last().unwrap().identifier.name;
match self.resolve_definition_of_name_in_module(containing_module,
name,
namespace) {
match self.resolve_definition_of_name_in_module(containing_module, name, namespace) {
NoNameDefinition => {
// We failed to resolve the name. Report an error.
return None;
@@ -3375,7 +3412,7 @@ fn resolve_identifier_in_local_ribs(&mut self,
// Check the local set of ribs.
let (name, ribs) = match namespace {
ValueNS => (mtwt::resolve(ident), &self.value_ribs),
TypeNS => (ident.name, &self.type_ribs)
TypeNS => (ident.name, &self.type_ribs),
};
for (i, rib) in ribs.iter().enumerate().rev() {
@@ -3383,15 +3420,18 @@ fn resolve_identifier_in_local_ribs(&mut self,
match def_like {
DlDef(def) => {
debug!("(resolving path in local ribs) resolved `{}` to {:?} at {}",
name, def, i);
name,
def,
i);
return Some(LocalDef {
ribs: Some((namespace, i)),
def: def
def: def,
});
}
def_like => {
debug!("(resolving path in local ribs) resolved `{}` to pseudo-def {:?}",
name, def_like);
name,
def_like);
return None;
}
}
@@ -3404,25 +3444,22 @@ fn resolve_identifier_in_local_ribs(&mut self,
fn resolve_item_by_name_in_lexical_scope(&mut self,
name: Name,
namespace: Namespace)
-> Option<Def> {
-> Option<Def> {
// Check the items.
let module = self.current_module.clone();
match self.resolve_item_in_lexical_scope(module,
name,
namespace) {
match self.resolve_item_in_lexical_scope(module, name, namespace) {
Success((target, _)) => {
match (*target.bindings).def_for_namespace(namespace) {
None => {
// This can happen if we were looking for a type and
// found a module instead. Modules don't have defs.
debug!("(resolving item path by identifier in lexical \
scope) failed to resolve {} after success...",
name);
debug!("(resolving item path by identifier in lexical scope) failed to \
resolve {} after success...",
name);
None
}
Some(def) => {
debug!("(resolving item path in lexical scope) \
resolved `{}` to item",
debug!("(resolving item path in lexical scope) resolved `{}` to item",
name);
// This lookup is "all public" because it only searched
// for one identifier in the current module (couldn't
@@ -3435,8 +3472,8 @@ fn resolve_item_by_name_in_lexical_scope(&mut self,
panic!("unexpected indeterminate result");
}
Failed(err) => {
debug!("(resolving item path by identifier in lexical scope) \
failed to resolve {}", name);
debug!("(resolving item path by identifier in lexical scope) failed to resolve {}",
name);
if let Some((span, msg)) = err {
resolve_error(self, span, ResolutionError::FailedToResolve(&*msg))
@@ -3447,8 +3484,8 @@ fn resolve_item_by_name_in_lexical_scope(&mut self,
}
}
fn with_no_errors<T, F>(&mut self, f: F) -> T where
F: FnOnce(&mut Resolver) -> T,
fn with_no_errors<T, F>(&mut self, f: F) -> T
where F: FnOnce(&mut Resolver) -> T
{
self.emit_errors = false;
let rs = f(self);
@@ -3457,8 +3494,9 @@ fn with_no_errors<T, F>(&mut self, f: F) -> T where
}
fn find_fallback_in_self_type(&mut self, name: Name) -> FallbackSuggestion {
fn extract_path_and_node_id(t: &Ty, allow: FallbackChecks)
-> Option<(Path, NodeId, FallbackChecks)> {
fn extract_path_and_node_id(t: &Ty,
allow: FallbackChecks)
-> Option<(Path, NodeId, FallbackChecks)> {
match t.node {
TyPath(None, ref path) => Some((path.clone(), t.id, allow)),
TyPtr(ref mut_ty) => extract_path_and_node_id(&*mut_ty.ty, OnlyTraitAndStatics),
@@ -3470,8 +3508,10 @@ fn extract_path_and_node_id(t: &Ty, allow: FallbackChecks)
}
}
fn get_module(this: &mut Resolver, span: Span, name_path: &[ast::Name])
-> Option<Rc<Module>> {
fn get_module(this: &mut Resolver,
span: Span,
name_path: &[ast::Name])
-> Option<Rc<Module>> {
let root = this.current_module.clone();
let last_name = name_path.last().unwrap();
@@ -3481,7 +3521,7 @@ fn get_module(this: &mut Resolver, span: Span, name_path: &[ast::Name])
None => {
match this.current_module.children.borrow().get(last_name) {
Some(child) => child.get_module_if_available(),
None => None
None => None,
}
}
}
@@ -3492,7 +3532,7 @@ fn get_module(this: &mut Resolver, span: Span, name_path: &[ast::Name])
span,
PathSearch) {
Success((module, _)) => Some(module),
_ => None
_ => None,
}
}
}
@@ -3502,13 +3542,13 @@ fn is_static_method(this: &Resolver, did: DefId) -> bool {
let sig = match this.ast_map.get(node_id) {
hir_map::NodeTraitItem(trait_item) => match trait_item.node {
hir::MethodTraitItem(ref sig, _) => sig,
_ => return false
_ => return false,
},
hir_map::NodeImplItem(impl_item) => match impl_item.node {
hir::MethodImplItem(ref sig, _) => sig,
_ => return false
_ => return false,
},
_ => return false
_ => return false,
};
sig.explicit_self.node == hir::SelfStatic
} else {
@@ -3548,7 +3588,7 @@ fn is_static_method(this: &Resolver, did: DefId) -> bool {
if let Some(binding) = module.children.borrow().get(&name) {
if let Some(DefMethod(did)) = binding.def_for_namespace(ValueNS) {
if is_static_method(self, did) {
return StaticMethod(path_names_to_string(&path, 0))
return StaticMethod(path_names_to_string(&path, 0));
}
if self.current_trait_ref.is_some() {
return TraitItem;
@@ -3598,9 +3638,7 @@ fn find_best_match_for_name(&mut self, name: &str) -> Option<String> {
// the typo'd name's length.
let max_distance = std::cmp::max(name.len(), 3) / 3;
if !values.is_empty() &&
values[smallest] <= max_distance &&
name != &maybes[smallest][..] {
if !values.is_empty() && values[smallest] <= max_distance && name != &maybes[smallest][..] {
Some(maybes[smallest].to_string())
@@ -3618,22 +3656,21 @@ fn resolve_expr(&mut self, expr: &Expr) {
// Next, resolve the node.
match expr.node {
ExprPath(ref maybe_qself, ref path) => {
let resolution =
match self.resolve_possibly_assoc_item(expr.id,
maybe_qself.as_ref(),
path,
ValueNS,
true) {
// `<T>::a::b::c` is resolved by typeck alone.
TypecheckRequired => {
let method_name = path.segments.last().unwrap().identifier.name;
let traits = self.get_traits_containing_item(method_name);
self.trait_map.insert(expr.id, traits);
visit::walk_expr(self, expr);
return;
}
ResolveAttempt(resolution) => resolution,
};
let resolution = match self.resolve_possibly_assoc_item(expr.id,
maybe_qself.as_ref(),
path,
ValueNS,
true) {
// `<T>::a::b::c` is resolved by typeck alone.
TypecheckRequired => {
let method_name = path.segments.last().unwrap().identifier.name;
let traits = self.get_traits_containing_item(method_name);
self.trait_map.insert(expr.id, traits);
visit::walk_expr(self, expr);
return;
}
ResolveAttempt(resolution) => resolution,
};
// This is a local path in the value namespace. Walk through
// scopes looking for it.
@@ -3646,8 +3683,7 @@ fn resolve_expr(&mut self, expr: &Expr) {
expr.span,
ResolutionError::StructVariantUsedAsFunction(&*path_name));
let msg = format!("did you mean to write: \
`{} {{ /* fields */ }}`?",
let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
path_name);
if self.emit_errors {
self.session.fileline_help(expr.span, &msg);
@@ -3679,24 +3715,22 @@ fn resolve_expr(&mut self, expr: &Expr) {
this.resolve_path(expr.id, path, 0, TypeNS, false)
});
match type_res.map(|r| r.base_def) {
Some(DefTy(struct_id, _))
if self.structs.contains_key(&struct_id) => {
resolve_error(
Some(DefTy(struct_id, _)) if self.structs.contains_key(&struct_id) => {
resolve_error(
self,
expr.span,
ResolutionError::StructVariantUsedAsFunction(
&*path_name)
);
let msg = format!("did you mean to write: \
`{} {{ /* fields */ }}`?",
path_name);
if self.emit_errors {
self.session.fileline_help(expr.span, &msg);
} else {
self.session.span_help(expr.span, &msg);
}
let msg = format!("did you mean to write: `{} {{ /* fields */ }}`?",
path_name);
if self.emit_errors {
self.session.fileline_help(expr.span, &msg);
} else {
self.session.span_help(expr.span, &msg);
}
}
_ => {
// Keep reporting some errors even if they're ignored above.
self.resolve_path(expr.id, path, 0, ValueNS, true);
@@ -3712,11 +3746,9 @@ fn resolve_expr(&mut self, expr: &Expr) {
});
if method_scope && special_names::self_.as_str() == &path_name[..] {
resolve_error(
self,
expr.span,
ResolutionError::SelfNotAvailableInStaticMethod
);
resolve_error(self,
expr.span,
ResolutionError::SelfNotAvailableInStaticMethod);
} else {
let last_name = path.segments.last().unwrap().identifier.name;
let mut msg = match self.find_fallback_in_self_type(last_name) {
@@ -3724,16 +3756,14 @@ fn resolve_expr(&mut self, expr: &Expr) {
// limit search to 5 to reduce the number
// of stupid suggestions
self.find_best_match_for_name(&path_name)
.map_or("".to_string(),
|x| format!("`{}`", x))
.map_or("".to_string(), |x| format!("`{}`", x))
}
Field => format!("`self.{}`", path_name),
Method |
TraitItem =>
format!("to call `self.{}`", path_name),
TraitItem => format!("to call `self.{}`", path_name),
TraitMethod(path_str) |
StaticMethod(path_str) =>
format!("to call `{}::{}`", path_str, path_name)
format!("to call `{}::{}`", path_str, path_name),
};
if !msg.is_empty() {
@@ -3742,8 +3772,7 @@ fn resolve_expr(&mut self, expr: &Expr) {
resolve_error(self,
expr.span,
ResolutionError::UnresolvedName(&*path_name,
&*msg));
ResolutionError::UnresolvedName(&*path_name, &*msg));
}
}
}
@@ -3796,16 +3825,15 @@ fn resolve_expr(&mut self, expr: &Expr) {
}
Some(DlDef(def @ DefLabel(_))) => {
// Since this def is a label, it is never read.
self.record_def(expr.id, PathResolution {
base_def: def,
last_private: LastMod(AllPublic),
depth: 0
})
self.record_def(expr.id,
PathResolution {
base_def: def,
last_private: LastMod(AllPublic),
depth: 0,
})
}
Some(_) => {
self.session.span_bug(expr.span,
"label wasn't mapped to a \
label def!")
self.session.span_bug(expr.span, "label wasn't mapped to a label def!")
}
}
}
@@ -3827,8 +3855,7 @@ fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
self.trait_map.insert(expr.id, traits);
}
ExprMethodCall(name, _, _) => {
debug!("(recording candidate traits for expr) recording \
traits for {}",
debug!("(recording candidate traits for expr) recording traits for {}",
expr.id);
let traits = self.get_traits_containing_item(name.node);
self.trait_map.insert(expr.id, traits);
@@ -3840,15 +3867,12 @@ fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
}
fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
debug!("(getting traits containing item) looking for '{}'",
name);
debug!("(getting traits containing item) looking for '{}'", name);
fn add_trait_info(found_traits: &mut Vec<DefId>,
trait_def_id: DefId,
name: Name) {
fn add_trait_info(found_traits: &mut Vec<DefId>, trait_def_id: DefId, name: Name) {
debug!("(adding trait info) found trait {:?} for method '{}'",
trait_def_id,
name);
trait_def_id,
name);
found_traits.push(trait_def_id);
}
@@ -3872,7 +3896,7 @@ fn add_trait_info(found_traits: &mut Vec<DefId>,
for (_, child_names) in search_module.children.borrow().iter() {
let def = match child_names.def_for_namespace(TypeNS) {
Some(def) => def,
None => continue
None => continue,
};
let trait_def_id = match def {
DefTrait(trait_def_id) => trait_def_id,
@@ -3919,21 +3943,25 @@ fn add_trait_info(found_traits: &mut Vec<DefId>,
fn record_def(&mut self, node_id: NodeId, resolution: PathResolution) {
debug!("(recording def) recording {:?} for {}", resolution, node_id);
assert!(match resolution.last_private {LastImport{..} => false, _ => true},
assert!(match resolution.last_private {
LastImport{..} => false,
_ => true,
},
"Import should only be used for `use` directives");
if let Some(prev_res) = self.def_map.borrow_mut().insert(node_id, resolution) {
let span = self.ast_map.opt_span(node_id).unwrap_or(codemap::DUMMY_SP);
self.session.span_bug(span, &format!("path resolved multiple times \
({:?} before, {:?} now)",
prev_res, resolution));
self.session.span_bug(span,
&format!("path resolved multiple times ({:?} before, {:?} now)",
prev_res,
resolution));
}
}
fn enforce_default_binding_mode(&mut self,
pat: &Pat,
pat_binding_mode: BindingMode,
descr: &str) {
pat: &Pat,
pat_binding_mode: BindingMode,
descr: &str) {
match pat_binding_mode {
BindByValue(_) => {}
BindByRef(..) => {
@@ -3966,7 +3994,9 @@ fn dump_module(&mut self, module_: Rc<Module>) {
for (&name, import_resolution) in import_resolutions.iter() {
let value_repr;
match import_resolution.target_for_namespace(ValueNS) {
None => { value_repr = "".to_string(); }
None => {
value_repr = "".to_string();
}
Some(_) => {
value_repr = " value:?".to_string();
// FIXME #4954
@@ -3975,7 +4005,9 @@ fn dump_module(&mut self, module_: Rc<Module>) {
let type_repr;
match import_resolution.target_for_namespace(TypeNS) {
None => { type_repr = "".to_string(); }
None => {
type_repr = "".to_string();
}
Some(_) => {
type_repr = " type:?".to_string();
// FIXME #4954
@@ -3998,12 +4030,12 @@ fn names_to_string(names: &[Name]) -> String {
result.push_str("::")
}
result.push_str(&name.as_str());
};
}
result
}
fn path_names_to_string(path: &Path, depth: usize) -> String {
let names: Vec<ast::Name> = path.segments[..path.segments.len()-depth]
let names: Vec<ast::Name> = path.segments[..path.segments.len() - depth]
.iter()
.map(|seg| seg.identifier.name)
.collect();
@@ -4043,13 +4075,13 @@ pub struct CrateMap {
pub export_map: ExportMap,
pub trait_map: TraitMap,
pub external_exports: ExternalExports,
pub glob_map: Option<GlobMap>
pub glob_map: Option<GlobMap>,
}
#[derive(PartialEq,Copy, Clone)]
pub enum MakeGlobMap {
Yes,
No
No,
}
/// Entry point to crate resolution.
@@ -4072,10 +4104,10 @@ pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
trait_map: resolver.trait_map,
external_exports: resolver.external_exports,
glob_map: if resolver.make_glob_map {
Some(resolver.glob_map)
} else {
None
},
Some(resolver.glob_map)
} else {
None
},
}
}
+16 -23
View File
@@ -30,8 +30,8 @@
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
struct ExportRecorder<'a, 'b:'a, 'tcx:'b> {
resolver: &'a mut Resolver<'b, 'tcx>
struct ExportRecorder<'a, 'b: 'a, 'tcx: 'b> {
resolver: &'a mut Resolver<'b, 'tcx>,
}
// Deref and DerefMut impls allow treating ExportRecorder as Resolver.
@@ -50,28 +50,26 @@ fn deref_mut<'c>(&'c mut self) -> &'c mut Resolver<'b, 'tcx> {
}
impl<'a, 'b, 'tcx> ExportRecorder<'a, 'b, 'tcx> {
fn record_exports_for_module_subtree(&mut self,
module_: Rc<Module>) {
fn record_exports_for_module_subtree(&mut self, module_: Rc<Module>) {
// If this isn't a local krate, then bail out. We don't need to record
// exports for nonlocal crates.
match module_.def_id.get() {
Some(def_id) if def_id.is_local() => {
// OK. Continue.
debug!("(recording exports for module subtree) recording \
exports for local module `{}`",
debug!("(recording exports for module subtree) recording exports for local \
module `{}`",
module_to_string(&*module_));
}
None => {
// Record exports for the root module.
debug!("(recording exports for module subtree) recording \
exports for root module `{}`",
debug!("(recording exports for module subtree) recording exports for root module \
`{}`",
module_to_string(&*module_));
}
Some(_) => {
// Bail out.
debug!("(recording exports for module subtree) not recording \
exports for `{}`",
debug!("(recording exports for module subtree) not recording exports for `{}`",
module_to_string(&*module_));
return;
}
@@ -118,10 +116,11 @@ fn add_exports_of_namebindings(&mut self,
match namebindings.def_for_namespace(ns) {
Some(d) => {
debug!("(computing exports) YES: export '{}' => {:?}",
name, d.def_id());
name,
d.def_id());
exports.push(Export {
name: name,
def_id: d.def_id()
def_id: d.def_id(),
});
}
d_opt => {
@@ -130,25 +129,19 @@ fn add_exports_of_namebindings(&mut self,
}
}
fn add_exports_for_module(&mut self,
exports: &mut Vec<Export>,
module_: &Module) {
fn add_exports_for_module(&mut self, exports: &mut Vec<Export>, module_: &Module) {
for (name, import_resolution) in module_.import_resolutions.borrow().iter() {
if !import_resolution.is_public {
continue
continue;
}
let xs = [TypeNS, ValueNS];
for &ns in &xs {
match import_resolution.target_for_namespace(ns) {
Some(target) => {
debug!("(computing exports) maybe export '{}'",
name);
self.add_exports_of_namebindings(exports,
*name,
&*target.bindings,
ns)
debug!("(computing exports) maybe export '{}'", name);
self.add_exports_of_namebindings(exports, *name, &*target.bindings, ns)
}
_ => ()
_ => (),
}
}
}
+172 -178
View File
@@ -42,14 +42,14 @@
#[derive(Copy, Clone,Debug)]
pub enum ImportDirectiveSubclass {
SingleImport(Name /* target */, Name /* source */),
GlobImport
GlobImport,
}
/// Whether an import can be shadowed by another import.
#[derive(Debug,PartialEq,Clone,Copy)]
pub enum Shadowable {
Always,
Never
Never,
}
/// One import directive.
@@ -64,13 +64,13 @@ pub struct ImportDirective {
}
impl ImportDirective {
pub fn new(module_path: Vec<Name> ,
subclass: ImportDirectiveSubclass,
span: Span,
id: NodeId,
is_public: bool,
shadowable: Shadowable)
-> ImportDirective {
pub fn new(module_path: Vec<Name>,
subclass: ImportDirectiveSubclass,
span: Span,
id: NodeId,
is_public: bool,
shadowable: Shadowable)
-> ImportDirective {
ImportDirective {
module_path: module_path,
subclass: subclass,
@@ -92,9 +92,9 @@ pub struct Target {
impl Target {
pub fn new(target_module: Rc<Module>,
bindings: Rc<NameBindings>,
shadowable: Shadowable)
-> Target {
bindings: Rc<NameBindings>,
shadowable: Shadowable)
-> Target {
Target {
target_module: target_module,
bindings: bindings,
@@ -144,17 +144,16 @@ pub fn new(id: NodeId, is_public: bool) -> ImportResolution {
}
}
pub fn target_for_namespace(&self, namespace: Namespace)
-> Option<Target> {
pub fn target_for_namespace(&self, namespace: Namespace) -> Option<Target> {
match namespace {
TypeNS => self.type_target.clone(),
TypeNS => self.type_target.clone(),
ValueNS => self.value_target.clone(),
}
}
pub fn id(&self, namespace: Namespace) -> NodeId {
match namespace {
TypeNS => self.type_id,
TypeNS => self.type_id,
ValueNS => self.value_id,
}
}
@@ -168,12 +167,9 @@ pub fn shadowable(&self, namespace: Namespace) -> Shadowable {
target.unwrap().shadowable
}
pub fn set_target_and_id(&mut self,
namespace: Namespace,
target: Option<Target>,
id: NodeId) {
pub fn set_target_and_id(&mut self, namespace: Namespace, target: Option<Target>, id: NodeId) {
match namespace {
TypeNS => {
TypeNS => {
self.type_target = target;
self.type_id = id;
}
@@ -191,8 +187,8 @@ struct ImportResolvingError {
help: String,
}
struct ImportResolver<'a, 'b:'a, 'tcx:'b> {
resolver: &'a mut Resolver<'b, 'tcx>
struct ImportResolver<'a, 'b: 'a, 'tcx: 'b> {
resolver: &'a mut Resolver<'b, 'tcx>,
}
impl<'a, 'b:'a, 'tcx:'b> ImportResolver<'a, 'b, 'tcx> {
@@ -211,7 +207,8 @@ fn resolve_imports(&mut self) {
let mut prev_unresolved_imports = 0;
loop {
debug!("(resolving imports) iteration {}, {} imports left",
i, self.resolver.unresolved_imports);
i,
self.resolver.unresolved_imports);
let module_root = self.resolver.graph_root.get_module();
let errors = self.resolve_imports_for_module_subtree(module_root.clone());
@@ -246,7 +243,8 @@ fn resolve_imports(&mut self) {
/// Attempts to resolve imports for the given module and all of its
/// submodules.
fn resolve_imports_for_module_subtree(&mut self, module_: Rc<Module>)
fn resolve_imports_for_module_subtree(&mut self,
module_: Rc<Module>)
-> Vec<ImportResolvingError> {
let mut errors = Vec::new();
debug!("(resolving imports for module subtree) resolving {}",
@@ -279,8 +277,7 @@ fn resolve_imports_for_module(&mut self, module: Rc<Module>) -> Vec<ImportResolv
let mut errors = Vec::new();
if module.all_imports_resolved() {
debug!("(resolving imports for module) all imports resolved for \
{}",
debug!("(resolving imports for module) all imports resolved for {}",
module_to_string(&*module));
return errors;
}
@@ -290,22 +287,19 @@ fn resolve_imports_for_module(&mut self, module: Rc<Module>) -> Vec<ImportResolv
let mut indeterminate_imports = Vec::new();
while module.resolved_import_count.get() + indeterminate_imports.len() < import_count {
let import_index = module.resolved_import_count.get();
match self.resolve_import_for_module(module.clone(),
&imports[import_index]) {
match self.resolve_import_for_module(module.clone(), &imports[import_index]) {
ResolveResult::Failed(err) => {
let import_directive = &imports[import_index];
let (span, help) = match err {
Some((span, msg)) => (span, format!(". {}", msg)),
None => (import_directive.span, String::new())
None => (import_directive.span, String::new()),
};
errors.push(ImportResolvingError {
span: span,
path: import_path_to_string(
&import_directive.module_path,
import_directive.subclass
),
help: help
});
span: span,
path: import_path_to_string(&import_directive.module_path,
import_directive.subclass),
help: help,
});
}
ResolveResult::Indeterminate => {}
ResolveResult::Success(()) => {
@@ -354,7 +348,7 @@ fn resolve_import_for_module(&mut self,
ResolveResult::Failed(err) => {
resolution_result = ResolveResult::Failed(err);
None
},
}
ResolveResult::Indeterminate => {
resolution_result = ResolveResult::Indeterminate;
None
@@ -371,20 +365,18 @@ fn resolve_import_for_module(&mut self,
match import_directive.subclass {
SingleImport(target, source) => {
resolution_result =
self.resolve_single_import(&module_,
containing_module,
target,
source,
import_directive,
lp);
resolution_result = self.resolve_single_import(&module_,
containing_module,
target,
source,
import_directive,
lp);
}
GlobImport => {
resolution_result =
self.resolve_glob_import(&module_,
containing_module,
import_directive,
lp);
resolution_result = self.resolve_glob_import(&module_,
containing_module,
import_directive,
lp);
}
}
}
@@ -433,8 +425,8 @@ fn resolve_single_import(&mut self,
directive: &ImportDirective,
lp: LastPrivate)
-> ResolveResult<()> {
debug!("(resolving single import) resolving `{}` = `{}::{}` from \
`{}` id {}, last private {:?}",
debug!("(resolving single import) resolving `{}` = `{}::{}` from `{}` id {}, last \
private {:?}",
target,
module_to_string(&*target_module),
source,
@@ -445,9 +437,9 @@ fn resolve_single_import(&mut self,
let lp = match lp {
LastMod(lp) => lp,
LastImport {..} => {
self.resolver.session
.span_bug(directive.span,
"not expecting Import here, must be LastMod")
self.resolver
.session
.span_bug(directive.span, "not expecting Import here, must be LastMod")
}
};
@@ -472,11 +464,10 @@ fn resolve_single_import(&mut self,
value_result = BoundResult(target_module.clone(),
(*child_name_bindings).clone());
if directive.is_public && !child_name_bindings.is_public(ValueNS) {
let msg = format!("`{}` is private, and cannot be reexported",
source);
let note_msg =
format!("Consider marking `{}` as `pub` in the imported module",
source);
let msg = format!("`{}` is private, and cannot be reexported", source);
let note_msg = format!("Consider marking `{}` as `pub` in the imported \
module",
source);
span_err!(self.resolver.session, directive.span, E0364, "{}", &msg);
self.resolver.session.span_note(directive.span, &note_msg);
pub_err = true;
@@ -487,8 +478,7 @@ fn resolve_single_import(&mut self,
type_result = BoundResult(target_module.clone(),
(*child_name_bindings).clone());
if !pub_err && directive.is_public && !child_name_bindings.is_public(TypeNS) {
let msg = format!("`{}` is private, and cannot be reexported",
source);
let msg = format!("`{}` is private, and cannot be reexported", source);
let note_msg = format!("Consider declaring module `{}` as a `pub mod`",
source);
span_err!(self.resolver.session, directive.span, E0365, "{}", &msg);
@@ -510,8 +500,7 @@ fn resolve_single_import(&mut self,
// able to resolve this import.
if target_module.pub_glob_count.get() > 0 {
debug!("(resolving single import) unresolved pub glob; \
bailing out");
debug!("(resolving single import) unresolved pub glob; bailing out");
return ResolveResult::Indeterminate;
}
@@ -531,14 +520,13 @@ fn resolve_single_import(&mut self,
type_result = UnboundResult;
}
}
Some(import_resolution)
if import_resolution.outstanding_references == 0 => {
Some(import_resolution) if import_resolution.outstanding_references == 0 => {
fn get_binding(this: &mut Resolver,
import_resolution: &ImportResolution,
namespace: Namespace,
source: Name)
-> NamespaceResult {
-> NamespaceResult {
// Import resolutions must be declared with "pub"
// in order to be exported.
@@ -555,8 +543,8 @@ fn get_binding(this: &mut Resolver,
bindings,
shadowable: _
}) => {
debug!("(resolving single import) found \
import in ns {:?}", namespace);
debug!("(resolving single import) found import in ns {:?}",
namespace);
let id = import_resolution.id(namespace);
// track used imports and extern crates as well
this.used_imports.insert((id, namespace));
@@ -564,7 +552,7 @@ fn get_binding(this: &mut Resolver,
match target_module.def_id.get() {
Some(DefId{krate: kid, ..}) => {
this.used_crates.insert(kid);
},
}
_ => {}
}
return BoundResult(target_module, bindings);
@@ -603,8 +591,8 @@ fn get_binding(this: &mut Resolver,
// In this case we continue as if we resolved the import and let the
// check_for_conflicts_between_imports_and_items call below handle
// the conflict
match (module_.def_id.get(), target_module.def_id.get()) {
(Some(id1), Some(id2)) if id1 == id2 => {
match (module_.def_id.get(), target_module.def_id.get()) {
(Some(id1), Some(id2)) if id1 == id2 => {
if value_result.is_unknown() {
value_result = UnboundResult;
}
@@ -612,10 +600,9 @@ fn get_binding(this: &mut Resolver,
type_result = UnboundResult;
}
}
_ => {
_ => {
// The import is unresolved. Bail out.
debug!("(resolving single import) unresolved import; \
bailing out");
debug!("(resolving single import) unresolved import; bailing out");
return ResolveResult::Indeterminate;
}
}
@@ -668,17 +655,15 @@ fn get_binding(this: &mut Resolver,
debug!("(resolving single import) found {:?} target: {:?}",
namespace_name,
name_bindings.def_for_namespace(namespace));
self.check_for_conflicting_import(
&import_resolution,
directive.span,
target,
namespace);
self.check_for_conflicting_import(&import_resolution,
directive.span,
target,
namespace);
self.check_that_import_is_importable(
&**name_bindings,
directive.span,
target,
namespace);
self.check_that_import_is_importable(&**name_bindings,
directive.span,
target,
namespace);
let target = Some(Target::new(target_module.clone(),
name_bindings.clone(),
@@ -687,7 +672,9 @@ fn get_binding(this: &mut Resolver,
import_resolution.is_public = directive.is_public;
*used_public = name_bindings.defined_in_public_namespace(namespace);
}
UnboundResult => { /* Continue. */ }
UnboundResult => {
// Continue.
}
UnknownResult => {
panic!("{:?} result should be known at this point", namespace_name);
}
@@ -697,11 +684,10 @@ fn get_binding(this: &mut Resolver,
check_and_write_import(TypeNS, &type_result, &mut type_used_public);
}
self.check_for_conflicts_between_imports_and_items(
module_,
import_resolution,
directive.span,
target);
self.check_for_conflicts_between_imports_and_items(module_,
import_resolution,
directive.span,
target);
if value_result.is_unbound() && type_result.is_unbound() {
let msg = format!("There is no `{}` in `{}`",
@@ -720,33 +706,45 @@ fn get_binding(this: &mut Resolver,
// purposes it's good enough to just favor one over the other.
let value_def_and_priv = import_resolution.value_target.as_ref().map(|target| {
let def = target.bindings.def_for_namespace(ValueNS).unwrap();
(def, if value_used_public { lp } else { DependsOn(def.def_id()) })
(def,
if value_used_public {
lp
} else {
DependsOn(def.def_id())
})
});
let type_def_and_priv = import_resolution.type_target.as_ref().map(|target| {
let def = target.bindings.def_for_namespace(TypeNS).unwrap();
(def, if type_used_public { lp } else { DependsOn(def.def_id()) })
(def,
if type_used_public {
lp
} else {
DependsOn(def.def_id())
})
});
let import_lp = LastImport {
value_priv: value_def_and_priv.map(|(_, p)| p),
value_used: Used,
type_priv: type_def_and_priv.map(|(_, p)| p),
type_used: Used
type_used: Used,
};
if let Some((def, _)) = value_def_and_priv {
self.resolver.def_map.borrow_mut().insert(directive.id, PathResolution {
base_def: def,
last_private: import_lp,
depth: 0
});
self.resolver.def_map.borrow_mut().insert(directive.id,
PathResolution {
base_def: def,
last_private: import_lp,
depth: 0,
});
}
if let Some((def, _)) = type_def_and_priv {
self.resolver.def_map.borrow_mut().insert(directive.id, PathResolution {
base_def: def,
last_private: import_lp,
depth: 0
});
self.resolver.def_map.borrow_mut().insert(directive.id,
PathResolution {
base_def: def,
last_private: import_lp,
depth: 0,
});
}
debug!("(resolving single import) successfully resolved import");
@@ -774,8 +772,7 @@ fn resolve_glob_import(&mut self,
// We must bail out if the node has unresolved imports of any kind
// (including globs).
if (*target_module).pub_count.get() > 0 {
debug!("(resolving glob import) target module has unresolved \
pub imports; bailing out");
debug!("(resolving glob import) target module has unresolved pub imports; bailing out");
return ResolveResult::Indeterminate;
}
@@ -787,21 +784,18 @@ fn resolve_glob_import(&mut self,
// This means we are trying to glob import a module into itself,
// and it is a no-go
debug!("(resolving glob imports) target module is current module; giving up");
return ResolveResult::Failed(Some((
import_directive.span,
"Cannot glob-import a module into itself.".into()
)));
return ResolveResult::Failed(Some((import_directive.span,
"Cannot glob-import a module into itself.".into())));
}
for (name, target_import_resolution) in import_resolutions.iter() {
debug!("(resolving glob import) writing module resolution \
{} into `{}`",
debug!("(resolving glob import) writing module resolution {} into `{}`",
*name,
module_to_string(module_));
if !target_import_resolution.is_public {
debug!("(resolving glob import) nevermind, just kidding");
continue
continue;
}
// Here we merge two import resolutions.
@@ -843,10 +837,8 @@ fn resolve_glob_import(&mut self,
// Simple: just copy the old import resolution.
let mut new_import_resolution = ImportResolution::new(id, is_public);
new_import_resolution.value_target =
target_import_resolution.value_target.clone();
new_import_resolution.type_target =
target_import_resolution.type_target.clone();
new_import_resolution.value_target = target_import_resolution.value_target.clone();
new_import_resolution.type_target = target_import_resolution.type_target.clone();
import_resolutions.insert(*name, new_import_resolution);
}
@@ -865,8 +857,7 @@ fn resolve_glob_import(&mut self,
// Add external module children from the containing module.
for (&name, module) in target_module.external_module_children.borrow().iter() {
let name_bindings =
Rc::new(Resolver::create_name_bindings_from_module(module.clone()));
let name_bindings = Rc::new(Resolver::create_name_bindings_from_module(module.clone()));
self.merge_import_resolution(module_,
target_module.clone(),
import_directive,
@@ -876,11 +867,12 @@ fn resolve_glob_import(&mut self,
// Record the destination of this import
if let Some(did) = target_module.def_id.get() {
self.resolver.def_map.borrow_mut().insert(id, PathResolution {
base_def: DefMod(did),
last_private: lp,
depth: 0
});
self.resolver.def_map.borrow_mut().insert(id,
PathResolution {
base_def: DefMod(did),
last_private: lp,
depth: 0,
});
}
debug!("(resolving glob import) successfully resolved import");
@@ -898,10 +890,11 @@ fn merge_import_resolution(&mut self,
let mut import_resolutions = module_.import_resolutions.borrow_mut();
let dest_import_resolution = import_resolutions.entry(name)
.or_insert_with(|| ImportResolution::new(id, is_public));
.or_insert_with(|| {
ImportResolution::new(id, is_public)
});
debug!("(resolving glob import) writing resolution `{}` in `{}` \
to `{}`",
debug!("(resolving glob import) writing resolution `{}` in `{}` to `{}`",
name,
module_to_string(&*containing_module),
module_to_string(module_));
@@ -918,18 +911,20 @@ fn merge_import_resolution(&mut self,
};
debug!("(resolving glob import) ... for {} target", namespace_name);
if dest_import_resolution.shadowable(namespace) == Shadowable::Never {
let msg = format!("a {} named `{}` has already been imported \
in this module",
let msg = format!("a {} named `{}` has already been imported in this \
module",
namespace_name,
name);
span_err!(self.resolver.session, import_directive.span, E0251, "{}", msg);
span_err!(self.resolver.session,
import_directive.span,
E0251,
"{}",
msg);
} else {
let target = Target::new(containing_module.clone(),
name_bindings.clone(),
import_directive.shadowable);
dest_import_resolution.set_target_and_id(namespace,
Some(target),
id);
dest_import_resolution.set_target_and_id(namespace, Some(target), id);
}
}
};
@@ -939,11 +934,10 @@ fn merge_import_resolution(&mut self,
dest_import_resolution.is_public = is_public;
self.check_for_conflicts_between_imports_and_items(
module_,
dest_import_resolution,
import_directive.span,
name);
self.check_for_conflicts_between_imports_and_items(module_,
dest_import_resolution,
import_directive.span,
name);
}
/// Checks that imported names and items don't have the same name.
@@ -963,28 +957,31 @@ fn check_for_conflicting_import(&mut self,
TypeNS => {
if let Some(ref ty_def) = *target.bindings.type_def.borrow() {
match ty_def.module_def {
Some(ref module)
if module.kind.get() == ModuleKind::NormalModuleKind =>
"module",
Some(ref module)
if module.kind.get() == ModuleKind::TraitModuleKind =>
"trait",
Some(ref module) if module.kind.get() ==
ModuleKind::NormalModuleKind => "module",
Some(ref module) if module.kind.get() ==
ModuleKind::TraitModuleKind => "trait",
_ => "type",
}
} else { "type" }
},
} else {
"type"
}
}
ValueNS => "value",
};
span_err!(self.resolver.session, import_span, E0252,
"a {} named `{}` has already been imported \
in this module", ns_word,
name);
span_err!(self.resolver.session,
import_span,
E0252,
"a {} named `{}` has already been imported in this module",
ns_word,
name);
let use_id = import_resolution.id(namespace);
let item = self.resolver.ast_map.expect_item(use_id);
// item is syntax::ast::Item;
span_note!(self.resolver.session, item.span,
"previous import of `{}` here",
name);
span_note!(self.resolver.session,
item.span,
"previous import of `{}` here",
name);
}
Some(_) | None => {}
}
@@ -997,8 +994,7 @@ fn check_that_import_is_importable(&mut self,
name: Name,
namespace: Namespace) {
if !name_bindings.defined_in_namespace_with(namespace, DefModifiers::IMPORTABLE) {
let msg = format!("`{}` is not directly importable",
name);
let msg = format!("`{}` is not directly importable", name);
span_err!(self.resolver.session, import_span, E0253, "{}", &msg[..]);
}
}
@@ -1006,8 +1002,7 @@ fn check_that_import_is_importable(&mut self,
/// Checks that imported names and items don't have the same name.
fn check_for_conflicts_between_imports_and_items(&mut self,
module: &Module,
import_resolution:
&ImportResolution,
import_resolution: &ImportResolution,
import_span: Span,
name: Name) {
// First, check for conflicts between imports and `extern crate`s.
@@ -1016,8 +1011,7 @@ fn check_for_conflicts_between_imports_and_items(&mut self,
.contains_key(&name) {
match import_resolution.type_target {
Some(ref target) if target.shadowable != Shadowable::Always => {
let msg = format!("import `{0}` conflicts with imported \
crate in this module \
let msg = format!("import `{0}` conflicts with imported crate in this module \
(maybe you meant `use {0}::*`?)",
name);
span_err!(self.resolver.session, import_span, E0254, "{}", &msg[..]);
@@ -1031,7 +1025,7 @@ fn check_for_conflicts_between_imports_and_items(&mut self,
let name_bindings = match children.get(&name) {
None => {
// There can't be any conflicts.
return
return;
}
Some(ref name_bindings) => (*name_bindings).clone(),
};
@@ -1039,7 +1033,9 @@ fn check_for_conflicts_between_imports_and_items(&mut self,
match import_resolution.value_target {
Some(ref target) if target.shadowable != Shadowable::Always => {
if let Some(ref value) = *name_bindings.value_def.borrow() {
span_err!(self.resolver.session, import_span, E0255,
span_err!(self.resolver.session,
import_span,
E0255,
"import `{}` conflicts with value in this module",
name);
if let Some(span) = value.value_span {
@@ -1054,17 +1050,18 @@ fn check_for_conflicts_between_imports_and_items(&mut self,
Some(ref target) if target.shadowable != Shadowable::Always => {
if let Some(ref ty) = *name_bindings.type_def.borrow() {
let (what, note) = match ty.module_def {
Some(ref module)
if module.kind.get() == ModuleKind::NormalModuleKind =>
("existing submodule", "note conflicting module here"),
Some(ref module)
if module.kind.get() == ModuleKind::TraitModuleKind =>
("trait in this module", "note conflicting trait here"),
_ => ("type in this module", "note conflicting type here"),
Some(ref module) if module.kind.get() == ModuleKind::NormalModuleKind =>
("existing submodule", "note conflicting module here"),
Some(ref module) if module.kind.get() == ModuleKind::TraitModuleKind =>
("trait in this module", "note conflicting trait here"),
_ => ("type in this module", "note conflicting type here"),
};
span_err!(self.resolver.session, import_span, E0256,
span_err!(self.resolver.session,
import_span,
E0256,
"import `{}` conflicts with {}",
name, what);
name,
what);
if let Some(span) = ty.type_span {
self.resolver.session.span_note(span, note);
}
@@ -1075,28 +1072,25 @@ fn check_for_conflicts_between_imports_and_items(&mut self,
}
}
fn import_path_to_string(names: &[Name],
subclass: ImportDirectiveSubclass)
-> String {
fn import_path_to_string(names: &[Name], subclass: ImportDirectiveSubclass) -> String {
if names.is_empty() {
import_directive_subclass_to_string(subclass)
} else {
(format!("{}::{}",
names_to_string(names),
import_directive_subclass_to_string(subclass))).to_string()
import_directive_subclass_to_string(subclass)))
.to_string()
}
}
fn import_directive_subclass_to_string(subclass: ImportDirectiveSubclass) -> String {
match subclass {
SingleImport(_, source) => source.to_string(),
GlobImport => "*".to_string()
GlobImport => "*".to_string(),
}
}
pub fn resolve_imports(resolver: &mut Resolver) {
let mut import_resolver = ImportResolver {
resolver: resolver,
};
let mut import_resolver = ImportResolver { resolver: resolver };
import_resolver.resolve_imports();
}