use single version of either in hir

This commit is contained in:
Aleksey Kladov 2019-06-11 01:06:11 +03:00
parent 75e6c03883
commit 156b7ee842
7 changed files with 73 additions and 68 deletions

1
Cargo.lock generated
View file

@ -1079,7 +1079,6 @@ dependencies = [
"chalk-ir 0.1.0 (git+https://github.com/flodiebold/chalk.git?branch=fuel)", "chalk-ir 0.1.0 (git+https://github.com/flodiebold/chalk.git?branch=fuel)",
"chalk-rust-ir 0.1.0 (git+https://github.com/flodiebold/chalk.git?branch=fuel)", "chalk-rust-ir 0.1.0 (git+https://github.com/flodiebold/chalk.git?branch=fuel)",
"chalk-solve 0.1.0 (git+https://github.com/flodiebold/chalk.git?branch=fuel)", "chalk-solve 0.1.0 (git+https://github.com/flodiebold/chalk.git?branch=fuel)",
"either 1.5.2 (registry+https://github.com/rust-lang/crates.io-index)",
"ena 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", "ena 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)",
"flexi_logger 0.11.5 (registry+https://github.com/rust-lang/crates.io-index)", "flexi_logger 0.11.5 (registry+https://github.com/rust-lang/crates.io-index)",
"insta 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)", "insta 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)",

View file

@ -12,7 +12,6 @@ rustc-hash = "1.0"
parking_lot = "0.8.0" parking_lot = "0.8.0"
ena = "0.11" ena = "0.11"
join_to_string = "0.1.3" join_to_string = "0.1.3"
either = "1.5.2"
once_cell = "0.2" once_cell = "0.2"
ra_syntax = { path = "../ra_syntax" } ra_syntax = { path = "../ra_syntax" }

View file

@ -25,4 +25,22 @@ impl<A, B> Either<A, B> {
Either::B(b) => Either::B(f2(b)), Either::B(b) => Either::B(f2(b)),
} }
} }
pub fn a(self) -> Option<A> {
match self {
Either::A(it) => Some(it),
Either::B(_) => None,
}
}
pub fn b(self) -> Option<B> {
match self {
Either::A(_) => None,
Either::B(it) => Some(it),
}
}
pub fn as_ref(&self) -> Either<&A, &B> {
match self {
Either::A(it) => Either::A(it),
Either::B(it) => Either::B(it),
}
}
} }

View file

