diff options
author | Dmitry <[email protected]> | 2020-08-14 19:32:05 +0100 |
---|---|---|
committer | Dmitry <[email protected]> | 2020-08-14 19:32:05 +0100 |
commit | 178c3e135a2a249692f7784712492e7884ae0c00 (patch) | |
tree | ac6b769dbf7162150caa0c1624786a4dd79ff3be /crates/hir | |
parent | 06ff8e6c760ff05f10e868b5d1f9d79e42fbb49c (diff) | |
parent | c2594daf2974dbd4ce3d9b7ec72481764abaceb5 (diff) |
Merge remote-tracking branch 'origin/master'
Diffstat (limited to 'crates/hir')
-rw-r--r-- | crates/hir/Cargo.toml | 24 | ||||
-rw-r--r-- | crates/hir/src/code_model.rs | 1719 | ||||
-rw-r--r-- | crates/hir/src/db.rs | 21 | ||||
-rw-r--r-- | crates/hir/src/diagnostics.rs | 6 | ||||
-rw-r--r-- | crates/hir/src/from_id.rs | 247 | ||||
-rw-r--r-- | crates/hir/src/has_source.rs | 135 | ||||
-rw-r--r-- | crates/hir/src/lib.rs | 63 | ||||
-rw-r--r-- | crates/hir/src/semantics.rs | 849 | ||||
-rw-r--r-- | crates/hir/src/semantics/source_to_def.rs | 275 | ||||
-rw-r--r-- | crates/hir/src/source_analyzer.rs | 534 |
10 files changed, 3873 insertions, 0 deletions
diff --git a/crates/hir/Cargo.toml b/crates/hir/Cargo.toml new file mode 100644 index 000000000..dbb2986b6 --- /dev/null +++ b/crates/hir/Cargo.toml | |||
@@ -0,0 +1,24 @@ | |||
1 | [package] | ||
2 | name = "hir" | ||
3 | version = "0.0.0" | ||
4 | license = "MIT OR Apache-2.0" | ||
5 | authors = ["rust-analyzer developers"] | ||
6 | edition = "2018" | ||
7 | |||
8 | [lib] | ||
9 | doctest = false | ||
10 | |||
11 | [dependencies] | ||
12 | log = "0.4.8" | ||
13 | rustc-hash = "1.1.0" | ||
14 | either = "1.5.3" | ||
15 | arrayvec = "0.5.1" | ||
16 | itertools = "0.9.0" | ||
17 | |||
18 | stdx = { path = "../stdx" } | ||
19 | syntax = { path = "../syntax" } | ||
20 | base_db = { path = "../base_db" } | ||
21 | profile = { path = "../profile" } | ||
22 | hir_expand = { path = "../hir_expand" } | ||
23 | hir_def = { path = "../hir_def" } | ||
24 | hir_ty = { path = "../hir_ty" } | ||
diff --git a/crates/hir/src/code_model.rs b/crates/hir/src/code_model.rs new file mode 100644 index 000000000..5dc3ae3b1 --- /dev/null +++ b/crates/hir/src/code_model.rs | |||
@@ -0,0 +1,1719 @@ | |||
1 | //! FIXME: write short doc here | ||
2 | use std::{iter, sync::Arc}; | ||
3 | |||
4 | use arrayvec::ArrayVec; | ||
5 | use base_db::{CrateId, Edition, FileId}; | ||
6 | use either::Either; | ||
7 | use hir_def::{ | ||
8 | adt::ReprKind, | ||
9 | adt::StructKind, | ||
10 | adt::VariantData, | ||
11 | builtin_type::BuiltinType, | ||
12 | docs::Documentation, | ||
13 | expr::{BindingAnnotation, Pat, PatId}, | ||
14 | import_map, | ||
15 | per_ns::PerNs, | ||
16 | resolver::{HasResolver, Resolver}, | ||
17 | src::HasSource as _, | ||
18 | type_ref::{Mutability, TypeRef}, | ||
19 | AdtId, AssocContainerId, ConstId, DefWithBodyId, EnumId, FunctionId, GenericDefId, HasModule, | ||
20 | ImplId, LocalEnumVariantId, LocalFieldId, LocalModuleId, Lookup, ModuleId, StaticId, StructId, | ||
21 | TraitId, TypeAliasId, TypeParamId, UnionId, | ||
22 | }; | ||
23 | use hir_expand::{ | ||
24 | diagnostics::DiagnosticSink, | ||
25 | name::{name, AsName}, | ||
26 | MacroDefId, MacroDefKind, | ||
27 | }; | ||
28 | use hir_ty::{ | ||
29 | autoderef, | ||
30 | display::{HirDisplayError, HirFormatter}, | ||
31 | method_resolution, ApplicationTy, CallableDefId, Canonical, FnSig, GenericPredicate, | ||
32 | InEnvironment, Substs, TraitEnvironment, Ty, TyDefId, TypeCtor, | ||
33 | }; | ||
34 | use rustc_hash::FxHashSet; | ||
35 | use stdx::impl_from; | ||
36 | use syntax::{ | ||
37 | ast::{self, AttrsOwner, NameOwner}, | ||
38 | AstNode, | ||
39 | }; | ||
40 | |||
41 | use crate::{ | ||
42 | db::{DefDatabase, HirDatabase}, | ||
43 | has_source::HasSource, | ||
44 | HirDisplay, InFile, Name, | ||
45 | }; | ||
46 | |||
47 | /// hir::Crate describes a single crate. It's the main interface with which | ||
48 | /// a crate's dependencies interact. Mostly, it should be just a proxy for the | ||
49 | /// root module. | ||
50 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
51 | pub struct Crate { | ||
52 | pub(crate) id: CrateId, | ||
53 | } | ||
54 | |||
55 | #[derive(Debug)] | ||
56 | pub struct CrateDependency { | ||
57 | pub krate: Crate, | ||
58 | pub name: Name, | ||
59 | } | ||
60 | |||
61 | impl Crate { | ||
62 | pub fn dependencies(self, db: &dyn HirDatabase) -> Vec<CrateDependency> { | ||
63 | db.crate_graph()[self.id] | ||
64 | .dependencies | ||
65 | .iter() | ||
66 | .map(|dep| { | ||
67 | let krate = Crate { id: dep.crate_id }; | ||
68 | let name = dep.as_name(); | ||
69 | CrateDependency { krate, name } | ||
70 | }) | ||
71 | .collect() | ||
72 | } | ||
73 | |||
74 | // FIXME: add `transitive_reverse_dependencies`. | ||
75 | pub fn reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> { | ||
76 | let crate_graph = db.crate_graph(); | ||
77 | crate_graph | ||
78 | .iter() | ||
79 | .filter(|&krate| { | ||
80 | crate_graph[krate].dependencies.iter().any(|it| it.crate_id == self.id) | ||
81 | }) | ||
82 | .map(|id| Crate { id }) | ||
83 | .collect() | ||
84 | } | ||
85 | |||
86 | pub fn root_module(self, db: &dyn HirDatabase) -> Module { | ||
87 | let module_id = db.crate_def_map(self.id).root; | ||
88 | Module::new(self, module_id) | ||
89 | } | ||
90 | |||
91 | pub fn root_file(self, db: &dyn HirDatabase) -> FileId { | ||
92 | db.crate_graph()[self.id].root_file_id | ||
93 | } | ||
94 | |||
95 | pub fn edition(self, db: &dyn HirDatabase) -> Edition { | ||
96 | db.crate_graph()[self.id].edition | ||
97 | } | ||
98 | |||
99 | pub fn display_name(self, db: &dyn HirDatabase) -> Option<String> { | ||
100 | db.crate_graph()[self.id].display_name.clone() | ||
101 | } | ||
102 | |||
103 | pub fn query_external_importables( | ||
104 | self, | ||
105 | db: &dyn DefDatabase, | ||
106 | query: &str, | ||
107 | ) -> impl Iterator<Item = Either<ModuleDef, MacroDef>> { | ||
108 | import_map::search_dependencies( | ||
109 | db, | ||
110 | self.into(), | ||
111 | import_map::Query::new(query).anchor_end().case_sensitive().limit(40), | ||
112 | ) | ||
113 | .into_iter() | ||
114 | .map(|item| match item { | ||
115 | ItemInNs::Types(mod_id) | ItemInNs::Values(mod_id) => Either::Left(mod_id.into()), | ||
116 | ItemInNs::Macros(mac_id) => Either::Right(mac_id.into()), | ||
117 | }) | ||
118 | } | ||
119 | |||
120 | pub fn all(db: &dyn HirDatabase) -> Vec<Crate> { | ||
121 | db.crate_graph().iter().map(|id| Crate { id }).collect() | ||
122 | } | ||
123 | } | ||
124 | |||
125 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
126 | pub struct Module { | ||
127 | pub(crate) id: ModuleId, | ||
128 | } | ||
129 | |||
130 | /// The defs which can be visible in the module. | ||
131 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
132 | pub enum ModuleDef { | ||
133 | Module(Module), | ||
134 | Function(Function), | ||
135 | Adt(Adt), | ||
136 | // Can't be directly declared, but can be imported. | ||
137 | EnumVariant(EnumVariant), | ||
138 | Const(Const), | ||
139 | Static(Static), | ||
140 | Trait(Trait), | ||
141 | TypeAlias(TypeAlias), | ||
142 | BuiltinType(BuiltinType), | ||
143 | } | ||
144 | impl_from!( | ||
145 | Module, | ||
146 | Function, | ||
147 | Adt(Struct, Enum, Union), | ||
148 | EnumVariant, | ||
149 | Const, | ||
150 | Static, | ||
151 | Trait, | ||
152 | TypeAlias, | ||
153 | BuiltinType | ||
154 | for ModuleDef | ||
155 | ); | ||
156 | |||
157 | impl ModuleDef { | ||
158 | pub fn module(self, db: &dyn HirDatabase) -> Option<Module> { | ||
159 | match self { | ||
160 | ModuleDef::Module(it) => it.parent(db), | ||
161 | ModuleDef::Function(it) => Some(it.module(db)), | ||
162 | ModuleDef::Adt(it) => Some(it.module(db)), | ||
163 | ModuleDef::EnumVariant(it) => Some(it.module(db)), | ||
164 | ModuleDef::Const(it) => Some(it.module(db)), | ||
165 | ModuleDef::Static(it) => Some(it.module(db)), | ||
166 | ModuleDef::Trait(it) => Some(it.module(db)), | ||
167 | ModuleDef::TypeAlias(it) => Some(it.module(db)), | ||
168 | ModuleDef::BuiltinType(_) => None, | ||
169 | } | ||
170 | } | ||
171 | |||
172 | pub fn definition_visibility(&self, db: &dyn HirDatabase) -> Option<Visibility> { | ||
173 | let module = match self { | ||
174 | ModuleDef::Module(it) => it.parent(db)?, | ||
175 | ModuleDef::Function(it) => return Some(it.visibility(db)), | ||
176 | ModuleDef::Adt(it) => it.module(db), | ||
177 | ModuleDef::EnumVariant(it) => { | ||
178 | let parent = it.parent_enum(db); | ||
179 | let module = it.module(db); | ||
180 | return module.visibility_of(db, &ModuleDef::Adt(Adt::Enum(parent))); | ||
181 | } | ||
182 | ModuleDef::Const(it) => return Some(it.visibility(db)), | ||
183 | ModuleDef::Static(it) => it.module(db), | ||
184 | ModuleDef::Trait(it) => it.module(db), | ||
185 | ModuleDef::TypeAlias(it) => return Some(it.visibility(db)), | ||
186 | ModuleDef::BuiltinType(_) => return None, | ||
187 | }; | ||
188 | |||
189 | module.visibility_of(db, self) | ||
190 | } | ||
191 | |||
192 | pub fn name(self, db: &dyn HirDatabase) -> Option<Name> { | ||
193 | match self { | ||
194 | ModuleDef::Adt(it) => Some(it.name(db)), | ||
195 | ModuleDef::Trait(it) => Some(it.name(db)), | ||
196 | ModuleDef::Function(it) => Some(it.name(db)), | ||
197 | ModuleDef::EnumVariant(it) => Some(it.name(db)), | ||
198 | ModuleDef::TypeAlias(it) => Some(it.name(db)), | ||
199 | |||
200 | ModuleDef::Module(it) => it.name(db), | ||
201 | ModuleDef::Const(it) => it.name(db), | ||
202 | ModuleDef::Static(it) => it.name(db), | ||
203 | |||
204 | ModuleDef::BuiltinType(it) => Some(it.as_name()), | ||
205 | } | ||
206 | } | ||
207 | } | ||
208 | |||
209 | pub use hir_def::{ | ||
210 | attr::Attrs, item_scope::ItemInNs, item_tree::ItemTreeNode, visibility::Visibility, | ||
211 | AssocItemId, AssocItemLoc, | ||
212 | }; | ||
213 | |||
214 | impl Module { | ||
215 | pub(crate) fn new(krate: Crate, crate_module_id: LocalModuleId) -> Module { | ||
216 | Module { id: ModuleId { krate: krate.id, local_id: crate_module_id } } | ||
217 | } | ||
218 | |||
219 | /// Name of this module. | ||
220 | pub fn name(self, db: &dyn HirDatabase) -> Option<Name> { | ||
221 | let def_map = db.crate_def_map(self.id.krate); | ||
222 | let parent = def_map[self.id.local_id].parent?; | ||
223 | def_map[parent].children.iter().find_map(|(name, module_id)| { | ||
224 | if *module_id == self.id.local_id { | ||
225 | Some(name.clone()) | ||
226 | } else { | ||
227 | None | ||
228 | } | ||
229 | }) | ||
230 | } | ||
231 | |||
232 | /// Returns the crate this module is part of. | ||
233 | pub fn krate(self) -> Crate { | ||
234 | Crate { id: self.id.krate } | ||
235 | } | ||
236 | |||
237 | /// Topmost parent of this module. Every module has a `crate_root`, but some | ||
238 | /// might be missing `krate`. This can happen if a module's file is not included | ||
239 | /// in the module tree of any target in `Cargo.toml`. | ||
240 | pub fn crate_root(self, db: &dyn HirDatabase) -> Module { | ||
241 | let def_map = db.crate_def_map(self.id.krate); | ||
242 | self.with_module_id(def_map.root) | ||
243 | } | ||
244 | |||
245 | /// Iterates over all child modules. | ||
246 | pub fn children(self, db: &dyn HirDatabase) -> impl Iterator<Item = Module> { | ||
247 | let def_map = db.crate_def_map(self.id.krate); | ||
248 | let children = def_map[self.id.local_id] | ||
249 | .children | ||
250 | .iter() | ||
251 | .map(|(_, module_id)| self.with_module_id(*module_id)) | ||
252 | .collect::<Vec<_>>(); | ||
253 | children.into_iter() | ||
254 | } | ||
255 | |||
256 | /// Finds a parent module. | ||
257 | pub fn parent(self, db: &dyn HirDatabase) -> Option<Module> { | ||
258 | let def_map = db.crate_def_map(self.id.krate); | ||
259 | let parent_id = def_map[self.id.local_id].parent?; | ||
260 | Some(self.with_module_id(parent_id)) | ||
261 | } | ||
262 | |||
263 | pub fn path_to_root(self, db: &dyn HirDatabase) -> Vec<Module> { | ||
264 | let mut res = vec![self]; | ||
265 | let mut curr = self; | ||
266 | while let Some(next) = curr.parent(db) { | ||
267 | res.push(next); | ||
268 | curr = next | ||
269 | } | ||
270 | res | ||
271 | } | ||
272 | |||
273 | /// Returns a `ModuleScope`: a set of items, visible in this module. | ||
274 | pub fn scope( | ||
275 | self, | ||
276 | db: &dyn HirDatabase, | ||
277 | visible_from: Option<Module>, | ||
278 | ) -> Vec<(Name, ScopeDef)> { | ||
279 | db.crate_def_map(self.id.krate)[self.id.local_id] | ||
280 | .scope | ||
281 | .entries() | ||
282 | .filter_map(|(name, def)| { | ||
283 | if let Some(m) = visible_from { | ||
284 | let filtered = | ||
285 | def.filter_visibility(|vis| vis.is_visible_from(db.upcast(), m.id)); | ||
286 | if filtered.is_none() && !def.is_none() { | ||
287 | None | ||
288 | } else { | ||
289 | Some((name, filtered)) | ||
290 | } | ||
291 | } else { | ||
292 | Some((name, def)) | ||
293 | } | ||
294 | }) | ||
295 | .flat_map(|(name, def)| { | ||
296 | ScopeDef::all_items(def).into_iter().map(move |item| (name.clone(), item)) | ||
297 | }) | ||
298 | .collect() | ||
299 | } | ||
300 | |||
301 | pub fn visibility_of(self, db: &dyn HirDatabase, def: &ModuleDef) -> Option<Visibility> { | ||
302 | db.crate_def_map(self.id.krate)[self.id.local_id].scope.visibility_of(def.clone().into()) | ||
303 | } | ||
304 | |||
305 | pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) { | ||
306 | let _p = profile::span("Module::diagnostics"); | ||
307 | let crate_def_map = db.crate_def_map(self.id.krate); | ||
308 | crate_def_map.add_diagnostics(db.upcast(), self.id.local_id, sink); | ||
309 | for decl in self.declarations(db) { | ||
310 | match decl { | ||
311 | crate::ModuleDef::Function(f) => f.diagnostics(db, sink), | ||
312 | crate::ModuleDef::Module(m) => { | ||
313 | // Only add diagnostics from inline modules | ||
314 | if crate_def_map[m.id.local_id].origin.is_inline() { | ||
315 | m.diagnostics(db, sink) | ||
316 | } | ||
317 | } | ||
318 | _ => (), | ||
319 | } | ||
320 | } | ||
321 | |||
322 | for impl_def in self.impl_defs(db) { | ||
323 | for item in impl_def.items(db) { | ||
324 | if let AssocItem::Function(f) = item { | ||
325 | f.diagnostics(db, sink); | ||
326 | } | ||
327 | } | ||
328 | } | ||
329 | } | ||
330 | |||
331 | pub fn declarations(self, db: &dyn HirDatabase) -> Vec<ModuleDef> { | ||
332 | let def_map = db.crate_def_map(self.id.krate); | ||
333 | def_map[self.id.local_id].scope.declarations().map(ModuleDef::from).collect() | ||
334 | } | ||
335 | |||
336 | pub fn impl_defs(self, db: &dyn HirDatabase) -> Vec<ImplDef> { | ||
337 | let def_map = db.crate_def_map(self.id.krate); | ||
338 | def_map[self.id.local_id].scope.impls().map(ImplDef::from).collect() | ||
339 | } | ||
340 | |||
341 | pub(crate) fn with_module_id(self, module_id: LocalModuleId) -> Module { | ||
342 | Module::new(self.krate(), module_id) | ||
343 | } | ||
344 | |||
345 | /// Finds a path that can be used to refer to the given item from within | ||
346 | /// this module, if possible. | ||
347 | pub fn find_use_path( | ||
348 | self, | ||
349 | db: &dyn DefDatabase, | ||
350 | item: impl Into<ItemInNs>, | ||
351 | ) -> Option<hir_def::path::ModPath> { | ||
352 | hir_def::find_path::find_path(db, item.into(), self.into()) | ||
353 | } | ||
354 | } | ||
355 | |||
356 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
357 | pub struct Field { | ||
358 | pub(crate) parent: VariantDef, | ||
359 | pub(crate) id: LocalFieldId, | ||
360 | } | ||
361 | |||
362 | #[derive(Debug, PartialEq, Eq)] | ||
363 | pub enum FieldSource { | ||
364 | Named(ast::RecordField), | ||
365 | Pos(ast::TupleField), | ||
366 | } | ||
367 | |||
368 | impl Field { | ||
369 | pub fn name(&self, db: &dyn HirDatabase) -> Name { | ||
370 | self.parent.variant_data(db).fields()[self.id].name.clone() | ||
371 | } | ||
372 | |||
373 | /// Returns the type as in the signature of the struct (i.e., with | ||
374 | /// placeholder types for type parameters). This is good for showing | ||
375 | /// signature help, but not so good to actually get the type of the field | ||
376 | /// when you actually have a variable of the struct. | ||
377 | pub fn signature_ty(&self, db: &dyn HirDatabase) -> Type { | ||
378 | let var_id = self.parent.into(); | ||
379 | let generic_def_id: GenericDefId = match self.parent { | ||
380 | VariantDef::Struct(it) => it.id.into(), | ||
381 | VariantDef::Union(it) => it.id.into(), | ||
382 | VariantDef::EnumVariant(it) => it.parent.id.into(), | ||
383 | }; | ||
384 | let substs = Substs::type_params(db, generic_def_id); | ||
385 | let ty = db.field_types(var_id)[self.id].clone().subst(&substs); | ||
386 | Type::new(db, self.parent.module(db).id.krate, var_id, ty) | ||
387 | } | ||
388 | |||
389 | pub fn parent_def(&self, _db: &dyn HirDatabase) -> VariantDef { | ||
390 | self.parent | ||
391 | } | ||
392 | } | ||
393 | |||
394 | impl HasVisibility for Field { | ||
395 | fn visibility(&self, db: &dyn HirDatabase) -> Visibility { | ||
396 | let variant_data = self.parent.variant_data(db); | ||
397 | let visibility = &variant_data.fields()[self.id].visibility; | ||
398 | let parent_id: hir_def::VariantId = self.parent.into(); | ||
399 | visibility.resolve(db.upcast(), &parent_id.resolver(db.upcast())) | ||
400 | } | ||
401 | } | ||
402 | |||
403 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
404 | pub struct Struct { | ||
405 | pub(crate) id: StructId, | ||
406 | } | ||
407 | |||
408 | impl Struct { | ||
409 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
410 | Module { id: self.id.lookup(db.upcast()).container.module(db.upcast()) } | ||
411 | } | ||
412 | |||
413 | pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> { | ||
414 | Some(self.module(db).krate()) | ||
415 | } | ||
416 | |||
417 | pub fn name(self, db: &dyn HirDatabase) -> Name { | ||
418 | db.struct_data(self.id).name.clone() | ||
419 | } | ||
420 | |||
421 | pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> { | ||
422 | db.struct_data(self.id) | ||
423 | .variant_data | ||
424 | .fields() | ||
425 | .iter() | ||
426 | .map(|(id, _)| Field { parent: self.into(), id }) | ||
427 | .collect() | ||
428 | } | ||
429 | |||
430 | pub fn ty(self, db: &dyn HirDatabase) -> Type { | ||
431 | Type::from_def(db, self.id.lookup(db.upcast()).container.module(db.upcast()).krate, self.id) | ||
432 | } | ||
433 | |||
434 | pub fn repr(self, db: &dyn HirDatabase) -> Option<ReprKind> { | ||
435 | db.struct_data(self.id).repr.clone() | ||
436 | } | ||
437 | |||
438 | fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> { | ||
439 | db.struct_data(self.id).variant_data.clone() | ||
440 | } | ||
441 | } | ||
442 | |||
443 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
444 | pub struct Union { | ||
445 | pub(crate) id: UnionId, | ||
446 | } | ||
447 | |||
448 | impl Union { | ||
449 | pub fn name(self, db: &dyn HirDatabase) -> Name { | ||
450 | db.union_data(self.id).name.clone() | ||
451 | } | ||
452 | |||
453 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
454 | Module { id: self.id.lookup(db.upcast()).container.module(db.upcast()) } | ||
455 | } | ||
456 | |||
457 | pub fn ty(self, db: &dyn HirDatabase) -> Type { | ||
458 | Type::from_def(db, self.id.lookup(db.upcast()).container.module(db.upcast()).krate, self.id) | ||
459 | } | ||
460 | |||
461 | pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> { | ||
462 | db.union_data(self.id) | ||
463 | .variant_data | ||
464 | .fields() | ||
465 | .iter() | ||
466 | .map(|(id, _)| Field { parent: self.into(), id }) | ||
467 | .collect() | ||
468 | } | ||
469 | |||
470 | fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> { | ||
471 | db.union_data(self.id).variant_data.clone() | ||
472 | } | ||
473 | } | ||
474 | |||
475 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
476 | pub struct Enum { | ||
477 | pub(crate) id: EnumId, | ||
478 | } | ||
479 | |||
480 | impl Enum { | ||
481 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
482 | Module { id: self.id.lookup(db.upcast()).container.module(db.upcast()) } | ||
483 | } | ||
484 | |||
485 | pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> { | ||
486 | Some(self.module(db).krate()) | ||
487 | } | ||
488 | |||
489 | pub fn name(self, db: &dyn HirDatabase) -> Name { | ||
490 | db.enum_data(self.id).name.clone() | ||
491 | } | ||
492 | |||
493 | pub fn variants(self, db: &dyn HirDatabase) -> Vec<EnumVariant> { | ||
494 | db.enum_data(self.id) | ||
495 | .variants | ||
496 | .iter() | ||
497 | .map(|(id, _)| EnumVariant { parent: self, id }) | ||
498 | .collect() | ||
499 | } | ||
500 | |||
501 | pub fn ty(self, db: &dyn HirDatabase) -> Type { | ||
502 | Type::from_def(db, self.id.lookup(db.upcast()).container.module(db.upcast()).krate, self.id) | ||
503 | } | ||
504 | } | ||
505 | |||
506 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
507 | pub struct EnumVariant { | ||
508 | pub(crate) parent: Enum, | ||
509 | pub(crate) id: LocalEnumVariantId, | ||
510 | } | ||
511 | |||
512 | impl EnumVariant { | ||
513 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
514 | self.parent.module(db) | ||
515 | } | ||
516 | pub fn parent_enum(self, _db: &dyn HirDatabase) -> Enum { | ||
517 | self.parent | ||
518 | } | ||
519 | |||
520 | pub fn name(self, db: &dyn HirDatabase) -> Name { | ||
521 | db.enum_data(self.parent.id).variants[self.id].name.clone() | ||
522 | } | ||
523 | |||
524 | pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> { | ||
525 | self.variant_data(db) | ||
526 | .fields() | ||
527 | .iter() | ||
528 | .map(|(id, _)| Field { parent: self.into(), id }) | ||
529 | .collect() | ||
530 | } | ||
531 | |||
532 | pub fn kind(self, db: &dyn HirDatabase) -> StructKind { | ||
533 | self.variant_data(db).kind() | ||
534 | } | ||
535 | |||
536 | pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> { | ||
537 | db.enum_data(self.parent.id).variants[self.id].variant_data.clone() | ||
538 | } | ||
539 | } | ||
540 | |||
541 | /// A Data Type | ||
542 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] | ||
543 | pub enum Adt { | ||
544 | Struct(Struct), | ||
545 | Union(Union), | ||
546 | Enum(Enum), | ||
547 | } | ||
548 | impl_from!(Struct, Union, Enum for Adt); | ||
549 | |||
550 | impl Adt { | ||
551 | pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool { | ||
552 | let subst = db.generic_defaults(self.into()); | ||
553 | subst.iter().any(|ty| &ty.value == &Ty::Unknown) | ||
554 | } | ||
555 | |||
556 | /// Turns this ADT into a type. Any type parameters of the ADT will be | ||
557 | /// turned into unknown types, which is good for e.g. finding the most | ||
558 | /// general set of completions, but will not look very nice when printed. | ||
559 | pub fn ty(self, db: &dyn HirDatabase) -> Type { | ||
560 | let id = AdtId::from(self); | ||
561 | Type::from_def(db, id.module(db.upcast()).krate, id) | ||
562 | } | ||
563 | |||
564 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
565 | match self { | ||
566 | Adt::Struct(s) => s.module(db), | ||
567 | Adt::Union(s) => s.module(db), | ||
568 | Adt::Enum(e) => e.module(db), | ||
569 | } | ||
570 | } | ||
571 | |||
572 | pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> { | ||
573 | Some(self.module(db).krate()) | ||
574 | } | ||
575 | |||
576 | pub fn name(self, db: &dyn HirDatabase) -> Name { | ||
577 | match self { | ||
578 | Adt::Struct(s) => s.name(db), | ||
579 | Adt::Union(u) => u.name(db), | ||
580 | Adt::Enum(e) => e.name(db), | ||
581 | } | ||
582 | } | ||
583 | } | ||
584 | |||
585 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] | ||
586 | pub enum VariantDef { | ||
587 | Struct(Struct), | ||
588 | Union(Union), | ||
589 | EnumVariant(EnumVariant), | ||
590 | } | ||
591 | impl_from!(Struct, Union, EnumVariant for VariantDef); | ||
592 | |||
593 | impl VariantDef { | ||
594 | pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> { | ||
595 | match self { | ||
596 | VariantDef::Struct(it) => it.fields(db), | ||
597 | VariantDef::Union(it) => it.fields(db), | ||
598 | VariantDef::EnumVariant(it) => it.fields(db), | ||
599 | } | ||
600 | } | ||
601 | |||
602 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
603 | match self { | ||
604 | VariantDef::Struct(it) => it.module(db), | ||
605 | VariantDef::Union(it) => it.module(db), | ||
606 | VariantDef::EnumVariant(it) => it.module(db), | ||
607 | } | ||
608 | } | ||
609 | |||
610 | pub fn name(&self, db: &dyn HirDatabase) -> Name { | ||
611 | match self { | ||
612 | VariantDef::Struct(s) => s.name(db), | ||
613 | VariantDef::Union(u) => u.name(db), | ||
614 | VariantDef::EnumVariant(e) => e.name(db), | ||
615 | } | ||
616 | } | ||
617 | |||
618 | pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> { | ||
619 | match self { | ||
620 | VariantDef::Struct(it) => it.variant_data(db), | ||
621 | VariantDef::Union(it) => it.variant_data(db), | ||
622 | VariantDef::EnumVariant(it) => it.variant_data(db), | ||
623 | } | ||
624 | } | ||
625 | } | ||
626 | |||
627 | /// The defs which have a body. | ||
628 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
629 | pub enum DefWithBody { | ||
630 | Function(Function), | ||
631 | Static(Static), | ||
632 | Const(Const), | ||
633 | } | ||
634 | impl_from!(Function, Const, Static for DefWithBody); | ||
635 | |||
636 | impl DefWithBody { | ||
637 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
638 | match self { | ||
639 | DefWithBody::Const(c) => c.module(db), | ||
640 | DefWithBody::Function(f) => f.module(db), | ||
641 | DefWithBody::Static(s) => s.module(db), | ||
642 | } | ||
643 | } | ||
644 | |||
645 | pub fn name(self, db: &dyn HirDatabase) -> Option<Name> { | ||
646 | match self { | ||
647 | DefWithBody::Function(f) => Some(f.name(db)), | ||
648 | DefWithBody::Static(s) => s.name(db), | ||
649 | DefWithBody::Const(c) => c.name(db), | ||
650 | } | ||
651 | } | ||
652 | } | ||
653 | |||
654 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
655 | pub struct Function { | ||
656 | pub(crate) id: FunctionId, | ||
657 | } | ||
658 | |||
659 | impl Function { | ||
660 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
661 | self.id.lookup(db.upcast()).module(db.upcast()).into() | ||
662 | } | ||
663 | |||
664 | pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> { | ||
665 | Some(self.module(db).krate()) | ||
666 | } | ||
667 | |||
668 | pub fn name(self, db: &dyn HirDatabase) -> Name { | ||
669 | db.function_data(self.id).name.clone() | ||
670 | } | ||
671 | |||
672 | pub fn has_self_param(self, db: &dyn HirDatabase) -> bool { | ||
673 | db.function_data(self.id).has_self_param | ||
674 | } | ||
675 | |||
676 | pub fn params(self, db: &dyn HirDatabase) -> Vec<TypeRef> { | ||
677 | db.function_data(self.id).params.clone() | ||
678 | } | ||
679 | |||
680 | pub fn is_unsafe(self, db: &dyn HirDatabase) -> bool { | ||
681 | db.function_data(self.id).is_unsafe | ||
682 | } | ||
683 | |||
684 | pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) { | ||
685 | hir_ty::diagnostics::validate_body(db, self.id.into(), sink) | ||
686 | } | ||
687 | } | ||
688 | |||
689 | impl HasVisibility for Function { | ||
690 | fn visibility(&self, db: &dyn HirDatabase) -> Visibility { | ||
691 | let function_data = db.function_data(self.id); | ||
692 | let visibility = &function_data.visibility; | ||
693 | visibility.resolve(db.upcast(), &self.id.resolver(db.upcast())) | ||
694 | } | ||
695 | } | ||
696 | |||
697 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
698 | pub struct Const { | ||
699 | pub(crate) id: ConstId, | ||
700 | } | ||
701 | |||
702 | impl Const { | ||
703 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
704 | Module { id: self.id.lookup(db.upcast()).module(db.upcast()) } | ||
705 | } | ||
706 | |||
707 | pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> { | ||
708 | Some(self.module(db).krate()) | ||
709 | } | ||
710 | |||
711 | pub fn name(self, db: &dyn HirDatabase) -> Option<Name> { | ||
712 | db.const_data(self.id).name.clone() | ||
713 | } | ||
714 | } | ||
715 | |||
716 | impl HasVisibility for Const { | ||
717 | fn visibility(&self, db: &dyn HirDatabase) -> Visibility { | ||
718 | let function_data = db.const_data(self.id); | ||
719 | let visibility = &function_data.visibility; | ||
720 | visibility.resolve(db.upcast(), &self.id.resolver(db.upcast())) | ||
721 | } | ||
722 | } | ||
723 | |||
724 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
725 | pub struct Static { | ||
726 | pub(crate) id: StaticId, | ||
727 | } | ||
728 | |||
729 | impl Static { | ||
730 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
731 | Module { id: self.id.lookup(db.upcast()).module(db.upcast()) } | ||
732 | } | ||
733 | |||
734 | pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> { | ||
735 | Some(self.module(db).krate()) | ||
736 | } | ||
737 | |||
738 | pub fn name(self, db: &dyn HirDatabase) -> Option<Name> { | ||
739 | db.static_data(self.id).name.clone() | ||
740 | } | ||
741 | |||
742 | pub fn is_mut(self, db: &dyn HirDatabase) -> bool { | ||
743 | db.static_data(self.id).mutable | ||
744 | } | ||
745 | } | ||
746 | |||
747 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
748 | pub struct Trait { | ||
749 | pub(crate) id: TraitId, | ||
750 | } | ||
751 | |||
752 | impl Trait { | ||
753 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
754 | Module { id: self.id.lookup(db.upcast()).container.module(db.upcast()) } | ||
755 | } | ||
756 | |||
757 | pub fn name(self, db: &dyn HirDatabase) -> Name { | ||
758 | db.trait_data(self.id).name.clone() | ||
759 | } | ||
760 | |||
761 | pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> { | ||
762 | db.trait_data(self.id).items.iter().map(|(_name, it)| (*it).into()).collect() | ||
763 | } | ||
764 | |||
765 | pub fn is_auto(self, db: &dyn HirDatabase) -> bool { | ||
766 | db.trait_data(self.id).auto | ||
767 | } | ||
768 | } | ||
769 | |||
770 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
771 | pub struct TypeAlias { | ||
772 | pub(crate) id: TypeAliasId, | ||
773 | } | ||
774 | |||
775 | impl TypeAlias { | ||
776 | pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool { | ||
777 | let subst = db.generic_defaults(self.id.into()); | ||
778 | subst.iter().any(|ty| &ty.value == &Ty::Unknown) | ||
779 | } | ||
780 | |||
781 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
782 | Module { id: self.id.lookup(db.upcast()).module(db.upcast()) } | ||
783 | } | ||
784 | |||
785 | pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> { | ||
786 | Some(self.module(db).krate()) | ||
787 | } | ||
788 | |||
789 | pub fn type_ref(self, db: &dyn HirDatabase) -> Option<TypeRef> { | ||
790 | db.type_alias_data(self.id).type_ref.clone() | ||
791 | } | ||
792 | |||
793 | pub fn ty(self, db: &dyn HirDatabase) -> Type { | ||
794 | Type::from_def(db, self.id.lookup(db.upcast()).module(db.upcast()).krate, self.id) | ||
795 | } | ||
796 | |||
797 | pub fn name(self, db: &dyn HirDatabase) -> Name { | ||
798 | db.type_alias_data(self.id).name.clone() | ||
799 | } | ||
800 | } | ||
801 | |||
802 | impl HasVisibility for TypeAlias { | ||
803 | fn visibility(&self, db: &dyn HirDatabase) -> Visibility { | ||
804 | let function_data = db.type_alias_data(self.id); | ||
805 | let visibility = &function_data.visibility; | ||
806 | visibility.resolve(db.upcast(), &self.id.resolver(db.upcast())) | ||
807 | } | ||
808 | } | ||
809 | |||
810 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
811 | pub struct MacroDef { | ||
812 | pub(crate) id: MacroDefId, | ||
813 | } | ||
814 | |||
815 | impl MacroDef { | ||
816 | /// FIXME: right now, this just returns the root module of the crate that | ||
817 | /// defines this macro. The reasons for this is that macros are expanded | ||
818 | /// early, in `hir_expand`, where modules simply do not exist yet. | ||
819 | pub fn module(self, db: &dyn HirDatabase) -> Option<Module> { | ||
820 | let krate = self.id.krate?; | ||
821 | let module_id = db.crate_def_map(krate).root; | ||
822 | Some(Module::new(Crate { id: krate }, module_id)) | ||
823 | } | ||
824 | |||
825 | /// XXX: this parses the file | ||
826 | pub fn name(self, db: &dyn HirDatabase) -> Option<Name> { | ||
827 | self.source(db).value.name().map(|it| it.as_name()) | ||
828 | } | ||
829 | |||
830 | /// Indicate it is a proc-macro | ||
831 | pub fn is_proc_macro(&self) -> bool { | ||
832 | matches!(self.id.kind, MacroDefKind::CustomDerive(_)) | ||
833 | } | ||
834 | |||
835 | /// Indicate it is a derive macro | ||
836 | pub fn is_derive_macro(&self) -> bool { | ||
837 | matches!(self.id.kind, MacroDefKind::CustomDerive(_) | MacroDefKind::BuiltInDerive(_)) | ||
838 | } | ||
839 | } | ||
840 | |||
841 | /// Invariant: `inner.as_assoc_item(db).is_some()` | ||
842 | /// We do not actively enforce this invariant. | ||
843 | #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] | ||
844 | pub enum AssocItem { | ||
845 | Function(Function), | ||
846 | Const(Const), | ||
847 | TypeAlias(TypeAlias), | ||
848 | } | ||
849 | pub enum AssocItemContainer { | ||
850 | Trait(Trait), | ||
851 | ImplDef(ImplDef), | ||
852 | } | ||
853 | pub trait AsAssocItem { | ||
854 | fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem>; | ||
855 | } | ||
856 | |||
857 | impl AsAssocItem for Function { | ||
858 | fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> { | ||
859 | as_assoc_item(db, AssocItem::Function, self.id) | ||
860 | } | ||
861 | } | ||
862 | impl AsAssocItem for Const { | ||
863 | fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> { | ||
864 | as_assoc_item(db, AssocItem::Const, self.id) | ||
865 | } | ||
866 | } | ||
867 | impl AsAssocItem for TypeAlias { | ||
868 | fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> { | ||
869 | as_assoc_item(db, AssocItem::TypeAlias, self.id) | ||
870 | } | ||
871 | } | ||
872 | fn as_assoc_item<ID, DEF, CTOR, AST>(db: &dyn HirDatabase, ctor: CTOR, id: ID) -> Option<AssocItem> | ||
873 | where | ||
874 | ID: Lookup<Data = AssocItemLoc<AST>>, | ||
875 | DEF: From<ID>, | ||
876 | CTOR: FnOnce(DEF) -> AssocItem, | ||
877 | AST: ItemTreeNode, | ||
878 | { | ||
879 | match id.lookup(db.upcast()).container { | ||
880 | AssocContainerId::TraitId(_) | AssocContainerId::ImplId(_) => Some(ctor(DEF::from(id))), | ||
881 | AssocContainerId::ContainerId(_) => None, | ||
882 | } | ||
883 | } | ||
884 | |||
885 | impl AssocItem { | ||
886 | pub fn name(self, db: &dyn HirDatabase) -> Option<Name> { | ||
887 | match self { | ||
888 | AssocItem::Function(it) => Some(it.name(db)), | ||
889 | AssocItem::Const(it) => it.name(db), | ||
890 | AssocItem::TypeAlias(it) => Some(it.name(db)), | ||
891 | } | ||
892 | } | ||
893 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
894 | match self { | ||
895 | AssocItem::Function(f) => f.module(db), | ||
896 | AssocItem::Const(c) => c.module(db), | ||
897 | AssocItem::TypeAlias(t) => t.module(db), | ||
898 | } | ||
899 | } | ||
900 | pub fn container(self, db: &dyn HirDatabase) -> AssocItemContainer { | ||
901 | let container = match self { | ||
902 | AssocItem::Function(it) => it.id.lookup(db.upcast()).container, | ||
903 | AssocItem::Const(it) => it.id.lookup(db.upcast()).container, | ||
904 | AssocItem::TypeAlias(it) => it.id.lookup(db.upcast()).container, | ||
905 | }; | ||
906 | match container { | ||
907 | AssocContainerId::TraitId(id) => AssocItemContainer::Trait(id.into()), | ||
908 | AssocContainerId::ImplId(id) => AssocItemContainer::ImplDef(id.into()), | ||
909 | AssocContainerId::ContainerId(_) => panic!("invalid AssocItem"), | ||
910 | } | ||
911 | } | ||
912 | } | ||
913 | |||
914 | impl HasVisibility for AssocItem { | ||
915 | fn visibility(&self, db: &dyn HirDatabase) -> Visibility { | ||
916 | match self { | ||
917 | AssocItem::Function(f) => f.visibility(db), | ||
918 | AssocItem::Const(c) => c.visibility(db), | ||
919 | AssocItem::TypeAlias(t) => t.visibility(db), | ||
920 | } | ||
921 | } | ||
922 | } | ||
923 | |||
924 | #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] | ||
925 | pub enum GenericDef { | ||
926 | Function(Function), | ||
927 | Adt(Adt), | ||
928 | Trait(Trait), | ||
929 | TypeAlias(TypeAlias), | ||
930 | ImplDef(ImplDef), | ||
931 | // enum variants cannot have generics themselves, but their parent enums | ||
932 | // can, and this makes some code easier to write | ||
933 | EnumVariant(EnumVariant), | ||
934 | // consts can have type parameters from their parents (i.e. associated consts of traits) | ||
935 | Const(Const), | ||
936 | } | ||
937 | impl_from!( | ||
938 | Function, | ||
939 | Adt(Struct, Enum, Union), | ||
940 | Trait, | ||
941 | TypeAlias, | ||
942 | ImplDef, | ||
943 | EnumVariant, | ||
944 | Const | ||
945 | for GenericDef | ||
946 | ); | ||
947 | |||
948 | impl GenericDef { | ||
949 | pub fn params(self, db: &dyn HirDatabase) -> Vec<TypeParam> { | ||
950 | let generics: Arc<hir_def::generics::GenericParams> = db.generic_params(self.into()); | ||
951 | generics | ||
952 | .types | ||
953 | .iter() | ||
954 | .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } }) | ||
955 | .collect() | ||
956 | } | ||
957 | } | ||
958 | |||
959 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] | ||
960 | pub struct Local { | ||
961 | pub(crate) parent: DefWithBodyId, | ||
962 | pub(crate) pat_id: PatId, | ||
963 | } | ||
964 | |||
965 | impl Local { | ||
966 | pub fn is_param(self, db: &dyn HirDatabase) -> bool { | ||
967 | let src = self.source(db); | ||
968 | match src.value { | ||
969 | Either::Left(bind_pat) => { | ||
970 | bind_pat.syntax().ancestors().any(|it| ast::Param::can_cast(it.kind())) | ||
971 | } | ||
972 | Either::Right(_self_param) => true, | ||
973 | } | ||
974 | } | ||
975 | |||
976 | // FIXME: why is this an option? It shouldn't be? | ||
977 | pub fn name(self, db: &dyn HirDatabase) -> Option<Name> { | ||
978 | let body = db.body(self.parent.into()); | ||
979 | match &body[self.pat_id] { | ||
980 | Pat::Bind { name, .. } => Some(name.clone()), | ||
981 | _ => None, | ||
982 | } | ||
983 | } | ||
984 | |||
985 | pub fn is_self(self, db: &dyn HirDatabase) -> bool { | ||
986 | self.name(db) == Some(name![self]) | ||
987 | } | ||
988 | |||
989 | pub fn is_mut(self, db: &dyn HirDatabase) -> bool { | ||
990 | let body = db.body(self.parent.into()); | ||
991 | match &body[self.pat_id] { | ||
992 | Pat::Bind { mode, .. } => match mode { | ||
993 | BindingAnnotation::Mutable | BindingAnnotation::RefMut => true, | ||
994 | _ => false, | ||
995 | }, | ||
996 | _ => false, | ||
997 | } | ||
998 | } | ||
999 | |||
1000 | pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody { | ||
1001 | self.parent.into() | ||
1002 | } | ||
1003 | |||
1004 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
1005 | self.parent(db).module(db) | ||
1006 | } | ||
1007 | |||
1008 | pub fn ty(self, db: &dyn HirDatabase) -> Type { | ||
1009 | let def = DefWithBodyId::from(self.parent); | ||
1010 | let infer = db.infer(def); | ||
1011 | let ty = infer[self.pat_id].clone(); | ||
1012 | let krate = def.module(db.upcast()).krate; | ||
1013 | Type::new(db, krate, def, ty) | ||
1014 | } | ||
1015 | |||
1016 | pub fn source(self, db: &dyn HirDatabase) -> InFile<Either<ast::IdentPat, ast::SelfParam>> { | ||
1017 | let (_body, source_map) = db.body_with_source_map(self.parent.into()); | ||
1018 | let src = source_map.pat_syntax(self.pat_id).unwrap(); // Hmm... | ||
1019 | let root = src.file_syntax(db.upcast()); | ||
1020 | src.map(|ast| { | ||
1021 | ast.map_left(|it| it.cast().unwrap().to_node(&root)).map_right(|it| it.to_node(&root)) | ||
1022 | }) | ||
1023 | } | ||
1024 | } | ||
1025 | |||
1026 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] | ||
1027 | pub struct TypeParam { | ||
1028 | pub(crate) id: TypeParamId, | ||
1029 | } | ||
1030 | |||
1031 | impl TypeParam { | ||
1032 | pub fn name(self, db: &dyn HirDatabase) -> Name { | ||
1033 | let params = db.generic_params(self.id.parent); | ||
1034 | params.types[self.id.local_id].name.clone().unwrap_or_else(Name::missing) | ||
1035 | } | ||
1036 | |||
1037 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
1038 | self.id.parent.module(db.upcast()).into() | ||
1039 | } | ||
1040 | |||
1041 | pub fn ty(self, db: &dyn HirDatabase) -> Type { | ||
1042 | let resolver = self.id.parent.resolver(db.upcast()); | ||
1043 | let environment = TraitEnvironment::lower(db, &resolver); | ||
1044 | let ty = Ty::Placeholder(self.id); | ||
1045 | Type { | ||
1046 | krate: self.id.parent.module(db.upcast()).krate, | ||
1047 | ty: InEnvironment { value: ty, environment }, | ||
1048 | } | ||
1049 | } | ||
1050 | |||
1051 | pub fn default(self, db: &dyn HirDatabase) -> Option<Type> { | ||
1052 | let params = db.generic_defaults(self.id.parent); | ||
1053 | let local_idx = hir_ty::param_idx(db, self.id)?; | ||
1054 | let resolver = self.id.parent.resolver(db.upcast()); | ||
1055 | let environment = TraitEnvironment::lower(db, &resolver); | ||
1056 | let ty = params.get(local_idx)?.clone(); | ||
1057 | let subst = Substs::type_params(db, self.id.parent); | ||
1058 | let ty = ty.subst(&subst.prefix(local_idx)); | ||
1059 | Some(Type { | ||
1060 | krate: self.id.parent.module(db.upcast()).krate, | ||
1061 | ty: InEnvironment { value: ty, environment }, | ||
1062 | }) | ||
1063 | } | ||
1064 | } | ||
1065 | |||
1066 | // FIXME: rename from `ImplDef` to `Impl` | ||
1067 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
1068 | pub struct ImplDef { | ||
1069 | pub(crate) id: ImplId, | ||
1070 | } | ||
1071 | |||
1072 | impl ImplDef { | ||
1073 | pub fn all_in_crate(db: &dyn HirDatabase, krate: Crate) -> Vec<ImplDef> { | ||
1074 | let inherent = db.inherent_impls_in_crate(krate.id); | ||
1075 | let trait_ = db.trait_impls_in_crate(krate.id); | ||
1076 | |||
1077 | inherent.all_impls().chain(trait_.all_impls()).map(Self::from).collect() | ||
1078 | } | ||
1079 | pub fn for_trait(db: &dyn HirDatabase, krate: Crate, trait_: Trait) -> Vec<ImplDef> { | ||
1080 | let impls = db.trait_impls_in_crate(krate.id); | ||
1081 | impls.for_trait(trait_.id).map(Self::from).collect() | ||
1082 | } | ||
1083 | |||
1084 | pub fn target_trait(self, db: &dyn HirDatabase) -> Option<TypeRef> { | ||
1085 | db.impl_data(self.id).target_trait.clone() | ||
1086 | } | ||
1087 | |||
1088 | pub fn target_type(self, db: &dyn HirDatabase) -> TypeRef { | ||
1089 | db.impl_data(self.id).target_type.clone() | ||
1090 | } | ||
1091 | |||
1092 | pub fn target_ty(self, db: &dyn HirDatabase) -> Type { | ||
1093 | let impl_data = db.impl_data(self.id); | ||
1094 | let resolver = self.id.resolver(db.upcast()); | ||
1095 | let ctx = hir_ty::TyLoweringContext::new(db, &resolver); | ||
1096 | let environment = TraitEnvironment::lower(db, &resolver); | ||
1097 | let ty = Ty::from_hir(&ctx, &impl_data.target_type); | ||
1098 | Type { | ||
1099 | krate: self.id.lookup(db.upcast()).container.module(db.upcast()).krate, | ||
1100 | ty: InEnvironment { value: ty, environment }, | ||
1101 | } | ||
1102 | } | ||
1103 | |||
1104 | pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> { | ||
1105 | db.impl_data(self.id).items.iter().map(|it| (*it).into()).collect() | ||
1106 | } | ||
1107 | |||
1108 | pub fn is_negative(self, db: &dyn HirDatabase) -> bool { | ||
1109 | db.impl_data(self.id).is_negative | ||
1110 | } | ||
1111 | |||
1112 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
1113 | self.id.lookup(db.upcast()).container.module(db.upcast()).into() | ||
1114 | } | ||
1115 | |||
1116 | pub fn krate(self, db: &dyn HirDatabase) -> Crate { | ||
1117 | Crate { id: self.module(db).id.krate } | ||
1118 | } | ||
1119 | |||
1120 | pub fn is_builtin_derive(self, db: &dyn HirDatabase) -> Option<InFile<ast::Attr>> { | ||
1121 | let src = self.source(db); | ||
1122 | let item = src.file_id.is_builtin_derive(db.upcast())?; | ||
1123 | let hygenic = hir_expand::hygiene::Hygiene::new(db.upcast(), item.file_id); | ||
1124 | |||
1125 | let attr = item | ||
1126 | .value | ||
1127 | .attrs() | ||
1128 | .filter_map(|it| { | ||
1129 | let path = hir_def::path::ModPath::from_src(it.path()?, &hygenic)?; | ||
1130 | if path.as_ident()?.to_string() == "derive" { | ||
1131 | Some(it) | ||
1132 | } else { | ||
1133 | None | ||
1134 | } | ||
1135 | }) | ||
1136 | .last()?; | ||
1137 | |||
1138 | Some(item.with_value(attr)) | ||
1139 | } | ||
1140 | } | ||
1141 | |||
1142 | #[derive(Clone, PartialEq, Eq, Debug)] | ||
1143 | pub struct Type { | ||
1144 | krate: CrateId, | ||
1145 | ty: InEnvironment<Ty>, | ||
1146 | } | ||
1147 | |||
1148 | impl Type { | ||
1149 | pub(crate) fn new_with_resolver( | ||
1150 | db: &dyn HirDatabase, | ||
1151 | resolver: &Resolver, | ||
1152 | ty: Ty, | ||
1153 | ) -> Option<Type> { | ||
1154 | let krate = resolver.krate()?; | ||
1155 | Some(Type::new_with_resolver_inner(db, krate, resolver, ty)) | ||
1156 | } | ||
1157 | pub(crate) fn new_with_resolver_inner( | ||
1158 | db: &dyn HirDatabase, | ||
1159 | krate: CrateId, | ||
1160 | resolver: &Resolver, | ||
1161 | ty: Ty, | ||
1162 | ) -> Type { | ||
1163 | let environment = TraitEnvironment::lower(db, &resolver); | ||
1164 | Type { krate, ty: InEnvironment { value: ty, environment } } | ||
1165 | } | ||
1166 | |||
1167 | fn new(db: &dyn HirDatabase, krate: CrateId, lexical_env: impl HasResolver, ty: Ty) -> Type { | ||
1168 | let resolver = lexical_env.resolver(db.upcast()); | ||
1169 | let environment = TraitEnvironment::lower(db, &resolver); | ||
1170 | Type { krate, ty: InEnvironment { value: ty, environment } } | ||
1171 | } | ||
1172 | |||
1173 | fn from_def( | ||
1174 | db: &dyn HirDatabase, | ||
1175 | krate: CrateId, | ||
1176 | def: impl HasResolver + Into<TyDefId> + Into<GenericDefId>, | ||
1177 | ) -> Type { | ||
1178 | let substs = Substs::build_for_def(db, def).fill_with_unknown().build(); | ||
1179 | let ty = db.ty(def.into()).subst(&substs); | ||
1180 | Type::new(db, krate, def, ty) | ||
1181 | } | ||
1182 | |||
1183 | pub fn is_unit(&self) -> bool { | ||
1184 | matches!( | ||
1185 | self.ty.value, | ||
1186 | Ty::Apply(ApplicationTy { ctor: TypeCtor::Tuple { cardinality: 0 }, .. }) | ||
1187 | ) | ||
1188 | } | ||
1189 | pub fn is_bool(&self) -> bool { | ||
1190 | matches!(self.ty.value, Ty::Apply(ApplicationTy { ctor: TypeCtor::Bool, .. })) | ||
1191 | } | ||
1192 | |||
1193 | pub fn is_mutable_reference(&self) -> bool { | ||
1194 | matches!( | ||
1195 | self.ty.value, | ||
1196 | Ty::Apply(ApplicationTy { ctor: TypeCtor::Ref(Mutability::Mut), .. }) | ||
1197 | ) | ||
1198 | } | ||
1199 | |||
1200 | pub fn is_unknown(&self) -> bool { | ||
1201 | matches!(self.ty.value, Ty::Unknown) | ||
1202 | } | ||
1203 | |||
1204 | /// Checks that particular type `ty` implements `std::future::Future`. | ||
1205 | /// This function is used in `.await` syntax completion. | ||
1206 | pub fn impls_future(&self, db: &dyn HirDatabase) -> bool { | ||
1207 | let krate = self.krate; | ||
1208 | |||
1209 | let std_future_trait = | ||
1210 | db.lang_item(krate, "future_trait".into()).and_then(|it| it.as_trait()); | ||
1211 | let std_future_trait = match std_future_trait { | ||
1212 | Some(it) => it, | ||
1213 | None => return false, | ||
1214 | }; | ||
1215 | |||
1216 | let canonical_ty = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) }; | ||
1217 | method_resolution::implements_trait( | ||
1218 | &canonical_ty, | ||
1219 | db, | ||
1220 | self.ty.environment.clone(), | ||
1221 | krate, | ||
1222 | std_future_trait, | ||
1223 | ) | ||
1224 | } | ||
1225 | |||
1226 | pub fn impls_trait(&self, db: &dyn HirDatabase, trait_: Trait, args: &[Type]) -> bool { | ||
1227 | let trait_ref = hir_ty::TraitRef { | ||
1228 | trait_: trait_.id, | ||
1229 | substs: Substs::build_for_def(db, trait_.id) | ||
1230 | .push(self.ty.value.clone()) | ||
1231 | .fill(args.iter().map(|t| t.ty.value.clone())) | ||
1232 | .build(), | ||
1233 | }; | ||
1234 | |||
1235 | let goal = Canonical { | ||
1236 | value: hir_ty::InEnvironment::new( | ||
1237 | self.ty.environment.clone(), | ||
1238 | hir_ty::Obligation::Trait(trait_ref), | ||
1239 | ), | ||
1240 | kinds: Arc::new([]), | ||
1241 | }; | ||
1242 | |||
1243 | db.trait_solve(self.krate, goal).is_some() | ||
1244 | } | ||
1245 | |||
1246 | pub fn as_callable(&self, db: &dyn HirDatabase) -> Option<Callable> { | ||
1247 | let def = match self.ty.value { | ||
1248 | Ty::Apply(ApplicationTy { ctor: TypeCtor::FnDef(def), parameters: _ }) => Some(def), | ||
1249 | _ => None, | ||
1250 | }; | ||
1251 | |||
1252 | let sig = self.ty.value.callable_sig(db)?; | ||
1253 | Some(Callable { ty: self.clone(), sig, def, is_bound_method: false }) | ||
1254 | } | ||
1255 | |||
1256 | pub fn is_closure(&self) -> bool { | ||
1257 | matches!(&self.ty.value, Ty::Apply(ApplicationTy { ctor: TypeCtor::Closure { .. }, .. })) | ||
1258 | } | ||
1259 | |||
1260 | pub fn is_fn(&self) -> bool { | ||
1261 | matches!(&self.ty.value, | ||
1262 | Ty::Apply(ApplicationTy { ctor: TypeCtor::FnDef(..), .. }) | | ||
1263 | Ty::Apply(ApplicationTy { ctor: TypeCtor::FnPtr { .. }, .. }) | ||
1264 | ) | ||
1265 | } | ||
1266 | |||
1267 | pub fn is_packed(&self, db: &dyn HirDatabase) -> bool { | ||
1268 | let adt_id = match self.ty.value { | ||
1269 | Ty::Apply(ApplicationTy { ctor: TypeCtor::Adt(adt_id), .. }) => adt_id, | ||
1270 | _ => return false, | ||
1271 | }; | ||
1272 | |||
1273 | let adt = adt_id.into(); | ||
1274 | match adt { | ||
1275 | Adt::Struct(s) => matches!(s.repr(db), Some(ReprKind::Packed)), | ||
1276 | _ => false, | ||
1277 | } | ||
1278 | } | ||
1279 | |||
1280 | pub fn is_raw_ptr(&self) -> bool { | ||
1281 | matches!(&self.ty.value, Ty::Apply(ApplicationTy { ctor: TypeCtor::RawPtr(..), .. })) | ||
1282 | } | ||
1283 | |||
1284 | pub fn contains_unknown(&self) -> bool { | ||
1285 | return go(&self.ty.value); | ||
1286 | |||
1287 | fn go(ty: &Ty) -> bool { | ||
1288 | match ty { | ||
1289 | Ty::Unknown => true, | ||
1290 | Ty::Apply(a_ty) => a_ty.parameters.iter().any(go), | ||
1291 | _ => false, | ||
1292 | } | ||
1293 | } | ||
1294 | } | ||
1295 | |||
1296 | pub fn fields(&self, db: &dyn HirDatabase) -> Vec<(Field, Type)> { | ||
1297 | if let Ty::Apply(a_ty) = &self.ty.value { | ||
1298 | let variant_id = match a_ty.ctor { | ||
1299 | TypeCtor::Adt(AdtId::StructId(s)) => s.into(), | ||
1300 | TypeCtor::Adt(AdtId::UnionId(u)) => u.into(), | ||
1301 | _ => return Vec::new(), | ||
1302 | }; | ||
1303 | |||
1304 | return db | ||
1305 | .field_types(variant_id) | ||
1306 | .iter() | ||
1307 | .map(|(local_id, ty)| { | ||
1308 | let def = Field { parent: variant_id.into(), id: local_id }; | ||
1309 | let ty = ty.clone().subst(&a_ty.parameters); | ||
1310 | (def, self.derived(ty)) | ||
1311 | }) | ||
1312 | .collect(); | ||
1313 | }; | ||
1314 | Vec::new() | ||
1315 | } | ||
1316 | |||
1317 | pub fn tuple_fields(&self, _db: &dyn HirDatabase) -> Vec<Type> { | ||
1318 | let mut res = Vec::new(); | ||
1319 | if let Ty::Apply(a_ty) = &self.ty.value { | ||
1320 | if let TypeCtor::Tuple { .. } = a_ty.ctor { | ||
1321 | for ty in a_ty.parameters.iter() { | ||
1322 | let ty = ty.clone(); | ||
1323 | res.push(self.derived(ty)); | ||
1324 | } | ||
1325 | } | ||
1326 | }; | ||
1327 | res | ||
1328 | } | ||
1329 | |||
1330 | pub fn autoderef<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Type> + 'a { | ||
1331 | // There should be no inference vars in types passed here | ||
1332 | // FIXME check that? | ||
1333 | let canonical = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) }; | ||
1334 | let environment = self.ty.environment.clone(); | ||
1335 | let ty = InEnvironment { value: canonical, environment }; | ||
1336 | autoderef(db, Some(self.krate), ty) | ||
1337 | .map(|canonical| canonical.value) | ||
1338 | .map(move |ty| self.derived(ty)) | ||
1339 | } | ||
1340 | |||
1341 | // This would be nicer if it just returned an iterator, but that runs into | ||
1342 | // lifetime problems, because we need to borrow temp `CrateImplDefs`. | ||
1343 | pub fn iterate_assoc_items<T>( | ||
1344 | self, | ||
1345 | db: &dyn HirDatabase, | ||
1346 | krate: Crate, | ||
1347 | mut callback: impl FnMut(AssocItem) -> Option<T>, | ||
1348 | ) -> Option<T> { | ||
1349 | for krate in self.ty.value.def_crates(db, krate.id)? { | ||
1350 | let impls = db.inherent_impls_in_crate(krate); | ||
1351 | |||
1352 | for impl_def in impls.for_self_ty(&self.ty.value) { | ||
1353 | for &item in db.impl_data(*impl_def).items.iter() { | ||
1354 | if let Some(result) = callback(item.into()) { | ||
1355 | return Some(result); | ||
1356 | } | ||
1357 | } | ||
1358 | } | ||
1359 | } | ||
1360 | None | ||
1361 | } | ||
1362 | |||
1363 | pub fn iterate_method_candidates<T>( | ||
1364 | &self, | ||
1365 | db: &dyn HirDatabase, | ||
1366 | krate: Crate, | ||
1367 | traits_in_scope: &FxHashSet<TraitId>, | ||
1368 | name: Option<&Name>, | ||
1369 | mut callback: impl FnMut(&Ty, Function) -> Option<T>, | ||
1370 | ) -> Option<T> { | ||
1371 | // There should be no inference vars in types passed here | ||
1372 | // FIXME check that? | ||
1373 | // FIXME replace Unknown by bound vars here | ||
1374 | let canonical = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) }; | ||
1375 | |||
1376 | let env = self.ty.environment.clone(); | ||
1377 | let krate = krate.id; | ||
1378 | |||
1379 | method_resolution::iterate_method_candidates( | ||
1380 | &canonical, | ||
1381 | db, | ||
1382 | env, | ||
1383 | krate, | ||
1384 | traits_in_scope, | ||
1385 | name, | ||
1386 | method_resolution::LookupMode::MethodCall, | ||
1387 | |ty, it| match it { | ||
1388 | AssocItemId::FunctionId(f) => callback(ty, f.into()), | ||
1389 | _ => None, | ||
1390 | }, | ||
1391 | ) | ||
1392 | } | ||
1393 | |||
1394 | pub fn iterate_path_candidates<T>( | ||
1395 | &self, | ||
1396 | db: &dyn HirDatabase, | ||
1397 | krate: Crate, | ||
1398 | traits_in_scope: &FxHashSet<TraitId>, | ||
1399 | name: Option<&Name>, | ||
1400 | mut callback: impl FnMut(&Ty, AssocItem) -> Option<T>, | ||
1401 | ) -> Option<T> { | ||
1402 | // There should be no inference vars in types passed here | ||
1403 | // FIXME check that? | ||
1404 | // FIXME replace Unknown by bound vars here | ||
1405 | let canonical = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) }; | ||
1406 | |||
1407 | let env = self.ty.environment.clone(); | ||
1408 | let krate = krate.id; | ||
1409 | |||
1410 | method_resolution::iterate_method_candidates( | ||
1411 | &canonical, | ||
1412 | db, | ||
1413 | env, | ||
1414 | krate, | ||
1415 | traits_in_scope, | ||
1416 | name, | ||
1417 | method_resolution::LookupMode::Path, | ||
1418 | |ty, it| callback(ty, it.into()), | ||
1419 | ) | ||
1420 | } | ||
1421 | |||
1422 | pub fn as_adt(&self) -> Option<Adt> { | ||
1423 | let (adt, _subst) = self.ty.value.as_adt()?; | ||
1424 | Some(adt.into()) | ||
1425 | } | ||
1426 | |||
1427 | pub fn as_dyn_trait(&self) -> Option<Trait> { | ||
1428 | self.ty.value.dyn_trait().map(Into::into) | ||
1429 | } | ||
1430 | |||
1431 | pub fn as_impl_traits(&self, db: &dyn HirDatabase) -> Option<Vec<Trait>> { | ||
1432 | self.ty.value.impl_trait_bounds(db).map(|it| { | ||
1433 | it.into_iter() | ||
1434 | .filter_map(|pred| match pred { | ||
1435 | hir_ty::GenericPredicate::Implemented(trait_ref) => { | ||
1436 | Some(Trait::from(trait_ref.trait_)) | ||
1437 | } | ||
1438 | _ => None, | ||
1439 | }) | ||
1440 | .collect() | ||
1441 | }) | ||
1442 | } | ||
1443 | |||
1444 | pub fn as_associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<Trait> { | ||
1445 | self.ty.value.associated_type_parent_trait(db).map(Into::into) | ||
1446 | } | ||
1447 | |||
1448 | // FIXME: provide required accessors such that it becomes implementable from outside. | ||
1449 | pub fn is_equal_for_find_impls(&self, other: &Type) -> bool { | ||
1450 | match (&self.ty.value, &other.ty.value) { | ||
1451 | (Ty::Apply(a_original_ty), Ty::Apply(ApplicationTy { ctor, parameters })) => match ctor | ||
1452 | { | ||
1453 | TypeCtor::Ref(..) => match parameters.as_single() { | ||
1454 | Ty::Apply(a_ty) => a_original_ty.ctor == a_ty.ctor, | ||
1455 | _ => false, | ||
1456 | }, | ||
1457 | _ => a_original_ty.ctor == *ctor, | ||
1458 | }, | ||
1459 | _ => false, | ||
1460 | } | ||
1461 | } | ||
1462 | |||
1463 | fn derived(&self, ty: Ty) -> Type { | ||
1464 | Type { | ||
1465 | krate: self.krate, | ||
1466 | ty: InEnvironment { value: ty, environment: self.ty.environment.clone() }, | ||
1467 | } | ||
1468 | } | ||
1469 | |||
1470 | pub fn walk(&self, db: &dyn HirDatabase, mut cb: impl FnMut(Type)) { | ||
1471 | // TypeWalk::walk for a Ty at first visits parameters and only after that the Ty itself. | ||
1472 | // We need a different order here. | ||
1473 | |||
1474 | fn walk_substs( | ||
1475 | db: &dyn HirDatabase, | ||
1476 | type_: &Type, | ||
1477 | substs: &Substs, | ||
1478 | cb: &mut impl FnMut(Type), | ||
1479 | ) { | ||
1480 | for ty in substs.iter() { | ||
1481 | walk_type(db, &type_.derived(ty.clone()), cb); | ||
1482 | } | ||
1483 | } | ||
1484 | |||
1485 | fn walk_bounds( | ||
1486 | db: &dyn HirDatabase, | ||
1487 | type_: &Type, | ||
1488 | bounds: &[GenericPredicate], | ||
1489 | cb: &mut impl FnMut(Type), | ||
1490 | ) { | ||
1491 | for pred in bounds { | ||
1492 | match pred { | ||
1493 | GenericPredicate::Implemented(trait_ref) => { | ||
1494 | cb(type_.clone()); | ||
1495 | walk_substs(db, type_, &trait_ref.substs, cb); | ||
1496 | } | ||
1497 | _ => (), | ||
1498 | } | ||
1499 | } | ||
1500 | } | ||
1501 | |||
1502 | fn walk_type(db: &dyn HirDatabase, type_: &Type, cb: &mut impl FnMut(Type)) { | ||
1503 | let ty = type_.ty.value.strip_references(); | ||
1504 | match ty { | ||
1505 | Ty::Apply(ApplicationTy { ctor, parameters }) => { | ||
1506 | match ctor { | ||
1507 | TypeCtor::Adt(_) => { | ||
1508 | cb(type_.derived(ty.clone())); | ||
1509 | } | ||
1510 | TypeCtor::AssociatedType(_) => { | ||
1511 | if let Some(_) = ty.associated_type_parent_trait(db) { | ||
1512 | cb(type_.derived(ty.clone())); | ||
1513 | } | ||
1514 | } | ||
1515 | _ => (), | ||
1516 | } | ||
1517 | |||
1518 | // adt params, tuples, etc... | ||
1519 | walk_substs(db, type_, parameters, cb); | ||
1520 | } | ||
1521 | Ty::Opaque(opaque_ty) => { | ||
1522 | if let Some(bounds) = ty.impl_trait_bounds(db) { | ||
1523 | walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb); | ||
1524 | } | ||
1525 | |||
1526 | walk_substs(db, type_, &opaque_ty.parameters, cb); | ||
1527 | } | ||
1528 | Ty::Placeholder(_) => { | ||
1529 | if let Some(bounds) = ty.impl_trait_bounds(db) { | ||
1530 | walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb); | ||
1531 | } | ||
1532 | } | ||
1533 | Ty::Dyn(bounds) => { | ||
1534 | walk_bounds(db, &type_.derived(ty.clone()), bounds.as_ref(), cb); | ||
1535 | } | ||
1536 | |||
1537 | _ => (), | ||
1538 | } | ||
1539 | } | ||
1540 | |||
1541 | walk_type(db, self, &mut cb); | ||
1542 | } | ||
1543 | } | ||
1544 | |||
1545 | impl HirDisplay for Type { | ||
1546 | fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> { | ||
1547 | self.ty.value.hir_fmt(f) | ||
1548 | } | ||
1549 | } | ||
1550 | |||
1551 | // FIXME: closures | ||
1552 | #[derive(Debug)] | ||
1553 | pub struct Callable { | ||
1554 | ty: Type, | ||
1555 | sig: FnSig, | ||
1556 | def: Option<CallableDefId>, | ||
1557 | pub(crate) is_bound_method: bool, | ||
1558 | } | ||
1559 | |||
1560 | pub enum CallableKind { | ||
1561 | Function(Function), | ||
1562 | TupleStruct(Struct), | ||
1563 | TupleEnumVariant(EnumVariant), | ||
1564 | Closure, | ||
1565 | } | ||
1566 | |||
1567 | impl Callable { | ||
1568 | pub fn kind(&self) -> CallableKind { | ||
1569 | match self.def { | ||
1570 | Some(CallableDefId::FunctionId(it)) => CallableKind::Function(it.into()), | ||
1571 | Some(CallableDefId::StructId(it)) => CallableKind::TupleStruct(it.into()), | ||
1572 | Some(CallableDefId::EnumVariantId(it)) => CallableKind::TupleEnumVariant(it.into()), | ||
1573 | None => CallableKind::Closure, | ||
1574 | } | ||
1575 | } | ||
1576 | pub fn receiver_param(&self, db: &dyn HirDatabase) -> Option<ast::SelfParam> { | ||
1577 | let func = match self.def { | ||
1578 | Some(CallableDefId::FunctionId(it)) if self.is_bound_method => it, | ||
1579 | _ => return None, | ||
1580 | }; | ||
1581 | let src = func.lookup(db.upcast()).source(db.upcast()); | ||
1582 | let param_list = src.value.param_list()?; | ||
1583 | param_list.self_param() | ||
1584 | } | ||
1585 | pub fn n_params(&self) -> usize { | ||
1586 | self.sig.params().len() - if self.is_bound_method { 1 } else { 0 } | ||
1587 | } | ||
1588 | pub fn params( | ||
1589 | &self, | ||
1590 | db: &dyn HirDatabase, | ||
1591 | ) -> Vec<(Option<Either<ast::SelfParam, ast::Pat>>, Type)> { | ||
1592 | let types = self | ||
1593 | .sig | ||
1594 | .params() | ||
1595 | .iter() | ||
1596 | .skip(if self.is_bound_method { 1 } else { 0 }) | ||
1597 | .map(|ty| self.ty.derived(ty.clone())); | ||
1598 | let patterns = match self.def { | ||
1599 | Some(CallableDefId::FunctionId(func)) => { | ||
1600 | let src = func.lookup(db.upcast()).source(db.upcast()); | ||
1601 | src.value.param_list().map(|param_list| { | ||
1602 | param_list | ||
1603 | .self_param() | ||
1604 | .map(|it| Some(Either::Left(it))) | ||
1605 | .filter(|_| !self.is_bound_method) | ||
1606 | .into_iter() | ||
1607 | .chain(param_list.params().map(|it| it.pat().map(Either::Right))) | ||
1608 | }) | ||
1609 | } | ||
1610 | _ => None, | ||
1611 | }; | ||
1612 | patterns.into_iter().flatten().chain(iter::repeat(None)).zip(types).collect() | ||
1613 | } | ||
1614 | pub fn return_type(&self) -> Type { | ||
1615 | self.ty.derived(self.sig.ret().clone()) | ||
1616 | } | ||
1617 | } | ||
1618 | |||
1619 | /// For IDE only | ||
1620 | #[derive(Debug)] | ||
1621 | pub enum ScopeDef { | ||
1622 | ModuleDef(ModuleDef), | ||
1623 | MacroDef(MacroDef), | ||
1624 | GenericParam(TypeParam), | ||
1625 | ImplSelfType(ImplDef), | ||
1626 | AdtSelfType(Adt), | ||
1627 | Local(Local), | ||
1628 | Unknown, | ||
1629 | } | ||
1630 | |||
1631 | impl ScopeDef { | ||
1632 | pub fn all_items(def: PerNs) -> ArrayVec<[Self; 3]> { | ||
1633 | let mut items = ArrayVec::new(); | ||
1634 | |||
1635 | match (def.take_types(), def.take_values()) { | ||
1636 | (Some(m1), None) => items.push(ScopeDef::ModuleDef(m1.into())), | ||
1637 | (None, Some(m2)) => items.push(ScopeDef::ModuleDef(m2.into())), | ||
1638 | (Some(m1), Some(m2)) => { | ||
1639 | // Some items, like unit structs and enum variants, are | ||
1640 | // returned as both a type and a value. Here we want | ||
1641 | // to de-duplicate them. | ||
1642 | if m1 != m2 { | ||
1643 | items.push(ScopeDef::ModuleDef(m1.into())); | ||
1644 | items.push(ScopeDef::ModuleDef(m2.into())); | ||
1645 | } else { | ||
1646 | items.push(ScopeDef::ModuleDef(m1.into())); | ||
1647 | } | ||
1648 | } | ||
1649 | (None, None) => {} | ||
1650 | }; | ||
1651 | |||
1652 | if let Some(macro_def_id) = def.take_macros() { | ||
1653 | items.push(ScopeDef::MacroDef(macro_def_id.into())); | ||
1654 | } | ||
1655 | |||
1656 | if items.is_empty() { | ||
1657 | items.push(ScopeDef::Unknown); | ||
1658 | } | ||
1659 | |||
1660 | items | ||
1661 | } | ||
1662 | } | ||
1663 | |||
1664 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] | ||
1665 | pub enum AttrDef { | ||
1666 | Module(Module), | ||
1667 | Field(Field), | ||
1668 | Adt(Adt), | ||
1669 | Function(Function), | ||
1670 | EnumVariant(EnumVariant), | ||
1671 | Static(Static), | ||
1672 | Const(Const), | ||
1673 | Trait(Trait), | ||
1674 | TypeAlias(TypeAlias), | ||
1675 | MacroDef(MacroDef), | ||
1676 | } | ||
1677 | |||
1678 | impl_from!( | ||
1679 | Module, | ||
1680 | Field, | ||
1681 | Adt(Struct, Enum, Union), | ||
1682 | EnumVariant, | ||
1683 | Static, | ||
1684 | Const, | ||
1685 | Function, | ||
1686 | Trait, | ||
1687 | TypeAlias, | ||
1688 | MacroDef | ||
1689 | for AttrDef | ||
1690 | ); | ||
1691 | |||
1692 | pub trait HasAttrs { | ||
1693 | fn attrs(self, db: &dyn HirDatabase) -> Attrs; | ||
1694 | } | ||
1695 | |||
1696 | impl<T: Into<AttrDef>> HasAttrs for T { | ||
1697 | fn attrs(self, db: &dyn HirDatabase) -> Attrs { | ||
1698 | let def: AttrDef = self.into(); | ||
1699 | db.attrs(def.into()) | ||
1700 | } | ||
1701 | } | ||
1702 | |||
1703 | pub trait Docs { | ||
1704 | fn docs(&self, db: &dyn HirDatabase) -> Option<Documentation>; | ||
1705 | } | ||
1706 | impl<T: Into<AttrDef> + Copy> Docs for T { | ||
1707 | fn docs(&self, db: &dyn HirDatabase) -> Option<Documentation> { | ||
1708 | let def: AttrDef = (*self).into(); | ||
1709 | db.documentation(def.into()) | ||
1710 | } | ||
1711 | } | ||
1712 | |||
1713 | pub trait HasVisibility { | ||
1714 | fn visibility(&self, db: &dyn HirDatabase) -> Visibility; | ||
1715 | fn is_visible_from(&self, db: &dyn HirDatabase, module: Module) -> bool { | ||
1716 | let vis = self.visibility(db); | ||
1717 | vis.is_visible_from(db.upcast(), module.id) | ||
1718 | } | ||
1719 | } | ||
diff --git a/crates/hir/src/db.rs b/crates/hir/src/db.rs new file mode 100644 index 000000000..07333c453 --- /dev/null +++ b/crates/hir/src/db.rs | |||
@@ -0,0 +1,21 @@ | |||
1 | //! FIXME: write short doc here | ||
2 | |||
3 | pub use hir_def::db::{ | ||
4 | AttrsQuery, BodyQuery, BodyWithSourceMapQuery, ConstDataQuery, CrateDefMapQueryQuery, | ||
5 | CrateLangItemsQuery, DefDatabase, DefDatabaseStorage, DocumentationQuery, EnumDataQuery, | ||
6 | ExprScopesQuery, FunctionDataQuery, GenericParamsQuery, ImplDataQuery, ImportMapQuery, | ||
7 | InternConstQuery, InternDatabase, InternDatabaseStorage, InternEnumQuery, InternFunctionQuery, | ||
8 | InternImplQuery, InternStaticQuery, InternStructQuery, InternTraitQuery, InternTypeAliasQuery, | ||
9 | InternUnionQuery, ItemTreeQuery, LangItemQuery, ModuleLangItemsQuery, StaticDataQuery, | ||
10 | StructDataQuery, TraitDataQuery, TypeAliasDataQuery, UnionDataQuery, | ||
11 | }; | ||
12 | pub use hir_expand::db::{ | ||
13 | AstDatabase, AstDatabaseStorage, AstIdMapQuery, InternEagerExpansionQuery, InternMacroQuery, | ||
14 | MacroArgTextQuery, MacroDefQuery, MacroExpandQuery, ParseMacroQuery, | ||
15 | }; | ||
16 | pub use hir_ty::db::*; | ||
17 | |||
18 | #[test] | ||
19 | fn hir_database_is_object_safe() { | ||
20 | fn _assert_object_safe(_: &dyn HirDatabase) {} | ||
21 | } | ||
diff --git a/crates/hir/src/diagnostics.rs b/crates/hir/src/diagnostics.rs new file mode 100644 index 000000000..363164b9b --- /dev/null +++ b/crates/hir/src/diagnostics.rs | |||
@@ -0,0 +1,6 @@ | |||
1 | //! FIXME: write short doc here | ||
2 | pub use hir_def::diagnostics::UnresolvedModule; | ||
3 | pub use hir_expand::diagnostics::{Diagnostic, DiagnosticSink, DiagnosticSinkBuilder}; | ||
4 | pub use hir_ty::diagnostics::{ | ||
5 | MismatchedArgCount, MissingFields, MissingMatchArms, MissingOkInTailExpr, NoSuchField, | ||
6 | }; | ||
diff --git a/crates/hir/src/from_id.rs b/crates/hir/src/from_id.rs new file mode 100644 index 000000000..a53ac1e08 --- /dev/null +++ b/crates/hir/src/from_id.rs | |||
@@ -0,0 +1,247 @@ | |||
1 | //! Utility module for converting between hir_def ids and code_model wrappers. | ||
2 | //! | ||
3 | //! It's unclear if we need this long-term, but it's definitelly useful while we | ||
4 | //! are splitting the hir. | ||
5 | |||
6 | use hir_def::{ | ||
7 | expr::PatId, AdtId, AssocItemId, AttrDefId, DefWithBodyId, EnumVariantId, FieldId, | ||
8 | GenericDefId, ModuleDefId, VariantId, | ||
9 | }; | ||
10 | |||
11 | use crate::{ | ||
12 | code_model::ItemInNs, Adt, AssocItem, AttrDef, DefWithBody, EnumVariant, Field, GenericDef, | ||
13 | Local, MacroDef, ModuleDef, VariantDef, | ||
14 | }; | ||
15 | |||
16 | macro_rules! from_id { | ||
17 | ($(($id:path, $ty:path)),*) => {$( | ||
18 | impl From<$id> for $ty { | ||
19 | fn from(id: $id) -> $ty { | ||
20 | $ty { id } | ||
21 | } | ||
22 | } | ||
23 | impl From<$ty> for $id { | ||
24 | fn from(ty: $ty) -> $id { | ||
25 | ty.id | ||
26 | } | ||
27 | } | ||
28 | )*} | ||
29 | } | ||
30 | |||
31 | from_id![ | ||
32 | (base_db::CrateId, crate::Crate), | ||
33 | (hir_def::ModuleId, crate::Module), | ||
34 | (hir_def::StructId, crate::Struct), | ||
35 | (hir_def::UnionId, crate::Union), | ||
36 | (hir_def::EnumId, crate::Enum), | ||
37 | (hir_def::TypeAliasId, crate::TypeAlias), | ||
38 | (hir_def::TraitId, crate::Trait), | ||
39 | (hir_def::StaticId, crate::Static), | ||
40 | (hir_def::ConstId, crate::Const), | ||
41 | (hir_def::FunctionId, crate::Function), | ||
42 | (hir_def::ImplId, crate::ImplDef), | ||
43 | (hir_def::TypeParamId, crate::TypeParam), | ||
44 | (hir_expand::MacroDefId, crate::MacroDef) | ||
45 | ]; | ||
46 | |||
47 | impl From<AdtId> for Adt { | ||
48 | fn from(id: AdtId) -> Self { | ||
49 | match id { | ||
50 | AdtId::StructId(it) => Adt::Struct(it.into()), | ||
51 | AdtId::UnionId(it) => Adt::Union(it.into()), | ||
52 | AdtId::EnumId(it) => Adt::Enum(it.into()), | ||
53 | } | ||
54 | } | ||
55 | } | ||
56 | |||
57 | impl From<Adt> for AdtId { | ||
58 | fn from(id: Adt) -> Self { | ||
59 | match id { | ||
60 | Adt::Struct(it) => AdtId::StructId(it.id), | ||
61 | Adt::Union(it) => AdtId::UnionId(it.id), | ||
62 | Adt::Enum(it) => AdtId::EnumId(it.id), | ||
63 | } | ||
64 | } | ||
65 | } | ||
66 | |||
67 | impl From<EnumVariantId> for EnumVariant { | ||
68 | fn from(id: EnumVariantId) -> Self { | ||
69 | EnumVariant { parent: id.parent.into(), id: id.local_id } | ||
70 | } | ||
71 | } | ||
72 | |||
73 | impl From<EnumVariant> for EnumVariantId { | ||
74 | fn from(def: EnumVariant) -> Self { | ||
75 | EnumVariantId { parent: def.parent.id, local_id: def.id } | ||
76 | } | ||
77 | } | ||
78 | |||
79 | impl From<ModuleDefId> for ModuleDef { | ||
80 | fn from(id: ModuleDefId) -> Self { | ||
81 | match id { | ||
82 | ModuleDefId::ModuleId(it) => ModuleDef::Module(it.into()), | ||
83 | ModuleDefId::FunctionId(it) => ModuleDef::Function(it.into()), | ||
84 | ModuleDefId::AdtId(it) => ModuleDef::Adt(it.into()), | ||
85 | ModuleDefId::EnumVariantId(it) => ModuleDef::EnumVariant(it.into()), | ||
86 | ModuleDefId::ConstId(it) => ModuleDef::Const(it.into()), | ||
87 | ModuleDefId::StaticId(it) => ModuleDef::Static(it.into()), | ||
88 | ModuleDefId::TraitId(it) => ModuleDef::Trait(it.into()), | ||
89 | ModuleDefId::TypeAliasId(it) => ModuleDef::TypeAlias(it.into()), | ||
90 | ModuleDefId::BuiltinType(it) => ModuleDef::BuiltinType(it), | ||
91 | } | ||
92 | } | ||
93 | } | ||
94 | |||
95 | impl From<ModuleDef> for ModuleDefId { | ||
96 | fn from(id: ModuleDef) -> Self { | ||
97 | match id { | ||
98 | ModuleDef::Module(it) => ModuleDefId::ModuleId(it.into()), | ||
99 | ModuleDef::Function(it) => ModuleDefId::FunctionId(it.into()), | ||
100 | ModuleDef::Adt(it) => ModuleDefId::AdtId(it.into()), | ||
101 | ModuleDef::EnumVariant(it) => ModuleDefId::EnumVariantId(it.into()), | ||
102 | ModuleDef::Const(it) => ModuleDefId::ConstId(it.into()), | ||
103 | ModuleDef::Static(it) => ModuleDefId::StaticId(it.into()), | ||
104 | ModuleDef::Trait(it) => ModuleDefId::TraitId(it.into()), | ||
105 | ModuleDef::TypeAlias(it) => ModuleDefId::TypeAliasId(it.into()), | ||
106 | ModuleDef::BuiltinType(it) => ModuleDefId::BuiltinType(it), | ||
107 | } | ||
108 | } | ||
109 | } | ||
110 | |||
111 | impl From<DefWithBody> for DefWithBodyId { | ||
112 | fn from(def: DefWithBody) -> Self { | ||
113 | match def { | ||
114 | DefWithBody::Function(it) => DefWithBodyId::FunctionId(it.id), | ||
115 | DefWithBody::Static(it) => DefWithBodyId::StaticId(it.id), | ||
116 | DefWithBody::Const(it) => DefWithBodyId::ConstId(it.id), | ||
117 | } | ||
118 | } | ||
119 | } | ||
120 | |||
121 | impl From<DefWithBodyId> for DefWithBody { | ||
122 | fn from(def: DefWithBodyId) -> Self { | ||
123 | match def { | ||
124 | DefWithBodyId::FunctionId(it) => DefWithBody::Function(it.into()), | ||
125 | DefWithBodyId::StaticId(it) => DefWithBody::Static(it.into()), | ||
126 | DefWithBodyId::ConstId(it) => DefWithBody::Const(it.into()), | ||
127 | } | ||
128 | } | ||
129 | } | ||
130 | |||
131 | impl From<AssocItemId> for AssocItem { | ||
132 | fn from(def: AssocItemId) -> Self { | ||
133 | match def { | ||
134 | AssocItemId::FunctionId(it) => AssocItem::Function(it.into()), | ||
135 | AssocItemId::TypeAliasId(it) => AssocItem::TypeAlias(it.into()), | ||
136 | AssocItemId::ConstId(it) => AssocItem::Const(it.into()), | ||
137 | } | ||
138 | } | ||
139 | } | ||
140 | |||
141 | impl From<GenericDef> for GenericDefId { | ||
142 | fn from(def: GenericDef) -> Self { | ||
143 | match def { | ||
144 | GenericDef::Function(it) => GenericDefId::FunctionId(it.id), | ||
145 | GenericDef::Adt(it) => GenericDefId::AdtId(it.into()), | ||
146 | GenericDef::Trait(it) => GenericDefId::TraitId(it.id), | ||
147 | GenericDef::TypeAlias(it) => GenericDefId::TypeAliasId(it.id), | ||
148 | GenericDef::ImplDef(it) => GenericDefId::ImplId(it.id), | ||
149 | GenericDef::EnumVariant(it) => { | ||
150 | GenericDefId::EnumVariantId(EnumVariantId { parent: it.parent.id, local_id: it.id }) | ||
151 | } | ||
152 | GenericDef::Const(it) => GenericDefId::ConstId(it.id), | ||
153 | } | ||
154 | } | ||
155 | } | ||
156 | |||
157 | impl From<Adt> for GenericDefId { | ||
158 | fn from(id: Adt) -> Self { | ||
159 | match id { | ||
160 | Adt::Struct(it) => it.id.into(), | ||
161 | Adt::Union(it) => it.id.into(), | ||
162 | Adt::Enum(it) => it.id.into(), | ||
163 | } | ||
164 | } | ||
165 | } | ||
166 | |||
167 | impl From<VariantId> for VariantDef { | ||
168 | fn from(def: VariantId) -> Self { | ||
169 | match def { | ||
170 | VariantId::StructId(it) => VariantDef::Struct(it.into()), | ||
171 | VariantId::EnumVariantId(it) => VariantDef::EnumVariant(it.into()), | ||
172 | VariantId::UnionId(it) => VariantDef::Union(it.into()), | ||
173 | } | ||
174 | } | ||
175 | } | ||
176 | |||
177 | impl From<VariantDef> for VariantId { | ||
178 | fn from(def: VariantDef) -> Self { | ||
179 | match def { | ||
180 | VariantDef::Struct(it) => VariantId::StructId(it.id), | ||
181 | VariantDef::EnumVariant(it) => VariantId::EnumVariantId(it.into()), | ||
182 | VariantDef::Union(it) => VariantId::UnionId(it.id), | ||
183 | } | ||
184 | } | ||
185 | } | ||
186 | |||
187 | impl From<Field> for FieldId { | ||
188 | fn from(def: Field) -> Self { | ||
189 | FieldId { parent: def.parent.into(), local_id: def.id } | ||
190 | } | ||
191 | } | ||
192 | |||
193 | impl From<FieldId> for Field { | ||
194 | fn from(def: FieldId) -> Self { | ||
195 | Field { parent: def.parent.into(), id: def.local_id } | ||
196 | } | ||
197 | } | ||
198 | |||
199 | impl From<AttrDef> for AttrDefId { | ||
200 | fn from(def: AttrDef) -> Self { | ||
201 | match def { | ||
202 | AttrDef::Module(it) => AttrDefId::ModuleId(it.id), | ||
203 | AttrDef::Field(it) => AttrDefId::FieldId(it.into()), | ||
204 | AttrDef::Adt(it) => AttrDefId::AdtId(it.into()), | ||
205 | AttrDef::Function(it) => AttrDefId::FunctionId(it.id), | ||
206 | AttrDef::EnumVariant(it) => AttrDefId::EnumVariantId(it.into()), | ||
207 | AttrDef::Static(it) => AttrDefId::StaticId(it.id), | ||
208 | AttrDef::Const(it) => AttrDefId::ConstId(it.id), | ||
209 | AttrDef::Trait(it) => AttrDefId::TraitId(it.id), | ||
210 | AttrDef::TypeAlias(it) => AttrDefId::TypeAliasId(it.id), | ||
211 | AttrDef::MacroDef(it) => AttrDefId::MacroDefId(it.id), | ||
212 | } | ||
213 | } | ||
214 | } | ||
215 | |||
216 | impl From<AssocItem> for GenericDefId { | ||
217 | fn from(item: AssocItem) -> Self { | ||
218 | match item { | ||
219 | AssocItem::Function(f) => f.id.into(), | ||
220 | AssocItem::Const(c) => c.id.into(), | ||
221 | AssocItem::TypeAlias(t) => t.id.into(), | ||
222 | } | ||
223 | } | ||
224 | } | ||
225 | |||
226 | impl From<(DefWithBodyId, PatId)> for Local { | ||
227 | fn from((parent, pat_id): (DefWithBodyId, PatId)) -> Self { | ||
228 | Local { parent, pat_id } | ||
229 | } | ||
230 | } | ||
231 | |||
232 | impl From<MacroDef> for ItemInNs { | ||
233 | fn from(macro_def: MacroDef) -> Self { | ||
234 | ItemInNs::Macros(macro_def.into()) | ||
235 | } | ||
236 | } | ||
237 | |||
238 | impl From<ModuleDef> for ItemInNs { | ||
239 | fn from(module_def: ModuleDef) -> Self { | ||
240 | match module_def { | ||
241 | ModuleDef::Static(_) | ModuleDef::Const(_) | ModuleDef::Function(_) => { | ||
242 | ItemInNs::Values(module_def.into()) | ||
243 | } | ||
244 | _ => ItemInNs::Types(module_def.into()), | ||
245 | } | ||
246 | } | ||
247 | } | ||
diff --git a/crates/hir/src/has_source.rs b/crates/hir/src/has_source.rs new file mode 100644 index 000000000..a50d4ff02 --- /dev/null +++ b/crates/hir/src/has_source.rs | |||
@@ -0,0 +1,135 @@ | |||
1 | //! FIXME: write short doc here | ||
2 | |||
3 | use either::Either; | ||
4 | use hir_def::{ | ||
5 | nameres::{ModuleOrigin, ModuleSource}, | ||
6 | src::{HasChildSource, HasSource as _}, | ||
7 | Lookup, VariantId, | ||
8 | }; | ||
9 | use syntax::ast; | ||
10 | |||
11 | use crate::{ | ||
12 | db::HirDatabase, Const, Enum, EnumVariant, Field, FieldSource, Function, ImplDef, MacroDef, | ||
13 | Module, Static, Struct, Trait, TypeAlias, TypeParam, Union, | ||
14 | }; | ||
15 | |||
16 | pub use hir_expand::InFile; | ||
17 | |||
18 | pub trait HasSource { | ||
19 | type Ast; | ||
20 | fn source(self, db: &dyn HirDatabase) -> InFile<Self::Ast>; | ||
21 | } | ||
22 | |||
23 | /// NB: Module is !HasSource, because it has two source nodes at the same time: | ||
24 | /// definition and declaration. | ||
25 | impl Module { | ||
26 | /// Returns a node which defines this module. That is, a file or a `mod foo {}` with items. | ||
27 | pub fn definition_source(self, db: &dyn HirDatabase) -> InFile<ModuleSource> { | ||
28 | let def_map = db.crate_def_map(self.id.krate); | ||
29 | def_map[self.id.local_id].definition_source(db.upcast()) | ||
30 | } | ||
31 | |||
32 | pub fn is_mod_rs(self, db: &dyn HirDatabase) -> bool { | ||
33 | let def_map = db.crate_def_map(self.id.krate); | ||
34 | match def_map[self.id.local_id].origin { | ||
35 | ModuleOrigin::File { is_mod_rs, .. } => is_mod_rs, | ||
36 | _ => false, | ||
37 | } | ||
38 | } | ||
39 | |||
40 | /// Returns a node which declares this module, either a `mod foo;` or a `mod foo {}`. | ||
41 | /// `None` for the crate root. | ||
42 | pub fn declaration_source(self, db: &dyn HirDatabase) -> Option<InFile<ast::Module>> { | ||
43 | let def_map = db.crate_def_map(self.id.krate); | ||
44 | def_map[self.id.local_id].declaration_source(db.upcast()) | ||
45 | } | ||
46 | } | ||
47 | |||
48 | impl HasSource for Field { | ||
49 | type Ast = FieldSource; | ||
50 | fn source(self, db: &dyn HirDatabase) -> InFile<FieldSource> { | ||
51 | let var = VariantId::from(self.parent); | ||
52 | let src = var.child_source(db.upcast()); | ||
53 | src.map(|it| match it[self.id].clone() { | ||
54 | Either::Left(it) => FieldSource::Pos(it), | ||
55 | Either::Right(it) => FieldSource::Named(it), | ||
56 | }) | ||
57 | } | ||
58 | } | ||
59 | impl HasSource for Struct { | ||
60 | type Ast = ast::Struct; | ||
61 | fn source(self, db: &dyn HirDatabase) -> InFile<ast::Struct> { | ||
62 | self.id.lookup(db.upcast()).source(db.upcast()) | ||
63 | } | ||
64 | } | ||
65 | impl HasSource for Union { | ||
66 | type Ast = ast::Union; | ||
67 | fn source(self, db: &dyn HirDatabase) -> InFile<ast::Union> { | ||
68 | self.id.lookup(db.upcast()).source(db.upcast()) | ||
69 | } | ||
70 | } | ||
71 | impl HasSource for Enum { | ||
72 | type Ast = ast::Enum; | ||
73 | fn source(self, db: &dyn HirDatabase) -> InFile<ast::Enum> { | ||
74 | self.id.lookup(db.upcast()).source(db.upcast()) | ||
75 | } | ||
76 | } | ||
77 | impl HasSource for EnumVariant { | ||
78 | type Ast = ast::Variant; | ||
79 | fn source(self, db: &dyn HirDatabase) -> InFile<ast::Variant> { | ||
80 | self.parent.id.child_source(db.upcast()).map(|map| map[self.id].clone()) | ||
81 | } | ||
82 | } | ||
83 | impl HasSource for Function { | ||
84 | type Ast = ast::Fn; | ||
85 | fn source(self, db: &dyn HirDatabase) -> InFile<ast::Fn> { | ||
86 | self.id.lookup(db.upcast()).source(db.upcast()) | ||
87 | } | ||
88 | } | ||
89 | impl HasSource for Const { | ||
90 | type Ast = ast::Const; | ||
91 | fn source(self, db: &dyn HirDatabase) -> InFile<ast::Const> { | ||
92 | self.id.lookup(db.upcast()).source(db.upcast()) | ||
93 | } | ||
94 | } | ||
95 | impl HasSource for Static { | ||
96 | type Ast = ast::Static; | ||
97 | fn source(self, db: &dyn HirDatabase) -> InFile<ast::Static> { | ||
98 | self.id.lookup(db.upcast()).source(db.upcast()) | ||
99 | } | ||
100 | } | ||
101 | impl HasSource for Trait { | ||
102 | type Ast = ast::Trait; | ||
103 | fn source(self, db: &dyn HirDatabase) -> InFile<ast::Trait> { | ||
104 | self.id.lookup(db.upcast()).source(db.upcast()) | ||
105 | } | ||
106 | } | ||
107 | impl HasSource for TypeAlias { | ||
108 | type Ast = ast::TypeAlias; | ||
109 | fn source(self, db: &dyn HirDatabase) -> InFile<ast::TypeAlias> { | ||
110 | self.id.lookup(db.upcast()).source(db.upcast()) | ||
111 | } | ||
112 | } | ||
113 | impl HasSource for MacroDef { | ||
114 | type Ast = ast::MacroCall; | ||
115 | fn source(self, db: &dyn HirDatabase) -> InFile<ast::MacroCall> { | ||
116 | InFile { | ||
117 | file_id: self.id.ast_id.expect("MacroDef without ast_id").file_id, | ||
118 | value: self.id.ast_id.expect("MacroDef without ast_id").to_node(db.upcast()), | ||
119 | } | ||
120 | } | ||
121 | } | ||
122 | impl HasSource for ImplDef { | ||
123 | type Ast = ast::Impl; | ||
124 | fn source(self, db: &dyn HirDatabase) -> InFile<ast::Impl> { | ||
125 | self.id.lookup(db.upcast()).source(db.upcast()) | ||
126 | } | ||
127 | } | ||
128 | |||
129 | impl HasSource for TypeParam { | ||
130 | type Ast = Either<ast::Trait, ast::TypeParam>; | ||
131 | fn source(self, db: &dyn HirDatabase) -> InFile<Self::Ast> { | ||
132 | let child_source = self.id.parent.child_source(db.upcast()); | ||
133 | child_source.map(|it| it[self.id.local_id].clone()) | ||
134 | } | ||
135 | } | ||
diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs new file mode 100644 index 000000000..4ae2bd085 --- /dev/null +++ b/crates/hir/src/lib.rs | |||
@@ -0,0 +1,63 @@ | |||
1 | //! HIR (previously known as descriptors) provides a high-level object oriented | ||
2 | //! access to Rust code. | ||
3 | //! | ||
4 | //! The principal difference between HIR and syntax trees is that HIR is bound | ||
5 | //! to a particular crate instance. That is, it has cfg flags and features | ||
6 | //! applied. So, the relation between syntax and HIR is many-to-one. | ||
7 | //! | ||
8 | //! HIR is the public API of the all of the compiler logic above syntax trees. | ||
9 | //! It is written in "OO" style. Each type is self contained (as in, it knows it's | ||
10 | //! parents and full context). It should be "clean code". | ||
11 | //! | ||
12 | //! `hir_*` crates are the implementation of the compiler logic. | ||
13 | //! They are written in "ECS" style, with relatively little abstractions. | ||
14 | //! Many types are not self-contained, and explicitly use local indexes, arenas, etc. | ||
15 | //! | ||
16 | //! `hir` is what insulates the "we don't know how to actually write an incremental compiler" | ||
17 | //! from the ide with completions, hovers, etc. It is a (soft, internal) boundary: | ||
18 | //! https://www.tedinski.com/2018/02/06/system-boundaries.html. | ||
19 | |||
20 | #![recursion_limit = "512"] | ||
21 | |||
22 | mod semantics; | ||
23 | pub mod db; | ||
24 | mod source_analyzer; | ||
25 | |||
26 | pub mod diagnostics; | ||
27 | |||
28 | mod from_id; | ||
29 | mod code_model; | ||
30 | |||
31 | mod has_source; | ||
32 | |||
33 | pub use crate::{ | ||
34 | code_model::{ | ||
35 | Adt, AsAssocItem, AssocItem, AssocItemContainer, AttrDef, Callable, CallableKind, Const, | ||
36 | Crate, CrateDependency, DefWithBody, Docs, Enum, EnumVariant, Field, FieldSource, Function, | ||
37 | GenericDef, HasAttrs, HasVisibility, ImplDef, Local, MacroDef, Module, ModuleDef, ScopeDef, | ||
38 | Static, Struct, Trait, Type, TypeAlias, TypeParam, Union, VariantDef, Visibility, | ||
39 | }, | ||
40 | has_source::HasSource, | ||
41 | semantics::{original_range, PathResolution, Semantics, SemanticsScope}, | ||
42 | }; | ||
43 | |||
44 | pub use hir_def::{ | ||
45 | adt::StructKind, | ||
46 | attr::Attrs, | ||
47 | body::scope::ExprScopes, | ||
48 | builtin_type::BuiltinType, | ||
49 | docs::Documentation, | ||
50 | nameres::ModuleSource, | ||
51 | path::{ModPath, Path, PathKind}, | ||
52 | type_ref::{Mutability, TypeRef}, | ||
53 | }; | ||
54 | pub use hir_expand::{ | ||
55 | name::Name, HirFileId, InFile, MacroCallId, MacroCallLoc, /* FIXME */ MacroDefId, | ||
56 | MacroFile, Origin, | ||
57 | }; | ||
58 | pub use hir_ty::display::HirDisplay; | ||
59 | |||
60 | // These are negative re-exports: pub using these names is forbidden, they | ||
61 | // should remain private to hir internals. | ||
62 | #[allow(unused)] | ||
63 | use hir_expand::hygiene::Hygiene; | ||
diff --git a/crates/hir/src/semantics.rs b/crates/hir/src/semantics.rs new file mode 100644 index 000000000..3953017c3 --- /dev/null +++ b/crates/hir/src/semantics.rs | |||
@@ -0,0 +1,849 @@ | |||
1 | //! See `Semantics`. | ||
2 | |||
3 | mod source_to_def; | ||
4 | |||
5 | use std::{cell::RefCell, fmt, iter::successors}; | ||
6 | |||
7 | use base_db::{FileId, FileRange}; | ||
8 | use hir_def::{ | ||
9 | resolver::{self, HasResolver, Resolver}, | ||
10 | AsMacroCall, FunctionId, TraitId, VariantId, | ||
11 | }; | ||
12 | use hir_expand::{hygiene::Hygiene, name::AsName, ExpansionInfo}; | ||
13 | use hir_ty::associated_type_shorthand_candidates; | ||
14 | use itertools::Itertools; | ||
15 | use rustc_hash::{FxHashMap, FxHashSet}; | ||
16 | use syntax::{ | ||
17 | algo::{find_node_at_offset, skip_trivia_token}, | ||
18 | ast, AstNode, Direction, SyntaxNode, SyntaxToken, TextRange, TextSize, | ||
19 | }; | ||
20 | |||
21 | use crate::{ | ||
22 | db::HirDatabase, | ||
23 | diagnostics::Diagnostic, | ||
24 | semantics::source_to_def::{ChildContainer, SourceToDefCache, SourceToDefCtx}, | ||
25 | source_analyzer::{resolve_hir_path, resolve_hir_path_qualifier, SourceAnalyzer}, | ||
26 | AssocItem, Callable, Crate, Field, Function, HirFileId, ImplDef, InFile, Local, MacroDef, | ||
27 | Module, ModuleDef, Name, Origin, Path, ScopeDef, Trait, Type, TypeAlias, TypeParam, TypeRef, | ||
28 | VariantDef, | ||
29 | }; | ||
30 | use resolver::TypeNs; | ||
31 | |||
32 | #[derive(Debug, Clone, PartialEq, Eq)] | ||
33 | pub enum PathResolution { | ||
34 | /// An item | ||
35 | Def(ModuleDef), | ||
36 | /// A local binding (only value namespace) | ||
37 | Local(Local), | ||
38 | /// A generic parameter | ||
39 | TypeParam(TypeParam), | ||
40 | SelfType(ImplDef), | ||
41 | Macro(MacroDef), | ||
42 | AssocItem(AssocItem), | ||
43 | } | ||
44 | |||
45 | impl PathResolution { | ||
46 | fn in_type_ns(&self) -> Option<TypeNs> { | ||
47 | match self { | ||
48 | PathResolution::Def(ModuleDef::Adt(adt)) => Some(TypeNs::AdtId((*adt).into())), | ||
49 | PathResolution::Def(ModuleDef::BuiltinType(builtin)) => { | ||
50 | Some(TypeNs::BuiltinType(*builtin)) | ||
51 | } | ||
52 | PathResolution::Def(ModuleDef::Const(_)) | ||
53 | | PathResolution::Def(ModuleDef::EnumVariant(_)) | ||
54 | | PathResolution::Def(ModuleDef::Function(_)) | ||
55 | | PathResolution::Def(ModuleDef::Module(_)) | ||
56 | | PathResolution::Def(ModuleDef::Static(_)) | ||
57 | | PathResolution::Def(ModuleDef::Trait(_)) => None, | ||
58 | PathResolution::Def(ModuleDef::TypeAlias(alias)) => { | ||
59 | Some(TypeNs::TypeAliasId((*alias).into())) | ||
60 | } | ||
61 | PathResolution::Local(_) | PathResolution::Macro(_) => None, | ||
62 | PathResolution::TypeParam(param) => Some(TypeNs::GenericParam((*param).into())), | ||
63 | PathResolution::SelfType(impl_def) => Some(TypeNs::SelfType((*impl_def).into())), | ||
64 | PathResolution::AssocItem(AssocItem::Const(_)) | ||
65 | | PathResolution::AssocItem(AssocItem::Function(_)) => None, | ||
66 | PathResolution::AssocItem(AssocItem::TypeAlias(alias)) => { | ||
67 | Some(TypeNs::TypeAliasId((*alias).into())) | ||
68 | } | ||
69 | } | ||
70 | } | ||
71 | |||
72 | /// Returns an iterator over associated types that may be specified after this path (using | ||
73 | /// `Ty::Assoc` syntax). | ||
74 | pub fn assoc_type_shorthand_candidates<R>( | ||
75 | &self, | ||
76 | db: &dyn HirDatabase, | ||
77 | mut cb: impl FnMut(TypeAlias) -> Option<R>, | ||
78 | ) -> Option<R> { | ||
79 | associated_type_shorthand_candidates(db, self.in_type_ns()?, |_, _, id| cb(id.into())) | ||
80 | } | ||
81 | } | ||
82 | |||
83 | /// Primary API to get semantic information, like types, from syntax trees. | ||
84 | pub struct Semantics<'db, DB> { | ||
85 | pub db: &'db DB, | ||
86 | imp: SemanticsImpl<'db>, | ||
87 | } | ||
88 | |||
89 | pub struct SemanticsImpl<'db> { | ||
90 | pub db: &'db dyn HirDatabase, | ||
91 | s2d_cache: RefCell<SourceToDefCache>, | ||
92 | expansion_info_cache: RefCell<FxHashMap<HirFileId, Option<ExpansionInfo>>>, | ||
93 | cache: RefCell<FxHashMap<SyntaxNode, HirFileId>>, | ||
94 | } | ||
95 | |||
96 | impl<DB> fmt::Debug for Semantics<'_, DB> { | ||
97 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
98 | write!(f, "Semantics {{ ... }}") | ||
99 | } | ||
100 | } | ||
101 | |||
102 | impl<'db, DB: HirDatabase> Semantics<'db, DB> { | ||
103 | pub fn new(db: &DB) -> Semantics<DB> { | ||
104 | let impl_ = SemanticsImpl::new(db); | ||
105 | Semantics { db, imp: impl_ } | ||
106 | } | ||
107 | |||
108 | pub fn parse(&self, file_id: FileId) -> ast::SourceFile { | ||
109 | self.imp.parse(file_id) | ||
110 | } | ||
111 | |||
112 | pub fn expand(&self, macro_call: &ast::MacroCall) -> Option<SyntaxNode> { | ||
113 | self.imp.expand(macro_call) | ||
114 | } | ||
115 | pub fn speculative_expand( | ||
116 | &self, | ||
117 | actual_macro_call: &ast::MacroCall, | ||
118 | hypothetical_args: &ast::TokenTree, | ||
119 | token_to_map: SyntaxToken, | ||
120 | ) -> Option<(SyntaxNode, SyntaxToken)> { | ||
121 | self.imp.speculative_expand(actual_macro_call, hypothetical_args, token_to_map) | ||
122 | } | ||
123 | |||
124 | pub fn descend_into_macros(&self, token: SyntaxToken) -> SyntaxToken { | ||
125 | self.imp.descend_into_macros(token) | ||
126 | } | ||
127 | |||
128 | pub fn descend_node_at_offset<N: ast::AstNode>( | ||
129 | &self, | ||
130 | node: &SyntaxNode, | ||
131 | offset: TextSize, | ||
132 | ) -> Option<N> { | ||
133 | self.imp.descend_node_at_offset(node, offset).find_map(N::cast) | ||
134 | } | ||
135 | |||
136 | pub fn original_range(&self, node: &SyntaxNode) -> FileRange { | ||
137 | self.imp.original_range(node) | ||
138 | } | ||
139 | |||
140 | pub fn diagnostics_display_range(&self, diagnostics: &dyn Diagnostic) -> FileRange { | ||
141 | self.imp.diagnostics_display_range(diagnostics) | ||
142 | } | ||
143 | |||
144 | pub fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ { | ||
145 | self.imp.ancestors_with_macros(node) | ||
146 | } | ||
147 | |||
148 | pub fn ancestors_at_offset_with_macros( | ||
149 | &self, | ||
150 | node: &SyntaxNode, | ||
151 | offset: TextSize, | ||
152 | ) -> impl Iterator<Item = SyntaxNode> + '_ { | ||
153 | self.imp.ancestors_at_offset_with_macros(node, offset) | ||
154 | } | ||
155 | |||
156 | /// Find a AstNode by offset inside SyntaxNode, if it is inside *Macrofile*, | ||
157 | /// search up until it is of the target AstNode type | ||
158 | pub fn find_node_at_offset_with_macros<N: AstNode>( | ||
159 | &self, | ||
160 | node: &SyntaxNode, | ||
161 | offset: TextSize, | ||
162 | ) -> Option<N> { | ||
163 | self.imp.ancestors_at_offset_with_macros(node, offset).find_map(N::cast) | ||
164 | } | ||
165 | |||
166 | /// Find a AstNode by offset inside SyntaxNode, if it is inside *MacroCall*, | ||
167 | /// descend it and find again | ||
168 | pub fn find_node_at_offset_with_descend<N: AstNode>( | ||
169 | &self, | ||
170 | node: &SyntaxNode, | ||
171 | offset: TextSize, | ||
172 | ) -> Option<N> { | ||
173 | if let Some(it) = find_node_at_offset(&node, offset) { | ||
174 | return Some(it); | ||
175 | } | ||
176 | |||
177 | self.imp.descend_node_at_offset(node, offset).find_map(N::cast) | ||
178 | } | ||
179 | |||
180 | pub fn type_of_expr(&self, expr: &ast::Expr) -> Option<Type> { | ||
181 | self.imp.type_of_expr(expr) | ||
182 | } | ||
183 | |||
184 | pub fn type_of_pat(&self, pat: &ast::Pat) -> Option<Type> { | ||
185 | self.imp.type_of_pat(pat) | ||
186 | } | ||
187 | |||
188 | pub fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> { | ||
189 | self.imp.type_of_self(param) | ||
190 | } | ||
191 | |||
192 | pub fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<Function> { | ||
193 | self.imp.resolve_method_call(call).map(Function::from) | ||
194 | } | ||
195 | |||
196 | pub fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> { | ||
197 | self.imp.resolve_method_call_as_callable(call) | ||
198 | } | ||
199 | |||
200 | pub fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Field> { | ||
201 | self.imp.resolve_field(field) | ||
202 | } | ||
203 | |||
204 | pub fn resolve_record_field( | ||
205 | &self, | ||
206 | field: &ast::RecordExprField, | ||
207 | ) -> Option<(Field, Option<Local>)> { | ||
208 | self.imp.resolve_record_field(field) | ||
209 | } | ||
210 | |||
211 | pub fn resolve_record_field_pat(&self, field: &ast::RecordPatField) -> Option<Field> { | ||
212 | self.imp.resolve_record_field_pat(field) | ||
213 | } | ||
214 | |||
215 | pub fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<MacroDef> { | ||
216 | self.imp.resolve_macro_call(macro_call) | ||
217 | } | ||
218 | |||
219 | pub fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> { | ||
220 | self.imp.resolve_path(path) | ||
221 | } | ||
222 | |||
223 | pub fn resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate> { | ||
224 | self.imp.resolve_extern_crate(extern_crate) | ||
225 | } | ||
226 | |||
227 | pub fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantDef> { | ||
228 | self.imp.resolve_variant(record_lit).map(VariantDef::from) | ||
229 | } | ||
230 | |||
231 | pub fn lower_path(&self, path: &ast::Path) -> Option<Path> { | ||
232 | self.imp.lower_path(path) | ||
233 | } | ||
234 | |||
235 | pub fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> { | ||
236 | self.imp.resolve_bind_pat_to_const(pat) | ||
237 | } | ||
238 | |||
239 | // FIXME: use this instead? | ||
240 | // pub fn resolve_name_ref(&self, name_ref: &ast::NameRef) -> Option<???>; | ||
241 | |||
242 | pub fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> { | ||
243 | self.imp.record_literal_missing_fields(literal) | ||
244 | } | ||
245 | |||
246 | pub fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> { | ||
247 | self.imp.record_pattern_missing_fields(pattern) | ||
248 | } | ||
249 | |||
250 | pub fn to_def<T: ToDef>(&self, src: &T) -> Option<T::Def> { | ||
251 | let src = self.imp.find_file(src.syntax().clone()).with_value(src).cloned(); | ||
252 | T::to_def(&self.imp, src) | ||
253 | } | ||
254 | |||
255 | pub fn to_module_def(&self, file: FileId) -> Option<Module> { | ||
256 | self.imp.to_module_def(file) | ||
257 | } | ||
258 | |||
259 | pub fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db> { | ||
260 | self.imp.scope(node) | ||
261 | } | ||
262 | |||
263 | pub fn scope_at_offset(&self, node: &SyntaxNode, offset: TextSize) -> SemanticsScope<'db> { | ||
264 | self.imp.scope_at_offset(node, offset) | ||
265 | } | ||
266 | |||
267 | pub fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> { | ||
268 | self.imp.scope_for_def(def) | ||
269 | } | ||
270 | |||
271 | pub fn assert_contains_node(&self, node: &SyntaxNode) { | ||
272 | self.imp.assert_contains_node(node) | ||
273 | } | ||
274 | |||
275 | pub fn is_unsafe_method_call(&self, method_call_expr: ast::MethodCallExpr) -> bool { | ||
276 | self.imp.is_unsafe_method_call(method_call_expr) | ||
277 | } | ||
278 | |||
279 | pub fn is_unsafe_ref_expr(&self, ref_expr: &ast::RefExpr) -> bool { | ||
280 | self.imp.is_unsafe_ref_expr(ref_expr) | ||
281 | } | ||
282 | |||
283 | pub fn is_unsafe_ident_pat(&self, ident_pat: &ast::IdentPat) -> bool { | ||
284 | self.imp.is_unsafe_ident_pat(ident_pat) | ||
285 | } | ||
286 | } | ||
287 | |||
288 | impl<'db> SemanticsImpl<'db> { | ||
289 | fn new(db: &'db dyn HirDatabase) -> Self { | ||
290 | SemanticsImpl { | ||
291 | db, | ||
292 | s2d_cache: Default::default(), | ||
293 | cache: Default::default(), | ||
294 | expansion_info_cache: Default::default(), | ||
295 | } | ||
296 | } | ||
297 | |||
298 | fn parse(&self, file_id: FileId) -> ast::SourceFile { | ||
299 | let tree = self.db.parse(file_id).tree(); | ||
300 | self.cache(tree.syntax().clone(), file_id.into()); | ||
301 | tree | ||
302 | } | ||
303 | |||
304 | fn expand(&self, macro_call: &ast::MacroCall) -> Option<SyntaxNode> { | ||
305 | let macro_call = self.find_file(macro_call.syntax().clone()).with_value(macro_call); | ||
306 | let sa = self.analyze2(macro_call.map(|it| it.syntax()), None); | ||
307 | let file_id = sa.expand(self.db, macro_call)?; | ||
308 | let node = self.db.parse_or_expand(file_id)?; | ||
309 | self.cache(node.clone(), file_id); | ||
310 | Some(node) | ||
311 | } | ||
312 | |||
313 | fn speculative_expand( | ||
314 | &self, | ||
315 | actual_macro_call: &ast::MacroCall, | ||
316 | hypothetical_args: &ast::TokenTree, | ||
317 | token_to_map: SyntaxToken, | ||
318 | ) -> Option<(SyntaxNode, SyntaxToken)> { | ||
319 | let macro_call = | ||
320 | self.find_file(actual_macro_call.syntax().clone()).with_value(actual_macro_call); | ||
321 | let sa = self.analyze2(macro_call.map(|it| it.syntax()), None); | ||
322 | let krate = sa.resolver.krate()?; | ||
323 | let macro_call_id = macro_call.as_call_id(self.db.upcast(), krate, |path| { | ||
324 | sa.resolver.resolve_path_as_macro(self.db.upcast(), &path) | ||
325 | })?; | ||
326 | hir_expand::db::expand_hypothetical( | ||
327 | self.db.upcast(), | ||
328 | macro_call_id, | ||
329 | hypothetical_args, | ||
330 | token_to_map, | ||
331 | ) | ||
332 | } | ||
333 | |||
334 | fn descend_into_macros(&self, token: SyntaxToken) -> SyntaxToken { | ||
335 | let _p = profile::span("descend_into_macros"); | ||
336 | let parent = token.parent(); | ||
337 | let parent = self.find_file(parent); | ||
338 | let sa = self.analyze2(parent.as_ref(), None); | ||
339 | |||
340 | let token = successors(Some(parent.with_value(token)), |token| { | ||
341 | self.db.check_canceled(); | ||
342 | let macro_call = token.value.ancestors().find_map(ast::MacroCall::cast)?; | ||
343 | let tt = macro_call.token_tree()?; | ||
344 | if !tt.syntax().text_range().contains_range(token.value.text_range()) { | ||
345 | return None; | ||
346 | } | ||
347 | let file_id = sa.expand(self.db, token.with_value(¯o_call))?; | ||
348 | let token = self | ||
349 | .expansion_info_cache | ||
350 | .borrow_mut() | ||
351 | .entry(file_id) | ||
352 | .or_insert_with(|| file_id.expansion_info(self.db.upcast())) | ||
353 | .as_ref()? | ||
354 | .map_token_down(token.as_ref())?; | ||
355 | |||
356 | self.cache(find_root(&token.value.parent()), token.file_id); | ||
357 | |||
358 | Some(token) | ||
359 | }) | ||
360 | .last() | ||
361 | .unwrap(); | ||
362 | |||
363 | token.value | ||
364 | } | ||
365 | |||
366 | fn descend_node_at_offset( | ||
367 | &self, | ||
368 | node: &SyntaxNode, | ||
369 | offset: TextSize, | ||
370 | ) -> impl Iterator<Item = SyntaxNode> + '_ { | ||
371 | // Handle macro token cases | ||
372 | node.token_at_offset(offset) | ||
373 | .map(|token| self.descend_into_macros(token)) | ||
374 | .map(|it| self.ancestors_with_macros(it.parent())) | ||
375 | .flatten() | ||
376 | } | ||
377 | |||
378 | fn original_range(&self, node: &SyntaxNode) -> FileRange { | ||
379 | let node = self.find_file(node.clone()); | ||
380 | original_range(self.db, node.as_ref()) | ||
381 | } | ||
382 | |||
383 | fn diagnostics_display_range(&self, diagnostics: &dyn Diagnostic) -> FileRange { | ||
384 | let src = diagnostics.display_source(); | ||
385 | let root = self.db.parse_or_expand(src.file_id).unwrap(); | ||
386 | let node = src.value.to_node(&root); | ||
387 | self.cache(root, src.file_id); | ||
388 | original_range(self.db, src.with_value(&node)) | ||
389 | } | ||
390 | |||
391 | fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ { | ||
392 | let node = self.find_file(node); | ||
393 | node.ancestors_with_macros(self.db.upcast()).map(|it| it.value) | ||
394 | } | ||
395 | |||
396 | fn ancestors_at_offset_with_macros( | ||
397 | &self, | ||
398 | node: &SyntaxNode, | ||
399 | offset: TextSize, | ||
400 | ) -> impl Iterator<Item = SyntaxNode> + '_ { | ||
401 | node.token_at_offset(offset) | ||
402 | .map(|token| self.ancestors_with_macros(token.parent())) | ||
403 | .kmerge_by(|node1, node2| node1.text_range().len() < node2.text_range().len()) | ||
404 | } | ||
405 | |||
406 | fn type_of_expr(&self, expr: &ast::Expr) -> Option<Type> { | ||
407 | self.analyze(expr.syntax()).type_of_expr(self.db, &expr) | ||
408 | } | ||
409 | |||
410 | fn type_of_pat(&self, pat: &ast::Pat) -> Option<Type> { | ||
411 | self.analyze(pat.syntax()).type_of_pat(self.db, &pat) | ||
412 | } | ||
413 | |||
414 | fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> { | ||
415 | self.analyze(param.syntax()).type_of_self(self.db, ¶m) | ||
416 | } | ||
417 | |||
418 | fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<FunctionId> { | ||
419 | self.analyze(call.syntax()).resolve_method_call(self.db, call) | ||
420 | } | ||
421 | |||
422 | fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> { | ||
423 | // FIXME: this erases Substs | ||
424 | let func = self.resolve_method_call(call)?; | ||
425 | let ty = self.db.value_ty(func.into()); | ||
426 | let resolver = self.analyze(call.syntax()).resolver; | ||
427 | let ty = Type::new_with_resolver(self.db, &resolver, ty.value)?; | ||
428 | let mut res = ty.as_callable(self.db)?; | ||
429 | res.is_bound_method = true; | ||
430 | Some(res) | ||
431 | } | ||
432 | |||
433 | fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Field> { | ||
434 | self.analyze(field.syntax()).resolve_field(self.db, field) | ||
435 | } | ||
436 | |||
437 | fn resolve_record_field(&self, field: &ast::RecordExprField) -> Option<(Field, Option<Local>)> { | ||
438 | self.analyze(field.syntax()).resolve_record_field(self.db, field) | ||
439 | } | ||
440 | |||
441 | fn resolve_record_field_pat(&self, field: &ast::RecordPatField) -> Option<Field> { | ||
442 | self.analyze(field.syntax()).resolve_record_field_pat(self.db, field) | ||
443 | } | ||
444 | |||
445 | fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<MacroDef> { | ||
446 | let sa = self.analyze(macro_call.syntax()); | ||
447 | let macro_call = self.find_file(macro_call.syntax().clone()).with_value(macro_call); | ||
448 | sa.resolve_macro_call(self.db, macro_call) | ||
449 | } | ||
450 | |||
451 | fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> { | ||
452 | self.analyze(path.syntax()).resolve_path(self.db, path) | ||
453 | } | ||
454 | |||
455 | fn resolve_extern_crate(&self, extern_crate: &ast::ExternCrate) -> Option<Crate> { | ||
456 | let krate = self.scope(extern_crate.syntax()).krate()?; | ||
457 | krate.dependencies(self.db).into_iter().find_map(|dep| { | ||
458 | if dep.name == extern_crate.name_ref()?.as_name() { | ||
459 | Some(dep.krate) | ||
460 | } else { | ||
461 | None | ||
462 | } | ||
463 | }) | ||
464 | } | ||
465 | |||
466 | fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantId> { | ||
467 | self.analyze(record_lit.syntax()).resolve_variant(self.db, record_lit) | ||
468 | } | ||
469 | |||
470 | fn lower_path(&self, path: &ast::Path) -> Option<Path> { | ||
471 | let src = self.find_file(path.syntax().clone()); | ||
472 | Path::from_src(path.clone(), &Hygiene::new(self.db.upcast(), src.file_id.into())) | ||
473 | } | ||
474 | |||
475 | fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> { | ||
476 | self.analyze(pat.syntax()).resolve_bind_pat_to_const(self.db, pat) | ||
477 | } | ||
478 | |||
479 | fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> { | ||
480 | self.analyze(literal.syntax()) | ||
481 | .record_literal_missing_fields(self.db, literal) | ||
482 | .unwrap_or_default() | ||
483 | } | ||
484 | |||
485 | fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> { | ||
486 | self.analyze(pattern.syntax()) | ||
487 | .record_pattern_missing_fields(self.db, pattern) | ||
488 | .unwrap_or_default() | ||
489 | } | ||
490 | |||
491 | fn with_ctx<F: FnOnce(&mut SourceToDefCtx) -> T, T>(&self, f: F) -> T { | ||
492 | let mut cache = self.s2d_cache.borrow_mut(); | ||
493 | let mut ctx = SourceToDefCtx { db: self.db, cache: &mut *cache }; | ||
494 | f(&mut ctx) | ||
495 | } | ||
496 | |||
497 | fn to_module_def(&self, file: FileId) -> Option<Module> { | ||
498 | self.with_ctx(|ctx| ctx.file_to_def(file)).map(Module::from) | ||
499 | } | ||
500 | |||
501 | fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db> { | ||
502 | let node = self.find_file(node.clone()); | ||
503 | let resolver = self.analyze2(node.as_ref(), None).resolver; | ||
504 | SemanticsScope { db: self.db, file_id: node.file_id, resolver } | ||
505 | } | ||
506 | |||
507 | fn scope_at_offset(&self, node: &SyntaxNode, offset: TextSize) -> SemanticsScope<'db> { | ||
508 | let node = self.find_file(node.clone()); | ||
509 | let resolver = self.analyze2(node.as_ref(), Some(offset)).resolver; | ||
510 | SemanticsScope { db: self.db, file_id: node.file_id, resolver } | ||
511 | } | ||
512 | |||
513 | fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> { | ||
514 | let file_id = self.db.lookup_intern_trait(def.id).id.file_id; | ||
515 | let resolver = def.id.resolver(self.db.upcast()); | ||
516 | SemanticsScope { db: self.db, file_id, resolver } | ||
517 | } | ||
518 | |||
519 | fn analyze(&self, node: &SyntaxNode) -> SourceAnalyzer { | ||
520 | let src = self.find_file(node.clone()); | ||
521 | self.analyze2(src.as_ref(), None) | ||
522 | } | ||
523 | |||
524 | fn analyze2(&self, src: InFile<&SyntaxNode>, offset: Option<TextSize>) -> SourceAnalyzer { | ||
525 | let _p = profile::span("Semantics::analyze2"); | ||
526 | |||
527 | let container = match self.with_ctx(|ctx| ctx.find_container(src)) { | ||
528 | Some(it) => it, | ||
529 | None => return SourceAnalyzer::new_for_resolver(Resolver::default(), src), | ||
530 | }; | ||
531 | |||
532 | let resolver = match container { | ||
533 | ChildContainer::DefWithBodyId(def) => { | ||
534 | return SourceAnalyzer::new_for_body(self.db, def, src, offset) | ||
535 | } | ||
536 | ChildContainer::TraitId(it) => it.resolver(self.db.upcast()), | ||
537 | ChildContainer::ImplId(it) => it.resolver(self.db.upcast()), | ||
538 | ChildContainer::ModuleId(it) => it.resolver(self.db.upcast()), | ||
539 | ChildContainer::EnumId(it) => it.resolver(self.db.upcast()), | ||
540 | ChildContainer::VariantId(it) => it.resolver(self.db.upcast()), | ||
541 | ChildContainer::TypeAliasId(it) => it.resolver(self.db.upcast()), | ||
542 | ChildContainer::GenericDefId(it) => it.resolver(self.db.upcast()), | ||
543 | }; | ||
544 | SourceAnalyzer::new_for_resolver(resolver, src) | ||
545 | } | ||
546 | |||
547 | fn cache(&self, root_node: SyntaxNode, file_id: HirFileId) { | ||
548 | assert!(root_node.parent().is_none()); | ||
549 | let mut cache = self.cache.borrow_mut(); | ||
550 | let prev = cache.insert(root_node, file_id); | ||
551 | assert!(prev == None || prev == Some(file_id)) | ||
552 | } | ||
553 | |||
554 | fn assert_contains_node(&self, node: &SyntaxNode) { | ||
555 | self.find_file(node.clone()); | ||
556 | } | ||
557 | |||
558 | fn lookup(&self, root_node: &SyntaxNode) -> Option<HirFileId> { | ||
559 | let cache = self.cache.borrow(); | ||
560 | cache.get(root_node).copied() | ||
561 | } | ||
562 | |||
563 | fn find_file(&self, node: SyntaxNode) -> InFile<SyntaxNode> { | ||
564 | let root_node = find_root(&node); | ||
565 | let file_id = self.lookup(&root_node).unwrap_or_else(|| { | ||
566 | panic!( | ||
567 | "\n\nFailed to lookup {:?} in this Semantics.\n\ | ||
568 | Make sure to use only query nodes, derived from this instance of Semantics.\n\ | ||
569 | root node: {:?}\n\ | ||
570 | known nodes: {}\n\n", | ||
571 | node, | ||
572 | root_node, | ||
573 | self.cache | ||
574 | .borrow() | ||
575 | .keys() | ||
576 | .map(|it| format!("{:?}", it)) | ||
577 | .collect::<Vec<_>>() | ||
578 | .join(", ") | ||
579 | ) | ||
580 | }); | ||
581 | InFile::new(file_id, node) | ||
582 | } | ||
583 | |||
584 | pub fn is_unsafe_method_call(&self, method_call_expr: ast::MethodCallExpr) -> bool { | ||
585 | method_call_expr | ||
586 | .expr() | ||
587 | .and_then(|expr| { | ||
588 | let field_expr = if let ast::Expr::FieldExpr(field_expr) = expr { | ||
589 | field_expr | ||
590 | } else { | ||
591 | return None; | ||
592 | }; | ||
593 | let ty = self.type_of_expr(&field_expr.expr()?)?; | ||
594 | if !ty.is_packed(self.db) { | ||
595 | return None; | ||
596 | } | ||
597 | |||
598 | let func = self.resolve_method_call(&method_call_expr).map(Function::from)?; | ||
599 | let is_unsafe = func.has_self_param(self.db) | ||
600 | && matches!(func.params(self.db).first(), Some(TypeRef::Reference(..))); | ||
601 | Some(is_unsafe) | ||
602 | }) | ||
603 | .unwrap_or(false) | ||
604 | } | ||
605 | |||
606 | pub fn is_unsafe_ref_expr(&self, ref_expr: &ast::RefExpr) -> bool { | ||
607 | ref_expr | ||
608 | .expr() | ||
609 | .and_then(|expr| { | ||
610 | let field_expr = match expr { | ||
611 | ast::Expr::FieldExpr(field_expr) => field_expr, | ||
612 | _ => return None, | ||
613 | }; | ||
614 | let expr = field_expr.expr()?; | ||
615 | self.type_of_expr(&expr) | ||
616 | }) | ||
617 | // Binding a reference to a packed type is possibly unsafe. | ||
618 | .map(|ty| ty.is_packed(self.db)) | ||
619 | .unwrap_or(false) | ||
620 | |||
621 | // FIXME This needs layout computation to be correct. It will highlight | ||
622 | // more than it should with the current implementation. | ||
623 | } | ||
624 | |||
625 | pub fn is_unsafe_ident_pat(&self, ident_pat: &ast::IdentPat) -> bool { | ||
626 | if !ident_pat.ref_token().is_some() { | ||
627 | return false; | ||
628 | } | ||
629 | |||
630 | ident_pat | ||
631 | .syntax() | ||
632 | .parent() | ||
633 | .and_then(|parent| { | ||
634 | // `IdentPat` can live under `RecordPat` directly under `RecordPatField` or | ||
635 | // `RecordPatFieldList`. `RecordPatField` also lives under `RecordPatFieldList`, | ||
636 | // so this tries to lookup the `IdentPat` anywhere along that structure to the | ||
637 | // `RecordPat` so we can get the containing type. | ||
638 | let record_pat = ast::RecordPatField::cast(parent.clone()) | ||
639 | .and_then(|record_pat| record_pat.syntax().parent()) | ||
640 | .or_else(|| Some(parent.clone())) | ||
641 | .and_then(|parent| { | ||
642 | ast::RecordPatFieldList::cast(parent)? | ||
643 | .syntax() | ||
644 | .parent() | ||
645 | .and_then(ast::RecordPat::cast) | ||
646 | }); | ||
647 | |||
648 | // If this doesn't match a `RecordPat`, fallback to a `LetStmt` to see if | ||
649 | // this is initialized from a `FieldExpr`. | ||
650 | if let Some(record_pat) = record_pat { | ||
651 | self.type_of_pat(&ast::Pat::RecordPat(record_pat)) | ||
652 | } else if let Some(let_stmt) = ast::LetStmt::cast(parent) { | ||
653 | let field_expr = match let_stmt.initializer()? { | ||
654 | ast::Expr::FieldExpr(field_expr) => field_expr, | ||
655 | _ => return None, | ||
656 | }; | ||
657 | |||
658 | self.type_of_expr(&field_expr.expr()?) | ||
659 | } else { | ||
660 | None | ||
661 | } | ||
662 | }) | ||
663 | // Binding a reference to a packed type is possibly unsafe. | ||
664 | .map(|ty| ty.is_packed(self.db)) | ||
665 | .unwrap_or(false) | ||
666 | } | ||
667 | } | ||
668 | |||
669 | pub trait ToDef: AstNode + Clone { | ||
670 | type Def; | ||
671 | |||
672 | fn to_def(sema: &SemanticsImpl, src: InFile<Self>) -> Option<Self::Def>; | ||
673 | } | ||
674 | |||
675 | macro_rules! to_def_impls { | ||
676 | ($(($def:path, $ast:path, $meth:ident)),* ,) => {$( | ||
677 | impl ToDef for $ast { | ||
678 | type Def = $def; | ||
679 | fn to_def(sema: &SemanticsImpl, src: InFile<Self>) -> Option<Self::Def> { | ||
680 | sema.with_ctx(|ctx| ctx.$meth(src)).map(<$def>::from) | ||
681 | } | ||
682 | } | ||
683 | )*} | ||
684 | } | ||
685 | |||
686 | to_def_impls![ | ||
687 | (crate::Module, ast::Module, module_to_def), | ||
688 | (crate::Struct, ast::Struct, struct_to_def), | ||
689 | (crate::Enum, ast::Enum, enum_to_def), | ||
690 | (crate::Union, ast::Union, union_to_def), | ||
691 | (crate::Trait, ast::Trait, trait_to_def), | ||
692 | (crate::ImplDef, ast::Impl, impl_to_def), | ||
693 | (crate::TypeAlias, ast::TypeAlias, type_alias_to_def), | ||
694 | (crate::Const, ast::Const, const_to_def), | ||
695 | (crate::Static, ast::Static, static_to_def), | ||
696 | (crate::Function, ast::Fn, fn_to_def), | ||
697 | (crate::Field, ast::RecordField, record_field_to_def), | ||
698 | (crate::Field, ast::TupleField, tuple_field_to_def), | ||
699 | (crate::EnumVariant, ast::Variant, enum_variant_to_def), | ||
700 | (crate::TypeParam, ast::TypeParam, type_param_to_def), | ||
701 | (crate::MacroDef, ast::MacroCall, macro_call_to_def), // this one is dubious, not all calls are macros | ||
702 | (crate::Local, ast::IdentPat, bind_pat_to_def), | ||
703 | ]; | ||
704 | |||
705 | fn find_root(node: &SyntaxNode) -> SyntaxNode { | ||
706 | node.ancestors().last().unwrap() | ||
707 | } | ||
708 | |||
709 | #[derive(Debug)] | ||
710 | pub struct SemanticsScope<'a> { | ||
711 | pub db: &'a dyn HirDatabase, | ||
712 | file_id: HirFileId, | ||
713 | resolver: Resolver, | ||
714 | } | ||
715 | |||
716 | impl<'a> SemanticsScope<'a> { | ||
717 | pub fn module(&self) -> Option<Module> { | ||
718 | Some(Module { id: self.resolver.module()? }) | ||
719 | } | ||
720 | |||
721 | pub fn krate(&self) -> Option<Crate> { | ||
722 | Some(Crate { id: self.resolver.krate()? }) | ||
723 | } | ||
724 | |||
725 | /// Note: `FxHashSet<TraitId>` should be treated as an opaque type, passed into `Type | ||
726 | // FIXME: rename to visible_traits to not repeat scope? | ||
727 | pub fn traits_in_scope(&self) -> FxHashSet<TraitId> { | ||
728 | let resolver = &self.resolver; | ||
729 | resolver.traits_in_scope(self.db.upcast()) | ||
730 | } | ||
731 | |||
732 | pub fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) { | ||
733 | let resolver = &self.resolver; | ||
734 | |||
735 | resolver.process_all_names(self.db.upcast(), &mut |name, def| { | ||
736 | let def = match def { | ||
737 | resolver::ScopeDef::PerNs(it) => { | ||
738 | let items = ScopeDef::all_items(it); | ||
739 | for item in items { | ||
740 | f(name.clone(), item); | ||
741 | } | ||
742 | return; | ||
743 | } | ||
744 | resolver::ScopeDef::ImplSelfType(it) => ScopeDef::ImplSelfType(it.into()), | ||
745 | resolver::ScopeDef::AdtSelfType(it) => ScopeDef::AdtSelfType(it.into()), | ||
746 | resolver::ScopeDef::GenericParam(id) => ScopeDef::GenericParam(TypeParam { id }), | ||
747 | resolver::ScopeDef::Local(pat_id) => { | ||
748 | let parent = resolver.body_owner().unwrap().into(); | ||
749 | ScopeDef::Local(Local { parent, pat_id }) | ||
750 | } | ||
751 | }; | ||
752 | f(name, def) | ||
753 | }) | ||
754 | } | ||
755 | |||
756 | /// Resolve a path as-if it was written at the given scope. This is | ||
757 | /// necessary a heuristic, as it doesn't take hygiene into account. | ||
758 | pub fn speculative_resolve(&self, path: &ast::Path) -> Option<PathResolution> { | ||
759 | let hygiene = Hygiene::new(self.db.upcast(), self.file_id); | ||
760 | let path = Path::from_src(path.clone(), &hygiene)?; | ||
761 | self.resolve_hir_path(&path) | ||
762 | } | ||
763 | |||
764 | pub fn resolve_hir_path(&self, path: &Path) -> Option<PathResolution> { | ||
765 | resolve_hir_path(self.db, &self.resolver, path) | ||
766 | } | ||
767 | |||
768 | /// Resolves a path where we know it is a qualifier of another path. | ||
769 | /// | ||
770 | /// For example, if we have: | ||
771 | /// ``` | ||
772 | /// mod my { | ||
773 | /// pub mod foo { | ||
774 | /// struct Bar; | ||
775 | /// } | ||
776 | /// | ||
777 | /// pub fn foo() {} | ||
778 | /// } | ||
779 | /// ``` | ||
780 | /// then we know that `foo` in `my::foo::Bar` refers to the module, not the function. | ||
781 | pub fn resolve_hir_path_qualifier(&self, path: &Path) -> Option<PathResolution> { | ||
782 | resolve_hir_path_qualifier(self.db, &self.resolver, path) | ||
783 | } | ||
784 | } | ||
785 | |||
786 | // FIXME: Change `HasSource` trait to work with `Semantics` and remove this? | ||
787 | pub fn original_range(db: &dyn HirDatabase, node: InFile<&SyntaxNode>) -> FileRange { | ||
788 | if let Some(range) = original_range_opt(db, node) { | ||
789 | let original_file = range.file_id.original_file(db.upcast()); | ||
790 | if range.file_id == original_file.into() { | ||
791 | return FileRange { file_id: original_file, range: range.value }; | ||
792 | } | ||
793 | |||
794 | log::error!("Fail to mapping up more for {:?}", range); | ||
795 | return FileRange { file_id: range.file_id.original_file(db.upcast()), range: range.value }; | ||
796 | } | ||
797 | |||
798 | // Fall back to whole macro call | ||
799 | if let Some(expansion) = node.file_id.expansion_info(db.upcast()) { | ||
800 | if let Some(call_node) = expansion.call_node() { | ||
801 | return FileRange { | ||
802 | file_id: call_node.file_id.original_file(db.upcast()), | ||
803 | range: call_node.value.text_range(), | ||
804 | }; | ||
805 | } | ||
806 | } | ||
807 | |||
808 | FileRange { file_id: node.file_id.original_file(db.upcast()), range: node.value.text_range() } | ||
809 | } | ||
810 | |||
811 | fn original_range_opt( | ||
812 | db: &dyn HirDatabase, | ||
813 | node: InFile<&SyntaxNode>, | ||
814 | ) -> Option<InFile<TextRange>> { | ||
815 | let expansion = node.file_id.expansion_info(db.upcast())?; | ||
816 | |||
817 | // the input node has only one token ? | ||
818 | let single = skip_trivia_token(node.value.first_token()?, Direction::Next)? | ||
819 | == skip_trivia_token(node.value.last_token()?, Direction::Prev)?; | ||
820 | |||
821 | Some(node.value.descendants().find_map(|it| { | ||
822 | let first = skip_trivia_token(it.first_token()?, Direction::Next)?; | ||
823 | let first = ascend_call_token(db, &expansion, node.with_value(first))?; | ||
824 | |||
825 | let last = skip_trivia_token(it.last_token()?, Direction::Prev)?; | ||
826 | let last = ascend_call_token(db, &expansion, node.with_value(last))?; | ||
827 | |||
828 | if (!single && first == last) || (first.file_id != last.file_id) { | ||
829 | return None; | ||
830 | } | ||
831 | |||
832 | Some(first.with_value(first.value.text_range().cover(last.value.text_range()))) | ||
833 | })?) | ||
834 | } | ||
835 | |||
836 | fn ascend_call_token( | ||
837 | db: &dyn HirDatabase, | ||
838 | expansion: &ExpansionInfo, | ||
839 | token: InFile<SyntaxToken>, | ||
840 | ) -> Option<InFile<SyntaxToken>> { | ||
841 | let (mapped, origin) = expansion.map_token_up(token.as_ref())?; | ||
842 | if origin != Origin::Call { | ||
843 | return None; | ||
844 | } | ||
845 | if let Some(info) = mapped.file_id.expansion_info(db.upcast()) { | ||
846 | return ascend_call_token(db, &info, mapped); | ||
847 | } | ||
848 | Some(mapped) | ||
849 | } | ||
diff --git a/crates/hir/src/semantics/source_to_def.rs b/crates/hir/src/semantics/source_to_def.rs new file mode 100644 index 000000000..5918b9541 --- /dev/null +++ b/crates/hir/src/semantics/source_to_def.rs | |||
@@ -0,0 +1,275 @@ | |||
1 | //! Maps *syntax* of various definitions to their semantic ids. | ||
2 | |||
3 | use base_db::FileId; | ||
4 | use hir_def::{ | ||
5 | child_by_source::ChildBySource, | ||
6 | dyn_map::DynMap, | ||
7 | expr::PatId, | ||
8 | keys::{self, Key}, | ||
9 | ConstId, DefWithBodyId, EnumId, EnumVariantId, FieldId, FunctionId, GenericDefId, ImplId, | ||
10 | ModuleId, StaticId, StructId, TraitId, TypeAliasId, TypeParamId, UnionId, VariantId, | ||
11 | }; | ||
12 | use hir_expand::{name::AsName, AstId, MacroDefKind}; | ||
13 | use rustc_hash::FxHashMap; | ||
14 | use stdx::impl_from; | ||
15 | use syntax::{ | ||
16 | ast::{self, NameOwner}, | ||
17 | match_ast, AstNode, SyntaxNode, | ||
18 | }; | ||
19 | |||
20 | use crate::{db::HirDatabase, InFile, MacroDefId}; | ||
21 | |||
22 | pub(super) type SourceToDefCache = FxHashMap<ChildContainer, DynMap>; | ||
23 | |||
24 | pub(super) struct SourceToDefCtx<'a, 'b> { | ||
25 | pub(super) db: &'b dyn HirDatabase, | ||
26 | pub(super) cache: &'a mut SourceToDefCache, | ||
27 | } | ||
28 | |||
29 | impl SourceToDefCtx<'_, '_> { | ||
30 | pub(super) fn file_to_def(&mut self, file: FileId) -> Option<ModuleId> { | ||
31 | let _p = profile::span("SourceBinder::to_module_def"); | ||
32 | let (krate, local_id) = self.db.relevant_crates(file).iter().find_map(|&crate_id| { | ||
33 | let crate_def_map = self.db.crate_def_map(crate_id); | ||
34 | let local_id = crate_def_map.modules_for_file(file).next()?; | ||
35 | Some((crate_id, local_id)) | ||
36 | })?; | ||
37 | Some(ModuleId { krate, local_id }) | ||
38 | } | ||
39 | |||
40 | pub(super) fn module_to_def(&mut self, src: InFile<ast::Module>) -> Option<ModuleId> { | ||
41 | let _p = profile::span("module_to_def"); | ||
42 | let parent_declaration = src | ||
43 | .as_ref() | ||
44 | .map(|it| it.syntax()) | ||
45 | .cloned() | ||
46 | .ancestors_with_macros(self.db.upcast()) | ||
47 | .skip(1) | ||
48 | .find_map(|it| { | ||
49 | let m = ast::Module::cast(it.value.clone())?; | ||
50 | Some(it.with_value(m)) | ||
51 | }); | ||
52 | |||
53 | let parent_module = match parent_declaration { | ||
54 | Some(parent_declaration) => self.module_to_def(parent_declaration), | ||
55 | None => { | ||
56 | let file_id = src.file_id.original_file(self.db.upcast()); | ||
57 | self.file_to_def(file_id) | ||
58 | } | ||
59 | }?; | ||
60 | |||
61 | let child_name = src.value.name()?.as_name(); | ||
62 | let def_map = self.db.crate_def_map(parent_module.krate); | ||
63 | let child_id = *def_map[parent_module.local_id].children.get(&child_name)?; | ||
64 | Some(ModuleId { krate: parent_module.krate, local_id: child_id }) | ||
65 | } | ||
66 | |||
67 | pub(super) fn trait_to_def(&mut self, src: InFile<ast::Trait>) -> Option<TraitId> { | ||
68 | self.to_def(src, keys::TRAIT) | ||
69 | } | ||
70 | pub(super) fn impl_to_def(&mut self, src: InFile<ast::Impl>) -> Option<ImplId> { | ||
71 | self.to_def(src, keys::IMPL) | ||
72 | } | ||
73 | pub(super) fn fn_to_def(&mut self, src: InFile<ast::Fn>) -> Option<FunctionId> { | ||
74 | self.to_def(src, keys::FUNCTION) | ||
75 | } | ||
76 | pub(super) fn struct_to_def(&mut self, src: InFile<ast::Struct>) -> Option<StructId> { | ||
77 | self.to_def(src, keys::STRUCT) | ||
78 | } | ||
79 | pub(super) fn enum_to_def(&mut self, src: InFile<ast::Enum>) -> Option<EnumId> { | ||
80 | self.to_def(src, keys::ENUM) | ||
81 | } | ||
82 | pub(super) fn union_to_def(&mut self, src: InFile<ast::Union>) -> Option<UnionId> { | ||
83 | self.to_def(src, keys::UNION) | ||
84 | } | ||
85 | pub(super) fn static_to_def(&mut self, src: InFile<ast::Static>) -> Option<StaticId> { | ||
86 | self.to_def(src, keys::STATIC) | ||
87 | } | ||
88 | pub(super) fn const_to_def(&mut self, src: InFile<ast::Const>) -> Option<ConstId> { | ||
89 | self.to_def(src, keys::CONST) | ||
90 | } | ||
91 | pub(super) fn type_alias_to_def(&mut self, src: InFile<ast::TypeAlias>) -> Option<TypeAliasId> { | ||
92 | self.to_def(src, keys::TYPE_ALIAS) | ||
93 | } | ||
94 | pub(super) fn record_field_to_def(&mut self, src: InFile<ast::RecordField>) -> Option<FieldId> { | ||
95 | self.to_def(src, keys::RECORD_FIELD) | ||
96 | } | ||
97 | pub(super) fn tuple_field_to_def(&mut self, src: InFile<ast::TupleField>) -> Option<FieldId> { | ||
98 | self.to_def(src, keys::TUPLE_FIELD) | ||
99 | } | ||
100 | pub(super) fn enum_variant_to_def( | ||
101 | &mut self, | ||
102 | src: InFile<ast::Variant>, | ||
103 | ) -> Option<EnumVariantId> { | ||
104 | self.to_def(src, keys::VARIANT) | ||
105 | } | ||
106 | pub(super) fn bind_pat_to_def( | ||
107 | &mut self, | ||
108 | src: InFile<ast::IdentPat>, | ||
109 | ) -> Option<(DefWithBodyId, PatId)> { | ||
110 | let container = self.find_pat_container(src.as_ref().map(|it| it.syntax()))?; | ||
111 | let (_body, source_map) = self.db.body_with_source_map(container); | ||
112 | let src = src.map(ast::Pat::from); | ||
113 | let pat_id = source_map.node_pat(src.as_ref())?; | ||
114 | Some((container, pat_id)) | ||
115 | } | ||
116 | |||
117 | fn to_def<Ast: AstNode + 'static, ID: Copy + 'static>( | ||
118 | &mut self, | ||
119 | src: InFile<Ast>, | ||
120 | key: Key<Ast, ID>, | ||
121 | ) -> Option<ID> { | ||
122 | let container = self.find_container(src.as_ref().map(|it| it.syntax()))?; | ||
123 | let db = self.db; | ||
124 | let dyn_map = | ||
125 | &*self.cache.entry(container).or_insert_with(|| container.child_by_source(db)); | ||
126 | dyn_map[key].get(&src).copied() | ||
127 | } | ||
128 | |||
129 | pub(super) fn type_param_to_def(&mut self, src: InFile<ast::TypeParam>) -> Option<TypeParamId> { | ||
130 | let container: ChildContainer = | ||
131 | self.find_type_param_container(src.as_ref().map(|it| it.syntax()))?.into(); | ||
132 | let db = self.db; | ||
133 | let dyn_map = | ||
134 | &*self.cache.entry(container).or_insert_with(|| container.child_by_source(db)); | ||
135 | dyn_map[keys::TYPE_PARAM].get(&src).copied() | ||
136 | } | ||
137 | |||
138 | // FIXME: use DynMap as well? | ||
139 | pub(super) fn macro_call_to_def(&mut self, src: InFile<ast::MacroCall>) -> Option<MacroDefId> { | ||
140 | let kind = MacroDefKind::Declarative; | ||
141 | let file_id = src.file_id.original_file(self.db.upcast()); | ||
142 | let krate = self.file_to_def(file_id)?.krate; | ||
143 | let file_ast_id = self.db.ast_id_map(src.file_id).ast_id(&src.value); | ||
144 | let ast_id = Some(AstId::new(src.file_id, file_ast_id)); | ||
145 | Some(MacroDefId { krate: Some(krate), ast_id, kind, local_inner: false }) | ||
146 | } | ||
147 | |||
148 | pub(super) fn find_container(&mut self, src: InFile<&SyntaxNode>) -> Option<ChildContainer> { | ||
149 | for container in src.cloned().ancestors_with_macros(self.db.upcast()).skip(1) { | ||
150 | let res: ChildContainer = match_ast! { | ||
151 | match (container.value) { | ||
152 | ast::Module(it) => { | ||
153 | let def = self.module_to_def(container.with_value(it))?; | ||
154 | def.into() | ||
155 | }, | ||
156 | ast::Trait(it) => { | ||
157 | let def = self.trait_to_def(container.with_value(it))?; | ||
158 | def.into() | ||
159 | }, | ||
160 | ast::Impl(it) => { | ||
161 | let def = self.impl_to_def(container.with_value(it))?; | ||
162 | def.into() | ||
163 | }, | ||
164 | ast::Fn(it) => { | ||
165 | let def = self.fn_to_def(container.with_value(it))?; | ||
166 | DefWithBodyId::from(def).into() | ||
167 | }, | ||
168 | ast::Struct(it) => { | ||
169 | let def = self.struct_to_def(container.with_value(it))?; | ||
170 | VariantId::from(def).into() | ||
171 | }, | ||
172 | ast::Enum(it) => { | ||
173 | let def = self.enum_to_def(container.with_value(it))?; | ||
174 | def.into() | ||
175 | }, | ||
176 | ast::Union(it) => { | ||
177 | let def = self.union_to_def(container.with_value(it))?; | ||
178 | VariantId::from(def).into() | ||
179 | }, | ||
180 | ast::Static(it) => { | ||
181 | let def = self.static_to_def(container.with_value(it))?; | ||
182 | DefWithBodyId::from(def).into() | ||
183 | }, | ||
184 | ast::Const(it) => { | ||
185 | let def = self.const_to_def(container.with_value(it))?; | ||
186 | DefWithBodyId::from(def).into() | ||
187 | }, | ||
188 | ast::TypeAlias(it) => { | ||
189 | let def = self.type_alias_to_def(container.with_value(it))?; | ||
190 | def.into() | ||
191 | }, | ||
192 | _ => continue, | ||
193 | } | ||
194 | }; | ||
195 | return Some(res); | ||
196 | } | ||
197 | |||
198 | let def = self.file_to_def(src.file_id.original_file(self.db.upcast()))?; | ||
199 | Some(def.into()) | ||
200 | } | ||
201 | |||
202 | fn find_type_param_container(&mut self, src: InFile<&SyntaxNode>) -> Option<GenericDefId> { | ||
203 | for container in src.cloned().ancestors_with_macros(self.db.upcast()).skip(1) { | ||
204 | let res: GenericDefId = match_ast! { | ||
205 | match (container.value) { | ||
206 | ast::Fn(it) => self.fn_to_def(container.with_value(it))?.into(), | ||
207 | ast::Struct(it) => self.struct_to_def(container.with_value(it))?.into(), | ||
208 | ast::Enum(it) => self.enum_to_def(container.with_value(it))?.into(), | ||
209 | ast::Trait(it) => self.trait_to_def(container.with_value(it))?.into(), | ||
210 | ast::TypeAlias(it) => self.type_alias_to_def(container.with_value(it))?.into(), | ||
211 | ast::Impl(it) => self.impl_to_def(container.with_value(it))?.into(), | ||
212 | _ => continue, | ||
213 | } | ||
214 | }; | ||
215 | return Some(res); | ||
216 | } | ||
217 | None | ||
218 | } | ||
219 | |||
220 | fn find_pat_container(&mut self, src: InFile<&SyntaxNode>) -> Option<DefWithBodyId> { | ||
221 | for container in src.cloned().ancestors_with_macros(self.db.upcast()).skip(1) { | ||
222 | let res: DefWithBodyId = match_ast! { | ||
223 | match (container.value) { | ||
224 | ast::Const(it) => self.const_to_def(container.with_value(it))?.into(), | ||
225 | ast::Static(it) => self.static_to_def(container.with_value(it))?.into(), | ||
226 | ast::Fn(it) => self.fn_to_def(container.with_value(it))?.into(), | ||
227 | _ => continue, | ||
228 | } | ||
229 | }; | ||
230 | return Some(res); | ||
231 | } | ||
232 | None | ||
233 | } | ||
234 | } | ||
235 | |||
236 | #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] | ||
237 | pub(crate) enum ChildContainer { | ||
238 | DefWithBodyId(DefWithBodyId), | ||
239 | ModuleId(ModuleId), | ||
240 | TraitId(TraitId), | ||
241 | ImplId(ImplId), | ||
242 | EnumId(EnumId), | ||
243 | VariantId(VariantId), | ||
244 | TypeAliasId(TypeAliasId), | ||
245 | /// XXX: this might be the same def as, for example an `EnumId`. However, | ||
246 | /// here the children generic parameters, and not, eg enum variants. | ||
247 | GenericDefId(GenericDefId), | ||
248 | } | ||
249 | impl_from! { | ||
250 | DefWithBodyId, | ||
251 | ModuleId, | ||
252 | TraitId, | ||
253 | ImplId, | ||
254 | EnumId, | ||
255 | VariantId, | ||
256 | TypeAliasId, | ||
257 | GenericDefId | ||
258 | for ChildContainer | ||
259 | } | ||
260 | |||
261 | impl ChildContainer { | ||
262 | fn child_by_source(self, db: &dyn HirDatabase) -> DynMap { | ||
263 | let db = db.upcast(); | ||
264 | match self { | ||
265 | ChildContainer::DefWithBodyId(it) => it.child_by_source(db), | ||
266 | ChildContainer::ModuleId(it) => it.child_by_source(db), | ||
267 | ChildContainer::TraitId(it) => it.child_by_source(db), | ||
268 | ChildContainer::ImplId(it) => it.child_by_source(db), | ||
269 | ChildContainer::EnumId(it) => it.child_by_source(db), | ||
270 | ChildContainer::VariantId(it) => it.child_by_source(db), | ||
271 | ChildContainer::TypeAliasId(_) => DynMap::default(), | ||
272 | ChildContainer::GenericDefId(it) => it.child_by_source(db), | ||
273 | } | ||
274 | } | ||
275 | } | ||
diff --git a/crates/hir/src/source_analyzer.rs b/crates/hir/src/source_analyzer.rs new file mode 100644 index 000000000..8750584f9 --- /dev/null +++ b/crates/hir/src/source_analyzer.rs | |||
@@ -0,0 +1,534 @@ | |||
1 | //! Lookup hir elements using positions in the source code. This is a lossy | ||
2 | //! transformation: in general, a single source might correspond to several | ||
3 | //! modules, functions, etc, due to macros, cfgs and `#[path=]` attributes on | ||
4 | //! modules. | ||
5 | //! | ||
6 | //! So, this modules should not be used during hir construction, it exists | ||
7 | //! purely for "IDE needs". | ||
8 | use std::{iter::once, sync::Arc}; | ||
9 | |||
10 | use hir_def::{ | ||
11 | body::{ | ||
12 | scope::{ExprScopes, ScopeId}, | ||
13 | Body, BodySourceMap, | ||
14 | }, | ||
15 | expr::{ExprId, Pat, PatId}, | ||
16 | resolver::{resolver_for_scope, Resolver, TypeNs, ValueNs}, | ||
17 | AsMacroCall, DefWithBodyId, FieldId, FunctionId, LocalFieldId, VariantId, | ||
18 | }; | ||
19 | use hir_expand::{hygiene::Hygiene, name::AsName, HirFileId, InFile}; | ||
20 | use hir_ty::{ | ||
21 | diagnostics::{record_literal_missing_fields, record_pattern_missing_fields}, | ||
22 | InferenceResult, Substs, Ty, | ||
23 | }; | ||
24 | use syntax::{ | ||
25 | ast::{self, AstNode}, | ||
26 | SyntaxNode, TextRange, TextSize, | ||
27 | }; | ||
28 | |||
29 | use crate::{ | ||
30 | db::HirDatabase, semantics::PathResolution, Adt, Const, EnumVariant, Field, Function, Local, | ||
31 | MacroDef, ModPath, ModuleDef, Path, PathKind, Static, Struct, Trait, Type, TypeAlias, | ||
32 | TypeParam, | ||
33 | }; | ||
34 | use base_db::CrateId; | ||
35 | |||
36 | /// `SourceAnalyzer` is a convenience wrapper which exposes HIR API in terms of | ||
37 | /// original source files. It should not be used inside the HIR itself. | ||
38 | #[derive(Debug)] | ||
39 | pub(crate) struct SourceAnalyzer { | ||
40 | file_id: HirFileId, | ||
41 | pub(crate) resolver: Resolver, | ||
42 | body: Option<Arc<Body>>, | ||
43 | body_source_map: Option<Arc<BodySourceMap>>, | ||
44 | infer: Option<Arc<InferenceResult>>, | ||
45 | scopes: Option<Arc<ExprScopes>>, | ||
46 | } | ||
47 | |||
48 | impl SourceAnalyzer { | ||
49 | pub(crate) fn new_for_body( | ||
50 | db: &dyn HirDatabase, | ||
51 | def: DefWithBodyId, | ||
52 | node: InFile<&SyntaxNode>, | ||
53 | offset: Option<TextSize>, | ||
54 | ) -> SourceAnalyzer { | ||
55 | let (body, source_map) = db.body_with_source_map(def); | ||
56 | let scopes = db.expr_scopes(def); | ||
57 | let scope = match offset { | ||
58 | None => scope_for(&scopes, &source_map, node), | ||
59 | Some(offset) => scope_for_offset(db, &scopes, &source_map, node.with_value(offset)), | ||
60 | }; | ||
61 | let resolver = resolver_for_scope(db.upcast(), def, scope); | ||
62 | SourceAnalyzer { | ||
63 | resolver, | ||
64 | body: Some(body), | ||
65 | body_source_map: Some(source_map), | ||
66 | infer: Some(db.infer(def)), | ||
67 | scopes: Some(scopes), | ||
68 | file_id: node.file_id, | ||
69 | } | ||
70 | } | ||
71 | |||
72 | pub(crate) fn new_for_resolver( | ||
73 | resolver: Resolver, | ||
74 | node: InFile<&SyntaxNode>, | ||
75 | ) -> SourceAnalyzer { | ||
76 | SourceAnalyzer { | ||
77 | resolver, | ||
78 | body: None, | ||
79 | body_source_map: None, | ||
80 | infer: None, | ||
81 | scopes: None, | ||
82 | file_id: node.file_id, | ||
83 | } | ||
84 | } | ||
85 | |||
86 | fn expr_id(&self, db: &dyn HirDatabase, expr: &ast::Expr) -> Option<ExprId> { | ||
87 | let src = match expr { | ||
88 | ast::Expr::MacroCall(call) => { | ||
89 | self.expand_expr(db, InFile::new(self.file_id, call.clone()))? | ||
90 | } | ||
91 | _ => InFile::new(self.file_id, expr.clone()), | ||
92 | }; | ||
93 | let sm = self.body_source_map.as_ref()?; | ||
94 | sm.node_expr(src.as_ref()) | ||
95 | } | ||
96 | |||
97 | fn pat_id(&self, pat: &ast::Pat) -> Option<PatId> { | ||
98 | // FIXME: macros, see `expr_id` | ||
99 | let src = InFile { file_id: self.file_id, value: pat }; | ||
100 | self.body_source_map.as_ref()?.node_pat(src) | ||
101 | } | ||
102 | |||
103 | fn expand_expr( | ||
104 | &self, | ||
105 | db: &dyn HirDatabase, | ||
106 | expr: InFile<ast::MacroCall>, | ||
107 | ) -> Option<InFile<ast::Expr>> { | ||
108 | let macro_file = self.body_source_map.as_ref()?.node_macro_file(expr.as_ref())?; | ||
109 | let expanded = db.parse_or_expand(macro_file)?; | ||
110 | |||
111 | let res = match ast::MacroCall::cast(expanded.clone()) { | ||
112 | Some(call) => self.expand_expr(db, InFile::new(macro_file, call))?, | ||
113 | _ => InFile::new(macro_file, ast::Expr::cast(expanded)?), | ||
114 | }; | ||
115 | Some(res) | ||
116 | } | ||
117 | |||
118 | pub(crate) fn type_of_expr(&self, db: &dyn HirDatabase, expr: &ast::Expr) -> Option<Type> { | ||
119 | let expr_id = self.expr_id(db, expr)?; | ||
120 | let ty = self.infer.as_ref()?[expr_id].clone(); | ||
121 | Type::new_with_resolver(db, &self.resolver, ty) | ||
122 | } | ||
123 | |||
124 | pub(crate) fn type_of_pat(&self, db: &dyn HirDatabase, pat: &ast::Pat) -> Option<Type> { | ||
125 | let pat_id = self.pat_id(pat)?; | ||
126 | let ty = self.infer.as_ref()?[pat_id].clone(); | ||
127 | Type::new_with_resolver(db, &self.resolver, ty) | ||
128 | } | ||
129 | |||
130 | pub(crate) fn type_of_self( | ||
131 | &self, | ||
132 | db: &dyn HirDatabase, | ||
133 | param: &ast::SelfParam, | ||
134 | ) -> Option<Type> { | ||
135 | let src = InFile { file_id: self.file_id, value: param }; | ||
136 | let pat_id = self.body_source_map.as_ref()?.node_self_param(src)?; | ||
137 | let ty = self.infer.as_ref()?[pat_id].clone(); | ||
138 | Type::new_with_resolver(db, &self.resolver, ty) | ||
139 | } | ||
140 | |||
141 | pub(crate) fn resolve_method_call( | ||
142 | &self, | ||
143 | db: &dyn HirDatabase, | ||
144 | call: &ast::MethodCallExpr, | ||
145 | ) -> Option<FunctionId> { | ||
146 | let expr_id = self.expr_id(db, &call.clone().into())?; | ||
147 | self.infer.as_ref()?.method_resolution(expr_id) | ||
148 | } | ||
149 | |||
150 | pub(crate) fn resolve_field( | ||
151 | &self, | ||
152 | db: &dyn HirDatabase, | ||
153 | field: &ast::FieldExpr, | ||
154 | ) -> Option<Field> { | ||
155 | let expr_id = self.expr_id(db, &field.clone().into())?; | ||
156 | self.infer.as_ref()?.field_resolution(expr_id).map(|it| it.into()) | ||
157 | } | ||
158 | |||
159 | pub(crate) fn resolve_record_field( | ||
160 | &self, | ||
161 | db: &dyn HirDatabase, | ||
162 | field: &ast::RecordExprField, | ||
163 | ) -> Option<(Field, Option<Local>)> { | ||
164 | let expr = field.expr()?; | ||
165 | let expr_id = self.expr_id(db, &expr)?; | ||
166 | let local = if field.name_ref().is_some() { | ||
167 | None | ||
168 | } else { | ||
169 | let local_name = field.field_name()?.as_name(); | ||
170 | let path = ModPath::from_segments(PathKind::Plain, once(local_name)); | ||
171 | match self.resolver.resolve_path_in_value_ns_fully(db.upcast(), &path) { | ||
172 | Some(ValueNs::LocalBinding(pat_id)) => { | ||
173 | Some(Local { pat_id, parent: self.resolver.body_owner()? }) | ||
174 | } | ||
175 | _ => None, | ||
176 | } | ||
177 | }; | ||
178 | let struct_field = self.infer.as_ref()?.record_field_resolution(expr_id)?; | ||
179 | Some((struct_field.into(), local)) | ||
180 | } | ||
181 | |||
182 | pub(crate) fn resolve_record_field_pat( | ||
183 | &self, | ||
184 | _db: &dyn HirDatabase, | ||
185 | field: &ast::RecordPatField, | ||
186 | ) -> Option<Field> { | ||
187 | let pat_id = self.pat_id(&field.pat()?)?; | ||
188 | let struct_field = self.infer.as_ref()?.record_field_pat_resolution(pat_id)?; | ||
189 | Some(struct_field.into()) | ||
190 | } | ||
191 | |||
192 | pub(crate) fn resolve_macro_call( | ||
193 | &self, | ||
194 | db: &dyn HirDatabase, | ||
195 | macro_call: InFile<&ast::MacroCall>, | ||
196 | ) -> Option<MacroDef> { | ||
197 | let hygiene = Hygiene::new(db.upcast(), macro_call.file_id); | ||
198 | let path = macro_call.value.path().and_then(|ast| Path::from_src(ast, &hygiene))?; | ||
199 | self.resolver.resolve_path_as_macro(db.upcast(), path.mod_path()).map(|it| it.into()) | ||
200 | } | ||
201 | |||
202 | pub(crate) fn resolve_bind_pat_to_const( | ||
203 | &self, | ||
204 | db: &dyn HirDatabase, | ||
205 | pat: &ast::IdentPat, | ||
206 | ) -> Option<ModuleDef> { | ||
207 | let pat_id = self.pat_id(&pat.clone().into())?; | ||
208 | let body = self.body.as_ref()?; | ||
209 | let path = match &body[pat_id] { | ||
210 | Pat::Path(path) => path, | ||
211 | _ => return None, | ||
212 | }; | ||
213 | let res = resolve_hir_path(db, &self.resolver, &path)?; | ||
214 | match res { | ||
215 | PathResolution::Def(def) => Some(def), | ||
216 | _ => None, | ||
217 | } | ||
218 | } | ||
219 | |||
220 | pub(crate) fn resolve_path( | ||
221 | &self, | ||
222 | db: &dyn HirDatabase, | ||
223 | path: &ast::Path, | ||
224 | ) -> Option<PathResolution> { | ||
225 | if let Some(path_expr) = path.syntax().parent().and_then(ast::PathExpr::cast) { | ||
226 | let expr_id = self.expr_id(db, &path_expr.into())?; | ||
227 | if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_expr(expr_id) { | ||
228 | return Some(PathResolution::AssocItem(assoc.into())); | ||
229 | } | ||
230 | if let Some(VariantId::EnumVariantId(variant)) = | ||
231 | self.infer.as_ref()?.variant_resolution_for_expr(expr_id) | ||
232 | { | ||
233 | return Some(PathResolution::Def(ModuleDef::EnumVariant(variant.into()))); | ||
234 | } | ||
235 | } | ||
236 | |||
237 | if let Some(path_pat) = path.syntax().parent().and_then(ast::PathPat::cast) { | ||
238 | let pat_id = self.pat_id(&path_pat.into())?; | ||
239 | if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_pat(pat_id) { | ||
240 | return Some(PathResolution::AssocItem(assoc.into())); | ||
241 | } | ||
242 | if let Some(VariantId::EnumVariantId(variant)) = | ||
243 | self.infer.as_ref()?.variant_resolution_for_pat(pat_id) | ||
244 | { | ||
245 | return Some(PathResolution::Def(ModuleDef::EnumVariant(variant.into()))); | ||
246 | } | ||
247 | } | ||
248 | |||
249 | if let Some(rec_lit) = path.syntax().parent().and_then(ast::RecordExpr::cast) { | ||
250 | let expr_id = self.expr_id(db, &rec_lit.into())?; | ||
251 | if let Some(VariantId::EnumVariantId(variant)) = | ||
252 | self.infer.as_ref()?.variant_resolution_for_expr(expr_id) | ||
253 | { | ||
254 | return Some(PathResolution::Def(ModuleDef::EnumVariant(variant.into()))); | ||
255 | } | ||
256 | } | ||
257 | |||
258 | if let Some(rec_pat) = path.syntax().parent().and_then(ast::RecordPat::cast) { | ||
259 | let pat_id = self.pat_id(&rec_pat.into())?; | ||
260 | if let Some(VariantId::EnumVariantId(variant)) = | ||
261 | self.infer.as_ref()?.variant_resolution_for_pat(pat_id) | ||
262 | { | ||
263 | return Some(PathResolution::Def(ModuleDef::EnumVariant(variant.into()))); | ||
264 | } | ||
265 | } | ||
266 | |||
267 | // This must be a normal source file rather than macro file. | ||
268 | let hir_path = Path::from_src(path.clone(), &Hygiene::new(db.upcast(), self.file_id))?; | ||
269 | |||
270 | // Case where path is a qualifier of another path, e.g. foo::bar::Baz where we | ||
271 | // trying to resolve foo::bar. | ||
272 | if let Some(outer_path) = path.syntax().parent().and_then(ast::Path::cast) { | ||
273 | if let Some(qualifier) = outer_path.qualifier() { | ||
274 | if path == &qualifier { | ||
275 | return resolve_hir_path_qualifier(db, &self.resolver, &hir_path); | ||
276 | } | ||
277 | } | ||
278 | } | ||
279 | |||
280 | resolve_hir_path(db, &self.resolver, &hir_path) | ||
281 | } | ||
282 | |||
283 | pub(crate) fn record_literal_missing_fields( | ||
284 | &self, | ||
285 | db: &dyn HirDatabase, | ||
286 | literal: &ast::RecordExpr, | ||
287 | ) -> Option<Vec<(Field, Type)>> { | ||
288 | let krate = self.resolver.krate()?; | ||
289 | let body = self.body.as_ref()?; | ||
290 | let infer = self.infer.as_ref()?; | ||
291 | |||
292 | let expr_id = self.expr_id(db, &literal.clone().into())?; | ||
293 | let substs = match &infer.type_of_expr[expr_id] { | ||
294 | Ty::Apply(a_ty) => &a_ty.parameters, | ||
295 | _ => return None, | ||
296 | }; | ||
297 | |||
298 | let (variant, missing_fields, _exhaustive) = | ||
299 | record_literal_missing_fields(db, infer, expr_id, &body[expr_id])?; | ||
300 | let res = self.missing_fields(db, krate, substs, variant, missing_fields); | ||
301 | Some(res) | ||
302 | } | ||
303 | |||
304 | pub(crate) fn record_pattern_missing_fields( | ||
305 | &self, | ||
306 | db: &dyn HirDatabase, | ||
307 | pattern: &ast::RecordPat, | ||
308 | ) -> Option<Vec<(Field, Type)>> { | ||
309 | let krate = self.resolver.krate()?; | ||
310 | let body = self.body.as_ref()?; | ||
311 | let infer = self.infer.as_ref()?; | ||
312 | |||
313 | let pat_id = self.pat_id(&pattern.clone().into())?; | ||
314 | let substs = match &infer.type_of_pat[pat_id] { | ||
315 | Ty::Apply(a_ty) => &a_ty.parameters, | ||
316 | _ => return None, | ||
317 | }; | ||
318 | |||
319 | let (variant, missing_fields, _exhaustive) = | ||
320 | record_pattern_missing_fields(db, infer, pat_id, &body[pat_id])?; | ||
321 | let res = self.missing_fields(db, krate, substs, variant, missing_fields); | ||
322 | Some(res) | ||
323 | } | ||
324 | |||
325 | fn missing_fields( | ||
326 | &self, | ||
327 | db: &dyn HirDatabase, | ||
328 | krate: CrateId, | ||
329 | substs: &Substs, | ||
330 | variant: VariantId, | ||
331 | missing_fields: Vec<LocalFieldId>, | ||
332 | ) -> Vec<(Field, Type)> { | ||
333 | let field_types = db.field_types(variant); | ||
334 | |||
335 | missing_fields | ||
336 | .into_iter() | ||
337 | .map(|local_id| { | ||
338 | let field = FieldId { parent: variant, local_id }; | ||
339 | let ty = field_types[local_id].clone().subst(substs); | ||
340 | (field.into(), Type::new_with_resolver_inner(db, krate, &self.resolver, ty)) | ||
341 | }) | ||
342 | .collect() | ||
343 | } | ||
344 | |||
345 | pub(crate) fn expand( | ||
346 | &self, | ||
347 | db: &dyn HirDatabase, | ||
348 | macro_call: InFile<&ast::MacroCall>, | ||
349 | ) -> Option<HirFileId> { | ||
350 | let krate = self.resolver.krate()?; | ||
351 | let macro_call_id = macro_call.as_call_id(db.upcast(), krate, |path| { | ||
352 | self.resolver.resolve_path_as_macro(db.upcast(), &path) | ||
353 | })?; | ||
354 | Some(macro_call_id.as_file()).filter(|it| it.expansion_level(db.upcast()) < 64) | ||
355 | } | ||
356 | |||
357 | pub(crate) fn resolve_variant( | ||
358 | &self, | ||
359 | db: &dyn HirDatabase, | ||
360 | record_lit: ast::RecordExpr, | ||
361 | ) -> Option<VariantId> { | ||
362 | let infer = self.infer.as_ref()?; | ||
363 | let expr_id = self.expr_id(db, &record_lit.into())?; | ||
364 | infer.variant_resolution_for_expr(expr_id) | ||
365 | } | ||
366 | } | ||
367 | |||
368 | fn scope_for( | ||
369 | scopes: &ExprScopes, | ||
370 | source_map: &BodySourceMap, | ||
371 | node: InFile<&SyntaxNode>, | ||
372 | ) -> Option<ScopeId> { | ||
373 | node.value | ||
374 | .ancestors() | ||
375 | .filter_map(ast::Expr::cast) | ||
376 | .filter_map(|it| source_map.node_expr(InFile::new(node.file_id, &it))) | ||
377 | .find_map(|it| scopes.scope_for(it)) | ||
378 | } | ||
379 | |||
380 | fn scope_for_offset( | ||
381 | db: &dyn HirDatabase, | ||
382 | scopes: &ExprScopes, | ||
383 | source_map: &BodySourceMap, | ||
384 | offset: InFile<TextSize>, | ||
385 | ) -> Option<ScopeId> { | ||
386 | scopes | ||
387 | .scope_by_expr() | ||
388 | .iter() | ||
389 | .filter_map(|(id, scope)| { | ||
390 | let source = source_map.expr_syntax(*id).ok()?; | ||
391 | // FIXME: correctly handle macro expansion | ||
392 | if source.file_id != offset.file_id { | ||
393 | return None; | ||
394 | } | ||
395 | let root = source.file_syntax(db.upcast()); | ||
396 | let node = source.value.to_node(&root); | ||
397 | Some((node.syntax().text_range(), scope)) | ||
398 | }) | ||
399 | // find containing scope | ||
400 | .min_by_key(|(expr_range, _scope)| { | ||
401 | ( | ||
402 | !(expr_range.start() <= offset.value && offset.value <= expr_range.end()), | ||
403 | expr_range.len(), | ||
404 | ) | ||
405 | }) | ||
406 | .map(|(expr_range, scope)| { | ||
407 | adjust(db, scopes, source_map, expr_range, offset).unwrap_or(*scope) | ||
408 | }) | ||
409 | } | ||
410 | |||
411 | // XXX: during completion, cursor might be outside of any particular | ||
412 | // expression. Try to figure out the correct scope... | ||
413 | fn adjust( | ||
414 | db: &dyn HirDatabase, | ||
415 | scopes: &ExprScopes, | ||
416 | source_map: &BodySourceMap, | ||
417 | expr_range: TextRange, | ||
418 | offset: InFile<TextSize>, | ||
419 | ) -> Option<ScopeId> { | ||
420 | let child_scopes = scopes | ||
421 | .scope_by_expr() | ||
422 | .iter() | ||
423 | .filter_map(|(id, scope)| { | ||
424 | let source = source_map.expr_syntax(*id).ok()?; | ||
425 | // FIXME: correctly handle macro expansion | ||
426 | if source.file_id != offset.file_id { | ||
427 | return None; | ||
428 | } | ||
429 | let root = source.file_syntax(db.upcast()); | ||
430 | let node = source.value.to_node(&root); | ||
431 | Some((node.syntax().text_range(), scope)) | ||
432 | }) | ||
433 | .filter(|&(range, _)| { | ||
434 | range.start() <= offset.value && expr_range.contains_range(range) && range != expr_range | ||
435 | }); | ||
436 | |||
437 | child_scopes | ||
438 | .max_by(|&(r1, _), &(r2, _)| { | ||
439 | if r1.contains_range(r2) { | ||
440 | std::cmp::Ordering::Greater | ||
441 | } else if r2.contains_range(r1) { | ||
442 | std::cmp::Ordering::Less | ||
443 | } else { | ||
444 | r1.start().cmp(&r2.start()) | ||
445 | } | ||
446 | }) | ||
447 | .map(|(_ptr, scope)| *scope) | ||
448 | } | ||
449 | |||
450 | pub(crate) fn resolve_hir_path( | ||
451 | db: &dyn HirDatabase, | ||
452 | resolver: &Resolver, | ||
453 | path: &Path, | ||
454 | ) -> Option<PathResolution> { | ||
455 | let types = | ||
456 | resolver.resolve_path_in_type_ns_fully(db.upcast(), path.mod_path()).map(|ty| match ty { | ||
457 | TypeNs::SelfType(it) => PathResolution::SelfType(it.into()), | ||
458 | TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }), | ||
459 | TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => { | ||
460 | PathResolution::Def(Adt::from(it).into()) | ||
461 | } | ||
462 | TypeNs::EnumVariantId(it) => PathResolution::Def(EnumVariant::from(it).into()), | ||
463 | TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()), | ||
464 | TypeNs::BuiltinType(it) => PathResolution::Def(it.into()), | ||
465 | TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()), | ||
466 | }); | ||
467 | |||
468 | let body_owner = resolver.body_owner(); | ||
469 | let values = | ||
470 | resolver.resolve_path_in_value_ns_fully(db.upcast(), path.mod_path()).and_then(|val| { | ||
471 | let res = match val { | ||
472 | ValueNs::LocalBinding(pat_id) => { | ||
473 | let var = Local { parent: body_owner?.into(), pat_id }; | ||
474 | PathResolution::Local(var) | ||
475 | } | ||
476 | ValueNs::FunctionId(it) => PathResolution::Def(Function::from(it).into()), | ||
477 | ValueNs::ConstId(it) => PathResolution::Def(Const::from(it).into()), | ||
478 | ValueNs::StaticId(it) => PathResolution::Def(Static::from(it).into()), | ||
479 | ValueNs::StructId(it) => PathResolution::Def(Struct::from(it).into()), | ||
480 | ValueNs::EnumVariantId(it) => PathResolution::Def(EnumVariant::from(it).into()), | ||
481 | ValueNs::ImplSelf(impl_id) => PathResolution::SelfType(impl_id.into()), | ||
482 | }; | ||
483 | Some(res) | ||
484 | }); | ||
485 | |||
486 | let items = resolver | ||
487 | .resolve_module_path_in_items(db.upcast(), path.mod_path()) | ||
488 | .take_types() | ||
489 | .map(|it| PathResolution::Def(it.into())); | ||
490 | |||
491 | types.or(values).or(items).or_else(|| { | ||
492 | resolver | ||
493 | .resolve_path_as_macro(db.upcast(), path.mod_path()) | ||
494 | .map(|def| PathResolution::Macro(def.into())) | ||
495 | }) | ||
496 | } | ||
497 | |||
498 | /// Resolves a path where we know it is a qualifier of another path. | ||
499 | /// | ||
500 | /// For example, if we have: | ||
501 | /// ``` | ||
502 | /// mod my { | ||
503 | /// pub mod foo { | ||
504 | /// struct Bar; | ||
505 | /// } | ||
506 | /// | ||
507 | /// pub fn foo() {} | ||
508 | /// } | ||
509 | /// ``` | ||
510 | /// then we know that `foo` in `my::foo::Bar` refers to the module, not the function. | ||
511 | pub(crate) fn resolve_hir_path_qualifier( | ||
512 | db: &dyn HirDatabase, | ||
513 | resolver: &Resolver, | ||
514 | path: &Path, | ||
515 | ) -> Option<PathResolution> { | ||
516 | let items = resolver | ||
517 | .resolve_module_path_in_items(db.upcast(), path.mod_path()) | ||
518 | .take_types() | ||
519 | .map(|it| PathResolution::Def(it.into())); | ||
520 | |||
521 | if items.is_some() { | ||
522 | return items; | ||
523 | } | ||
524 | |||
525 | resolver.resolve_path_in_type_ns_fully(db.upcast(), path.mod_path()).map(|ty| match ty { | ||
526 | TypeNs::SelfType(it) => PathResolution::SelfType(it.into()), | ||
527 | TypeNs::GenericParam(id) => PathResolution::TypeParam(TypeParam { id }), | ||
528 | TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => PathResolution::Def(Adt::from(it).into()), | ||
529 | TypeNs::EnumVariantId(it) => PathResolution::Def(EnumVariant::from(it).into()), | ||
530 | TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()), | ||
531 | TypeNs::BuiltinType(it) => PathResolution::Def(it.into()), | ||
532 | TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()), | ||
533 | }) | ||
534 | } | ||