diff options
Diffstat (limited to 'crates')
26 files changed, 548 insertions, 62 deletions
diff --git a/crates/ra_analysis/src/completion/complete_dot.rs b/crates/ra_analysis/src/completion/complete_dot.rs index f24835d17..031d8b98f 100644 --- a/crates/ra_analysis/src/completion/complete_dot.rs +++ b/crates/ra_analysis/src/completion/complete_dot.rs | |||
@@ -73,6 +73,21 @@ mod tests { | |||
73 | } | 73 | } |
74 | 74 | ||
75 | #[test] | 75 | #[test] |
76 | fn test_struct_field_completion_self() { | ||
77 | check_ref_completion( | ||
78 | r" | ||
79 | struct A { the_field: u32 } | ||
80 | impl A { | ||
81 | fn foo(self) { | ||
82 | self.<|> | ||
83 | } | ||
84 | } | ||
85 | ", | ||
86 | r#"the_field"#, | ||
87 | ); | ||
88 | } | ||
89 | |||
90 | #[test] | ||
76 | fn test_no_struct_field_completion_for_method_call() { | 91 | fn test_no_struct_field_completion_for_method_call() { |
77 | check_ref_completion( | 92 | check_ref_completion( |
78 | r" | 93 | r" |
diff --git a/crates/ra_analysis/src/db.rs b/crates/ra_analysis/src/db.rs index d7740f0c4..5422a400b 100644 --- a/crates/ra_analysis/src/db.rs +++ b/crates/ra_analysis/src/db.rs | |||
@@ -105,6 +105,7 @@ salsa::database_storage! { | |||
105 | fn type_for_field() for hir::db::TypeForFieldQuery; | 105 | fn type_for_field() for hir::db::TypeForFieldQuery; |
106 | fn struct_data() for hir::db::StructDataQuery; | 106 | fn struct_data() for hir::db::StructDataQuery; |
107 | fn enum_data() for hir::db::EnumDataQuery; | 107 | fn enum_data() for hir::db::EnumDataQuery; |
108 | fn impls_in_module() for hir::db::ImplsInModuleQuery; | ||
108 | } | 109 | } |
109 | } | 110 | } |
110 | } | 111 | } |
diff --git a/crates/ra_analysis/src/mock_analysis.rs b/crates/ra_analysis/src/mock_analysis.rs index 960529404..846c76cfe 100644 --- a/crates/ra_analysis/src/mock_analysis.rs +++ b/crates/ra_analysis/src/mock_analysis.rs | |||
@@ -4,7 +4,7 @@ use relative_path::RelativePathBuf; | |||
4 | use test_utils::{extract_offset, extract_range, parse_fixture, CURSOR_MARKER}; | 4 | use test_utils::{extract_offset, extract_range, parse_fixture, CURSOR_MARKER}; |
5 | use ra_db::mock::FileMap; | 5 | use ra_db::mock::FileMap; |
6 | 6 | ||
7 | use crate::{Analysis, AnalysisChange, AnalysisHost, FileId, FilePosition, FileRange, SourceRootId}; | 7 | use crate::{Analysis, AnalysisChange, AnalysisHost, CrateGraph, FileId, FilePosition, FileRange, SourceRootId}; |
8 | 8 | ||
9 | /// Mock analysis is used in test to bootstrap an AnalysisHost/Analysis | 9 | /// Mock analysis is used in test to bootstrap an AnalysisHost/Analysis |
10 | /// from a set of in-memory files. | 10 | /// from a set of in-memory files. |
@@ -87,12 +87,17 @@ impl MockAnalysis { | |||
87 | let source_root = SourceRootId(0); | 87 | let source_root = SourceRootId(0); |
88 | let mut change = AnalysisChange::new(); | 88 | let mut change = AnalysisChange::new(); |
89 | change.add_root(source_root, true); | 89 | change.add_root(source_root, true); |
90 | let mut crate_graph = CrateGraph::default(); | ||
90 | for (path, contents) in self.files.into_iter() { | 91 | for (path, contents) in self.files.into_iter() { |
91 | assert!(path.starts_with('/')); | 92 | assert!(path.starts_with('/')); |
92 | let path = RelativePathBuf::from_path(&path[1..]).unwrap(); | 93 | let path = RelativePathBuf::from_path(&path[1..]).unwrap(); |
93 | let file_id = file_map.add(path.clone()); | 94 | let file_id = file_map.add(path.clone()); |
95 | if path == "/lib.rs" || path == "/main.rs" { | ||
96 | crate_graph.add_crate_root(file_id); | ||
97 | } | ||
94 | change.add_file(source_root, file_id, path, Arc::new(contents)); | 98 | change.add_file(source_root, file_id, path, Arc::new(contents)); |
95 | } | 99 | } |
100 | change.set_crate_graph(crate_graph); | ||
96 | // change.set_file_resolver(Arc::new(file_map)); | 101 | // change.set_file_resolver(Arc::new(file_map)); |
97 | host.apply_change(change); | 102 | host.apply_change(change); |
98 | host | 103 | host |
diff --git a/crates/ra_analysis/tests/test/main.rs b/crates/ra_analysis/tests/test/main.rs index 859778024..beeae1e19 100644 --- a/crates/ra_analysis/tests/test/main.rs +++ b/crates/ra_analysis/tests/test/main.rs | |||
@@ -138,14 +138,14 @@ fn test_resolve_parent_module_for_inline() { | |||
138 | fn test_resolve_crate_root() { | 138 | fn test_resolve_crate_root() { |
139 | let mock = MockAnalysis::with_files( | 139 | let mock = MockAnalysis::with_files( |
140 | " | 140 | " |
141 | //- /lib.rs | 141 | //- /bar.rs |
142 | mod foo; | 142 | mod foo; |
143 | //- /foo.rs | 143 | //- /bar/foo.rs |
144 | // emtpy <|> | 144 | // emtpy <|> |
145 | ", | 145 | ", |
146 | ); | 146 | ); |
147 | let root_file = mock.id_of("/lib.rs"); | 147 | let root_file = mock.id_of("/bar.rs"); |
148 | let mod_file = mock.id_of("/foo.rs"); | 148 | let mod_file = mock.id_of("/bar/foo.rs"); |
149 | let mut host = mock.analysis_host(); | 149 | let mut host = mock.analysis_host(); |
150 | assert!(host.analysis().crate_for(mod_file).unwrap().is_empty()); | 150 | assert!(host.analysis().crate_for(mod_file).unwrap().is_empty()); |
151 | 151 | ||
diff --git a/crates/ra_hir/src/db.rs b/crates/ra_hir/src/db.rs index 73a4cdc5c..58296fc6f 100644 --- a/crates/ra_hir/src/db.rs +++ b/crates/ra_hir/src/db.rs | |||
@@ -13,6 +13,7 @@ use crate::{ | |||
13 | nameres::{ItemMap, InputModuleItems}}, | 13 | nameres::{ItemMap, InputModuleItems}}, |
14 | ty::{InferenceResult, Ty}, | 14 | ty::{InferenceResult, Ty}, |
15 | adt::{StructData, EnumData}, | 15 | adt::{StructData, EnumData}, |
16 | impl_block::ModuleImplBlocks, | ||
16 | }; | 17 | }; |
17 | 18 | ||
18 | salsa::query_group! { | 19 | salsa::query_group! { |
@@ -87,6 +88,11 @@ pub trait HirDatabase: SyntaxDatabase | |||
87 | type ModuleTreeQuery; | 88 | type ModuleTreeQuery; |
88 | use fn crate::module::imp::module_tree; | 89 | use fn crate::module::imp::module_tree; |
89 | } | 90 | } |
91 | |||
92 | fn impls_in_module(source_root_id: SourceRootId, module_id: ModuleId) -> Cancelable<Arc<ModuleImplBlocks>> { | ||
93 | type ImplsInModuleQuery; | ||
94 | use fn crate::impl_block::impls_in_module; | ||
95 | } | ||
90 | } | 96 | } |
91 | 97 | ||
92 | } | 98 | } |
diff --git a/crates/ra_hir/src/function.rs b/crates/ra_hir/src/function.rs index 5a44132fc..75ef308ae 100644 --- a/crates/ra_hir/src/function.rs +++ b/crates/ra_hir/src/function.rs | |||
@@ -11,11 +11,11 @@ use ra_syntax::{ | |||
11 | ast::{self, AstNode, DocCommentsOwner, NameOwner}, | 11 | ast::{self, AstNode, DocCommentsOwner, NameOwner}, |
12 | }; | 12 | }; |
13 | 13 | ||
14 | use crate::{DefId, DefKind, HirDatabase, ty::InferenceResult, Module}; | 14 | use crate::{DefId, DefKind, HirDatabase, ty::InferenceResult, Module, Crate, impl_block::ImplBlock}; |
15 | 15 | ||
16 | pub use self::scope::FnScopes; | 16 | pub use self::scope::FnScopes; |
17 | 17 | ||
18 | #[derive(Debug)] | 18 | #[derive(Debug, Clone, PartialEq, Eq)] |
19 | pub struct Function { | 19 | pub struct Function { |
20 | def_id: DefId, | 20 | def_id: DefId, |
21 | } | 21 | } |
@@ -25,6 +25,10 @@ impl Function { | |||
25 | Function { def_id } | 25 | Function { def_id } |
26 | } | 26 | } |
27 | 27 | ||
28 | pub fn def_id(&self) -> DefId { | ||
29 | self.def_id | ||
30 | } | ||
31 | |||
28 | pub fn syntax(&self, db: &impl HirDatabase) -> ast::FnDefNode { | 32 | pub fn syntax(&self, db: &impl HirDatabase) -> ast::FnDefNode { |
29 | let def_loc = self.def_id.loc(db); | 33 | let def_loc = self.def_id.loc(db); |
30 | assert!(def_loc.kind == DefKind::Function); | 34 | assert!(def_loc.kind == DefKind::Function); |
@@ -48,6 +52,15 @@ impl Function { | |||
48 | pub fn module(&self, db: &impl HirDatabase) -> Cancelable<Module> { | 52 | pub fn module(&self, db: &impl HirDatabase) -> Cancelable<Module> { |
49 | self.def_id.module(db) | 53 | self.def_id.module(db) |
50 | } | 54 | } |
55 | |||
56 | pub fn krate(&self, db: &impl HirDatabase) -> Cancelable<Option<Crate>> { | ||
57 | self.def_id.krate(db) | ||
58 | } | ||
59 | |||
60 | /// The containing impl block, if this is a method. | ||
61 | pub fn impl_block(&self, db: &impl HirDatabase) -> Cancelable<Option<ImplBlock>> { | ||
62 | self.def_id.impl_block(db) | ||
63 | } | ||
51 | } | 64 | } |
52 | 65 | ||
53 | #[derive(Debug, Clone)] | 66 | #[derive(Debug, Clone)] |
diff --git a/crates/ra_hir/src/ids.rs b/crates/ra_hir/src/ids.rs index 66adacc7d..4d6378e02 100644 --- a/crates/ra_hir/src/ids.rs +++ b/crates/ra_hir/src/ids.rs | |||
@@ -2,7 +2,7 @@ use ra_db::{SourceRootId, LocationIntener, Cancelable, FileId}; | |||
2 | use ra_syntax::{SourceFileNode, SyntaxKind, SyntaxNode, SyntaxNodeRef, SourceFile, AstNode, ast}; | 2 | use ra_syntax::{SourceFileNode, SyntaxKind, SyntaxNode, SyntaxNodeRef, SourceFile, AstNode, ast}; |
3 | use ra_arena::{Arena, RawId, impl_arena_id}; | 3 | use ra_arena::{Arena, RawId, impl_arena_id}; |
4 | 4 | ||
5 | use crate::{HirDatabase, PerNs, ModuleId, Module, Def, Function, Struct, Enum}; | 5 | use crate::{HirDatabase, PerNs, ModuleId, Module, Def, Function, Struct, Enum, ImplBlock, Crate}; |
6 | 6 | ||
7 | /// hir makes a heavy use of ids: integer (u32) handlers to various things. You | 7 | /// hir makes a heavy use of ids: integer (u32) handlers to various things. You |
8 | /// can think of id as a pointer (but without a lifetime) or a file descriptor | 8 | /// can think of id as a pointer (but without a lifetime) or a file descriptor |
@@ -177,6 +177,18 @@ impl DefId { | |||
177 | let loc = self.loc(db); | 177 | let loc = self.loc(db); |
178 | Module::new(db, loc.source_root_id, loc.module_id) | 178 | Module::new(db, loc.source_root_id, loc.module_id) |
179 | } | 179 | } |
180 | |||
181 | /// Returns the containing crate. | ||
182 | pub fn krate(&self, db: &impl HirDatabase) -> Cancelable<Option<Crate>> { | ||
183 | Ok(self.module(db)?.krate(db)) | ||
184 | } | ||
185 | |||
186 | /// Returns the containing impl block, if this is an impl item. | ||
187 | pub fn impl_block(self, db: &impl HirDatabase) -> Cancelable<Option<ImplBlock>> { | ||
188 | let loc = self.loc(db); | ||
189 | let module_impls = db.impls_in_module(loc.source_root_id, loc.module_id)?; | ||
190 | Ok(ImplBlock::containing(module_impls, self)) | ||
191 | } | ||
180 | } | 192 | } |
181 | 193 | ||
182 | impl DefLoc { | 194 | impl DefLoc { |
diff --git a/crates/ra_hir/src/impl_block.rs b/crates/ra_hir/src/impl_block.rs new file mode 100644 index 000000000..01afa84c4 --- /dev/null +++ b/crates/ra_hir/src/impl_block.rs | |||
@@ -0,0 +1,180 @@ | |||
1 | use std::sync::Arc; | ||
2 | use rustc_hash::FxHashMap; | ||
3 | |||
4 | use ra_arena::{Arena, RawId, impl_arena_id}; | ||
5 | use ra_syntax::ast::{self, AstNode}; | ||
6 | use ra_db::{LocationIntener, Cancelable, SourceRootId}; | ||
7 | |||
8 | use crate::{ | ||
9 | DefId, DefLoc, DefKind, SourceItemId, SourceFileItems, | ||
10 | Module, Function, | ||
11 | db::HirDatabase, | ||
12 | type_ref::TypeRef, | ||
13 | module::{ModuleSourceNode, ModuleId}, | ||
14 | }; | ||
15 | |||
16 | #[derive(Debug, Clone, PartialEq, Eq)] | ||
17 | pub struct ImplBlock { | ||
18 | module_impl_blocks: Arc<ModuleImplBlocks>, | ||
19 | impl_id: ImplId, | ||
20 | } | ||
21 | |||
22 | impl ImplBlock { | ||
23 | pub(crate) fn containing( | ||
24 | module_impl_blocks: Arc<ModuleImplBlocks>, | ||
25 | def_id: DefId, | ||
26 | ) -> Option<ImplBlock> { | ||
27 | let impl_id = *module_impl_blocks.impls_by_def.get(&def_id)?; | ||
28 | Some(ImplBlock { | ||
29 | module_impl_blocks, | ||
30 | impl_id, | ||
31 | }) | ||
32 | } | ||
33 | |||
34 | fn impl_data(&self) -> &ImplData { | ||
35 | &self.module_impl_blocks.impls[self.impl_id] | ||
36 | } | ||
37 | |||
38 | pub fn target_trait(&self) -> Option<&TypeRef> { | ||
39 | self.impl_data().target_trait.as_ref() | ||
40 | } | ||
41 | |||
42 | pub fn target_type(&self) -> &TypeRef { | ||
43 | &self.impl_data().target_type | ||
44 | } | ||
45 | |||
46 | pub fn items(&self) -> &[ImplItem] { | ||
47 | &self.impl_data().items | ||
48 | } | ||
49 | } | ||
50 | |||
51 | #[derive(Debug, Clone, PartialEq, Eq)] | ||
52 | pub struct ImplData { | ||
53 | target_trait: Option<TypeRef>, | ||
54 | target_type: TypeRef, | ||
55 | items: Vec<ImplItem>, | ||
56 | } | ||
57 | |||
58 | impl ImplData { | ||
59 | pub(crate) fn from_ast( | ||
60 | db: &impl AsRef<LocationIntener<DefLoc, DefId>>, | ||
61 | file_items: &SourceFileItems, | ||
62 | module: &Module, | ||
63 | node: ast::ImplBlock, | ||
64 | ) -> Self { | ||
65 | let target_trait = node.target_type().map(TypeRef::from_ast); | ||
66 | let target_type = TypeRef::from_ast_opt(node.target_type()); | ||
67 | let file_id = module.source().file_id(); | ||
68 | let items = if let Some(item_list) = node.item_list() { | ||
69 | item_list | ||
70 | .impl_items() | ||
71 | .map(|item_node| { | ||
72 | let kind = match item_node { | ||
73 | ast::ImplItem::FnDef(..) => DefKind::Function, | ||
74 | ast::ImplItem::ConstDef(..) => DefKind::Item, | ||
75 | ast::ImplItem::TypeDef(..) => DefKind::Item, | ||
76 | }; | ||
77 | let item_id = file_items.id_of_unchecked(item_node.syntax()); | ||
78 | let def_loc = DefLoc { | ||
79 | kind, | ||
80 | source_root_id: module.source_root_id, | ||
81 | module_id: module.module_id, | ||
82 | source_item_id: SourceItemId { | ||
83 | file_id, | ||
84 | item_id: Some(item_id), | ||
85 | }, | ||
86 | }; | ||
87 | let def_id = def_loc.id(db); | ||
88 | match item_node { | ||
89 | ast::ImplItem::FnDef(..) => ImplItem::Method(Function::new(def_id)), | ||
90 | ast::ImplItem::ConstDef(..) => ImplItem::Const(def_id), | ||
91 | ast::ImplItem::TypeDef(..) => ImplItem::Type(def_id), | ||
92 | } | ||
93 | }) | ||
94 | .collect() | ||
95 | } else { | ||
96 | Vec::new() | ||
97 | }; | ||
98 | ImplData { | ||
99 | target_trait, | ||
100 | target_type, | ||
101 | items, | ||
102 | } | ||
103 | } | ||
104 | } | ||
105 | |||
106 | #[derive(Debug, Clone, PartialEq, Eq)] | ||
107 | pub enum ImplItem { | ||
108 | Method(Function), | ||
109 | // these don't have their own types yet | ||
110 | Const(DefId), | ||
111 | Type(DefId), | ||
112 | // Existential | ||
113 | } | ||
114 | |||
115 | impl ImplItem { | ||
116 | pub fn def_id(&self) -> DefId { | ||
117 | match self { | ||
118 | ImplItem::Method(f) => f.def_id(), | ||
119 | ImplItem::Const(def_id) => *def_id, | ||
120 | ImplItem::Type(def_id) => *def_id, | ||
121 | } | ||
122 | } | ||
123 | } | ||
124 | |||
125 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] | ||
126 | pub struct ImplId(pub RawId); | ||
127 | impl_arena_id!(ImplId); | ||
128 | |||
129 | /// Collection of impl blocks is a two-step process: First we collect the blocks | ||
130 | /// per-module; then we build an index of all impl blocks in the crate. This | ||
131 | /// way, we avoid having to do this process for the whole crate whenever someone | ||
132 | /// types in any file; as long as the impl blocks in the file don't change, we | ||
133 | /// don't need to do the second step again. | ||
134 | /// | ||
135 | /// (The second step does not yet exist currently.) | ||
136 | #[derive(Debug, PartialEq, Eq)] | ||
137 | pub struct ModuleImplBlocks { | ||
138 | impls: Arena<ImplId, ImplData>, | ||
139 | impls_by_def: FxHashMap<DefId, ImplId>, | ||
140 | } | ||
141 | |||
142 | impl ModuleImplBlocks { | ||
143 | fn new() -> Self { | ||
144 | ModuleImplBlocks { | ||
145 | impls: Arena::default(), | ||
146 | impls_by_def: FxHashMap::default(), | ||
147 | } | ||
148 | } | ||
149 | |||
150 | fn collect(&mut self, db: &impl HirDatabase, module: Module) -> Cancelable<()> { | ||
151 | let module_source_node = module.source().resolve(db); | ||
152 | let node = match &module_source_node { | ||
153 | ModuleSourceNode::SourceFile(node) => node.borrowed().syntax(), | ||
154 | ModuleSourceNode::Module(node) => node.borrowed().syntax(), | ||
155 | }; | ||
156 | |||
157 | let source_file_items = db.file_items(module.source().file_id()); | ||
158 | |||
159 | for impl_block_ast in node.children().filter_map(ast::ImplBlock::cast) { | ||
160 | let impl_block = ImplData::from_ast(db, &source_file_items, &module, impl_block_ast); | ||
161 | let id = self.impls.alloc(impl_block); | ||
162 | for impl_item in &self.impls[id].items { | ||
163 | self.impls_by_def.insert(impl_item.def_id(), id); | ||
164 | } | ||
165 | } | ||
166 | |||
167 | Ok(()) | ||
168 | } | ||
169 | } | ||
170 | |||
171 | pub(crate) fn impls_in_module( | ||
172 | db: &impl HirDatabase, | ||
173 | source_root_id: SourceRootId, | ||
174 | module_id: ModuleId, | ||
175 | ) -> Cancelable<Arc<ModuleImplBlocks>> { | ||
176 | let mut result = ModuleImplBlocks::new(); | ||
177 | let module = Module::new(db, source_root_id, module_id)?; | ||
178 | result.collect(db, module)?; | ||
179 | Ok(Arc::new(result)) | ||
180 | } | ||
diff --git a/crates/ra_hir/src/krate.rs b/crates/ra_hir/src/krate.rs index a0821d15d..5194e280b 100644 --- a/crates/ra_hir/src/krate.rs +++ b/crates/ra_hir/src/krate.rs | |||
@@ -5,7 +5,7 @@ use crate::{HirDatabase, Module, Name, AsName, HirFileId}; | |||
5 | /// hir::Crate describes a single crate. It's the main inteface with which | 5 | /// hir::Crate describes a single crate. It's the main inteface with which |
6 | /// crate's dependencies interact. Mostly, it should be just a proxy for the | 6 | /// crate's dependencies interact. Mostly, it should be just a proxy for the |
7 | /// root module. | 7 | /// root module. |
8 | #[derive(Debug)] | 8 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] |
9 | pub struct Crate { | 9 | pub struct Crate { |
10 | crate_id: CrateId, | 10 | crate_id: CrateId, |
11 | } | 11 | } |
diff --git a/crates/ra_hir/src/lib.rs b/crates/ra_hir/src/lib.rs index 344b543b6..2abcec441 100644 --- a/crates/ra_hir/src/lib.rs +++ b/crates/ra_hir/src/lib.rs | |||
@@ -31,6 +31,7 @@ mod function; | |||
31 | mod adt; | 31 | mod adt; |
32 | mod type_ref; | 32 | mod type_ref; |
33 | mod ty; | 33 | mod ty; |
34 | mod impl_block; | ||
34 | 35 | ||
35 | use crate::{ | 36 | use crate::{ |
36 | db::HirDatabase, | 37 | db::HirDatabase, |
@@ -48,6 +49,7 @@ pub use self::{ | |||
48 | function::{Function, FnScopes}, | 49 | function::{Function, FnScopes}, |
49 | adt::{Struct, Enum}, | 50 | adt::{Struct, Enum}, |
50 | ty::Ty, | 51 | ty::Ty, |
52 | impl_block::{ImplBlock, ImplItem}, | ||
51 | }; | 53 | }; |
52 | 54 | ||
53 | pub use self::function::FnSignatureInfo; | 55 | pub use self::function::FnSignatureInfo; |
diff --git a/crates/ra_hir/src/mock.rs b/crates/ra_hir/src/mock.rs index 89b18194a..a9db932ff 100644 --- a/crates/ra_hir/src/mock.rs +++ b/crates/ra_hir/src/mock.rs | |||
@@ -30,6 +30,10 @@ impl MockDatabase { | |||
30 | let file_id = db.add_file(&mut source_root, "/main.rs", text); | 30 | let file_id = db.add_file(&mut source_root, "/main.rs", text); |
31 | db.query_mut(ra_db::SourceRootQuery) | 31 | db.query_mut(ra_db::SourceRootQuery) |
32 | .set(WORKSPACE, Arc::new(source_root.clone())); | 32 | .set(WORKSPACE, Arc::new(source_root.clone())); |
33 | |||
34 | let mut crate_graph = CrateGraph::default(); | ||
35 | crate_graph.add_crate_root(file_id); | ||
36 | db.set_crate_graph(crate_graph); | ||
33 | (db, source_root, file_id) | 37 | (db, source_root, file_id) |
34 | } | 38 | } |
35 | 39 | ||
@@ -203,6 +207,7 @@ salsa::database_storage! { | |||
203 | fn type_for_field() for db::TypeForFieldQuery; | 207 | fn type_for_field() for db::TypeForFieldQuery; |
204 | fn struct_data() for db::StructDataQuery; | 208 | fn struct_data() for db::StructDataQuery; |
205 | fn enum_data() for db::EnumDataQuery; | 209 | fn enum_data() for db::EnumDataQuery; |
210 | fn impls_in_module() for db::ImplsInModuleQuery; | ||
206 | } | 211 | } |
207 | } | 212 | } |
208 | } | 213 | } |
diff --git a/crates/ra_hir/src/module.rs b/crates/ra_hir/src/module.rs index c70dc54dd..b9821115c 100644 --- a/crates/ra_hir/src/module.rs +++ b/crates/ra_hir/src/module.rs | |||
@@ -71,6 +71,21 @@ impl Module { | |||
71 | }) | 71 | }) |
72 | } | 72 | } |
73 | 73 | ||
74 | /// Returns an iterator of all children of this module. | ||
75 | pub fn children<'a>(&'a self) -> impl Iterator<Item = (Name, Module)> + 'a { | ||
76 | self.module_id | ||
77 | .children(&self.tree) | ||
78 | .map(move |(name, module_id)| { | ||
79 | ( | ||
80 | name, | ||
81 | Module { | ||
82 | module_id, | ||
83 | ..self.clone() | ||
84 | }, | ||
85 | ) | ||
86 | }) | ||
87 | } | ||
88 | |||
74 | /// Returns the crate this module is part of. | 89 | /// Returns the crate this module is part of. |
75 | pub fn krate(&self, db: &impl HirDatabase) -> Option<Crate> { | 90 | pub fn krate(&self, db: &impl HirDatabase) -> Option<Crate> { |
76 | let root_id = self.module_id.crate_root(&self.tree); | 91 | let root_id = self.module_id.crate_root(&self.tree); |
diff --git a/crates/ra_hir/src/name.rs b/crates/ra_hir/src/name.rs index 51e8b3da8..017caf442 100644 --- a/crates/ra_hir/src/name.rs +++ b/crates/ra_hir/src/name.rs | |||
@@ -51,6 +51,7 @@ impl Name { | |||
51 | "u128" => KnownName::U128, | 51 | "u128" => KnownName::U128, |
52 | "f32" => KnownName::F32, | 52 | "f32" => KnownName::F32, |
53 | "f64" => KnownName::F64, | 53 | "f64" => KnownName::F64, |
54 | "Self" => KnownName::Self_, | ||
54 | _ => return None, | 55 | _ => return None, |
55 | }; | 56 | }; |
56 | Some(name) | 57 | Some(name) |
@@ -84,7 +85,7 @@ impl AsName for ra_db::Dependency { | |||
84 | // const ISIZE: Name = Name::new("isize") | 85 | // const ISIZE: Name = Name::new("isize") |
85 | // ``` | 86 | // ``` |
86 | // but const-fn is not that powerful yet. | 87 | // but const-fn is not that powerful yet. |
87 | #[derive(Debug)] | 88 | #[derive(Debug, PartialEq, Eq)] |
88 | pub(crate) enum KnownName { | 89 | pub(crate) enum KnownName { |
89 | Isize, | 90 | Isize, |
90 | I8, | 91 | I8, |
@@ -102,4 +103,6 @@ pub(crate) enum KnownName { | |||
102 | 103 | ||
103 | F32, | 104 | F32, |
104 | F64, | 105 | F64, |
106 | |||
107 | Self_, | ||
105 | } | 108 | } |
diff --git a/crates/ra_hir/src/path.rs b/crates/ra_hir/src/path.rs index 93f7203fe..9fdfa0d13 100644 --- a/crates/ra_hir/src/path.rs +++ b/crates/ra_hir/src/path.rs | |||
@@ -70,6 +70,11 @@ impl Path { | |||
70 | self.kind == PathKind::Plain && self.segments.len() == 1 | 70 | self.kind == PathKind::Plain && self.segments.len() == 1 |
71 | } | 71 | } |
72 | 72 | ||
73 | /// `true` if this path is just a standalone `self` | ||
74 | pub fn is_self(&self) -> bool { | ||
75 | self.kind == PathKind::Self_ && self.segments.len() == 0 | ||
76 | } | ||
77 | |||
73 | /// If this path is a single identifier, like `foo`, return its name. | 78 | /// If this path is a single identifier, like `foo`, return its name. |
74 | pub fn as_ident(&self) -> Option<&Name> { | 79 | pub fn as_ident(&self) -> Option<&Name> { |
75 | if self.kind != PathKind::Plain || self.segments.len() > 1 { | 80 | if self.kind != PathKind::Plain || self.segments.len() > 1 { |
diff --git a/crates/ra_hir/src/ty.rs b/crates/ra_hir/src/ty.rs index 719b3f7cd..e33762e0d 100644 --- a/crates/ra_hir/src/ty.rs +++ b/crates/ra_hir/src/ty.rs | |||
@@ -31,9 +31,10 @@ use ra_syntax::{ | |||
31 | }; | 31 | }; |
32 | 32 | ||
33 | use crate::{ | 33 | use crate::{ |
34 | Def, DefId, FnScopes, Module, Function, Struct, Enum, Path, Name, AsName, | 34 | Def, DefId, FnScopes, Module, Function, Struct, Enum, Path, Name, AsName, ImplBlock, |
35 | db::HirDatabase, | 35 | db::HirDatabase, |
36 | type_ref::{TypeRef, Mutability}, | 36 | type_ref::{TypeRef, Mutability}, |
37 | name::KnownName, | ||
37 | }; | 38 | }; |
38 | 39 | ||
39 | /// The ID of a type variable. | 40 | /// The ID of a type variable. |
@@ -235,6 +236,7 @@ impl Ty { | |||
235 | pub(crate) fn from_hir( | 236 | pub(crate) fn from_hir( |
236 | db: &impl HirDatabase, | 237 | db: &impl HirDatabase, |
237 | module: &Module, | 238 | module: &Module, |
239 | impl_block: Option<&ImplBlock>, | ||
238 | type_ref: &TypeRef, | 240 | type_ref: &TypeRef, |
239 | ) -> Cancelable<Self> { | 241 | ) -> Cancelable<Self> { |
240 | Ok(match type_ref { | 242 | Ok(match type_ref { |
@@ -242,29 +244,29 @@ impl Ty { | |||
242 | TypeRef::Tuple(inner) => { | 244 | TypeRef::Tuple(inner) => { |
243 | let inner_tys = inner | 245 | let inner_tys = inner |
244 | .iter() | 246 | .iter() |
245 | .map(|tr| Ty::from_hir(db, module, tr)) | 247 | .map(|tr| Ty::from_hir(db, module, impl_block, tr)) |
246 | .collect::<Cancelable<Vec<_>>>()?; | 248 | .collect::<Cancelable<Vec<_>>>()?; |
247 | Ty::Tuple(inner_tys.into()) | 249 | Ty::Tuple(inner_tys.into()) |
248 | } | 250 | } |
249 | TypeRef::Path(path) => Ty::from_hir_path(db, module, path)?, | 251 | TypeRef::Path(path) => Ty::from_hir_path(db, module, impl_block, path)?, |
250 | TypeRef::RawPtr(inner, mutability) => { | 252 | TypeRef::RawPtr(inner, mutability) => { |
251 | let inner_ty = Ty::from_hir(db, module, inner)?; | 253 | let inner_ty = Ty::from_hir(db, module, impl_block, inner)?; |
252 | Ty::RawPtr(Arc::new(inner_ty), *mutability) | 254 | Ty::RawPtr(Arc::new(inner_ty), *mutability) |
253 | } | 255 | } |
254 | TypeRef::Array(_inner) => Ty::Unknown, // TODO | 256 | TypeRef::Array(_inner) => Ty::Unknown, // TODO |
255 | TypeRef::Slice(inner) => { | 257 | TypeRef::Slice(inner) => { |
256 | let inner_ty = Ty::from_hir(db, module, inner)?; | 258 | let inner_ty = Ty::from_hir(db, module, impl_block, inner)?; |
257 | Ty::Slice(Arc::new(inner_ty)) | 259 | Ty::Slice(Arc::new(inner_ty)) |
258 | } | 260 | } |
259 | TypeRef::Reference(inner, mutability) => { | 261 | TypeRef::Reference(inner, mutability) => { |
260 | let inner_ty = Ty::from_hir(db, module, inner)?; | 262 | let inner_ty = Ty::from_hir(db, module, impl_block, inner)?; |
261 | Ty::Ref(Arc::new(inner_ty), *mutability) | 263 | Ty::Ref(Arc::new(inner_ty), *mutability) |
262 | } | 264 | } |
263 | TypeRef::Placeholder => Ty::Unknown, | 265 | TypeRef::Placeholder => Ty::Unknown, |
264 | TypeRef::Fn(params) => { | 266 | TypeRef::Fn(params) => { |
265 | let mut inner_tys = params | 267 | let mut inner_tys = params |
266 | .iter() | 268 | .iter() |
267 | .map(|tr| Ty::from_hir(db, module, tr)) | 269 | .map(|tr| Ty::from_hir(db, module, impl_block, tr)) |
268 | .collect::<Cancelable<Vec<_>>>()?; | 270 | .collect::<Cancelable<Vec<_>>>()?; |
269 | let return_ty = inner_tys | 271 | let return_ty = inner_tys |
270 | .pop() | 272 | .pop() |
@@ -279,9 +281,21 @@ impl Ty { | |||
279 | }) | 281 | }) |
280 | } | 282 | } |
281 | 283 | ||
284 | pub(crate) fn from_hir_opt( | ||
285 | db: &impl HirDatabase, | ||
286 | module: &Module, | ||
287 | impl_block: Option<&ImplBlock>, | ||
288 | type_ref: Option<&TypeRef>, | ||
289 | ) -> Cancelable<Self> { | ||
290 | type_ref | ||
291 | .map(|t| Ty::from_hir(db, module, impl_block, t)) | ||
292 | .unwrap_or(Ok(Ty::Unknown)) | ||
293 | } | ||
294 | |||
282 | pub(crate) fn from_hir_path( | 295 | pub(crate) fn from_hir_path( |
283 | db: &impl HirDatabase, | 296 | db: &impl HirDatabase, |
284 | module: &Module, | 297 | module: &Module, |
298 | impl_block: Option<&ImplBlock>, | ||
285 | path: &Path, | 299 | path: &Path, |
286 | ) -> Cancelable<Self> { | 300 | ) -> Cancelable<Self> { |
287 | if let Some(name) = path.as_ident() { | 301 | if let Some(name) = path.as_ident() { |
@@ -291,6 +305,8 @@ impl Ty { | |||
291 | return Ok(Ty::Uint(uint_ty)); | 305 | return Ok(Ty::Uint(uint_ty)); |
292 | } else if let Some(float_ty) = primitive::FloatTy::from_name(name) { | 306 | } else if let Some(float_ty) = primitive::FloatTy::from_name(name) { |
293 | return Ok(Ty::Float(float_ty)); | 307 | return Ok(Ty::Float(float_ty)); |
308 | } else if name.as_known_name() == Some(KnownName::Self_) { | ||
309 | return Ty::from_hir_opt(db, module, None, impl_block.map(|i| i.target_type())); | ||
294 | } | 310 | } |
295 | } | 311 | } |
296 | 312 | ||
@@ -308,18 +324,20 @@ impl Ty { | |||
308 | pub(crate) fn from_ast_opt( | 324 | pub(crate) fn from_ast_opt( |
309 | db: &impl HirDatabase, | 325 | db: &impl HirDatabase, |
310 | module: &Module, | 326 | module: &Module, |
327 | impl_block: Option<&ImplBlock>, | ||
311 | node: Option<ast::TypeRef>, | 328 | node: Option<ast::TypeRef>, |
312 | ) -> Cancelable<Self> { | 329 | ) -> Cancelable<Self> { |
313 | node.map(|n| Ty::from_ast(db, module, n)) | 330 | node.map(|n| Ty::from_ast(db, module, impl_block, n)) |
314 | .unwrap_or(Ok(Ty::Unknown)) | 331 | .unwrap_or(Ok(Ty::Unknown)) |
315 | } | 332 | } |
316 | 333 | ||
317 | pub(crate) fn from_ast( | 334 | pub(crate) fn from_ast( |
318 | db: &impl HirDatabase, | 335 | db: &impl HirDatabase, |
319 | module: &Module, | 336 | module: &Module, |
337 | impl_block: Option<&ImplBlock>, | ||
320 | node: ast::TypeRef, | 338 | node: ast::TypeRef, |
321 | ) -> Cancelable<Self> { | 339 | ) -> Cancelable<Self> { |
322 | Ty::from_hir(db, module, &TypeRef::from_ast(node)) | 340 | Ty::from_hir(db, module, impl_block, &TypeRef::from_ast(node)) |
323 | } | 341 | } |
324 | 342 | ||
325 | pub fn unit() -> Self { | 343 | pub fn unit() -> Self { |
@@ -402,18 +420,19 @@ impl fmt::Display for Ty { | |||
402 | fn type_for_fn(db: &impl HirDatabase, f: Function) -> Cancelable<Ty> { | 420 | fn type_for_fn(db: &impl HirDatabase, f: Function) -> Cancelable<Ty> { |
403 | let syntax = f.syntax(db); | 421 | let syntax = f.syntax(db); |
404 | let module = f.module(db)?; | 422 | let module = f.module(db)?; |
423 | let impl_block = f.impl_block(db)?; | ||
405 | let node = syntax.borrowed(); | 424 | let node = syntax.borrowed(); |
406 | // TODO we ignore type parameters for now | 425 | // TODO we ignore type parameters for now |
407 | let input = node | 426 | let input = node |
408 | .param_list() | 427 | .param_list() |
409 | .map(|pl| { | 428 | .map(|pl| { |
410 | pl.params() | 429 | pl.params() |
411 | .map(|p| Ty::from_ast_opt(db, &module, p.type_ref())) | 430 | .map(|p| Ty::from_ast_opt(db, &module, impl_block.as_ref(), p.type_ref())) |
412 | .collect() | 431 | .collect() |
413 | }) | 432 | }) |
414 | .unwrap_or_else(|| Ok(Vec::new()))?; | 433 | .unwrap_or_else(|| Ok(Vec::new()))?; |
415 | let output = if let Some(type_ref) = node.ret_type().and_then(|rt| rt.type_ref()) { | 434 | let output = if let Some(type_ref) = node.ret_type().and_then(|rt| rt.type_ref()) { |
416 | Ty::from_ast(db, &module, type_ref)? | 435 | Ty::from_ast(db, &module, impl_block.as_ref(), type_ref)? |
417 | } else { | 436 | } else { |
418 | Ty::unit() | 437 | Ty::unit() |
419 | }; | 438 | }; |
@@ -467,12 +486,13 @@ pub(super) fn type_for_field(db: &impl HirDatabase, def_id: DefId, field: Name) | |||
467 | ), | 486 | ), |
468 | }; | 487 | }; |
469 | let module = def_id.module(db)?; | 488 | let module = def_id.module(db)?; |
489 | let impl_block = def_id.impl_block(db)?; | ||
470 | let type_ref = if let Some(tr) = variant_data.get_field_type_ref(&field) { | 490 | let type_ref = if let Some(tr) = variant_data.get_field_type_ref(&field) { |
471 | tr | 491 | tr |
472 | } else { | 492 | } else { |
473 | return Ok(Ty::Unknown); | 493 | return Ok(Ty::Unknown); |
474 | }; | 494 | }; |
475 | Ty::from_hir(db, &module, &type_ref) | 495 | Ty::from_hir(db, &module, impl_block.as_ref(), &type_ref) |
476 | } | 496 | } |
477 | 497 | ||
478 | /// The result of type inference: A mapping from expressions and patterns to types. | 498 | /// The result of type inference: A mapping from expressions and patterns to types. |
@@ -496,19 +516,32 @@ impl InferenceResult { | |||
496 | struct InferenceContext<'a, D: HirDatabase> { | 516 | struct InferenceContext<'a, D: HirDatabase> { |
497 | db: &'a D, | 517 | db: &'a D, |
498 | scopes: Arc<FnScopes>, | 518 | scopes: Arc<FnScopes>, |
519 | /// The self param for the current method, if it exists. | ||
520 | self_param: Option<LocalSyntaxPtr>, | ||
499 | module: Module, | 521 | module: Module, |
522 | impl_block: Option<ImplBlock>, | ||
500 | var_unification_table: InPlaceUnificationTable<TypeVarId>, | 523 | var_unification_table: InPlaceUnificationTable<TypeVarId>, |
501 | type_of: FxHashMap<LocalSyntaxPtr, Ty>, | 524 | type_of: FxHashMap<LocalSyntaxPtr, Ty>, |
525 | /// The return type of the function being inferred. | ||
526 | return_ty: Ty, | ||
502 | } | 527 | } |
503 | 528 | ||
504 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | 529 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { |
505 | fn new(db: &'a D, scopes: Arc<FnScopes>, module: Module) -> Self { | 530 | fn new( |
531 | db: &'a D, | ||
532 | scopes: Arc<FnScopes>, | ||
533 | module: Module, | ||
534 | impl_block: Option<ImplBlock>, | ||
535 | ) -> Self { | ||
506 | InferenceContext { | 536 | InferenceContext { |
507 | type_of: FxHashMap::default(), | 537 | type_of: FxHashMap::default(), |
508 | var_unification_table: InPlaceUnificationTable::new(), | 538 | var_unification_table: InPlaceUnificationTable::new(), |
539 | self_param: None, // set during parameter typing | ||
540 | return_ty: Ty::Unknown, // set in collect_fn_signature | ||
509 | db, | 541 | db, |
510 | scopes, | 542 | scopes, |
511 | module, | 543 | module, |
544 | impl_block, | ||
512 | } | 545 | } |
513 | } | 546 | } |
514 | 547 | ||
@@ -525,6 +558,14 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { | |||
525 | self.type_of.insert(LocalSyntaxPtr::new(node), ty); | 558 | self.type_of.insert(LocalSyntaxPtr::new(node), ty); |
526 | } | 559 | } |
527 | 560 | ||
561 | fn make_ty(&self, type_ref: &TypeRef) -> Cancelable<Ty> { | ||
562 | Ty::from_hir(self.db, &self.module, self.impl_block.as_ref(), type_ref) | ||
563 | } | ||
564 | |||
565 | fn make_ty_opt(&self, type_ref: Option<&TypeRef>) -> Cancelable<Ty> { | ||
566 | Ty::from_hir_opt(self.db, &self.module, self.impl_block.as_ref(), type_ref) | ||
567 | } | ||
568 | |||
528 | fn unify(&mut self, ty1: &Ty, ty2: &Ty) -> bool { | 569 | fn unify(&mut self, ty1: &Ty, ty2: &Ty) -> bool { |
529 | match (ty1, ty2) { | 570 | match (ty1, ty2) { |
530 | (Ty::Unknown, ..) => true, | 571 | (Ty::Unknown, ..) => true, |
@@ -628,6 +669,12 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { | |||
628 | let ty = self.resolve_ty_as_possible(ty.clone()); | 669 | let ty = self.resolve_ty_as_possible(ty.clone()); |
629 | return Ok(Some(ty)); | 670 | return Ok(Some(ty)); |
630 | }; | 671 | }; |
672 | } else if path.is_self() { | ||
673 | // resolve `self` param | ||
674 | let self_param = ctry!(self.self_param); | ||
675 | let ty = ctry!(self.type_of.get(&self_param)); | ||
676 | let ty = self.resolve_ty_as_possible(ty.clone()); | ||
677 | return Ok(Some(ty)); | ||
631 | }; | 678 | }; |
632 | 679 | ||
633 | // resolve in module | 680 | // resolve in module |
@@ -826,7 +873,12 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { | |||
826 | } | 873 | } |
827 | ast::Expr::CastExpr(e) => { | 874 | ast::Expr::CastExpr(e) => { |
828 | let _inner_ty = self.infer_expr_opt(e.expr(), &Expectation::none())?; | 875 | let _inner_ty = self.infer_expr_opt(e.expr(), &Expectation::none())?; |
829 | let cast_ty = Ty::from_ast_opt(self.db, &self.module, e.type_ref())?; | 876 | let cast_ty = Ty::from_ast_opt( |
877 | self.db, | ||
878 | &self.module, | ||
879 | self.impl_block.as_ref(), | ||
880 | e.type_ref(), | ||
881 | )?; | ||
830 | let cast_ty = self.insert_type_vars(cast_ty); | 882 | let cast_ty = self.insert_type_vars(cast_ty); |
831 | // TODO do the coercion... | 883 | // TODO do the coercion... |
832 | cast_ty | 884 | cast_ty |
@@ -880,7 +932,12 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { | |||
880 | for stmt in node.statements() { | 932 | for stmt in node.statements() { |
881 | match stmt { | 933 | match stmt { |
882 | ast::Stmt::LetStmt(stmt) => { | 934 | ast::Stmt::LetStmt(stmt) => { |
883 | let decl_ty = Ty::from_ast_opt(self.db, &self.module, stmt.type_ref())?; | 935 | let decl_ty = Ty::from_ast_opt( |
936 | self.db, | ||
937 | &self.module, | ||
938 | self.impl_block.as_ref(), | ||
939 | stmt.type_ref(), | ||
940 | )?; | ||
884 | let decl_ty = self.insert_type_vars(decl_ty); | 941 | let decl_ty = self.insert_type_vars(decl_ty); |
885 | let ty = if let Some(expr) = stmt.initializer() { | 942 | let ty = if let Some(expr) = stmt.initializer() { |
886 | let expr_ty = self.infer_expr(expr, &Expectation::has_type(decl_ty))?; | 943 | let expr_ty = self.infer_expr(expr, &Expectation::has_type(decl_ty))?; |
@@ -906,46 +963,71 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { | |||
906 | self.write_ty(node.syntax(), ty.clone()); | 963 | self.write_ty(node.syntax(), ty.clone()); |
907 | Ok(ty) | 964 | Ok(ty) |
908 | } | 965 | } |
966 | |||
967 | fn collect_fn_signature(&mut self, node: ast::FnDef) -> Cancelable<()> { | ||
968 | if let Some(param_list) = node.param_list() { | ||
969 | if let Some(self_param) = param_list.self_param() { | ||
970 | let self_type = if let Some(type_ref) = self_param.type_ref() { | ||
971 | let ty = self.make_ty(&TypeRef::from_ast(type_ref))?; | ||
972 | self.insert_type_vars(ty) | ||
973 | } else { | ||
974 | // TODO this should be handled by desugaring during HIR conversion | ||
975 | let ty = self.make_ty_opt(self.impl_block.as_ref().map(|i| i.target_type()))?; | ||
976 | let ty = match self_param.flavor() { | ||
977 | ast::SelfParamFlavor::Owned => ty, | ||
978 | ast::SelfParamFlavor::Ref => Ty::Ref(Arc::new(ty), Mutability::Shared), | ||
979 | ast::SelfParamFlavor::MutRef => Ty::Ref(Arc::new(ty), Mutability::Mut), | ||
980 | }; | ||
981 | self.insert_type_vars(ty) | ||
982 | }; | ||
983 | if let Some(self_kw) = self_param.self_kw() { | ||
984 | let self_param = LocalSyntaxPtr::new(self_kw.syntax()); | ||
985 | self.self_param = Some(self_param); | ||
986 | self.type_of.insert(self_param, self_type); | ||
987 | } | ||
988 | } | ||
989 | for param in param_list.params() { | ||
990 | let pat = if let Some(pat) = param.pat() { | ||
991 | pat | ||
992 | } else { | ||
993 | continue; | ||
994 | }; | ||
995 | let ty = if let Some(type_ref) = param.type_ref() { | ||
996 | let ty = self.make_ty(&TypeRef::from_ast(type_ref))?; | ||
997 | self.insert_type_vars(ty) | ||
998 | } else { | ||
999 | // missing type annotation | ||
1000 | self.new_type_var() | ||
1001 | }; | ||
1002 | self.type_of.insert(LocalSyntaxPtr::new(pat.syntax()), ty); | ||
1003 | } | ||
1004 | } | ||
1005 | |||
1006 | self.return_ty = if let Some(type_ref) = node.ret_type().and_then(|n| n.type_ref()) { | ||
1007 | let ty = self.make_ty(&TypeRef::from_ast(type_ref))?; | ||
1008 | self.insert_type_vars(ty) | ||
1009 | } else { | ||
1010 | Ty::unit() | ||
1011 | }; | ||
1012 | |||
1013 | Ok(()) | ||
1014 | } | ||
909 | } | 1015 | } |
910 | 1016 | ||
911 | pub fn infer(db: &impl HirDatabase, def_id: DefId) -> Cancelable<Arc<InferenceResult>> { | 1017 | pub fn infer(db: &impl HirDatabase, def_id: DefId) -> Cancelable<Arc<InferenceResult>> { |
912 | let function = Function::new(def_id); // TODO: consts also need inference | 1018 | let function = Function::new(def_id); // TODO: consts also need inference |
913 | let scopes = function.scopes(db); | 1019 | let scopes = function.scopes(db); |
914 | let module = function.module(db)?; | 1020 | let module = function.module(db)?; |
915 | let mut ctx = InferenceContext::new(db, scopes, module); | 1021 | let impl_block = function.impl_block(db)?; |
1022 | let mut ctx = InferenceContext::new(db, scopes, module, impl_block); | ||
916 | 1023 | ||
917 | let syntax = function.syntax(db); | 1024 | let syntax = function.syntax(db); |
918 | let node = syntax.borrowed(); | 1025 | let node = syntax.borrowed(); |
919 | 1026 | ||
920 | if let Some(param_list) = node.param_list() { | 1027 | ctx.collect_fn_signature(node)?; |
921 | for param in param_list.params() { | ||
922 | let pat = if let Some(pat) = param.pat() { | ||
923 | pat | ||
924 | } else { | ||
925 | continue; | ||
926 | }; | ||
927 | if let Some(type_ref) = param.type_ref() { | ||
928 | let ty = Ty::from_ast(db, &ctx.module, type_ref)?; | ||
929 | let ty = ctx.insert_type_vars(ty); | ||
930 | ctx.type_of.insert(LocalSyntaxPtr::new(pat.syntax()), ty); | ||
931 | } else { | ||
932 | // TODO self param | ||
933 | let type_var = ctx.new_type_var(); | ||
934 | ctx.type_of | ||
935 | .insert(LocalSyntaxPtr::new(pat.syntax()), type_var); | ||
936 | }; | ||
937 | } | ||
938 | } | ||
939 | |||
940 | let ret_ty = if let Some(type_ref) = node.ret_type().and_then(|n| n.type_ref()) { | ||
941 | let ty = Ty::from_ast(db, &ctx.module, type_ref)?; | ||
942 | ctx.insert_type_vars(ty) | ||
943 | } else { | ||
944 | Ty::unit() | ||
945 | }; | ||
946 | 1028 | ||
947 | if let Some(block) = node.body() { | 1029 | if let Some(block) = node.body() { |
948 | ctx.infer_block(block, &Expectation::has_type(ret_ty))?; | 1030 | ctx.infer_block(block, &Expectation::has_type(ctx.return_ty.clone()))?; |
949 | } | 1031 | } |
950 | 1032 | ||
951 | Ok(Arc::new(ctx.resolve_all())) | 1033 | Ok(Arc::new(ctx.resolve_all())) |
diff --git a/crates/ra_hir/src/ty/tests.rs b/crates/ra_hir/src/ty/tests.rs index 93bf431c4..fb53fcf0b 100644 --- a/crates/ra_hir/src/ty/tests.rs +++ b/crates/ra_hir/src/ty/tests.rs | |||
@@ -134,6 +134,25 @@ fn test() -> &mut &f64 { | |||
134 | ); | 134 | ); |
135 | } | 135 | } |
136 | 136 | ||
137 | #[test] | ||
138 | fn infer_self() { | ||
139 | check_inference( | ||
140 | r#" | ||
141 | struct S; | ||
142 | |||
143 | impl S { | ||
144 | fn test(&self) { | ||
145 | self; | ||
146 | } | ||
147 | fn test2(self: &Self) { | ||
148 | self; | ||
149 | } | ||
150 | } | ||
151 | "#, | ||
152 | "0007_self.txt", | ||
153 | ); | ||
154 | } | ||
155 | |||
137 | fn infer(content: &str) -> String { | 156 | fn infer(content: &str) -> String { |
138 | let (db, _, file_id) = MockDatabase::with_single_file(content); | 157 | let (db, _, file_id) = MockDatabase::with_single_file(content); |
139 | let source_file = db.source_file(file_id); | 158 | let source_file = db.source_file(file_id); |
diff --git a/crates/ra_hir/src/ty/tests/data/0007_self.txt b/crates/ra_hir/src/ty/tests/data/0007_self.txt new file mode 100644 index 000000000..db4ba17d0 --- /dev/null +++ b/crates/ra_hir/src/ty/tests/data/0007_self.txt | |||
@@ -0,0 +1,6 @@ | |||
1 | [50; 54) 'self': &S | ||
2 | [34; 38) 'self': &S | ||
3 | [40; 61) '{ ... }': () | ||
4 | [88; 109) '{ ... }': () | ||
5 | [98; 102) 'self': &S | ||
6 | [75; 79) 'self': &S | ||
diff --git a/crates/ra_syntax/src/ast.rs b/crates/ra_syntax/src/ast.rs index 7f986d322..2a3bd27e2 100644 --- a/crates/ra_syntax/src/ast.rs +++ b/crates/ra_syntax/src/ast.rs | |||
@@ -482,6 +482,37 @@ impl<'a> PrefixExpr<'a> { | |||
482 | } | 482 | } |
483 | } | 483 | } |
484 | 484 | ||
485 | #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] | ||
486 | pub enum SelfParamFlavor { | ||
487 | /// self | ||
488 | Owned, | ||
489 | /// &self | ||
490 | Ref, | ||
491 | /// &mut self | ||
492 | MutRef, | ||
493 | } | ||
494 | |||
495 | impl<'a> SelfParam<'a> { | ||
496 | pub fn flavor(&self) -> SelfParamFlavor { | ||
497 | let borrowed = self.syntax().children().any(|n| n.kind() == AMP); | ||
498 | if borrowed { | ||
499 | // check for a `mut` coming after the & -- `mut &self` != `&mut self` | ||
500 | if self | ||
501 | .syntax() | ||
502 | .children() | ||
503 | .skip_while(|n| n.kind() != AMP) | ||
504 | .any(|n| n.kind() == MUT_KW) | ||
505 | { | ||
506 | SelfParamFlavor::MutRef | ||
507 | } else { | ||
508 | SelfParamFlavor::Ref | ||
509 | } | ||
510 | } else { | ||
511 | SelfParamFlavor::Owned | ||
512 | } | ||
513 | } | ||
514 | } | ||
515 | |||
485 | #[test] | 516 | #[test] |
486 | fn test_doc_comment_of_items() { | 517 | fn test_doc_comment_of_items() { |
487 | let file = SourceFileNode::parse( | 518 | let file = SourceFileNode::parse( |
diff --git a/crates/ra_syntax/src/ast/generated.rs b/crates/ra_syntax/src/ast/generated.rs index c1c63f555..7df6a9c46 100644 --- a/crates/ra_syntax/src/ast/generated.rs +++ b/crates/ra_syntax/src/ast/generated.rs | |||
@@ -1442,7 +1442,39 @@ impl<R: TreeRoot<RaTypes>> ImplBlockNode<R> { | |||
1442 | } | 1442 | } |
1443 | 1443 | ||
1444 | 1444 | ||
1445 | impl<'a> ImplBlock<'a> {} | 1445 | impl<'a> ImplBlock<'a> { |
1446 | pub fn item_list(self) -> Option<ItemList<'a>> { | ||
1447 | super::child_opt(self) | ||
1448 | } | ||
1449 | } | ||
1450 | |||
1451 | // ImplItem | ||
1452 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
1453 | pub enum ImplItem<'a> { | ||
1454 | FnDef(FnDef<'a>), | ||
1455 | TypeDef(TypeDef<'a>), | ||
1456 | ConstDef(ConstDef<'a>), | ||
1457 | } | ||
1458 | |||
1459 | impl<'a> AstNode<'a> for ImplItem<'a> { | ||
1460 | fn cast(syntax: SyntaxNodeRef<'a>) -> Option<Self> { | ||
1461 | match syntax.kind() { | ||
1462 | FN_DEF => Some(ImplItem::FnDef(FnDef { syntax })), | ||
1463 | TYPE_DEF => Some(ImplItem::TypeDef(TypeDef { syntax })), | ||
1464 | CONST_DEF => Some(ImplItem::ConstDef(ConstDef { syntax })), | ||
1465 | _ => None, | ||
1466 | } | ||
1467 | } | ||
1468 | fn syntax(self) -> SyntaxNodeRef<'a> { | ||
1469 | match self { | ||
1470 | ImplItem::FnDef(inner) => inner.syntax(), | ||
1471 | ImplItem::TypeDef(inner) => inner.syntax(), | ||
1472 | ImplItem::ConstDef(inner) => inner.syntax(), | ||
1473 | } | ||
1474 | } | ||
1475 | } | ||
1476 | |||
1477 | impl<'a> ImplItem<'a> {} | ||
1446 | 1478 | ||
1447 | // ImplTraitType | 1479 | // ImplTraitType |
1448 | #[derive(Debug, Clone, Copy,)] | 1480 | #[derive(Debug, Clone, Copy,)] |
@@ -1555,7 +1587,11 @@ impl<R: TreeRoot<RaTypes>> ItemListNode<R> { | |||
1555 | 1587 | ||
1556 | impl<'a> ast::FnDefOwner<'a> for ItemList<'a> {} | 1588 | impl<'a> ast::FnDefOwner<'a> for ItemList<'a> {} |
1557 | impl<'a> ast::ModuleItemOwner<'a> for ItemList<'a> {} | 1589 | impl<'a> ast::ModuleItemOwner<'a> for ItemList<'a> {} |
1558 | impl<'a> ItemList<'a> {} | 1590 | impl<'a> ItemList<'a> { |
1591 | pub fn impl_items(self) -> impl Iterator<Item = ImplItem<'a>> + 'a { | ||
1592 | super::children(self) | ||
1593 | } | ||
1594 | } | ||
1559 | 1595 | ||
1560 | // Label | 1596 | // Label |
1561 | #[derive(Debug, Clone, Copy,)] | 1597 | #[derive(Debug, Clone, Copy,)] |
@@ -3452,6 +3488,43 @@ impl<'a> ReturnExpr<'a> { | |||
3452 | } | 3488 | } |
3453 | } | 3489 | } |
3454 | 3490 | ||
3491 | // SelfKw | ||
3492 | #[derive(Debug, Clone, Copy,)] | ||
3493 | pub struct SelfKwNode<R: TreeRoot<RaTypes> = OwnedRoot> { | ||
3494 | pub(crate) syntax: SyntaxNode<R>, | ||
3495 | } | ||
3496 | pub type SelfKw<'a> = SelfKwNode<RefRoot<'a>>; | ||
3497 | |||
3498 | impl<R1: TreeRoot<RaTypes>, R2: TreeRoot<RaTypes>> PartialEq<SelfKwNode<R1>> for SelfKwNode<R2> { | ||
3499 | fn eq(&self, other: &SelfKwNode<R1>) -> bool { self.syntax == other.syntax } | ||
3500 | } | ||
3501 | impl<R: TreeRoot<RaTypes>> Eq for SelfKwNode<R> {} | ||
3502 | impl<R: TreeRoot<RaTypes>> Hash for SelfKwNode<R> { | ||
3503 | fn hash<H: Hasher>(&self, state: &mut H) { self.syntax.hash(state) } | ||
3504 | } | ||
3505 | |||
3506 | impl<'a> AstNode<'a> for SelfKw<'a> { | ||
3507 | fn cast(syntax: SyntaxNodeRef<'a>) -> Option<Self> { | ||
3508 | match syntax.kind() { | ||
3509 | SELF_KW => Some(SelfKw { syntax }), | ||
3510 | _ => None, | ||
3511 | } | ||
3512 | } | ||
3513 | fn syntax(self) -> SyntaxNodeRef<'a> { self.syntax } | ||
3514 | } | ||
3515 | |||
3516 | impl<R: TreeRoot<RaTypes>> SelfKwNode<R> { | ||
3517 | pub fn borrowed(&self) -> SelfKw { | ||
3518 | SelfKwNode { syntax: self.syntax.borrowed() } | ||
3519 | } | ||
3520 | pub fn owned(&self) -> SelfKwNode { | ||
3521 | SelfKwNode { syntax: self.syntax.owned() } | ||
3522 | } | ||
3523 | } | ||
3524 | |||
3525 | |||
3526 | impl<'a> SelfKw<'a> {} | ||
3527 | |||
3455 | // SelfParam | 3528 | // SelfParam |
3456 | #[derive(Debug, Clone, Copy,)] | 3529 | #[derive(Debug, Clone, Copy,)] |
3457 | pub struct SelfParamNode<R: TreeRoot<RaTypes> = OwnedRoot> { | 3530 | pub struct SelfParamNode<R: TreeRoot<RaTypes> = OwnedRoot> { |
@@ -3487,7 +3560,15 @@ impl<R: TreeRoot<RaTypes>> SelfParamNode<R> { | |||
3487 | } | 3560 | } |
3488 | 3561 | ||
3489 | 3562 | ||
3490 | impl<'a> SelfParam<'a> {} | 3563 | impl<'a> SelfParam<'a> { |
3564 | pub fn type_ref(self) -> Option<TypeRef<'a>> { | ||
3565 | super::child_opt(self) | ||
3566 | } | ||
3567 | |||
3568 | pub fn self_kw(self) -> Option<SelfKw<'a>> { | ||
3569 | super::child_opt(self) | ||
3570 | } | ||
3571 | } | ||
3491 | 3572 | ||
3492 | // SlicePat | 3573 | // SlicePat |
3493 | #[derive(Debug, Clone, Copy,)] | 3574 | #[derive(Debug, Clone, Copy,)] |
diff --git a/crates/ra_syntax/src/grammar.ron b/crates/ra_syntax/src/grammar.ron index 9a4a96fac..c55e9e07a 100644 --- a/crates/ra_syntax/src/grammar.ron +++ b/crates/ra_syntax/src/grammar.ron | |||
@@ -284,6 +284,7 @@ Grammar( | |||
284 | options: [ "ItemList" ] | 284 | options: [ "ItemList" ] |
285 | ), | 285 | ), |
286 | "ItemList": ( | 286 | "ItemList": ( |
287 | collections: [["impl_items", "ImplItem"]], | ||
287 | traits: [ "FnDefOwner", "ModuleItemOwner" ], | 288 | traits: [ "FnDefOwner", "ModuleItemOwner" ], |
288 | ), | 289 | ), |
289 | "ConstDef": ( traits: [ | 290 | "ConstDef": ( traits: [ |
@@ -307,7 +308,7 @@ Grammar( | |||
307 | "AttrsOwner", | 308 | "AttrsOwner", |
308 | "DocCommentsOwner" | 309 | "DocCommentsOwner" |
309 | ] ), | 310 | ] ), |
310 | "ImplBlock": (collections: []), | 311 | "ImplBlock": (options: ["ItemList"]), |
311 | 312 | ||
312 | "ParenType": (options: ["TypeRef"]), | 313 | "ParenType": (options: ["TypeRef"]), |
313 | "TupleType": ( collections: [["fields", "TypeRef"]] ), | 314 | "TupleType": ( collections: [["fields", "TypeRef"]] ), |
@@ -351,6 +352,9 @@ Grammar( | |||
351 | enum: ["StructDef", "EnumDef", "FnDef", "TraitDef", "TypeDef", "ImplBlock", | 352 | enum: ["StructDef", "EnumDef", "FnDef", "TraitDef", "TypeDef", "ImplBlock", |
352 | "UseItem", "ExternCrateItem", "ConstDef", "StaticDef", "Module" ] | 353 | "UseItem", "ExternCrateItem", "ConstDef", "StaticDef", "Module" ] |
353 | ), | 354 | ), |
355 | "ImplItem": ( | ||
356 | enum: ["FnDef", "TypeDef", "ConstDef"] | ||
357 | ), | ||
354 | 358 | ||
355 | "TupleExpr": (), | 359 | "TupleExpr": (), |
356 | "ArrayExpr": (), | 360 | "ArrayExpr": (), |
@@ -530,7 +534,8 @@ Grammar( | |||
530 | ["params", "Param"] | 534 | ["params", "Param"] |
531 | ] | 535 | ] |
532 | ), | 536 | ), |
533 | "SelfParam": (), | 537 | "SelfParam": (options: ["TypeRef", "SelfKw"]), |
538 | "SelfKw": (), | ||
534 | "Param": ( | 539 | "Param": ( |
535 | options: [ "Pat", "TypeRef" ], | 540 | options: [ "Pat", "TypeRef" ], |
536 | ), | 541 | ), |
diff --git a/crates/ra_syntax/src/grammar/items.rs b/crates/ra_syntax/src/grammar/items.rs index b9a00b565..265e84570 100644 --- a/crates/ra_syntax/src/grammar/items.rs +++ b/crates/ra_syntax/src/grammar/items.rs | |||
@@ -151,7 +151,7 @@ pub(super) fn maybe_item(p: &mut Parser, flavor: ItemFlavor) -> MaybeItem { | |||
151 | // test unsafe_default_impl | 151 | // test unsafe_default_impl |
152 | // unsafe default impl Foo {} | 152 | // unsafe default impl Foo {} |
153 | IMPL_KW => { | 153 | IMPL_KW => { |
154 | traits::impl_item(p); | 154 | traits::impl_block(p); |
155 | IMPL_BLOCK | 155 | IMPL_BLOCK |
156 | } | 156 | } |
157 | _ => { | 157 | _ => { |
diff --git a/crates/ra_syntax/src/grammar/items/traits.rs b/crates/ra_syntax/src/grammar/items/traits.rs index d4da8b2f7..0a0621753 100644 --- a/crates/ra_syntax/src/grammar/items/traits.rs +++ b/crates/ra_syntax/src/grammar/items/traits.rs | |||
@@ -40,9 +40,9 @@ pub(crate) fn trait_item_list(p: &mut Parser) { | |||
40 | m.complete(p, ITEM_LIST); | 40 | m.complete(p, ITEM_LIST); |
41 | } | 41 | } |
42 | 42 | ||
43 | // test impl_item | 43 | // test impl_block |
44 | // impl Foo {} | 44 | // impl Foo {} |
45 | pub(super) fn impl_item(p: &mut Parser) { | 45 | pub(super) fn impl_block(p: &mut Parser) { |
46 | assert!(p.at(IMPL_KW)); | 46 | assert!(p.at(IMPL_KW)); |
47 | p.bump(); | 47 | p.bump(); |
48 | if choose_type_params_over_qpath(p) { | 48 | if choose_type_params_over_qpath(p) { |
@@ -52,7 +52,7 @@ pub(super) fn impl_item(p: &mut Parser) { | |||
52 | // TODO: never type | 52 | // TODO: never type |
53 | // impl ! {} | 53 | // impl ! {} |
54 | 54 | ||
55 | // test impl_item_neg | 55 | // test impl_block_neg |
56 | // impl !Send for X {} | 56 | // impl !Send for X {} |
57 | p.eat(EXCL); | 57 | p.eat(EXCL); |
58 | impl_type(p); | 58 | impl_type(p); |
diff --git a/crates/ra_syntax/tests/data/parser/inline/ok/0063_impl_item_neg.rs b/crates/ra_syntax/tests/data/parser/inline/ok/0063_impl_block_neg.rs index b7527c870..b7527c870 100644 --- a/crates/ra_syntax/tests/data/parser/inline/ok/0063_impl_item_neg.rs +++ b/crates/ra_syntax/tests/data/parser/inline/ok/0063_impl_block_neg.rs | |||
diff --git a/crates/ra_syntax/tests/data/parser/inline/ok/0063_impl_item_neg.txt b/crates/ra_syntax/tests/data/parser/inline/ok/0063_impl_block_neg.txt index 563e43508..563e43508 100644 --- a/crates/ra_syntax/tests/data/parser/inline/ok/0063_impl_item_neg.txt +++ b/crates/ra_syntax/tests/data/parser/inline/ok/0063_impl_block_neg.txt | |||
diff --git a/crates/ra_syntax/tests/data/parser/inline/ok/0079_impl_item.rs b/crates/ra_syntax/tests/data/parser/inline/ok/0079_impl_block.rs index d6337f6b3..d6337f6b3 100644 --- a/crates/ra_syntax/tests/data/parser/inline/ok/0079_impl_item.rs +++ b/crates/ra_syntax/tests/data/parser/inline/ok/0079_impl_block.rs | |||
diff --git a/crates/ra_syntax/tests/data/parser/inline/ok/0079_impl_item.txt b/crates/ra_syntax/tests/data/parser/inline/ok/0079_impl_block.txt index a2c218aa9..a2c218aa9 100644 --- a/crates/ra_syntax/tests/data/parser/inline/ok/0079_impl_item.txt +++ b/crates/ra_syntax/tests/data/parser/inline/ok/0079_impl_block.txt | |||