@ -56,7 +56,6 @@ mod tests;
use std::sync::Arc; use std::sync::Arc;
use rustc_hash::{FxHashMap, FxHashSet}; use rustc_hash::{FxHashMap, FxHashSet};
use either::Either;
use ra_arena::{Arena, RawId, impl_arena_id}; use ra_arena::{Arena, RawId, impl_arena_id};
use ra_db::{FileId, Edition}; use ra_db::{FileId, Edition};
use test_utils::tested_by; use test_utils::tested_by;
@ -70,6 +69,7 @@ use crate::{
ids::MacroDefId, ids::MacroDefId,
diagnostics::DiagnosticSink, diagnostics::DiagnosticSink,
nameres::diagnostics::DefDiagnostic, nameres::diagnostics::DefDiagnostic,
either::Either,
AstId, AstId,
}; };
@ -164,8 +164,8 @@ impl ModuleScope {
} }
fn get_item_or_macro(&self, name: &Name) -> Option<ItemOrMacro> { fn get_item_or_macro(&self, name: &Name) -> Option<ItemOrMacro> {
match (self.get(name), self.macros.get(name)) { match (self.get(name), self.macros.get(name)) {
(Some(item), _) if !item.def.is_none() => Some(Either::Left(item.def)), (Some(item), _) if !item.def.is_none() => Some(Either::A(item.def)),
(_, Some(macro_)) => Some(Either::Right(*macro_)), (_, Some(macro_)) => Some(Either::B(*macro_)),
_ => None, _ => None,
} }
} }
@ -190,7 +190,7 @@ struct ResolvePathResult {
impl ResolvePathResult { impl ResolvePathResult {
fn empty(reached_fixedpoint: ReachedFixedPoint) -> ResolvePathResult { fn empty(reached_fixedpoint: ReachedFixedPoint) -> ResolvePathResult {
ResolvePathResult::with(Either::Left(PerNs::none()), reached_fixedpoint, None) ResolvePathResult::with(Either::A(PerNs::none()), reached_fixedpoint, None)
} }
fn with( fn with(
@ -217,13 +217,13 @@ enum ReachedFixedPoint {
/// helper function for select item or macro to use /// helper function for select item or macro to use
fn or(left: ItemOrMacro, right: ItemOrMacro) -> ItemOrMacro { fn or(left: ItemOrMacro, right: ItemOrMacro) -> ItemOrMacro {
match (left, right) { match (left, right) {
(Either::Left(s), Either::Left(o)) => Either::Left(s.or(o)), (Either::A(s), Either::A(o)) => Either::A(s.or(o)),
(Either::Right(s), _) => Either::Right(s), (Either::B(s), _) => Either::B(s),
(Either::Left(s), Either::Right(o)) => { (Either::A(s), Either::B(o)) => {
if !s.is_none() { if !s.is_none() {
Either::Left(s) Either::A(s)
} else { } else {
Either::Right(o) Either::B(o)
} }
} }
} }
@ -306,7 +306,7 @@ impl CrateDefMap {
path: &Path, path: &Path,
) -> (PerNs<ModuleDef>, Option<usize>) { ) -> (PerNs<ModuleDef>, Option<usize>) {
let res = self.resolve_path_fp_with_macro(db, ResolveMode::Other, original_module, path); let res = self.resolve_path_fp_with_macro(db, ResolveMode::Other, original_module, path);
(res.resolved_def.left().unwrap_or_else(PerNs::none), res.segment_index) (res.resolved_def.a().unwrap_or_else(PerNs::none), res.segment_index)
} }
pub(crate) fn resolve_path_with_macro( pub(crate) fn resolve_path_with_macro(
@ -330,10 +330,10 @@ impl CrateDefMap {
) -> ResolvePathResult { ) -> ResolvePathResult {
let mut segments = path.segments.iter().enumerate(); let mut segments = path.segments.iter().enumerate();
let mut curr_per_ns: ItemOrMacro = match path.kind { let mut curr_per_ns: ItemOrMacro = match path.kind {
PathKind::Crate => Either::Left(PerNs::types( PathKind::Crate => {
Module { krate: self.krate, module_id: self.root }.into(), Either::A(PerNs::types(Module { krate: self.krate, module_id: self.root }.into()))
)), }
PathKind::Self_ => Either::Left(PerNs::types( PathKind::Self_ => Either::A(PerNs::types(
Module { krate: self.krate, module_id: original_module }.into(), Module { krate: self.krate, module_id: original_module }.into(),
)), )),
// plain import or absolute path in 2015: crate-relative with // plain import or absolute path in 2015: crate-relative with
@ -361,7 +361,7 @@ impl CrateDefMap {
} }
PathKind::Super => { PathKind::Super => {
if let Some(p) = self.modules[original_module].parent { if let Some(p) = self.modules[original_module].parent {
Either::Left(PerNs::types(Module { krate: self.krate, module_id: p }.into())) Either::A(PerNs::types(Module { krate: self.krate, module_id: p }.into()))
} else { } else {
log::debug!("super path in root module"); log::debug!("super path in root module");
return ResolvePathResult::empty(ReachedFixedPoint::Yes); return ResolvePathResult::empty(ReachedFixedPoint::Yes);
@ -375,7 +375,7 @@ impl CrateDefMap {
}; };
if let Some(def) = self.extern_prelude.get(&segment.name) { if let Some(def) = self.extern_prelude.get(&segment.name) {
log::debug!("absolute path {:?} resolved to crate {:?}", path, def); log::debug!("absolute path {:?} resolved to crate {:?}", path, def);
Either::Left(PerNs::types(*def)) Either::A(PerNs::types(*def))
} else { } else {
return ResolvePathResult::empty(ReachedFixedPoint::No); // extern crate declarations can add to the extern prelude return ResolvePathResult::empty(ReachedFixedPoint::No); // extern crate declarations can add to the extern prelude
} }
@ -383,7 +383,7 @@ impl CrateDefMap {
}; };
for (i, segment) in segments { for (i, segment) in segments {
let curr = match curr_per_ns.as_ref().left().and_then(|m| m.as_ref().take_types()) { let curr = match curr_per_ns.as_ref().a().and_then(|m| m.as_ref().take_types()) {
Some(r) => r, Some(r) => r,
None => { None => {
// we still have path segments left, but the path so far // we still have path segments left, but the path so far
@ -424,10 +424,10 @@ impl CrateDefMap {
// enum variant // enum variant
tested_by!(can_import_enum_variant); tested_by!(can_import_enum_variant);
match e.variant(db, &segment.name) { match e.variant(db, &segment.name) {
Some(variant) => Either::Left(PerNs::both(variant.into(), variant.into())), Some(variant) => Either::A(PerNs::both(variant.into(), variant.into())),
None => { None => {
return ResolvePathResult::with( return ResolvePathResult::with(
Either::Left(PerNs::types((*e).into())), Either::A(PerNs::types((*e).into())),
ReachedFixedPoint::Yes, ReachedFixedPoint::Yes,
Some(i), Some(i),
); );
@ -444,7 +444,7 @@ impl CrateDefMap {
); );
return ResolvePathResult::with( return ResolvePathResult::with(
Either::Left(PerNs::types(*s)), Either::A(PerNs::types(*s)),
ReachedFixedPoint::Yes, ReachedFixedPoint::Yes,
Some(i), Some(i),
); );
@ -458,10 +458,10 @@ impl CrateDefMap {
let from_crate_root = self[self.root] let from_crate_root = self[self.root]
.scope .scope
.get_item_or_macro(name) .get_item_or_macro(name)
.unwrap_or_else(|| Either::Left(PerNs::none())); .unwrap_or_else(|| Either::A(PerNs::none()));
let from_extern_prelude = self.resolve_name_in_extern_prelude(name); let from_extern_prelude = self.resolve_name_in_extern_prelude(name);
or(from_crate_root, Either::Left(from_extern_prelude)) or(from_crate_root, Either::A(from_extern_prelude))
} }
pub(crate) fn resolve_name_in_module( pub(crate) fn resolve_name_in_module(
@ -470,7 +470,7 @@ impl CrateDefMap {
module: CrateModuleId, module: CrateModuleId,
name: &Name, name: &Name,
) -> PerNs<ModuleDef> { ) -> PerNs<ModuleDef> {
self.resolve_name_in_module_with_macro(db, module, name).left().unwrap_or_else(PerNs::none) self.resolve_name_in_module_with_macro(db, module, name).a().unwrap_or_else(PerNs::none)
} }
fn resolve_name_in_module_with_macro( fn resolve_name_in_module_with_macro(
@ -483,15 +483,13 @@ impl CrateDefMap {
// - current module / scope // - current module / scope
// - extern prelude // - extern prelude
// - std prelude // - std prelude
let from_scope = self[module] let from_scope =
.scope self[module].scope.get_item_or_macro(name).unwrap_or_else(|| Either::A(PerNs::none()));
.get_item_or_macro(name)
.unwrap_or_else(|| Either::Left(PerNs::none()));
let from_extern_prelude = let from_extern_prelude =
self.extern_prelude.get(name).map_or(PerNs::none(), |&it| PerNs::types(it)); self.extern_prelude.get(name).map_or(PerNs::none(), |&it| PerNs::types(it));
let from_prelude = self.resolve_in_prelude(db, name); let from_prelude = self.resolve_in_prelude(db, name);
or(from_scope, or(Either::Left(from_extern_prelude), from_prelude)) or(from_scope, or(Either::A(from_extern_prelude), from_prelude))
} }
fn resolve_name_in_extern_prelude(&self, name: &Name) -> PerNs<ModuleDef> { fn resolve_name_in_extern_prelude(&self, name: &Name) -> PerNs<ModuleDef> {
@ -505,9 +503,9 @@ impl CrateDefMap {
} else { } else {
db.crate_def_map(prelude.krate)[prelude.module_id].scope.get_item_or_macro(name) db.crate_def_map(prelude.krate)[prelude.module_id].scope.get_item_or_macro(name)
}; };
resolution.unwrap_or_else(|| Either::Left(PerNs::none())) resolution.unwrap_or_else(|| Either::A(PerNs::none()))
} else { } else {
Either::Left(PerNs::none()) Either::A(PerNs::none())
} }
} }
} }

View file

@ -1,6 +1,5 @@
use arrayvec::ArrayVec; use arrayvec::ArrayVec;
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use either::Either;
use relative_path::RelativePathBuf; use relative_path::RelativePathBuf;
use test_utils::tested_by; use test_utils::tested_by;
use ra_db::FileId; use ra_db::FileId;
@ -9,7 +8,7 @@ use ra_syntax::ast;
use crate::{ use crate::{
Function, Module, Struct, Union, Enum, Const, Static, Trait, TypeAlias, MacroDef, Function, Module, Struct, Union, Enum, Const, Static, Trait, TypeAlias, MacroDef,
DefDatabase, HirFileId, Name, Path, AstDatabase, DefDatabase, HirFileId, Name, Path, AstDatabase,
KnownName, KnownName, AstId,
nameres::{ nameres::{
Resolution, PerNs, ModuleDef, ReachedFixedPoint, ResolveMode, Resolution, PerNs, ModuleDef, ReachedFixedPoint, ResolveMode,
CrateDefMap, CrateModuleId, ModuleData, ItemOrMacro, CrateDefMap, CrateModuleId, ModuleData, ItemOrMacro,
@ -17,7 +16,7 @@ use crate::{
raw, raw,
}, },
ids::{AstItemDef, LocationCtx, MacroCallLoc, MacroCallId, MacroDefId, MacroFileKind}, ids::{AstItemDef, LocationCtx, MacroCallLoc, MacroCallId, MacroDefId, MacroFileKind},
AstId, either::Either,
}; };
pub(super) fn collect_defs( pub(super) fn collect_defs(
@ -129,12 +128,7 @@ where
let unresolved_imports = std::mem::replace(&mut self.unresolved_imports, Vec::new()); let unresolved_imports = std::mem::replace(&mut self.unresolved_imports, Vec::new());
// show unresolved imports in completion, etc // show unresolved imports in completion, etc
for (module_id, import, import_data) in unresolved_imports { for (module_id, import, import_data) in unresolved_imports {
self.record_resolved_import( self.record_resolved_import(module_id, Either::A(PerNs::none()), import, &import_data)
module_id,
Either::Left(PerNs::none()),
import,
&import_data,
)
} }
} }
@ -159,7 +153,7 @@ where
// What we should do is that, in CrateDefMap, we should maintain a // What we should do is that, in CrateDefMap, we should maintain a
// separate tower of macro scopes, with ids. Then, for each item in the // separate tower of macro scopes, with ids. Then, for each item in the
// module, we need to store it's macro scope. // module, we need to store it's macro scope.
let def = Either::Right(MacroDef { id: macro_id }); let def = Either::B(MacroDef { id: macro_id });
// In Rust, `#[macro_export]` macros are unconditionally visible at the // In Rust, `#[macro_export]` macros are unconditionally visible at the
// crate root, even if the parent modules is **not** visible. // crate root, even if the parent modules is **not** visible.
@ -203,7 +197,7 @@ where
.as_ident() .as_ident()
.expect("extern crate should have been desugared to one-element path"), .expect("extern crate should have been desugared to one-element path"),
); );
(Either::Left(res), ReachedFixedPoint::Yes) (Either::A(res), ReachedFixedPoint::Yes)
} else { } else {
let res = self.def_map.resolve_path_fp_with_macro( let res = self.def_map.resolve_path_fp_with_macro(
self.db, self.db,
@ -225,7 +219,7 @@ where
) { ) {
if import.is_glob { if import.is_glob {
log::debug!("glob import: {:?}", import); log::debug!("glob import: {:?}", import);
match def.left().and_then(|item| item.take_types()) { match def.a().and_then(|item| item.take_types()) {
Some(ModuleDef::Module(m)) => { Some(ModuleDef::Module(m)) => {
if import.is_prelude { if import.is_prelude {
tested_by!(std_prelude); tested_by!(std_prelude);
@ -238,11 +232,11 @@ where
let items = scope let items = scope
.items .items
.iter() .iter()
.map(|(name, res)| (name.clone(), Either::Left(res.clone()))); .map(|(name, res)| (name.clone(), Either::A(res.clone())));
let macros = scope let macros = scope
.macros .macros
.iter() .iter()
.map(|(name, res)| (name.clone(), Either::Right(res.clone()))); .map(|(name, res)| (name.clone(), Either::B(res.clone())));
let all = items.chain(macros).collect::<Vec<_>>(); let all = items.chain(macros).collect::<Vec<_>>();
self.update(module_id, Some(import_id), &all); self.update(module_id, Some(import_id), &all);
@ -254,11 +248,11 @@ where
let items = scope let items = scope
.items .items
.iter() .iter()
.map(|(name, res)| (name.clone(), Either::Left(res.clone()))); .map(|(name, res)| (name.clone(), Either::A(res.clone())));
let macros = scope let macros = scope
.macros .macros
.iter() .iter()
.map(|(name, res)| (name.clone(), Either::Right(res.clone()))); .map(|(name, res)| (name.clone(), Either::B(res.clone())));
let all = items.chain(macros).collect::<Vec<_>>(); let all = items.chain(macros).collect::<Vec<_>>();
@ -282,7 +276,7 @@ where
import: Some(import_id), import: Some(import_id),
}; };
let name = variant.name(self.db)?; let name = variant.name(self.db)?;
Some((name, Either::Left(res))) Some((name, Either::A(res)))
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
self.update(module_id, Some(import_id), &resolutions); self.update(module_id, Some(import_id), &resolutions);
@ -302,16 +296,16 @@ where
// extern crates in the crate root are special-cased to insert entries into the extern prelude: rust-lang/rust#54658 // extern crates in the crate root are special-cased to insert entries into the extern prelude: rust-lang/rust#54658
if import.is_extern_crate && module_id == self.def_map.root { if import.is_extern_crate && module_id == self.def_map.root {
if let Some(def) = def.left().and_then(|item| item.take_types()) { if let Some(def) = def.a().and_then(|item| item.take_types()) {
self.def_map.extern_prelude.insert(name.clone(), def); self.def_map.extern_prelude.insert(name.clone(), def);
} }
} }
let resolution = match def { let resolution = match def {
Either::Left(item) => { Either::A(item) => {
Either::Left(Resolution { def: item, import: Some(import_id) }) Either::A(Resolution { def: item, import: Some(import_id) })
} }
Either::Right(macro_) => Either::Right(macro_), Either::B(macro_) => Either::B(macro_),
}; };
self.update(module_id, Some(import_id), &[(name, resolution)]); self.update(module_id, Some(import_id), &[(name, resolution)]);
@ -346,7 +340,7 @@ where
for (name, res) in resolutions { for (name, res) in resolutions {
match res { match res {
// item // item
Either::Left(res) => { Either::A(res) => {
let existing = module_items.items.entry(name.clone()).or_default(); let existing = module_items.items.entry(name.clone()).or_default();
if existing.def.types.is_none() && res.def.types.is_some() { if existing.def.types.is_none() && res.def.types.is_some() {
@ -369,7 +363,7 @@ where
} }
} }
// macro // macro
Either::Right(res) => { Either::B(res) => {
// Always shadowing // Always shadowing
module_items.macros.insert(name.clone(), *res); module_items.macros.insert(name.clone(), *res);
} }
@ -404,7 +398,7 @@ where
path, path,
); );
if let Some(def) = resolved_res.resolved_def.right() { if let Some(def) = resolved_res.resolved_def.b() {
let call_id = MacroCallLoc { def: def.id, ast_id: *ast_id }.id(self.db); let call_id = MacroCallLoc { def: def.id, ast_id: *ast_id }.id(self.db);
resolved.push((*module_id, call_id, def.id)); resolved.push((*module_id, call_id, def.id));
res = ReachedFixedPoint::No; res = ReachedFixedPoint::No;
@ -570,7 +564,7 @@ where
), ),
import: None, import: None,
}; };
self.def_collector.update(self.module_id, None, &[(name, Either::Left(resolution))]); self.def_collector.update(self.module_id, None, &[(name, Either::A(resolution))]);
res res
} }
@ -601,7 +595,7 @@ where
raw::DefKind::TypeAlias(ast_id) => PerNs::types(def!(TypeAlias, ast_id)), raw::DefKind::TypeAlias(ast_id) => PerNs::types(def!(TypeAlias, ast_id)),
}; };
let resolution = Resolution { def, import: None }; let resolution = Resolution { def, import: None };
self.def_collector.update(self.module_id, None, &[(name, Either::Left(resolution))]) self.def_collector.update(self.module_id, None, &[(name, Either::A(resolution))])
} }
fn collect_macro(&mut self, mac: &raw::MacroData) { fn collect_macro(&mut self, mac: &raw::MacroData) {

View file

@ -8,10 +8,9 @@ use std::sync::Arc;
use ra_db::SourceDatabase; use ra_db::SourceDatabase;
use test_utils::covers; use test_utils::covers;
use insta::assert_snapshot_matches; use insta::assert_snapshot_matches;
use either::Either;
use crate::{ use crate::{
Crate, Crate, Either,
mock::{MockDatabase, CrateGraphFixture}, mock::{MockDatabase, CrateGraphFixture},
nameres::Resolution, nameres::Resolution,
}; };
@ -37,19 +36,17 @@ fn render_crate_def_map(map: &CrateDefMap) -> String {
*buf += path; *buf += path;
*buf += "\n"; *buf += "\n";
let items = let items = map.modules[module].scope.items.iter().map(|(name, it)| (name, Either::A(it)));
map.modules[module].scope.items.iter().map(|(name, it)| (name, Either::Left(it))); let macros = map.modules[module].scope.macros.iter().map(|(name, m)| (name, Either::B(m)));
let macros =
map.modules[module].scope.macros.iter().map(|(name, m)| (name, Either::Right(m)));
let mut entries = items.chain(macros).collect::<Vec<_>>(); let mut entries = items.chain(macros).collect::<Vec<_>>();
entries.sort_by_key(|(name, _)| *name); entries.sort_by_key(|(name, _)| *name);
for (name, res) in entries { for (name, res) in entries {
match res { match res {
Either::Left(it) => { Either::A(it) => {
*buf += &format!("{}: {}\n", name, dump_resolution(it)); *buf += &format!("{}: {}\n", name, dump_resolution(it));
} }
Either::Right(_) => { Either::B(_) => {
*buf += &format!("{}: m\n", name); *buf += &format!("{}: m\n", name);
} }
} }

View file

@ -2,7 +2,6 @@
use std::sync::Arc; use std::sync::Arc;
use rustc_hash::{FxHashMap, FxHashSet}; use rustc_hash::{FxHashMap, FxHashSet};
use either::Either;
use crate::{ use crate::{
ModuleDef, Trait, MacroDef, ModuleDef, Trait, MacroDef,
@ -14,6 +13,7 @@ use crate::{
expr::{scope::{ExprScopes, ScopeId}, PatId}, expr::{scope::{ExprScopes, ScopeId}, PatId},
impl_block::ImplBlock, impl_block::ImplBlock,
path::Path, path::Path,
either::Either,
}; };
#[derive(Debug, Clone, Default)] #[derive(Debug, Clone, Default)]
@ -137,7 +137,7 @@ impl Resolver {
) -> Option<MacroDef> { ) -> Option<MacroDef> {
let (item_map, module) = self.module()?; let (item_map, module) = self.module()?;
match item_map.resolve_path_with_macro(db, module, path) { match item_map.resolve_path_with_macro(db, module, path) {
(Either::Right(macro_def), None) => Some(macro_def), (Either::B(macro_def), None) => Some(macro_def),
_ => None, _ => None,
} }
} }