From b21829f7edd71fb14911fc6ba47fe715757e415f Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Fri, 15 Nov 2019 21:28:00 +0300 Subject: Remove old impls infrastructure --- crates/ra_hir/src/code_model.rs | 25 ++- crates/ra_hir/src/db.rs | 20 +-- crates/ra_hir/src/from_id.rs | 15 +- crates/ra_hir/src/from_source.rs | 10 +- crates/ra_hir/src/impl_block.rs | 260 +++--------------------------- crates/ra_hir/src/lang_item.rs | 2 +- crates/ra_hir/src/lib.rs | 6 +- crates/ra_hir/src/resolve.rs | 5 +- crates/ra_hir/src/ty/method_resolution.rs | 80 +++------ crates/ra_hir/src/ty/traits/chalk.rs | 6 +- 10 files changed, 84 insertions(+), 345 deletions(-) (limited to 'crates/ra_hir/src') diff --git a/crates/ra_hir/src/code_model.rs b/crates/ra_hir/src/code_model.rs index 078bd8609..731cc1fff 100644 --- a/crates/ra_hir/src/code_model.rs +++ b/crates/ra_hir/src/code_model.rs @@ -11,7 +11,7 @@ use hir_def::{ body::scope::ExprScopes, builtin_type::BuiltinType, type_ref::{Mutability, TypeRef}, - CrateModuleId, LocalEnumVariantId, LocalStructFieldId, ModuleId, UnionId, + CrateModuleId, ImplId, LocalEnumVariantId, LocalStructFieldId, ModuleId, UnionId, }; use hir_expand::{ diagnostics::DiagnosticSink, @@ -29,7 +29,6 @@ use crate::{ AstItemDef, ConstId, EnumId, FunctionId, MacroDefId, StaticId, StructId, TraitId, TypeAliasId, }, - impl_block::ImplBlock, resolve::{Resolver, Scope, TypeNs}, traits::TraitData, ty::{InferenceResult, Namespace, TraitRef}, @@ -243,12 +242,8 @@ impl Module { } pub fn impl_blocks(self, db: &impl DefDatabase) -> Vec { - let module_impl_blocks = db.impls_in_module(self); - module_impl_blocks - .impls - .iter() - .map(|(impl_id, _)| ImplBlock::from_id(self, impl_id)) - .collect() + let def_map = db.crate_def_map(self.id.krate); + def_map[self.id.module_id].impls.iter().copied().map(ImplBlock::from).collect() } fn with_module_id(self, module_id: CrateModuleId) -> Module { @@ -693,8 +688,7 @@ impl Function { /// The containing impl block, if this is a method. pub fn impl_block(self, db: &impl DefDatabase) -> Option { - let module_impls = db.impls_in_module(self.module(db)); - ImplBlock::containing(module_impls, self.into()) + ImplBlock::containing(db, self.into()) } /// The containing trait, if this is a trait method definition. @@ -759,8 +753,7 @@ impl Const { /// The containing impl block, if this is a method. pub fn impl_block(self, db: &impl DefDatabase) -> Option { - let module_impls = db.impls_in_module(self.module(db)); - ImplBlock::containing(module_impls, self.into()) + ImplBlock::containing(db, self.into()) } pub fn parent_trait(self, db: &impl DefDatabase) -> Option { @@ -973,8 +966,7 @@ impl TypeAlias { /// The containing impl block, if this is a method. pub fn impl_block(self, db: &impl DefDatabase) -> Option { - let module_impls = db.impls_in_module(self.module(db)); - ImplBlock::containing(module_impls, self.into()) + ImplBlock::containing(db, self.into()) } /// The containing trait, if this is a trait method definition. @@ -1137,3 +1129,8 @@ pub struct GenericParam { pub(crate) parent: GenericDef, pub(crate) idx: u32, } + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct ImplBlock { + pub(crate) id: ImplId, +} diff --git a/crates/ra_hir/src/db.rs b/crates/ra_hir/src/db.rs index c60029c01..276b0774f 100644 --- a/crates/ra_hir/src/db.rs +++ b/crates/ra_hir/src/db.rs @@ -10,7 +10,6 @@ use crate::{ debug::HirDebugDatabase, generics::{GenericDef, GenericParams}, ids, - impl_block::{ImplBlock, ImplSourceMap, ModuleImplBlocks}, lang_item::{LangItemTarget, LangItems}, traits::TraitData, ty::{ @@ -18,14 +17,14 @@ use crate::{ InferenceResult, Namespace, Substs, Ty, TypableDef, TypeCtor, }, type_alias::TypeAliasData, - Const, ConstData, Crate, DefWithBody, FnData, Function, Module, Static, StructField, Trait, - TypeAlias, + Const, ConstData, Crate, DefWithBody, FnData, Function, ImplBlock, Module, Static, StructField, + Trait, TypeAlias, }; pub use hir_def::db::{ BodyQuery, BodyWithSourceMapQuery, CrateDefMapQuery, DefDatabase2, DefDatabase2Storage, - EnumDataQuery, ExprScopesQuery, InternDatabase, InternDatabaseStorage, RawItemsQuery, - RawItemsWithSourceMapQuery, StructDataQuery, + EnumDataQuery, ExprScopesQuery, ImplDataQuery, InternDatabase, InternDatabaseStorage, + RawItemsQuery, RawItemsWithSourceMapQuery, StructDataQuery, }; pub use hir_expand::db::{ AstDatabase, AstDatabaseStorage, AstIdMapQuery, MacroArgQuery, MacroDefQuery, MacroExpandQuery, @@ -42,15 +41,6 @@ pub trait DefDatabase: HirDebugDatabase + DefDatabase2 { #[salsa::invoke(crate::traits::TraitItemsIndex::trait_items_index)] fn trait_items_index(&self, module: Module) -> crate::traits::TraitItemsIndex; - #[salsa::invoke(ModuleImplBlocks::impls_in_module_with_source_map_query)] - fn impls_in_module_with_source_map( - &self, - module: Module, - ) -> (Arc, Arc); - - #[salsa::invoke(ModuleImplBlocks::impls_in_module_query)] - fn impls_in_module(&self, module: Module) -> Arc; - #[salsa::invoke(crate::generics::GenericParams::generic_params_query)] fn generic_params(&self, def: GenericDef) -> Arc; @@ -128,7 +118,7 @@ pub trait HirDatabase: DefDatabase + AstDatabase { #[salsa::interned] fn intern_type_ctor(&self, type_ctor: TypeCtor) -> ids::TypeCtorId; #[salsa::interned] - fn intern_impl(&self, impl_: Impl) -> ids::GlobalImplId; + fn intern_chalk_impl(&self, impl_: Impl) -> ids::GlobalImplId; #[salsa::invoke(crate::ty::traits::chalk::associated_ty_data_query)] fn associated_ty_data(&self, id: chalk_ir::TypeId) -> Arc; diff --git a/crates/ra_hir/src/from_id.rs b/crates/ra_hir/src/from_id.rs index 9633ef586..f2203e995 100644 --- a/crates/ra_hir/src/from_id.rs +++ b/crates/ra_hir/src/from_id.rs @@ -3,9 +3,9 @@ //! It's unclear if we need this long-term, but it's definitelly useful while we //! are splitting the hir. -use hir_def::{AdtId, DefWithBodyId, EnumVariantId, ModuleDefId}; +use hir_def::{AdtId, AssocItemId, DefWithBodyId, EnumVariantId, ModuleDefId}; -use crate::{Adt, DefWithBody, EnumVariant, ModuleDef}; +use crate::{Adt, AssocItem, DefWithBody, EnumVariant, ModuleDef}; macro_rules! from_id { ($(($id:path, $ty:path)),*) => {$( @@ -27,6 +27,7 @@ from_id![ (hir_def::StaticId, crate::Static), (hir_def::ConstId, crate::Const), (hir_def::FunctionId, crate::Function), + (hir_def::ImplId, crate::ImplBlock), (hir_expand::MacroDefId, crate::MacroDef) ]; @@ -71,3 +72,13 @@ impl From for DefWithBodyId { } } } + +impl From for AssocItem { + fn from(def: AssocItemId) -> Self { + match def { + AssocItemId::FunctionId(it) => AssocItem::Function(it.into()), + AssocItemId::TypeAliasId(it) => AssocItem::TypeAlias(it.into()), + AssocItemId::ConstId(it) => AssocItem::Const(it.into()), + } + } +} diff --git a/crates/ra_hir/src/from_source.rs b/crates/ra_hir/src/from_source.rs index 7e5523c54..ec56dfa6a 100644 --- a/crates/ra_hir/src/from_source.rs +++ b/crates/ra_hir/src/from_source.rs @@ -82,14 +82,8 @@ impl FromSource for TypeAlias { impl FromSource for ImplBlock { type Ast = ast::ImplBlock; fn from_source(db: &(impl DefDatabase + AstDatabase), src: Source) -> Option { - let module_src = crate::ModuleSource::from_child_node( - db, - src.file_id.original_file(db), - &src.ast.syntax(), - ); - let module = Module::from_definition(db, Source { file_id: src.file_id, ast: module_src })?; - let impls = module.impl_blocks(db); - impls.into_iter().find(|b| b.source(db) == src) + let id = from_source(db, src)?; + Some(ImplBlock { id }) } } diff --git a/crates/ra_hir/src/impl_block.rs b/crates/ra_hir/src/impl_block.rs index b1a014074..0c2bb8fee 100644 --- a/crates/ra_hir/src/impl_block.rs +++ b/crates/ra_hir/src/impl_block.rs @@ -1,88 +1,38 @@ //! FIXME: write short doc here -use rustc_hash::FxHashMap; -use std::sync::Arc; - -use hir_def::{attr::Attr, type_ref::TypeRef}; -use hir_expand::hygiene::Hygiene; -use ra_arena::{impl_arena_id, map::ArenaMap, Arena, RawId}; -use ra_cfg::CfgOptions; -use ra_syntax::{ - ast::{self, AstNode}, - AstPtr, -}; +use hir_def::{type_ref::TypeRef, AstItemDef}; +use ra_syntax::ast::{self}; use crate::{ - code_model::{Module, ModuleSource}, db::{AstDatabase, DefDatabase, HirDatabase}, generics::HasGenericParams, - ids::LocationCtx, - ids::MacroCallLoc, resolve::Resolver, ty::Ty, - AssocItem, AstId, Const, Function, HasSource, HirFileId, MacroFileKind, Path, Source, TraitRef, - TypeAlias, + AssocItem, Crate, HasSource, ImplBlock, Module, Source, TraitRef, }; -#[derive(Debug, Default, PartialEq, Eq)] -pub struct ImplSourceMap { - map: ArenaMap>>, -} - -impl ImplSourceMap { - fn insert(&mut self, impl_id: ImplId, file_id: HirFileId, impl_block: &ast::ImplBlock) { - let source = Source { file_id, ast: AstPtr::new(impl_block) }; - self.map.insert(impl_id, source) - } - - pub fn get(&self, db: &impl AstDatabase, impl_id: ImplId) -> Source { - let src = self.map[impl_id]; - let root = src.file_syntax(db); - src.map(|ptr| ptr.to_node(&root)) - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub struct ImplBlock { - module: Module, - impl_id: ImplId, -} - impl HasSource for ImplBlock { type Ast = ast::ImplBlock; fn source(self, db: &(impl DefDatabase + AstDatabase)) -> Source { - let source_map = db.impls_in_module_with_source_map(self.module).1; - source_map.get(db, self.impl_id) + self.id.source(db) } } impl ImplBlock { - pub(crate) fn containing( - module_impl_blocks: Arc, - item: AssocItem, - ) -> Option { - let impl_id = *module_impl_blocks.impls_by_def.get(&item)?; - Some(ImplBlock { module: module_impl_blocks.module, impl_id }) - } - - pub(crate) fn from_id(module: Module, impl_id: ImplId) -> ImplBlock { - ImplBlock { module, impl_id } - } - - pub fn id(&self) -> ImplId { - self.impl_id - } - - pub fn module(&self) -> Module { - self.module + pub(crate) fn containing(db: &impl DefDatabase, item: AssocItem) -> Option { + let module = item.module(db); + let crate_def_map = db.crate_def_map(module.id.krate); + crate_def_map[module.id.module_id].impls.iter().copied().map(ImplBlock::from).find(|it| { + db.impl_data(it.id).items().iter().copied().map(AssocItem::from).any(|it| it == item) + }) } pub fn target_trait(&self, db: &impl DefDatabase) -> Option { - db.impls_in_module(self.module).impls[self.impl_id].target_trait().cloned() + db.impl_data(self.id).target_trait().cloned() } pub fn target_type(&self, db: &impl DefDatabase) -> TypeRef { - db.impls_in_module(self.module).impls[self.impl_id].target_type().clone() + db.impl_data(self.id).target_type().clone() } pub fn target_ty(&self, db: &impl HirDatabase) -> Ty { @@ -95,15 +45,23 @@ impl ImplBlock { } pub fn items(&self, db: &impl DefDatabase) -> Vec { - db.impls_in_module(self.module).impls[self.impl_id].items().to_vec() + db.impl_data(self.id).items().iter().map(|it| (*it).into()).collect() } pub fn is_negative(&self, db: &impl DefDatabase) -> bool { - db.impls_in_module(self.module).impls[self.impl_id].negative + db.impl_data(self.id).is_negative() + } + + pub fn module(&self, db: &impl DefDatabase) -> Module { + self.id.module(db).into() + } + + pub fn krate(&self, db: &impl DefDatabase) -> Crate { + Crate { crate_id: self.module(db).id.krate } } pub(crate) fn resolver(&self, db: &impl DefDatabase) -> Resolver { - let r = self.module().resolver(db); + let r = self.module(db).resolver(db); // add generic params, if present let p = self.generic_params(db); let r = if !p.params.is_empty() { r.push_generic_params_scope(p) } else { r }; @@ -111,175 +69,3 @@ impl ImplBlock { r } } - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ImplData { - target_trait: Option, - target_type: TypeRef, - items: Vec, - negative: bool, -} - -impl ImplData { - pub(crate) fn from_ast( - db: &(impl DefDatabase + AstDatabase), - file_id: HirFileId, - module: Module, - node: &ast::ImplBlock, - ) -> Self { - let target_trait = node.target_trait().map(TypeRef::from_ast); - let target_type = TypeRef::from_ast_opt(node.target_type()); - let ctx = LocationCtx::new(db, module.id, file_id); - let negative = node.is_negative(); - let items = if let Some(item_list) = node.item_list() { - item_list - .impl_items() - .map(|item_node| match item_node { - ast::ImplItem::FnDef(it) => Function { id: ctx.to_def(&it) }.into(), - ast::ImplItem::ConstDef(it) => Const { id: ctx.to_def(&it) }.into(), - ast::ImplItem::TypeAliasDef(it) => TypeAlias { id: ctx.to_def(&it) }.into(), - }) - .collect() - } else { - Vec::new() - }; - ImplData { target_trait, target_type, items, negative } - } - - pub fn target_trait(&self) -> Option<&TypeRef> { - self.target_trait.as_ref() - } - - pub fn target_type(&self) -> &TypeRef { - &self.target_type - } - - pub fn items(&self) -> &[AssocItem] { - &self.items - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct ImplId(pub RawId); -impl_arena_id!(ImplId); - -/// The collection of impl blocks is a two-step process: first we collect the -/// blocks per-module; then we build an index of all impl blocks in the crate. -/// This way, we avoid having to do this process for the whole crate whenever -/// a file is changed; as long as the impl blocks in the file don't change, -/// we don't need to do the second step again. -#[derive(Debug, PartialEq, Eq)] -pub struct ModuleImplBlocks { - pub(crate) module: Module, - pub(crate) impls: Arena, - impls_by_def: FxHashMap, -} - -impl ModuleImplBlocks { - pub(crate) fn impls_in_module_with_source_map_query( - db: &(impl DefDatabase + AstDatabase), - module: Module, - ) -> (Arc, Arc) { - let mut source_map = ImplSourceMap::default(); - let crate_graph = db.crate_graph(); - let cfg_options = crate_graph.cfg_options(module.id.krate); - - let result = ModuleImplBlocks::collect(db, cfg_options, module, &mut source_map); - (Arc::new(result), Arc::new(source_map)) - } - - pub(crate) fn impls_in_module_query( - db: &impl DefDatabase, - module: Module, - ) -> Arc { - db.impls_in_module_with_source_map(module).0 - } - - fn collect( - db: &(impl DefDatabase + AstDatabase), - cfg_options: &CfgOptions, - module: Module, - source_map: &mut ImplSourceMap, - ) -> Self { - let mut m = ModuleImplBlocks { - module, - impls: Arena::default(), - impls_by_def: FxHashMap::default(), - }; - - let src = m.module.definition_source(db); - match &src.ast { - ModuleSource::SourceFile(node) => { - m.collect_from_item_owner(db, cfg_options, source_map, node, src.file_id) - } - ModuleSource::Module(node) => { - let item_list = node.item_list().expect("inline module should have item list"); - m.collect_from_item_owner(db, cfg_options, source_map, &item_list, src.file_id) - } - }; - m - } - - fn collect_from_item_owner( - &mut self, - db: &(impl DefDatabase + AstDatabase), - cfg_options: &CfgOptions, - source_map: &mut ImplSourceMap, - owner: &dyn ast::ModuleItemOwner, - file_id: HirFileId, - ) { - let hygiene = Hygiene::new(db, file_id); - for item in owner.items_with_macros() { - match item { - ast::ItemOrMacro::Item(ast::ModuleItem::ImplBlock(impl_block_ast)) => { - let attrs = Attr::from_attrs_owner(&impl_block_ast, &hygiene); - if attrs.map_or(false, |attrs| { - attrs.iter().any(|attr| attr.is_cfg_enabled(cfg_options) == Some(false)) - }) { - continue; - } - - let impl_block = ImplData::from_ast(db, file_id, self.module, &impl_block_ast); - let id = self.impls.alloc(impl_block); - for &impl_item in &self.impls[id].items { - self.impls_by_def.insert(impl_item, id); - } - - source_map.insert(id, file_id, &impl_block_ast); - } - ast::ItemOrMacro::Item(_) => (), - ast::ItemOrMacro::Macro(macro_call) => { - let attrs = Attr::from_attrs_owner(¯o_call, &hygiene); - if attrs.map_or(false, |attrs| { - attrs.iter().any(|attr| attr.is_cfg_enabled(cfg_options) == Some(false)) - }) { - continue; - } - - //FIXME: we should really cut down on the boilerplate required to process a macro - let ast_id = AstId::new(file_id, db.ast_id_map(file_id).ast_id(¯o_call)); - if let Some(path) = - macro_call.path().and_then(|path| Path::from_src(path, &hygiene)) - { - if let Some(def) = self.module.resolver(db).resolve_path_as_macro(db, &path) - { - let call_id = db.intern_macro(MacroCallLoc { def: def.id, ast_id }); - let file_id = call_id.as_file(MacroFileKind::Items); - if let Some(item_list) = - db.parse_or_expand(file_id).and_then(ast::MacroItems::cast) - { - self.collect_from_item_owner( - db, - cfg_options, - source_map, - &item_list, - file_id, - ) - } - } - } - } - } - } - } -} diff --git a/crates/ra_hir/src/lang_item.rs b/crates/ra_hir/src/lang_item.rs index e1780ed38..fa2ef8a17 100644 --- a/crates/ra_hir/src/lang_item.rs +++ b/crates/ra_hir/src/lang_item.rs @@ -25,7 +25,7 @@ impl LangItemTarget { Some(match self { LangItemTarget::Enum(e) => e.module(db).krate(), LangItemTarget::Function(f) => f.module(db).krate(), - LangItemTarget::ImplBlock(i) => i.module().krate(), + LangItemTarget::ImplBlock(i) => i.krate(db), LangItemTarget::Static(s) => s.module(db).krate(), LangItemTarget::Struct(s) => s.module(db).krate(), LangItemTarget::Trait(t) => t.module(db).krate(), diff --git a/crates/ra_hir/src/lib.rs b/crates/ra_hir/src/lib.rs index 5ba847d35..da33c9591 100644 --- a/crates/ra_hir/src/lib.rs +++ b/crates/ra_hir/src/lib.rs @@ -54,12 +54,11 @@ mod test_db; #[cfg(test)] mod marks; -use hir_expand::AstId; - -use crate::{ids::MacroFileKind, resolve::Resolver}; +use crate::resolve::Resolver; pub use crate::{ adt::VariantDef, + code_model::ImplBlock, code_model::{ attrs::{AttrDef, Attrs}, docs::{DocDef, Docs, Documentation}, @@ -72,7 +71,6 @@ pub use crate::{ from_source::FromSource, generics::GenericDef, ids::{HirFileId, MacroCallId, MacroCallLoc, MacroDefId, MacroFile}, - impl_block::ImplBlock, resolve::ScopeDef, source_binder::{PathResolution, ScopeEntryWithSyntax, SourceAnalyzer}, ty::{ diff --git a/crates/ra_hir/src/resolve.rs b/crates/ra_hir/src/resolve.rs index 2fb913108..79b92180a 100644 --- a/crates/ra_hir/src/resolve.rs +++ b/crates/ra_hir/src/resolve.rs @@ -15,9 +15,8 @@ use crate::{ db::{DefDatabase, HirDatabase}, expr::{ExprScopes, PatId, ScopeId}, generics::GenericParams, - impl_block::ImplBlock, - Adt, Const, DefWithBody, Enum, EnumVariant, Function, Local, MacroDef, ModuleDef, PerNs, - Static, Struct, Trait, TypeAlias, + Adt, Const, DefWithBody, Enum, EnumVariant, Function, ImplBlock, Local, MacroDef, ModuleDef, + PerNs, Static, Struct, Trait, TypeAlias, }; #[derive(Debug, Clone, Default)] diff --git a/crates/ra_hir/src/ty/method_resolution.rs b/crates/ra_hir/src/ty/method_resolution.rs index eb5ca6769..9aad2d3fe 100644 --- a/crates/ra_hir/src/ty/method_resolution.rs +++ b/crates/ra_hir/src/ty/method_resolution.rs @@ -5,16 +5,14 @@ use std::sync::Arc; use arrayvec::ArrayVec; -use hir_def::CrateModuleId; use rustc_hash::FxHashMap; use crate::{ db::HirDatabase, - impl_block::{ImplBlock, ImplId}, resolve::Resolver, ty::primitive::{FloatBitness, Uncertain}, ty::{Ty, TypeCtor}, - AssocItem, Crate, Function, Module, Mutability, Name, Trait, + AssocItem, Crate, Function, ImplBlock, Module, Mutability, Name, Trait, }; use super::{autoderef, lower, Canonical, InEnvironment, TraitEnvironment, TraitRef}; @@ -39,65 +37,46 @@ impl TyFingerprint { #[derive(Debug, PartialEq, Eq)] pub struct CrateImplBlocks { - /// To make sense of the CrateModuleIds, we need the source root. - krate: Crate, - impls: FxHashMap>, - impls_by_trait: FxHashMap>, + impls: FxHashMap>, + impls_by_trait: FxHashMap>, } impl CrateImplBlocks { - pub fn lookup_impl_blocks<'a>(&'a self, ty: &Ty) -> impl Iterator + 'a { + pub(crate) fn impls_in_crate_query( + db: &impl HirDatabase, + krate: Crate, + ) -> Arc { + let mut crate_impl_blocks = + CrateImplBlocks { impls: FxHashMap::default(), impls_by_trait: FxHashMap::default() }; + if let Some(module) = krate.root_module(db) { + crate_impl_blocks.collect_recursive(db, module); + } + Arc::new(crate_impl_blocks) + } + pub fn lookup_impl_blocks(&self, ty: &Ty) -> impl Iterator + '_ { let fingerprint = TyFingerprint::for_impl(ty); - fingerprint.and_then(|f| self.impls.get(&f)).into_iter().flat_map(|i| i.iter()).map( - move |(module_id, impl_id)| { - let module = Module::new(self.krate, *module_id); - ImplBlock::from_id(module, *impl_id) - }, - ) + fingerprint.and_then(|f| self.impls.get(&f)).into_iter().flatten().copied() } - pub fn lookup_impl_blocks_for_trait<'a>( - &'a self, - tr: Trait, - ) -> impl Iterator + 'a { - self.impls_by_trait.get(&tr).into_iter().flat_map(|i| i.iter()).map( - move |(module_id, impl_id)| { - let module = Module::new(self.krate, *module_id); - ImplBlock::from_id(module, *impl_id) - }, - ) + pub fn lookup_impl_blocks_for_trait(&self, tr: Trait) -> impl Iterator + '_ { + self.impls_by_trait.get(&tr).into_iter().flatten().copied() } pub fn all_impls<'a>(&'a self) -> impl Iterator + 'a { - self.impls.values().chain(self.impls_by_trait.values()).flat_map(|i| i.iter()).map( - move |(module_id, impl_id)| { - let module = Module::new(self.krate, *module_id); - ImplBlock::from_id(module, *impl_id) - }, - ) + self.impls.values().chain(self.impls_by_trait.values()).flatten().copied() } fn collect_recursive(&mut self, db: &impl HirDatabase, module: Module) { - let module_impl_blocks = db.impls_in_module(module); - - for (impl_id, _) in module_impl_blocks.impls.iter() { - let impl_block = ImplBlock::from_id(module_impl_blocks.module, impl_id); - + for impl_block in module.impl_blocks(db) { let target_ty = impl_block.target_ty(db); if impl_block.target_trait(db).is_some() { if let Some(tr) = impl_block.target_trait_ref(db) { - self.impls_by_trait - .entry(tr.trait_) - .or_insert_with(Vec::new) - .push((module.id.module_id, impl_id)); + self.impls_by_trait.entry(tr.trait_).or_default().push(impl_block); } } else { if let Some(target_ty_fp) = TyFingerprint::for_impl(&target_ty) { - self.impls - .entry(target_ty_fp) - .or_insert_with(Vec::new) - .push((module.id.module_id, impl_id)); + self.impls.entry(target_ty_fp).or_default().push(impl_block); } } } @@ -106,21 +85,6 @@ impl CrateImplBlocks { self.collect_recursive(db, child); } } - - pub(crate) fn impls_in_crate_query( - db: &impl HirDatabase, - krate: Crate, - ) -> Arc { - let mut crate_impl_blocks = CrateImplBlocks { - krate, - impls: FxHashMap::default(), - impls_by_trait: FxHashMap::default(), - }; - if let Some(module) = krate.root_module(db) { - crate_impl_blocks.collect_recursive(db, module); - } - Arc::new(crate_impl_blocks) - } } fn def_crates(db: &impl HirDatabase, cur_crate: Crate, ty: &Ty) -> Option> { diff --git a/crates/ra_hir/src/ty/traits/chalk.rs b/crates/ra_hir/src/ty/traits/chalk.rs index 75351c17d..68304b950 100644 --- a/crates/ra_hir/src/ty/traits/chalk.rs +++ b/crates/ra_hir/src/ty/traits/chalk.rs @@ -191,11 +191,11 @@ impl ToChalk for Impl { type Chalk = chalk_ir::ImplId; fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::ImplId { - db.intern_impl(self).into() + db.intern_chalk_impl(self).into() } fn from_chalk(db: &impl HirDatabase, impl_id: chalk_ir::ImplId) -> Impl { - db.lookup_intern_impl(impl_id.into()) + db.lookup_intern_chalk_impl(impl_id.into()) } } @@ -630,7 +630,7 @@ fn impl_block_datum( .target_trait_ref(db) .expect("FIXME handle unresolved impl block trait ref") .subst(&bound_vars); - let impl_type = if impl_block.module().krate() == krate { + let impl_type = if impl_block.krate(db) == krate { chalk_rust_ir::ImplType::Local } else { chalk_rust_ir::ImplType::External -- cgit v1.2.3 From 4c90b7e2ecd03e739a3c92bbe5afd4c90fe2812d Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Fri, 15 Nov 2019 23:24:56 +0300 Subject: Sourcify some things If we want to support macros properly, we need to get rid of those FileIds everywhere... --- crates/ra_hir/src/from_source.rs | 5 ++--- crates/ra_hir/src/source_binder.rs | 15 +++++++-------- 2 files changed, 9 insertions(+), 11 deletions(-) (limited to 'crates/ra_hir/src') diff --git a/crates/ra_hir/src/from_source.rs b/crates/ra_hir/src/from_source.rs index ec56dfa6a..79152a57c 100644 --- a/crates/ra_hir/src/from_source.rs +++ b/crates/ra_hir/src/from_source.rs @@ -196,9 +196,8 @@ where N: AstNode, DEF: AstItemDef, { - let module_src = - crate::ModuleSource::from_child_node(db, src.file_id.original_file(db), &src.ast.syntax()); - let module = Module::from_definition(db, Source { file_id: src.file_id, ast: module_src })?; + let module_src = ModuleSource::from_child_node(db, src.as_ref().map(|it| it.syntax())); + let module = Module::from_definition(db, Source::new(src.file_id, module_src))?; let ctx = LocationCtx::new(db, module.id, src.file_id); Some(DEF::from_ast(ctx, &src.ast)) } diff --git a/crates/ra_hir/src/source_binder.rs b/crates/ra_hir/src/source_binder.rs index 662d3f880..f08827ed3 100644 --- a/crates/ra_hir/src/source_binder.rs +++ b/crates/ra_hir/src/source_binder.rs @@ -56,7 +56,7 @@ fn try_get_resolver_for_node( }, _ => { if node.kind() == FN_DEF || node.kind() == CONST_DEF || node.kind() == STATIC_DEF { - Some(def_with_body_from_child_node(db, file_id, node)?.resolver(db)) + Some(def_with_body_from_child_node(db, Source::new(file_id.into(), node))?.resolver(db)) } else { // FIXME add missing cases None @@ -68,14 +68,13 @@ fn try_get_resolver_for_node( fn def_with_body_from_child_node( db: &impl HirDatabase, - file_id: FileId, - node: &SyntaxNode, + child: Source<&SyntaxNode>, ) -> Option { - let src = crate::ModuleSource::from_child_node(db, file_id, node); - let module = Module::from_definition(db, crate::Source { file_id: file_id.into(), ast: src })?; - let ctx = LocationCtx::new(db, module.id, file_id.into()); + let module_source = crate::ModuleSource::from_child_node(db, child); + let module = Module::from_definition(db, Source::new(child.file_id, module_source))?; + let ctx = LocationCtx::new(db, module.id, child.file_id); - node.ancestors().find_map(|node| { + child.ast.ancestors().find_map(|node| { match_ast! { match node { ast::FnDef(def) => { Some(Function {id: ctx.to_def(&def) }.into()) }, @@ -142,7 +141,7 @@ impl SourceAnalyzer { node: &SyntaxNode, offset: Option, ) -> SourceAnalyzer { - let def_with_body = def_with_body_from_child_node(db, file_id, node); + let def_with_body = def_with_body_from_child_node(db, Source::new(file_id.into(), node)); if let Some(def) = def_with_body { let source_map = def.body_source_map(db); let scopes = def.expr_scopes(db); -- cgit v1.2.3 From bd8af6a413bb2f762bb696d20727e21cb2d4cb62 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Sat, 16 Nov 2019 00:05:10 +0300 Subject: Sourcify some more --- crates/ra_hir/src/source_binder.rs | 34 +++++++++++++++++++++------------- 1 file changed, 21 insertions(+), 13 deletions(-) (limited to 'crates/ra_hir/src') diff --git a/crates/ra_hir/src/source_binder.rs b/crates/ra_hir/src/source_binder.rs index f08827ed3..f3bccd8ed 100644 --- a/crates/ra_hir/src/source_binder.rs +++ b/crates/ra_hir/src/source_binder.rs @@ -141,13 +141,16 @@ impl SourceAnalyzer { node: &SyntaxNode, offset: Option, ) -> SourceAnalyzer { - let def_with_body = def_with_body_from_child_node(db, Source::new(file_id.into(), node)); + let node_source = Source::new(file_id.into(), node); + let def_with_body = def_with_body_from_child_node(db, node_source); if let Some(def) = def_with_body { let source_map = def.body_source_map(db); let scopes = def.expr_scopes(db); let scope = match offset { - None => scope_for(&scopes, &source_map, file_id.into(), &node), - Some(offset) => scope_for_offset(&scopes, &source_map, file_id.into(), offset), + None => scope_for(&scopes, &source_map, node_source), + Some(offset) => { + scope_for_offset(&scopes, &source_map, Source::new(file_id.into(), offset)) + } }; let resolver = expr::resolver_for_scope(db, def, scope); SourceAnalyzer { @@ -287,7 +290,8 @@ impl SourceAnalyzer { let name = name_ref.as_name(); let source_map = self.body_source_map.as_ref()?; let scopes = self.scopes.as_ref()?; - let scope = scope_for(scopes, source_map, self.file_id.into(), name_ref.syntax())?; + let scope = + scope_for(scopes, source_map, Source::new(self.file_id.into(), name_ref.syntax()))?; let entry = scopes.resolve_name_in_scope(scope, &name)?; Some(ScopeEntryWithSyntax { name: entry.name().clone(), @@ -408,20 +412,19 @@ impl SourceAnalyzer { fn scope_for( scopes: &ExprScopes, source_map: &BodySourceMap, - file_id: HirFileId, - node: &SyntaxNode, + node: Source<&SyntaxNode>, ) -> Option { - node.ancestors() + node.ast + .ancestors() .filter_map(ast::Expr::cast) - .filter_map(|it| source_map.node_expr(Source { file_id, ast: &it })) + .filter_map(|it| source_map.node_expr(Source::new(node.file_id, &it))) .find_map(|it| scopes.scope_for(it)) } fn scope_for_offset( scopes: &ExprScopes, source_map: &BodySourceMap, - file_id: HirFileId, - offset: TextUnit, + offset: Source, ) -> Option { scopes .scope_by_expr() @@ -429,7 +432,7 @@ fn scope_for_offset( .filter_map(|(id, scope)| { let source = source_map.expr_syntax(*id)?; // FIXME: correctly handle macro expansion - if source.file_id != file_id { + if source.file_id != offset.file_id { return None; } let syntax_node_ptr = @@ -438,9 +441,14 @@ fn scope_for_offset( }) // find containing scope .min_by_key(|(ptr, _scope)| { - (!(ptr.range().start() <= offset && offset <= ptr.range().end()), ptr.range().len()) + ( + !(ptr.range().start() <= offset.ast && offset.ast <= ptr.range().end()), + ptr.range().len(), + ) + }) + .map(|(ptr, scope)| { + adjust(scopes, source_map, ptr, offset.file_id, offset.ast).unwrap_or(*scope) }) - .map(|(ptr, scope)| adjust(scopes, source_map, ptr, file_id, offset).unwrap_or(*scope)) } // XXX: during completion, cursor might be outside of any particular -- cgit v1.2.3 From 0404e647e69f758ac84c742b06dddefb01cc4ad6 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Sat, 16 Nov 2019 00:40:54 +0300 Subject: Prepare SourceAnalyzer for macros --- crates/ra_hir/src/source_binder.rs | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) (limited to 'crates/ra_hir/src') diff --git a/crates/ra_hir/src/source_binder.rs b/crates/ra_hir/src/source_binder.rs index f3bccd8ed..540ddd0b5 100644 --- a/crates/ra_hir/src/source_binder.rs +++ b/crates/ra_hir/src/source_binder.rs @@ -91,7 +91,7 @@ fn def_with_body_from_child_node( #[derive(Debug)] pub struct SourceAnalyzer { // FIXME: this doesn't handle macros at all - file_id: FileId, + file_id: HirFileId, resolver: Resolver, body_owner: Option, body_source_map: Option>, @@ -159,7 +159,7 @@ impl SourceAnalyzer { body_source_map: Some(source_map), infer: Some(def.infer(db)), scopes: Some(scopes), - file_id, + file_id: file_id.into(), } } else { SourceAnalyzer { @@ -171,18 +171,18 @@ impl SourceAnalyzer { body_source_map: None, infer: None, scopes: None, - file_id, + file_id: file_id.into(), } } } fn expr_id(&self, expr: &ast::Expr) -> Option { - let src = Source { file_id: self.file_id.into(), ast: expr }; + let src = Source { file_id: self.file_id, ast: expr }; self.body_source_map.as_ref()?.node_expr(src) } fn pat_id(&self, pat: &ast::Pat) -> Option { - let src = Source { file_id: self.file_id.into(), ast: pat }; + let src = Source { file_id: self.file_id, ast: pat }; self.body_source_map.as_ref()?.node_pat(src) } @@ -290,8 +290,7 @@ impl SourceAnalyzer { let name = name_ref.as_name(); let source_map = self.body_source_map.as_ref()?; let scopes = self.scopes.as_ref()?; - let scope = - scope_for(scopes, source_map, Source::new(self.file_id.into(), name_ref.syntax()))?; + let scope = scope_for(scopes, source_map, Source::new(self.file_id, name_ref.syntax()))?; let entry = scopes.resolve_name_in_scope(scope, &name)?; Some(ScopeEntryWithSyntax { name: entry.name().clone(), -- cgit v1.2.3 From 60fd260e7fb8c88cb9037377dc75f901a54bbe20 Mon Sep 17 00:00:00 2001 From: kjeremy Date: Fri, 15 Nov 2019 16:20:00 -0500 Subject: Handle ast::MacroCall in classify_name and impl FromSource for MacroDef Fixes #2260 --- crates/ra_hir/src/from_source.rs | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) (limited to 'crates/ra_hir/src') diff --git a/crates/ra_hir/src/from_source.rs b/crates/ra_hir/src/from_source.rs index 79152a57c..1c26756c9 100644 --- a/crates/ra_hir/src/from_source.rs +++ b/crates/ra_hir/src/from_source.rs @@ -1,7 +1,7 @@ //! FIXME: write short doc here use hir_def::{ModuleId, StructId, StructOrUnionId, UnionId}; -use hir_expand::name::AsName; +use hir_expand::{name::AsName, AstId, MacroDefId, MacroDefKind}; use ra_syntax::{ ast::{self, AstNode, NameOwner}, match_ast, @@ -11,8 +11,8 @@ use crate::{ db::{AstDatabase, DefDatabase, HirDatabase}, ids::{AstItemDef, LocationCtx}, Const, DefWithBody, Enum, EnumVariant, FieldSource, Function, HasBody, HasSource, ImplBlock, - Local, Module, ModuleSource, Source, Static, Struct, StructField, Trait, TypeAlias, Union, - VariantDef, + Local, MacroDef, Module, ModuleSource, Source, Static, Struct, StructField, Trait, TypeAlias, + Union, VariantDef, }; pub trait FromSource: Sized { @@ -77,7 +77,22 @@ impl FromSource for TypeAlias { Some(TypeAlias { id }) } } -// FIXME: add impl FromSource for MacroDef + +impl FromSource for MacroDef { + type Ast = ast::MacroCall; + fn from_source(db: &(impl DefDatabase + AstDatabase), src: Source) -> Option { + let kind = MacroDefKind::Declarative; + + let module_src = ModuleSource::from_child_node(db, src.as_ref().map(|it| it.syntax())); + let module = Module::from_definition(db, Source::new(src.file_id, module_src))?; + let krate = module.krate().crate_id(); + + let ast_id = AstId::new(src.file_id, db.ast_id_map(src.file_id).ast_id(&src.ast)); + + let id: MacroDefId = MacroDefId { krate, ast_id, kind }; + Some(MacroDef { id }) + } +} impl FromSource for ImplBlock { type Ast = ast::ImplBlock; -- cgit v1.2.3 From 1c819fc8f66def9661c7640051a40e5e820acd71 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Sat, 16 Nov 2019 00:40:54 +0300 Subject: Prepare SourceAnalyzer for macros --- crates/ra_hir/src/source_binder.rs | 1 - 1 file changed, 1 deletion(-) (limited to 'crates/ra_hir/src') diff --git a/crates/ra_hir/src/source_binder.rs b/crates/ra_hir/src/source_binder.rs index 540ddd0b5..633f3e913 100644 --- a/crates/ra_hir/src/source_binder.rs +++ b/crates/ra_hir/src/source_binder.rs @@ -90,7 +90,6 @@ fn def_with_body_from_child_node( /// original source files. It should not be used inside the HIR itself. #[derive(Debug)] pub struct SourceAnalyzer { - // FIXME: this doesn't handle macros at all file_id: HirFileId, resolver: Resolver, body_owner: Option, -- cgit v1.2.3 From d898ecb8f2c19eb041bcb27c7ce9edd9d891f2c2 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Sat, 16 Nov 2019 00:56:51 +0300 Subject: Force passing Source when creating a SourceAnalyzer --- crates/ra_hir/src/source_binder.rs | 50 +++++++++++++++----------------------- crates/ra_hir/src/ty/tests.rs | 17 +++++++------ 2 files changed, 29 insertions(+), 38 deletions(-) (limited to 'crates/ra_hir/src') diff --git a/crates/ra_hir/src/source_binder.rs b/crates/ra_hir/src/source_binder.rs index 633f3e913..5764dc26d 100644 --- a/crates/ra_hir/src/source_binder.rs +++ b/crates/ra_hir/src/source_binder.rs @@ -12,7 +12,6 @@ use hir_def::{ path::known, }; use hir_expand::{name::AsName, Source}; -use ra_db::FileId; use ra_syntax::{ ast::{self, AstNode}, match_ast, AstPtr, @@ -30,38 +29,32 @@ use crate::{ HirFileId, Local, MacroDef, Module, Name, Path, Resolver, Static, Struct, Ty, }; -fn try_get_resolver_for_node( - db: &impl HirDatabase, - file_id: FileId, - node: &SyntaxNode, -) -> Option { +fn try_get_resolver_for_node(db: &impl HirDatabase, node: Source<&SyntaxNode>) -> Option { match_ast! { - match node { + match (node.ast) { ast::Module(it) => { - let src = crate::Source { file_id: file_id.into(), ast: it }; + let src = node.with_ast(it); Some(crate::Module::from_declaration(db, src)?.resolver(db)) }, ast::SourceFile(it) => { - let src = - crate::Source { file_id: file_id.into(), ast: crate::ModuleSource::SourceFile(it) }; + let src = node.with_ast(crate::ModuleSource::SourceFile(it)); Some(crate::Module::from_definition(db, src)?.resolver(db)) }, ast::StructDef(it) => { - let src = crate::Source { file_id: file_id.into(), ast: it }; + let src = node.with_ast(it); Some(Struct::from_source(db, src)?.resolver(db)) }, ast::EnumDef(it) => { - let src = crate::Source { file_id: file_id.into(), ast: it }; + let src = node.with_ast(it); Some(Enum::from_source(db, src)?.resolver(db)) }, - _ => { - if node.kind() == FN_DEF || node.kind() == CONST_DEF || node.kind() == STATIC_DEF { - Some(def_with_body_from_child_node(db, Source::new(file_id.into(), node))?.resolver(db)) - } else { - // FIXME add missing cases - None + _ => match node.ast.kind() { + FN_DEF | CONST_DEF | STATIC_DEF => { + Some(def_with_body_from_child_node(db, node)?.resolver(db)) } - }, + // FIXME add missing cases + _ => None + } } } } @@ -136,20 +129,16 @@ pub struct ReferenceDescriptor { impl SourceAnalyzer { pub fn new( db: &impl HirDatabase, - file_id: FileId, - node: &SyntaxNode, + node: Source<&SyntaxNode>, offset: Option, ) -> SourceAnalyzer { - let node_source = Source::new(file_id.into(), node); - let def_with_body = def_with_body_from_child_node(db, node_source); + let def_with_body = def_with_body_from_child_node(db, node); if let Some(def) = def_with_body { let source_map = def.body_source_map(db); let scopes = def.expr_scopes(db); let scope = match offset { - None => scope_for(&scopes, &source_map, node_source), - Some(offset) => { - scope_for_offset(&scopes, &source_map, Source::new(file_id.into(), offset)) - } + None => scope_for(&scopes, &source_map, node), + Some(offset) => scope_for_offset(&scopes, &source_map, node.with_ast(offset)), }; let resolver = expr::resolver_for_scope(db, def, scope); SourceAnalyzer { @@ -158,19 +147,20 @@ impl SourceAnalyzer { body_source_map: Some(source_map), infer: Some(def.infer(db)), scopes: Some(scopes), - file_id: file_id.into(), + file_id: node.file_id, } } else { SourceAnalyzer { resolver: node + .ast .ancestors() - .find_map(|node| try_get_resolver_for_node(db, file_id, &node)) + .find_map(|it| try_get_resolver_for_node(db, node.with_ast(&it))) .unwrap_or_default(), body_owner: None, body_source_map: None, infer: None, scopes: None, - file_id: file_id.into(), + file_id: node.file_id, } } } diff --git a/crates/ra_hir/src/ty/tests.rs b/crates/ra_hir/src/ty/tests.rs index fe9346c78..9a26e02fa 100644 --- a/crates/ra_hir/src/ty/tests.rs +++ b/crates/ra_hir/src/ty/tests.rs @@ -1,3 +1,6 @@ +mod never_type; +mod coercion; + use std::fmt::Write; use std::sync::Arc; @@ -11,7 +14,7 @@ use ra_syntax::{ use test_utils::covers; use crate::{ - expr::BodySourceMap, test_db::TestDB, ty::display::HirDisplay, ty::InferenceResult, + expr::BodySourceMap, test_db::TestDB, ty::display::HirDisplay, ty::InferenceResult, Source, SourceAnalyzer, }; @@ -19,9 +22,6 @@ use crate::{ // against snapshots of the expected results using insta. Use cargo-insta to // update the snapshots. -mod never_type; -mod coercion; - #[test] fn cfg_impl_block() { let (db, pos) = TestDB::with_position( @@ -4609,7 +4609,8 @@ fn test() where T: Trait, U: Trait { fn type_at_pos(db: &TestDB, pos: FilePosition) -> String { let file = db.parse(pos.file_id).ok().unwrap(); let expr = algo::find_node_at_offset::(file.syntax(), pos.offset).unwrap(); - let analyzer = SourceAnalyzer::new(db, pos.file_id, expr.syntax(), Some(pos.offset)); + let analyzer = + SourceAnalyzer::new(db, Source::new(pos.file_id.into(), expr.syntax()), Some(pos.offset)); let ty = analyzer.type_of(db, &expr).unwrap(); ty.display(db).to_string() } @@ -4674,7 +4675,7 @@ fn infer(content: &str) -> String { for node in source_file.syntax().descendants() { if node.kind() == FN_DEF || node.kind() == CONST_DEF || node.kind() == STATIC_DEF { - let analyzer = SourceAnalyzer::new(&db, file_id, &node, None); + let analyzer = SourceAnalyzer::new(&db, Source::new(file_id.into(), &node), None); infer_def(analyzer.inference_result(), analyzer.body_source_map()); } } @@ -4715,7 +4716,7 @@ fn typing_whitespace_inside_a_function_should_not_invalidate_types() { let file = db.parse(pos.file_id).ok().unwrap(); let node = file.syntax().token_at_offset(pos.offset).right_biased().unwrap().parent(); let events = db.log_executed(|| { - SourceAnalyzer::new(&db, pos.file_id, &node, None); + SourceAnalyzer::new(&db, Source::new(pos.file_id.into(), &node), None); }); assert!(format!("{:?}", events).contains("infer")) } @@ -4735,7 +4736,7 @@ fn typing_whitespace_inside_a_function_should_not_invalidate_types() { let file = db.parse(pos.file_id).ok().unwrap(); let node = file.syntax().token_at_offset(pos.offset).right_biased().unwrap().parent(); let events = db.log_executed(|| { - SourceAnalyzer::new(&db, pos.file_id, &node, None); + SourceAnalyzer::new(&db, Source::new(pos.file_id.into(), &node), None); }); assert!(!format!("{:?}", events).contains("infer"), "{:#?}", events) } -- cgit v1.2.3 From e21b82e035050570a8d8e77ebe8b50f7d34ad251 Mon Sep 17 00:00:00 2001 From: Florian Diebold Date: Fri, 15 Nov 2019 20:32:58 +0100 Subject: Upgrade Chalk Associated type values (in impls) are now a separate entity in Chalk, so we have to intern separate IDs for them. --- crates/ra_hir/src/db.rs | 15 +- crates/ra_hir/src/ids.rs | 6 + crates/ra_hir/src/ty/traits.rs | 13 +- crates/ra_hir/src/ty/traits/chalk.rs | 286 ++++++++++++++++++++++------------- 4 files changed, 210 insertions(+), 110 deletions(-) (limited to 'crates/ra_hir/src') diff --git a/crates/ra_hir/src/db.rs b/crates/ra_hir/src/db.rs index 276b0774f..d9fad0ae2 100644 --- a/crates/ra_hir/src/db.rs +++ b/crates/ra_hir/src/db.rs @@ -13,8 +13,10 @@ use crate::{ lang_item::{LangItemTarget, LangItems}, traits::TraitData, ty::{ - method_resolution::CrateImplBlocks, traits::Impl, CallableDef, FnSig, GenericPredicate, - InferenceResult, Namespace, Substs, Ty, TypableDef, TypeCtor, + method_resolution::CrateImplBlocks, + traits::{AssocTyValue, Impl}, + CallableDef, FnSig, GenericPredicate, InferenceResult, Namespace, Substs, Ty, TypableDef, + TypeCtor, }, type_alias::TypeAliasData, Const, ConstData, Crate, DefWithBody, FnData, Function, ImplBlock, Module, Static, StructField, @@ -119,6 +121,8 @@ pub trait HirDatabase: DefDatabase + AstDatabase { fn intern_type_ctor(&self, type_ctor: TypeCtor) -> ids::TypeCtorId; #[salsa::interned] fn intern_chalk_impl(&self, impl_: Impl) -> ids::GlobalImplId; + #[salsa::interned] + fn intern_assoc_ty_value(&self, assoc_ty_value: AssocTyValue) -> ids::AssocTyValueId; #[salsa::invoke(crate::ty::traits::chalk::associated_ty_data_query)] fn associated_ty_data(&self, id: chalk_ir::TypeId) -> Arc; @@ -140,6 +144,13 @@ pub trait HirDatabase: DefDatabase + AstDatabase { #[salsa::invoke(crate::ty::traits::chalk::impl_datum_query)] fn impl_datum(&self, krate: Crate, impl_id: chalk_ir::ImplId) -> Arc; + #[salsa::invoke(crate::ty::traits::chalk::associated_ty_value_query)] + fn associated_ty_value( + &self, + krate: Crate, + id: chalk_rust_ir::AssociatedTyValueId, + ) -> Arc; + #[salsa::invoke(crate::ty::traits::trait_solve_query)] fn trait_solve( &self, diff --git a/crates/ra_hir/src/ids.rs b/crates/ra_hir/src/ids.rs index fe083c0c6..2b59365fb 100644 --- a/crates/ra_hir/src/ids.rs +++ b/crates/ra_hir/src/ids.rs @@ -37,3 +37,9 @@ impl_intern_key!(TypeCtorId); #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct GlobalImplId(salsa::InternId); impl_intern_key!(GlobalImplId); + +/// This exists just for Chalk, because it needs a unique ID for each associated +/// type value in an impl (even synthetic ones). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct AssocTyValueId(salsa::InternId); +impl_intern_key!(AssocTyValueId); diff --git a/crates/ra_hir/src/ty/traits.rs b/crates/ra_hir/src/ty/traits.rs index 4f1eab150..771525deb 100644 --- a/crates/ra_hir/src/ty/traits.rs +++ b/crates/ra_hir/src/ty/traits.rs @@ -8,7 +8,7 @@ use ra_prof::profile; use rustc_hash::FxHashSet; use super::{Canonical, GenericPredicate, HirDisplay, ProjectionTy, TraitRef, Ty, TypeWalk}; -use crate::{db::HirDatabase, expr::ExprId, Crate, DefWithBody, ImplBlock, Trait}; +use crate::{db::HirDatabase, expr::ExprId, Crate, DefWithBody, ImplBlock, Trait, TypeAlias}; use self::chalk::{from_chalk, ToChalk}; @@ -300,3 +300,14 @@ pub enum Impl { /// Closure types implement the Fn traits synthetically. ClosureFnTraitImpl(ClosureFnTraitImplData), } + +/// An associated type value. Usually this comes from a `type` declaration +/// inside an impl block, but for built-in impls we have to synthesize it. +/// (We only need this because Chalk wants a unique ID for each of these.) +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum AssocTyValue { + /// A normal assoc type value from an impl block. + TypeAlias(TypeAlias), + /// The output type of the Fn trait implementation. + ClosureFnTraitImplOutput(ClosureFnTraitImplData), +} diff --git a/crates/ra_hir/src/ty/traits/chalk.rs b/crates/ra_hir/src/ty/traits/chalk.rs index 68304b950..e39e8aaca 100644 --- a/crates/ra_hir/src/ty/traits/chalk.rs +++ b/crates/ra_hir/src/ty/traits/chalk.rs @@ -7,22 +7,19 @@ use chalk_ir::{ cast::Cast, family::ChalkIr, Identifier, ImplId, Parameter, PlaceholderIndex, TypeId, TypeKindId, TypeName, UniverseIndex, }; -use chalk_rust_ir::{AssociatedTyDatum, ImplDatum, StructDatum, TraitDatum}; +use chalk_rust_ir::{AssociatedTyDatum, AssociatedTyValue, ImplDatum, StructDatum, TraitDatum}; use hir_expand::name; use ra_db::salsa::{InternId, InternKey}; -use super::{Canonical, ChalkContext, Impl, Obligation}; +use super::{AssocTyValue, Canonical, ChalkContext, Impl, Obligation}; use crate::{ db::HirDatabase, generics::{GenericDef, HasGenericParams}, ty::display::HirDisplay, - ty::{ - ApplicationTy, GenericPredicate, Namespace, ProjectionTy, Substs, TraitRef, Ty, TypeCtor, - TypeWalk, - }, - AssocItem, Crate, HasBody, ImplBlock, Trait, TypeAlias, + ty::{ApplicationTy, GenericPredicate, ProjectionTy, Substs, TraitRef, Ty, TypeCtor, TypeWalk}, + Crate, HasBody, ImplBlock, Trait, TypeAlias, }; /// This represents a trait whose name we could not resolve. @@ -59,29 +56,29 @@ impl ToChalk for Ty { } }; let parameters = apply_ty.parameters.to_chalk(db); - chalk_ir::ApplicationTy { name, parameters }.cast() + chalk_ir::ApplicationTy { name, parameters }.cast().intern() } Ty::Projection(proj_ty) => { let associated_ty_id = proj_ty.associated_ty.to_chalk(db); let parameters = proj_ty.parameters.to_chalk(db); - chalk_ir::ProjectionTy { associated_ty_id, parameters }.cast() + chalk_ir::ProjectionTy { associated_ty_id, parameters }.cast().intern() } Ty::Param { idx, .. } => { PlaceholderIndex { ui: UniverseIndex::ROOT, idx: idx as usize }.to_ty::() } - Ty::Bound(idx) => chalk_ir::Ty::BoundVar(idx as usize), + Ty::Bound(idx) => chalk_ir::TyData::BoundVar(idx as usize).intern(), Ty::Infer(_infer_ty) => panic!("uncanonicalized infer ty"), // FIXME use Chalk's Dyn/Opaque once the bugs with that are fixed Ty::Unknown | Ty::Dyn(_) | Ty::Opaque(_) => { let parameters = Vec::new(); let name = TypeName::Error; - chalk_ir::ApplicationTy { name, parameters }.cast() + chalk_ir::ApplicationTy { name, parameters }.cast().intern() } } } fn from_chalk(db: &impl HirDatabase, chalk: chalk_ir::Ty) -> Self { - match chalk { - chalk_ir::Ty::Apply(apply_ty) => { + match chalk.data().clone() { + chalk_ir::TyData::Apply(apply_ty) => { // FIXME this is kind of hacky due to the fact that // TypeName::Placeholder is a Ty::Param on our side match apply_ty.name { @@ -104,21 +101,21 @@ impl ToChalk for Ty { } } } - chalk_ir::Ty::Projection(proj) => { + chalk_ir::TyData::Projection(proj) => { let associated_ty = from_chalk(db, proj.associated_ty_id); let parameters = from_chalk(db, proj.parameters); Ty::Projection(ProjectionTy { associated_ty, parameters }) } - chalk_ir::Ty::ForAll(_) => unimplemented!(), - chalk_ir::Ty::BoundVar(idx) => Ty::Bound(idx as u32), - chalk_ir::Ty::InferenceVar(_iv) => Ty::Unknown, - chalk_ir::Ty::Dyn(where_clauses) => { + chalk_ir::TyData::ForAll(_) => unimplemented!(), + chalk_ir::TyData::BoundVar(idx) => Ty::Bound(idx as u32), + chalk_ir::TyData::InferenceVar(_iv) => Ty::Unknown, + chalk_ir::TyData::Dyn(where_clauses) => { assert_eq!(where_clauses.binders.len(), 1); let predicates = where_clauses.value.into_iter().map(|c| from_chalk(db, c)).collect(); Ty::Dyn(predicates) } - chalk_ir::Ty::Opaque(where_clauses) => { + chalk_ir::TyData::Opaque(where_clauses) => { assert_eq!(where_clauses.binders.len(), 1); let predicates = where_clauses.value.into_iter().map(|c| from_chalk(db, c)).collect(); @@ -211,6 +208,21 @@ impl ToChalk for TypeAlias { } } +impl ToChalk for AssocTyValue { + type Chalk = chalk_rust_ir::AssociatedTyValueId; + + fn to_chalk(self, db: &impl HirDatabase) -> chalk_rust_ir::AssociatedTyValueId { + db.intern_assoc_ty_value(self).into() + } + + fn from_chalk( + db: &impl HirDatabase, + assoc_ty_value_id: chalk_rust_ir::AssociatedTyValueId, + ) -> AssocTyValue { + db.lookup_intern_assoc_ty_value(assoc_ty_value_id.into()) + } +} + impl ToChalk for GenericPredicate { type Chalk = chalk_ir::QuantifiedWhereClause; @@ -462,13 +474,11 @@ where fn type_name(&self, _id: TypeKindId) -> Identifier { unimplemented!() } - fn split_projection<'p>( + fn associated_ty_value( &self, - projection: &'p chalk_ir::ProjectionTy, - ) -> (Arc, &'p [Parameter], &'p [Parameter]) { - debug!("split_projection {:?}", projection); - // we don't support GATs, so I think this should always be correct currently - (self.db.associated_ty_data(projection.associated_ty_id), &projection.parameters, &[]) + id: chalk_rust_ir::AssociatedTyValueId, + ) -> Arc { + self.db.associated_ty_value(self.krate, id) } fn custom_clauses(&self) -> Vec> { vec![] @@ -493,19 +503,16 @@ pub(crate) fn associated_ty_data_query( _ => panic!("associated type not in trait"), }; let generic_params = type_alias.generic_params(db); - let parameter_kinds = generic_params - .params_including_parent() - .into_iter() - .map(|p| chalk_ir::ParameterKind::Ty(lalrpop_intern::intern(&p.name.to_string()))) - .collect(); + let bound_data = chalk_rust_ir::AssociatedTyDatumBound { + // FIXME add bounds and where clauses + bounds: vec![], + where_clauses: vec![], + }; let datum = AssociatedTyDatum { trait_id: trait_.to_chalk(db), id, name: lalrpop_intern::intern(&type_alias.name(db).to_string()), - parameter_kinds, - // FIXME add bounds and where clauses - bounds: vec![], - where_clauses: vec![], + binders: make_binders(bound_data, generic_params.count_params_including_parent()), }; Arc::new(datum) } @@ -517,14 +524,7 @@ pub(crate) fn trait_datum_query( ) -> Arc { debug!("trait_datum {:?}", trait_id); if trait_id == UNKNOWN_TRAIT { - let trait_datum_bound = chalk_rust_ir::TraitDatumBound { - trait_ref: chalk_ir::TraitRef { - trait_id: UNKNOWN_TRAIT, - parameters: vec![chalk_ir::Ty::BoundVar(0).cast()], - }, - associated_ty_ids: Vec::new(), - where_clauses: Vec::new(), - }; + let trait_datum_bound = chalk_rust_ir::TraitDatumBound { where_clauses: Vec::new() }; let flags = chalk_rust_ir::TraitFlags { auto: false, @@ -532,18 +532,24 @@ pub(crate) fn trait_datum_query( upstream: true, fundamental: false, non_enumerable: true, + coinductive: false, }; - return Arc::new(TraitDatum { binders: make_binders(trait_datum_bound, 1), flags }); + return Arc::new(TraitDatum { + id: trait_id, + binders: make_binders(trait_datum_bound, 1), + flags, + associated_ty_ids: vec![], + }); } let trait_: Trait = from_chalk(db, trait_id); debug!("trait {:?} = {:?}", trait_id, trait_.name(db)); let generic_params = trait_.generic_params(db); let bound_vars = Substs::bound_vars(&generic_params); - let trait_ref = trait_.trait_ref(db).subst(&bound_vars).to_chalk(db); let flags = chalk_rust_ir::TraitFlags { auto: trait_.is_auto(db), upstream: trait_.module(db).krate() != krate, non_enumerable: true, + coinductive: false, // only relevant for Chalk testing // FIXME set these flags correctly marker: false, fundamental: false, @@ -558,10 +564,13 @@ pub(crate) fn trait_datum_query( }) .map(|type_alias| type_alias.to_chalk(db)) .collect(); - let trait_datum_bound = - chalk_rust_ir::TraitDatumBound { trait_ref, where_clauses, associated_ty_ids }; - let trait_datum = - TraitDatum { binders: make_binders(trait_datum_bound, bound_vars.len()), flags }; + let trait_datum_bound = chalk_rust_ir::TraitDatumBound { where_clauses }; + let trait_datum = TraitDatum { + id: trait_id, + binders: make_binders(trait_datum_bound, bound_vars.len()), + flags, + associated_ty_ids, + }; Arc::new(trait_datum) } @@ -588,17 +597,12 @@ pub(crate) fn struct_datum_query( // FIXME set fundamental flag correctly fundamental: false, }; - let self_ty = chalk_ir::ApplicationTy { - name: TypeName::TypeKindId(type_ctor.to_chalk(db).into()), - parameters: (0..num_params).map(|i| chalk_ir::Ty::BoundVar(i).cast()).collect(), - }; let struct_datum_bound = chalk_rust_ir::StructDatumBound { - self_ty, fields: Vec::new(), // FIXME add fields (only relevant for auto traits) where_clauses, - flags, }; - let struct_datum = StructDatum { binders: make_binders(struct_datum_bound, num_params) }; + let struct_datum = + StructDatum { id: struct_id, binders: make_binders(struct_datum_bound, num_params), flags }; Arc::new(struct_datum) } @@ -612,10 +616,9 @@ pub(crate) fn impl_datum_query( let impl_: Impl = from_chalk(db, impl_id); match impl_ { Impl::ImplBlock(impl_block) => impl_block_datum(db, krate, impl_id, impl_block), - Impl::ClosureFnTraitImpl(data) => { - closure_fn_trait_impl_datum(db, krate, impl_id, data).unwrap_or_else(invalid_impl_datum) - } + Impl::ClosureFnTraitImpl(data) => closure_fn_trait_impl_datum(db, krate, data), } + .unwrap_or_else(invalid_impl_datum) } fn impl_block_datum( @@ -623,13 +626,11 @@ fn impl_block_datum( krate: Crate, impl_id: ImplId, impl_block: ImplBlock, -) -> Arc { +) -> Option> { let generic_params = impl_block.generic_params(db); let bound_vars = Substs::bound_vars(&generic_params); - let trait_ref = impl_block - .target_trait_ref(db) - .expect("FIXME handle unresolved impl block trait ref") - .subst(&bound_vars); + let trait_ref = impl_block.target_trait_ref(db)?.subst(&bound_vars); + let trait_ = trait_ref.trait_; let impl_type = if impl_block.krate(db) == krate { chalk_rust_ir::ImplType::Local } else { @@ -644,28 +645,7 @@ fn impl_block_datum( trait_ref.display(db), where_clauses ); - let trait_ = trait_ref.trait_; let trait_ref = trait_ref.to_chalk(db); - let associated_ty_values = impl_block - .items(db) - .into_iter() - .filter_map(|item| match item { - AssocItem::TypeAlias(t) => Some(t), - _ => None, - }) - .filter_map(|t| { - let assoc_ty = trait_.associated_type_by_name(db, &t.name(db))?; - let ty = db.type_for_def(t.into(), Namespace::Types).subst(&bound_vars); - Some(chalk_rust_ir::AssociatedTyValue { - impl_id, - associated_ty_id: assoc_ty.to_chalk(db), - value: chalk_ir::Binders { - value: chalk_rust_ir::AssociatedTyValueBound { ty: ty.to_chalk(db) }, - binders: vec![], // we don't support GATs yet - }, - }) - }) - .collect(); let polarity = if negative { chalk_rust_ir::Polarity::Negative @@ -673,31 +653,41 @@ fn impl_block_datum( chalk_rust_ir::Polarity::Positive }; - let impl_datum_bound = - chalk_rust_ir::ImplDatumBound { trait_ref, where_clauses, associated_ty_values }; + let impl_datum_bound = chalk_rust_ir::ImplDatumBound { trait_ref, where_clauses }; + let associated_ty_value_ids = impl_block + .items(db) + .into_iter() + .filter_map(|item| match item { + crate::AssocItem::TypeAlias(type_alias) => Some(type_alias), + _ => None, + }) + .filter(|type_alias| { + // don't include associated types that don't exist in the trait + trait_.associated_type_by_name(db, &type_alias.name(db)).is_some() + }) + .map(|type_alias| AssocTyValue::TypeAlias(type_alias).to_chalk(db)) + .collect(); debug!("impl_datum: {:?}", impl_datum_bound); let impl_datum = ImplDatum { binders: make_binders(impl_datum_bound, bound_vars.len()), impl_type, polarity, + associated_ty_value_ids, }; - Arc::new(impl_datum) + Some(Arc::new(impl_datum)) } fn invalid_impl_datum() -> Arc { let trait_ref = chalk_ir::TraitRef { trait_id: UNKNOWN_TRAIT, - parameters: vec![chalk_ir::Ty::BoundVar(0).cast()], - }; - let impl_datum_bound = chalk_rust_ir::ImplDatumBound { - trait_ref, - where_clauses: Vec::new(), - associated_ty_values: Vec::new(), + parameters: vec![chalk_ir::TyData::BoundVar(0).cast().intern().cast()], }; + let impl_datum_bound = chalk_rust_ir::ImplDatumBound { trait_ref, where_clauses: Vec::new() }; let impl_datum = ImplDatum { binders: make_binders(impl_datum_bound, 1), impl_type: chalk_rust_ir::ImplType::External, polarity: chalk_rust_ir::Polarity::Positive, + associated_ty_value_ids: Vec::new(), }; Arc::new(impl_datum) } @@ -705,15 +695,19 @@ fn invalid_impl_datum() -> Arc { fn closure_fn_trait_impl_datum( db: &impl HirDatabase, krate: Crate, - impl_id: ImplId, data: super::ClosureFnTraitImplData, ) -> Option> { // for some closure |X, Y| -> Z: // impl Fn<(T, U)> for closure V> { Output = V } - let fn_once_trait = get_fn_trait(db, krate, super::FnTrait::FnOnce)?; let trait_ = get_fn_trait(db, krate, data.fn_trait)?; // get corresponding fn trait + // validate FnOnce trait, since we need it in the assoc ty value definition + // and don't want to return a valid value only to find out later that FnOnce + // is broken + let fn_once_trait = get_fn_trait(db, krate, super::FnTrait::FnOnce)?; + fn_once_trait.associated_type_by_name(db, &name::OUTPUT_TYPE)?; + let num_args: u16 = match &data.def.body(db)[data.expr] { crate::expr::Expr::Lambda { args, .. } => args.len() as u16, _ => { @@ -726,7 +720,6 @@ fn closure_fn_trait_impl_datum( TypeCtor::Tuple { cardinality: num_args }, Substs::builder(num_args as usize).fill_with_bound_vars(0).build(), ); - let output_ty = Ty::Bound(num_args.into()); let sig_ty = Ty::apply( TypeCtor::FnPtr { num_args }, Substs::builder(num_args as usize + 1).fill_with_bound_vars(0).build(), @@ -739,32 +732,99 @@ fn closure_fn_trait_impl_datum( substs: Substs::build_for_def(db, trait_).push(self_ty).push(arg_ty).build(), }; - let output_ty_id = fn_once_trait.associated_type_by_name(db, &name::OUTPUT_TYPE)?; - - let output_ty_value = chalk_rust_ir::AssociatedTyValue { - associated_ty_id: output_ty_id.to_chalk(db), - impl_id, - value: make_binders( - chalk_rust_ir::AssociatedTyValueBound { ty: output_ty.to_chalk(db) }, - 0, - ), - }; + let output_ty_id = AssocTyValue::ClosureFnTraitImplOutput(data.clone()).to_chalk(db); let impl_type = chalk_rust_ir::ImplType::External; let impl_datum_bound = chalk_rust_ir::ImplDatumBound { trait_ref: trait_ref.to_chalk(db), where_clauses: Vec::new(), - associated_ty_values: vec![output_ty_value], }; let impl_datum = ImplDatum { binders: make_binders(impl_datum_bound, num_args as usize + 1), impl_type, polarity: chalk_rust_ir::Polarity::Positive, + associated_ty_value_ids: vec![output_ty_id], }; Some(Arc::new(impl_datum)) } +pub(crate) fn associated_ty_value_query( + db: &impl HirDatabase, + krate: Crate, + id: chalk_rust_ir::AssociatedTyValueId, +) -> Arc { + let data: AssocTyValue = from_chalk(db, id); + match data { + AssocTyValue::TypeAlias(type_alias) => { + type_alias_associated_ty_value(db, krate, type_alias) + } + AssocTyValue::ClosureFnTraitImplOutput(data) => { + closure_fn_trait_output_assoc_ty_value(db, krate, data) + } + } +} + +fn type_alias_associated_ty_value( + db: &impl HirDatabase, + _krate: Crate, + type_alias: TypeAlias, +) -> Arc { + let impl_block = type_alias.impl_block(db).expect("assoc ty value should be in impl"); + let impl_id = Impl::ImplBlock(impl_block).to_chalk(db); + let trait_ = impl_block + .target_trait_ref(db) + .expect("assoc ty value should not exist") // we don't return any assoc ty values if the impl'd trait can't be resolved + .trait_; + let assoc_ty = trait_ + .associated_type_by_name(db, &type_alias.name(db)) + .expect("assoc ty value should not exist"); // validated when building the impl data as well + let generic_params = impl_block.generic_params(db); + let bound_vars = Substs::bound_vars(&generic_params); + let ty = db.type_for_def(type_alias.into(), crate::ty::Namespace::Types).subst(&bound_vars); + let value_bound = chalk_rust_ir::AssociatedTyValueBound { ty: ty.to_chalk(db) }; + let value = chalk_rust_ir::AssociatedTyValue { + impl_id, + associated_ty_id: assoc_ty.to_chalk(db), + value: make_binders(value_bound, bound_vars.len()), + }; + Arc::new(value) +} + +fn closure_fn_trait_output_assoc_ty_value( + db: &impl HirDatabase, + krate: Crate, + data: super::ClosureFnTraitImplData, +) -> Arc { + let impl_id = Impl::ClosureFnTraitImpl(data.clone()).to_chalk(db); + + let num_args: u16 = match &data.def.body(db)[data.expr] { + crate::expr::Expr::Lambda { args, .. } => args.len() as u16, + _ => { + log::warn!("closure for closure type {:?} not found", data); + 0 + } + }; + + let output_ty = Ty::Bound(num_args.into()); + + let fn_once_trait = + get_fn_trait(db, krate, super::FnTrait::FnOnce).expect("assoc ty value should not exist"); + + let output_ty_id = fn_once_trait + .associated_type_by_name(db, &name::OUTPUT_TYPE) + .expect("assoc ty value should not exist"); + + let value_bound = chalk_rust_ir::AssociatedTyValueBound { ty: output_ty.to_chalk(db) }; + + let value = chalk_rust_ir::AssociatedTyValue { + associated_ty_id: output_ty_id.to_chalk(db), + impl_id, + value: make_binders(value_bound, num_args as usize + 1), + }; + Arc::new(value) +} + fn get_fn_trait(db: &impl HirDatabase, krate: Crate, fn_trait: super::FnTrait) -> Option { let target = db.lang_item(krate, fn_trait.lang_item_name().into())?; match target { @@ -803,3 +863,15 @@ impl From for chalk_ir::ImplId { chalk_ir::ImplId(id_to_chalk(impl_id)) } } + +impl From for crate::ids::AssocTyValueId { + fn from(id: chalk_rust_ir::AssociatedTyValueId) -> Self { + id_from_chalk(id.0) + } +} + +impl From for chalk_rust_ir::AssociatedTyValueId { + fn from(assoc_ty_value_id: crate::ids::AssocTyValueId) -> Self { + chalk_rust_ir::AssociatedTyValueId(id_to_chalk(assoc_ty_value_id)) + } +} -- cgit v1.2.3 From 9c2a9a9a0635e53466749fdedcdc5a371e658cde Mon Sep 17 00:00:00 2001 From: Florian Diebold Date: Fri, 15 Nov 2019 21:00:27 +0100 Subject: Use Chalk's dyn/impl trait support --- crates/ra_hir/src/ty/method_resolution.rs | 6 +----- crates/ra_hir/src/ty/tests.rs | 12 ++++++------ crates/ra_hir/src/ty/traits/chalk.rs | 11 +++++++++-- 3 files changed, 16 insertions(+), 13 deletions(-) (limited to 'crates/ra_hir/src') diff --git a/crates/ra_hir/src/ty/method_resolution.rs b/crates/ra_hir/src/ty/method_resolution.rs index 9aad2d3fe..d20aeaacf 100644 --- a/crates/ra_hir/src/ty/method_resolution.rs +++ b/crates/ra_hir/src/ty/method_resolution.rs @@ -228,14 +228,10 @@ fn iterate_trait_method_candidates( 'traits: for t in traits { let data = t.trait_data(db); - // FIXME this is a bit of a hack, since Chalk should say the same thing - // anyway, but currently Chalk doesn't implement `dyn/impl Trait` yet - let inherently_implemented = ty.value.inherent_trait() == Some(t); - // we'll be lazy about checking whether the type implements the // trait, but if we find out it doesn't, we'll skip the rest of the // iteration - let mut known_implemented = inherently_implemented; + let mut known_implemented = false; for &item in data.items() { if !is_valid_candidate(db, name, mode, item) { continue; diff --git a/crates/ra_hir/src/ty/tests.rs b/crates/ra_hir/src/ty/tests.rs index 9a26e02fa..838cb4d23 100644 --- a/crates/ra_hir/src/ty/tests.rs +++ b/crates/ra_hir/src/ty/tests.rs @@ -3983,11 +3983,11 @@ fn test(x: impl Trait, y: &impl Trait) { [180; 183) 'bar': fn bar() -> impl Trait [180; 185) 'bar()': impl Trait [191; 192) 'x': impl Trait - [191; 198) 'x.foo()': {unknown} + [191; 198) 'x.foo()': u64 [204; 205) 'y': &impl Trait - [204; 211) 'y.foo()': {unknown} + [204; 211) 'y.foo()': u64 [217; 218) 'z': impl Trait - [217; 224) 'z.foo()': {unknown} + [217; 224) 'z.foo()': u64 [230; 231) 'x': impl Trait [230; 238) 'x.foo2()': i64 [244; 245) 'y': &impl Trait @@ -4033,11 +4033,11 @@ fn test(x: dyn Trait, y: &dyn Trait) { [177; 180) 'bar': fn bar() -> dyn Trait [177; 182) 'bar()': dyn Trait [188; 189) 'x': dyn Trait - [188; 195) 'x.foo()': {unknown} + [188; 195) 'x.foo()': u64 [201; 202) 'y': &dyn Trait - [201; 208) 'y.foo()': {unknown} + [201; 208) 'y.foo()': u64 [214; 215) 'z': dyn Trait - [214; 221) 'z.foo()': {unknown} + [214; 221) 'z.foo()': u64 [227; 228) 'x': dyn Trait [227; 235) 'x.foo2()': i64 [241; 242) 'y': &dyn Trait diff --git a/crates/ra_hir/src/ty/traits/chalk.rs b/crates/ra_hir/src/ty/traits/chalk.rs index e39e8aaca..81a378bac 100644 --- a/crates/ra_hir/src/ty/traits/chalk.rs +++ b/crates/ra_hir/src/ty/traits/chalk.rs @@ -68,8 +68,15 @@ impl ToChalk for Ty { } Ty::Bound(idx) => chalk_ir::TyData::BoundVar(idx as usize).intern(), Ty::Infer(_infer_ty) => panic!("uncanonicalized infer ty"), - // FIXME use Chalk's Dyn/Opaque once the bugs with that are fixed - Ty::Unknown | Ty::Dyn(_) | Ty::Opaque(_) => { + Ty::Dyn(predicates) => { + let where_clauses = predicates.iter().cloned().map(|p| p.to_chalk(db)).collect(); + chalk_ir::TyData::Dyn(make_binders(where_clauses, 1)).intern() + } + Ty::Opaque(predicates) => { + let where_clauses = predicates.iter().cloned().map(|p| p.to_chalk(db)).collect(); + chalk_ir::TyData::Opaque(make_binders(where_clauses, 1)).intern() + } + Ty::Unknown => { let parameters = Vec::new(); let name = TypeName::Error; chalk_ir::ApplicationTy { name, parameters }.cast().intern() -- cgit v1.2.3 From 351c29d859d74f7a61e654bdbcad634bfb136225 Mon Sep 17 00:00:00 2001 From: Florian Diebold Date: Sat, 16 Nov 2019 12:53:13 +0100 Subject: Fix handling of the binders in dyn/impl Trait We need to be more careful now when substituting bound variables (previously, we didn't have anything that used bound variables except Chalk, so it was not a problem). This is obviously quite ad-hoc; Chalk has more infrastructure for handling this in a principled way, which we maybe should adopt. --- crates/ra_hir/src/ty.rs | 89 ++++++++++++++++++++++++------------- crates/ra_hir/src/ty/infer/unify.rs | 22 ++++----- crates/ra_hir/src/ty/tests.rs | 43 ++++++++++++++++++ crates/ra_hir/src/ty/traits.rs | 7 +-- 4 files changed, 116 insertions(+), 45 deletions(-) (limited to 'crates/ra_hir/src') diff --git a/crates/ra_hir/src/ty.rs b/crates/ra_hir/src/ty.rs index ff6030ac4..a54135188 100644 --- a/crates/ra_hir/src/ty.rs +++ b/crates/ra_hir/src/ty.rs @@ -224,8 +224,8 @@ impl TypeWalk for ProjectionTy { self.parameters.walk(f); } - fn walk_mut(&mut self, f: &mut impl FnMut(&mut Ty)) { - self.parameters.walk_mut(f); + fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { + self.parameters.walk_mut_binders(f, binders); } } @@ -291,6 +291,20 @@ pub enum Ty { #[derive(Clone, PartialEq, Eq, Debug, Hash)] pub struct Substs(Arc<[Ty]>); +impl TypeWalk for Substs { + fn walk(&self, f: &mut impl FnMut(&Ty)) { + for t in self.0.iter() { + t.walk(f); + } + } + + fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { + for t in make_mut_slice(&mut self.0) { + t.walk_mut_binders(f, binders); + } + } +} + impl Substs { pub fn empty() -> Substs { Substs(Arc::new([])) @@ -304,18 +318,6 @@ impl Substs { Substs(self.0[..std::cmp::min(self.0.len(), n)].into()) } - pub fn walk(&self, f: &mut impl FnMut(&Ty)) { - for t in self.0.iter() { - t.walk(f); - } - } - - pub fn walk_mut(&mut self, f: &mut impl FnMut(&mut Ty)) { - for t in make_mut_slice(&mut self.0) { - t.walk_mut(f); - } - } - pub fn as_single(&self) -> &Ty { if self.0.len() != 1 { panic!("expected substs of len 1, got {:?}", self); @@ -440,8 +442,8 @@ impl TypeWalk for TraitRef { self.substs.walk(f); } - fn walk_mut(&mut self, f: &mut impl FnMut(&mut Ty)) { - self.substs.walk_mut(f); + fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { + self.substs.walk_mut_binders(f, binders); } } @@ -491,10 +493,12 @@ impl TypeWalk for GenericPredicate { } } - fn walk_mut(&mut self, f: &mut impl FnMut(&mut Ty)) { + fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { match self { - GenericPredicate::Implemented(trait_ref) => trait_ref.walk_mut(f), - GenericPredicate::Projection(projection_pred) => projection_pred.walk_mut(f), + GenericPredicate::Implemented(trait_ref) => trait_ref.walk_mut_binders(f, binders), + GenericPredicate::Projection(projection_pred) => { + projection_pred.walk_mut_binders(f, binders) + } GenericPredicate::Error => {} } } @@ -544,9 +548,9 @@ impl TypeWalk for FnSig { } } - fn walk_mut(&mut self, f: &mut impl FnMut(&mut Ty)) { + fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { for t in make_mut_slice(&mut self.params_and_return) { - t.walk_mut(f); + t.walk_mut_binders(f, binders); } } } @@ -671,7 +675,20 @@ impl Ty { /// types, similar to Chalk's `Fold` trait. pub trait TypeWalk { fn walk(&self, f: &mut impl FnMut(&Ty)); - fn walk_mut(&mut self, f: &mut impl FnMut(&mut Ty)); + fn walk_mut(&mut self, f: &mut impl FnMut(&mut Ty)) { + self.walk_mut_binders(&mut |ty, _binders| f(ty), 0); + } + /// Walk the type, counting entered binders. + /// + /// `Ty::Bound` variables use DeBruijn indexing, which means that 0 refers + /// to the innermost binder, 1 to the next, etc.. So when we want to + /// substitute a certain bound variable, we can't just walk the whole type + /// and blindly replace each instance of a certain index; when we 'enter' + /// things that introduce new bound variables, we have to keep track of + /// that. Currently, the only thing that introduces bound variables on our + /// side are `Ty::Dyn` and `Ty::Opaque`, which each introduce a bound + /// variable for the self type. + fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize); fn fold(mut self, f: &mut impl FnMut(Ty) -> Ty) -> Self where @@ -700,14 +717,22 @@ pub trait TypeWalk { } /// Substitutes `Ty::Bound` vars (as opposed to type parameters). - fn subst_bound_vars(self, substs: &Substs) -> Self + fn subst_bound_vars(mut self, substs: &Substs) -> Self where Self: Sized, { - self.fold(&mut |ty| match ty { - Ty::Bound(idx) => substs.get(idx as usize).cloned().unwrap_or_else(|| Ty::Bound(idx)), - ty => ty, - }) + self.walk_mut_binders( + &mut |ty, binders| match ty { + &mut Ty::Bound(idx) => { + if idx as usize >= binders && (idx as usize - binders) < substs.len() { + *ty = substs.0[idx as usize - binders].clone(); + } + } + _ => {} + }, + 0, + ); + self } /// Shifts up `Ty::Bound` vars by `n`. @@ -748,22 +773,22 @@ impl TypeWalk for Ty { f(self); } - fn walk_mut(&mut self, f: &mut impl FnMut(&mut Ty)) { + fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { match self { Ty::Apply(a_ty) => { - a_ty.parameters.walk_mut(f); + a_ty.parameters.walk_mut_binders(f, binders); } Ty::Projection(p_ty) => { - p_ty.parameters.walk_mut(f); + p_ty.parameters.walk_mut_binders(f, binders); } Ty::Dyn(predicates) | Ty::Opaque(predicates) => { for p in make_mut_slice(predicates) { - p.walk_mut(f); + p.walk_mut_binders(f, binders + 1); } } Ty::Param { .. } | Ty::Bound(_) | Ty::Infer(_) | Ty::Unknown => {} } - f(self); + f(self, binders); } } diff --git a/crates/ra_hir/src/ty/infer/unify.rs b/crates/ra_hir/src/ty/infer/unify.rs index ca33cc7f8..64d9394cf 100644 --- a/crates/ra_hir/src/ty/infer/unify.rs +++ b/crates/ra_hir/src/ty/infer/unify.rs @@ -134,17 +134,19 @@ where } impl Canonicalized { - pub fn decanonicalize_ty(&self, ty: Ty) -> Ty { - ty.fold(&mut |ty| match ty { - Ty::Bound(idx) => { - if (idx as usize) < self.free_vars.len() { - Ty::Infer(self.free_vars[idx as usize]) - } else { - Ty::Bound(idx) + pub fn decanonicalize_ty(&self, mut ty: Ty) -> Ty { + ty.walk_mut_binders( + &mut |ty, binders| match ty { + &mut Ty::Bound(idx) => { + if idx as usize >= binders && (idx as usize - binders) < self.free_vars.len() { + *ty = Ty::Infer(self.free_vars[idx as usize - binders]); + } } - } - ty => ty, - }) + _ => {} + }, + 0, + ); + ty } pub fn apply_solution( diff --git a/crates/ra_hir/src/ty/tests.rs b/crates/ra_hir/src/ty/tests.rs index 838cb4d23..ca1693679 100644 --- a/crates/ra_hir/src/ty/tests.rs +++ b/crates/ra_hir/src/ty/tests.rs @@ -4184,6 +4184,49 @@ fn test>(x: T, y: impl Trait) { ); } +#[test] +fn impl_trait_assoc_binding_projection_bug() { + let (db, pos) = TestDB::with_position( + r#" +//- /main.rs crate:main deps:std +pub trait Language { + type Kind; +} +pub enum RustLanguage {} +impl Language for RustLanguage { + type Kind = SyntaxKind; +} +struct SyntaxNode {} +fn foo() -> impl Iterator> {} + +trait Clone { + fn clone(&self) -> Self; +} + +fn api_walkthrough() { + for node in foo() { + node.clone()<|>; + } +} + +//- /std.rs crate:std +#[prelude_import] use iter::*; +mod iter { + trait IntoIterator { + type Item; + } + trait Iterator { + type Item; + } + impl IntoIterator for T { + type Item = ::Item; + } +} +"#, + ); + assert_eq!("{unknown}", type_at_pos(&db, pos)); +} + #[test] fn projection_eq_within_chalk() { // std::env::set_var("CHALK_DEBUG", "1"); diff --git a/crates/ra_hir/src/ty/traits.rs b/crates/ra_hir/src/ty/traits.rs index 771525deb..99dbab99e 100644 --- a/crates/ra_hir/src/ty/traits.rs +++ b/crates/ra_hir/src/ty/traits.rs @@ -165,9 +165,9 @@ impl TypeWalk for ProjectionPredicate { self.ty.walk(f); } - fn walk_mut(&mut self, f: &mut impl FnMut(&mut Ty)) { - self.projection_ty.walk_mut(f); - self.ty.walk_mut(f); + fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { + self.projection_ty.walk_mut_binders(f, binders); + self.ty.walk_mut_binders(f, binders); } } @@ -188,6 +188,7 @@ pub(crate) fn trait_solve_query( } let canonical = goal.to_chalk(db).cast(); + // We currently don't deal with universes (I think / hope they're not yet // relevant for our use cases?) let u_canonical = chalk_ir::UCanonical { canonical, universes: 1 }; -- cgit v1.2.3 From ee190388ab9068167f665bec39edd4546336ee3d Mon Sep 17 00:00:00 2001 From: Florian Diebold Date: Sat, 16 Nov 2019 13:21:51 +0100 Subject: Upgrade Chalk again --- crates/ra_hir/src/db.rs | 17 ++++++++++++----- crates/ra_hir/src/ty/traits.rs | 9 ++++++--- crates/ra_hir/src/ty/traits/chalk.rs | 32 ++++++++++++++++---------------- 3 files changed, 34 insertions(+), 24 deletions(-) (limited to 'crates/ra_hir/src') diff --git a/crates/ra_hir/src/db.rs b/crates/ra_hir/src/db.rs index d9fad0ae2..d75d71d66 100644 --- a/crates/ra_hir/src/db.rs +++ b/crates/ra_hir/src/db.rs @@ -125,31 +125,38 @@ pub trait HirDatabase: DefDatabase + AstDatabase { fn intern_assoc_ty_value(&self, assoc_ty_value: AssocTyValue) -> ids::AssocTyValueId; #[salsa::invoke(crate::ty::traits::chalk::associated_ty_data_query)] - fn associated_ty_data(&self, id: chalk_ir::TypeId) -> Arc; + fn associated_ty_data( + &self, + id: chalk_ir::TypeId, + ) -> Arc>; #[salsa::invoke(crate::ty::traits::chalk::trait_datum_query)] fn trait_datum( &self, krate: Crate, trait_id: chalk_ir::TraitId, - ) -> Arc; + ) -> Arc>; #[salsa::invoke(crate::ty::traits::chalk::struct_datum_query)] fn struct_datum( &self, krate: Crate, struct_id: chalk_ir::StructId, - ) -> Arc; + ) -> Arc>; #[salsa::invoke(crate::ty::traits::chalk::impl_datum_query)] - fn impl_datum(&self, krate: Crate, impl_id: chalk_ir::ImplId) -> Arc; + fn impl_datum( + &self, + krate: Crate, + impl_id: chalk_ir::ImplId, + ) -> Arc>; #[salsa::invoke(crate::ty::traits::chalk::associated_ty_value_query)] fn associated_ty_value( &self, krate: Crate, id: chalk_rust_ir::AssociatedTyValueId, - ) -> Arc; + ) -> Arc>; #[salsa::invoke(crate::ty::traits::trait_solve_query)] fn trait_solve( diff --git a/crates/ra_hir/src/ty/traits.rs b/crates/ra_hir/src/ty/traits.rs index 99dbab99e..45f725438 100644 --- a/crates/ra_hir/src/ty/traits.rs +++ b/crates/ra_hir/src/ty/traits.rs @@ -17,7 +17,7 @@ pub(crate) mod chalk; #[derive(Debug, Clone)] pub struct TraitSolver { krate: Crate, - inner: Arc>, + inner: Arc>>, } /// We need eq for salsa @@ -34,7 +34,7 @@ impl TraitSolver { &self, db: &impl HirDatabase, goal: &chalk_ir::UCanonical>>, - ) -> Option { + ) -> Option> { let context = ChalkContext { db, krate: self.krate }; debug!("solve goal: {:?}", goal); let mut solver = match self.inner.lock() { @@ -196,7 +196,10 @@ pub(crate) fn trait_solve_query( solution.map(|solution| solution_from_chalk(db, solution)) } -fn solution_from_chalk(db: &impl HirDatabase, solution: chalk_solve::Solution) -> Solution { +fn solution_from_chalk( + db: &impl HirDatabase, + solution: chalk_solve::Solution, +) -> Solution { let convert_subst = |subst: chalk_ir::Canonical>| { let value = subst .value diff --git a/crates/ra_hir/src/ty/traits/chalk.rs b/crates/ra_hir/src/ty/traits/chalk.rs index 81a378bac..9bf93981a 100644 --- a/crates/ra_hir/src/ty/traits/chalk.rs +++ b/crates/ra_hir/src/ty/traits/chalk.rs @@ -418,20 +418,20 @@ fn convert_where_clauses( result } -impl<'a, DB> chalk_solve::RustIrDatabase for ChalkContext<'a, DB> +impl<'a, DB> chalk_solve::RustIrDatabase for ChalkContext<'a, DB> where DB: HirDatabase, { - fn associated_ty_data(&self, id: TypeId) -> Arc { + fn associated_ty_data(&self, id: TypeId) -> Arc> { self.db.associated_ty_data(id) } - fn trait_datum(&self, trait_id: chalk_ir::TraitId) -> Arc { + fn trait_datum(&self, trait_id: chalk_ir::TraitId) -> Arc> { self.db.trait_datum(self.krate, trait_id) } - fn struct_datum(&self, struct_id: chalk_ir::StructId) -> Arc { + fn struct_datum(&self, struct_id: chalk_ir::StructId) -> Arc> { self.db.struct_datum(self.krate, struct_id) } - fn impl_datum(&self, impl_id: ImplId) -> Arc { + fn impl_datum(&self, impl_id: ImplId) -> Arc> { self.db.impl_datum(self.krate, impl_id) } fn impls_for_trait( @@ -484,7 +484,7 @@ where fn associated_ty_value( &self, id: chalk_rust_ir::AssociatedTyValueId, - ) -> Arc { + ) -> Arc> { self.db.associated_ty_value(self.krate, id) } fn custom_clauses(&self) -> Vec> { @@ -502,7 +502,7 @@ where pub(crate) fn associated_ty_data_query( db: &impl HirDatabase, id: TypeId, -) -> Arc { +) -> Arc> { debug!("associated_ty_data {:?}", id); let type_alias: TypeAlias = from_chalk(db, id); let trait_ = match type_alias.container(db) { @@ -528,7 +528,7 @@ pub(crate) fn trait_datum_query( db: &impl HirDatabase, krate: Crate, trait_id: chalk_ir::TraitId, -) -> Arc { +) -> Arc> { debug!("trait_datum {:?}", trait_id); if trait_id == UNKNOWN_TRAIT { let trait_datum_bound = chalk_rust_ir::TraitDatumBound { where_clauses: Vec::new() }; @@ -585,7 +585,7 @@ pub(crate) fn struct_datum_query( db: &impl HirDatabase, krate: Crate, struct_id: chalk_ir::StructId, -) -> Arc { +) -> Arc> { debug!("struct_datum {:?}", struct_id); let type_ctor: TypeCtor = from_chalk(db, struct_id); debug!("struct {:?} = {:?}", struct_id, type_ctor); @@ -617,7 +617,7 @@ pub(crate) fn impl_datum_query( db: &impl HirDatabase, krate: Crate, impl_id: ImplId, -) -> Arc { +) -> Arc> { let _p = ra_prof::profile("impl_datum"); debug!("impl_datum {:?}", impl_id); let impl_: Impl = from_chalk(db, impl_id); @@ -633,7 +633,7 @@ fn impl_block_datum( krate: Crate, impl_id: ImplId, impl_block: ImplBlock, -) -> Option> { +) -> Option>> { let generic_params = impl_block.generic_params(db); let bound_vars = Substs::bound_vars(&generic_params); let trait_ref = impl_block.target_trait_ref(db)?.subst(&bound_vars); @@ -684,7 +684,7 @@ fn impl_block_datum( Some(Arc::new(impl_datum)) } -fn invalid_impl_datum() -> Arc { +fn invalid_impl_datum() -> Arc> { let trait_ref = chalk_ir::TraitRef { trait_id: UNKNOWN_TRAIT, parameters: vec![chalk_ir::TyData::BoundVar(0).cast().intern().cast()], @@ -703,7 +703,7 @@ fn closure_fn_trait_impl_datum( db: &impl HirDatabase, krate: Crate, data: super::ClosureFnTraitImplData, -) -> Option> { +) -> Option>> { // for some closure |X, Y| -> Z: // impl Fn<(T, U)> for closure V> { Output = V } @@ -760,7 +760,7 @@ pub(crate) fn associated_ty_value_query( db: &impl HirDatabase, krate: Crate, id: chalk_rust_ir::AssociatedTyValueId, -) -> Arc { +) -> Arc> { let data: AssocTyValue = from_chalk(db, id); match data { AssocTyValue::TypeAlias(type_alias) => { @@ -776,7 +776,7 @@ fn type_alias_associated_ty_value( db: &impl HirDatabase, _krate: Crate, type_alias: TypeAlias, -) -> Arc { +) -> Arc> { let impl_block = type_alias.impl_block(db).expect("assoc ty value should be in impl"); let impl_id = Impl::ImplBlock(impl_block).to_chalk(db); let trait_ = impl_block @@ -802,7 +802,7 @@ fn closure_fn_trait_output_assoc_ty_value( db: &impl HirDatabase, krate: Crate, data: super::ClosureFnTraitImplData, -) -> Arc { +) -> Arc> { let impl_id = Impl::ClosureFnTraitImpl(data.clone()).to_chalk(db); let num_args: u16 = match &data.def.body(db)[data.expr] { -- cgit v1.2.3 From 2eaa8c94a8a6b5cd86139c5e010ae95268b28658 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Sat, 16 Nov 2019 16:49:26 +0300 Subject: Goto definition works inside macros --- crates/ra_hir/src/source_binder.rs | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) (limited to 'crates/ra_hir/src') diff --git a/crates/ra_hir/src/source_binder.rs b/crates/ra_hir/src/source_binder.rs index 5764dc26d..75a467fb3 100644 --- a/crates/ra_hir/src/source_binder.rs +++ b/crates/ra_hir/src/source_binder.rs @@ -11,7 +11,7 @@ use hir_def::{ expr::{ExprId, PatId}, path::known, }; -use hir_expand::{name::AsName, Source}; +use hir_expand::{name::AsName, AstId, MacroCallId, MacroCallLoc, MacroFileKind, Source}; use ra_syntax::{ ast::{self, AstNode}, match_ast, AstPtr, @@ -126,6 +126,20 @@ pub struct ReferenceDescriptor { pub name: String, } +pub struct Expansion { + macro_call_id: MacroCallId, +} + +impl Expansion { + pub fn translate_offset(&self, db: &impl HirDatabase, offset: TextUnit) -> Option { + let exp_info = self.file_id().expansion_info(db)?; + exp_info.translate_offset(offset) + } + pub fn file_id(&self) -> HirFileId { + self.macro_call_id.as_file(MacroFileKind::Items) + } +} + impl SourceAnalyzer { pub fn new( db: &impl HirDatabase, @@ -386,6 +400,13 @@ impl SourceAnalyzer { implements_trait(&canonical_ty, db, &self.resolver, krate, std_future_trait) } + pub fn expand(&self, db: &impl HirDatabase, macro_call: &ast::MacroCall) -> Option { + let def = self.resolve_macro_call(db, macro_call)?.id; + let ast_id = AstId::new(self.file_id, db.ast_id_map(self.file_id).ast_id(macro_call)); + let macro_call_loc = MacroCallLoc { def, ast_id }; + Some(Expansion { macro_call_id: db.intern_macro(macro_call_loc) }) + } + #[cfg(test)] pub(crate) fn body_source_map(&self) -> Arc { self.body_source_map.clone().unwrap() -- cgit v1.2.3 From 7e2f4b30db8a0d734b3a1fc9f6ad77b2adc9aa2a Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Sun, 17 Nov 2019 18:35:05 +0300 Subject: Disable doctests --- crates/ra_hir/src/ty.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'crates/ra_hir/src') diff --git a/crates/ra_hir/src/ty.rs b/crates/ra_hir/src/ty.rs index a54135188..b7f50b714 100644 --- a/crates/ra_hir/src/ty.rs +++ b/crates/ra_hir/src/ty.rs @@ -79,7 +79,7 @@ pub enum TypeCtor { /// /// For example the type of `bar` here: /// - /// ```rust + /// ``` /// fn foo() -> i32 { 1 } /// let bar = foo; // bar: fn() -> i32 {foo} /// ``` @@ -89,7 +89,7 @@ pub enum TypeCtor { /// /// For example the type of `bar` here: /// - /// ```rust + /// ``` /// fn foo() -> i32 { 1 } /// let bar: fn() -> i32 = foo; /// ``` -- cgit v1.2.3 From fd52d721e1ed9794048d63e546f43805d24d7ab8 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Sun, 17 Nov 2019 20:15:55 +0300 Subject: More correct expansion mapping We can't really map arbitrary ranges, we only can map tokens --- crates/ra_hir/src/source_binder.rs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) (limited to 'crates/ra_hir/src') diff --git a/crates/ra_hir/src/source_binder.rs b/crates/ra_hir/src/source_binder.rs index 75a467fb3..f0ed8e2b2 100644 --- a/crates/ra_hir/src/source_binder.rs +++ b/crates/ra_hir/src/source_binder.rs @@ -16,7 +16,7 @@ use ra_syntax::{ ast::{self, AstNode}, match_ast, AstPtr, SyntaxKind::*, - SyntaxNode, SyntaxNodePtr, TextRange, TextUnit, + SyntaxNode, SyntaxNodePtr, SyntaxToken, TextRange, TextUnit, }; use crate::{ @@ -131,11 +131,16 @@ pub struct Expansion { } impl Expansion { - pub fn translate_offset(&self, db: &impl HirDatabase, offset: TextUnit) -> Option { + pub fn map_token_down( + &self, + db: &impl HirDatabase, + token: Source<&SyntaxToken>, + ) -> Option> { let exp_info = self.file_id().expansion_info(db)?; - exp_info.translate_offset(offset) + exp_info.map_token_down(token) } - pub fn file_id(&self) -> HirFileId { + + fn file_id(&self) -> HirFileId { self.macro_call_id.as_file(MacroFileKind::Items) } } -- cgit v1.2.3