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/ra_hir/src/code_model.rs | |
parent | 06ff8e6c760ff05f10e868b5d1f9d79e42fbb49c (diff) | |
parent | c2594daf2974dbd4ce3d9b7ec72481764abaceb5 (diff) |
Merge remote-tracking branch 'origin/master'
Diffstat (limited to 'crates/ra_hir/src/code_model.rs')
-rw-r--r-- | crates/ra_hir/src/code_model.rs | 1695 |
1 files changed, 0 insertions, 1695 deletions
diff --git a/crates/ra_hir/src/code_model.rs b/crates/ra_hir/src/code_model.rs deleted file mode 100644 index 27cdabea0..000000000 --- a/crates/ra_hir/src/code_model.rs +++ /dev/null | |||
@@ -1,1695 +0,0 @@ | |||
1 | //! FIXME: write short doc here | ||
2 | use std::{iter, sync::Arc}; | ||
3 | |||
4 | use arrayvec::ArrayVec; | ||
5 | use either::Either; | ||
6 | use hir_def::{ | ||
7 | adt::StructKind, | ||
8 | adt::VariantData, | ||
9 | builtin_type::BuiltinType, | ||
10 | docs::Documentation, | ||
11 | expr::{BindingAnnotation, Pat, PatId}, | ||
12 | import_map, | ||
13 | per_ns::PerNs, | ||
14 | resolver::{HasResolver, Resolver}, | ||
15 | src::HasSource as _, | ||
16 | type_ref::{Mutability, TypeRef}, | ||
17 | AdtId, AssocContainerId, ConstId, DefWithBodyId, EnumId, FunctionId, GenericDefId, HasModule, | ||
18 | ImplId, LocalEnumVariantId, LocalFieldId, LocalModuleId, Lookup, ModuleId, StaticId, StructId, | ||
19 | TraitId, TypeAliasId, TypeParamId, UnionId, | ||
20 | }; | ||
21 | use hir_expand::{ | ||
22 | diagnostics::DiagnosticSink, | ||
23 | name::{name, AsName}, | ||
24 | MacroDefId, MacroDefKind, | ||
25 | }; | ||
26 | use hir_ty::{ | ||
27 | autoderef, | ||
28 | display::{HirDisplayError, HirFormatter}, | ||
29 | method_resolution, ApplicationTy, CallableDefId, Canonical, FnSig, GenericPredicate, | ||
30 | InEnvironment, Substs, TraitEnvironment, Ty, TyDefId, TypeCtor, | ||
31 | }; | ||
32 | use ra_db::{CrateId, Edition, FileId}; | ||
33 | use ra_prof::profile; | ||
34 | use ra_syntax::{ | ||
35 | ast::{self, AttrsOwner, NameOwner}, | ||
36 | AstNode, | ||
37 | }; | ||
38 | use rustc_hash::FxHashSet; | ||
39 | use stdx::impl_from; | ||
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) -> Option<Module> { | ||
87 | let module_id = db.crate_def_map(self.id).root; | ||
88 | Some(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("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 | fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> { | ||
435 | db.struct_data(self.id).variant_data.clone() | ||
436 | } | ||
437 | } | ||
438 | |||
439 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
440 | pub struct Union { | ||
441 | pub(crate) id: UnionId, | ||
442 | } | ||
443 | |||
444 | impl Union { | ||
445 | pub fn name(self, db: &dyn HirDatabase) -> Name { | ||
446 | db.union_data(self.id).name.clone() | ||
447 | } | ||
448 | |||
449 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
450 | Module { id: self.id.lookup(db.upcast()).container.module(db.upcast()) } | ||
451 | } | ||
452 | |||
453 | pub fn ty(self, db: &dyn HirDatabase) -> Type { | ||
454 | Type::from_def(db, self.id.lookup(db.upcast()).container.module(db.upcast()).krate, self.id) | ||
455 | } | ||
456 | |||
457 | pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> { | ||
458 | db.union_data(self.id) | ||
459 | .variant_data | ||
460 | .fields() | ||
461 | .iter() | ||
462 | .map(|(id, _)| Field { parent: self.into(), id }) | ||
463 | .collect() | ||
464 | } | ||
465 | |||
466 | fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> { | ||
467 | db.union_data(self.id).variant_data.clone() | ||
468 | } | ||
469 | } | ||
470 | |||
471 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
472 | pub struct Enum { | ||
473 | pub(crate) id: EnumId, | ||
474 | } | ||
475 | |||
476 | impl Enum { | ||
477 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
478 | Module { id: self.id.lookup(db.upcast()).container.module(db.upcast()) } | ||
479 | } | ||
480 | |||
481 | pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> { | ||
482 | Some(self.module(db).krate()) | ||
483 | } | ||
484 | |||
485 | pub fn name(self, db: &dyn HirDatabase) -> Name { | ||
486 | db.enum_data(self.id).name.clone() | ||
487 | } | ||
488 | |||
489 | pub fn variants(self, db: &dyn HirDatabase) -> Vec<EnumVariant> { | ||
490 | db.enum_data(self.id) | ||
491 | .variants | ||
492 | .iter() | ||
493 | .map(|(id, _)| EnumVariant { parent: self, id }) | ||
494 | .collect() | ||
495 | } | ||
496 | |||
497 | pub fn ty(self, db: &dyn HirDatabase) -> Type { | ||
498 | Type::from_def(db, self.id.lookup(db.upcast()).container.module(db.upcast()).krate, self.id) | ||
499 | } | ||
500 | } | ||
501 | |||
502 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
503 | pub struct EnumVariant { | ||
504 | pub(crate) parent: Enum, | ||
505 | pub(crate) id: LocalEnumVariantId, | ||
506 | } | ||
507 | |||
508 | impl EnumVariant { | ||
509 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
510 | self.parent.module(db) | ||
511 | } | ||
512 | pub fn parent_enum(self, _db: &dyn HirDatabase) -> Enum { | ||
513 | self.parent | ||
514 | } | ||
515 | |||
516 | pub fn name(self, db: &dyn HirDatabase) -> Name { | ||
517 | db.enum_data(self.parent.id).variants[self.id].name.clone() | ||
518 | } | ||
519 | |||
520 | pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> { | ||
521 | self.variant_data(db) | ||
522 | .fields() | ||
523 | .iter() | ||
524 | .map(|(id, _)| Field { parent: self.into(), id }) | ||
525 | .collect() | ||
526 | } | ||
527 | |||
528 | pub fn kind(self, db: &dyn HirDatabase) -> StructKind { | ||
529 | self.variant_data(db).kind() | ||
530 | } | ||
531 | |||
532 | pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> { | ||
533 | db.enum_data(self.parent.id).variants[self.id].variant_data.clone() | ||
534 | } | ||
535 | } | ||
536 | |||
537 | /// A Data Type | ||
538 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] | ||
539 | pub enum Adt { | ||
540 | Struct(Struct), | ||
541 | Union(Union), | ||
542 | Enum(Enum), | ||
543 | } | ||
544 | impl_from!(Struct, Union, Enum for Adt); | ||
545 | |||
546 | impl Adt { | ||
547 | pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool { | ||
548 | let subst = db.generic_defaults(self.into()); | ||
549 | subst.iter().any(|ty| &ty.value == &Ty::Unknown) | ||
550 | } | ||
551 | |||
552 | /// Turns this ADT into a type. Any type parameters of the ADT will be | ||
553 | /// turned into unknown types, which is good for e.g. finding the most | ||
554 | /// general set of completions, but will not look very nice when printed. | ||
555 | pub fn ty(self, db: &dyn HirDatabase) -> Type { | ||
556 | let id = AdtId::from(self); | ||
557 | Type::from_def(db, id.module(db.upcast()).krate, id) | ||
558 | } | ||
559 | |||
560 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
561 | match self { | ||
562 | Adt::Struct(s) => s.module(db), | ||
563 | Adt::Union(s) => s.module(db), | ||
564 | Adt::Enum(e) => e.module(db), | ||
565 | } | ||
566 | } | ||
567 | |||
568 | pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> { | ||
569 | Some(self.module(db).krate()) | ||
570 | } | ||
571 | |||
572 | pub fn name(self, db: &dyn HirDatabase) -> Name { | ||
573 | match self { | ||
574 | Adt::Struct(s) => s.name(db), | ||
575 | Adt::Union(u) => u.name(db), | ||
576 | Adt::Enum(e) => e.name(db), | ||
577 | } | ||
578 | } | ||
579 | } | ||
580 | |||
581 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] | ||
582 | pub enum VariantDef { | ||
583 | Struct(Struct), | ||
584 | Union(Union), | ||
585 | EnumVariant(EnumVariant), | ||
586 | } | ||
587 | impl_from!(Struct, Union, EnumVariant for VariantDef); | ||
588 | |||
589 | impl VariantDef { | ||
590 | pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> { | ||
591 | match self { | ||
592 | VariantDef::Struct(it) => it.fields(db), | ||
593 | VariantDef::Union(it) => it.fields(db), | ||
594 | VariantDef::EnumVariant(it) => it.fields(db), | ||
595 | } | ||
596 | } | ||
597 | |||
598 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
599 | match self { | ||
600 | VariantDef::Struct(it) => it.module(db), | ||
601 | VariantDef::Union(it) => it.module(db), | ||
602 | VariantDef::EnumVariant(it) => it.module(db), | ||
603 | } | ||
604 | } | ||
605 | |||
606 | pub fn name(&self, db: &dyn HirDatabase) -> Name { | ||
607 | match self { | ||
608 | VariantDef::Struct(s) => s.name(db), | ||
609 | VariantDef::Union(u) => u.name(db), | ||
610 | VariantDef::EnumVariant(e) => e.name(db), | ||
611 | } | ||
612 | } | ||
613 | |||
614 | pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> { | ||
615 | match self { | ||
616 | VariantDef::Struct(it) => it.variant_data(db), | ||
617 | VariantDef::Union(it) => it.variant_data(db), | ||
618 | VariantDef::EnumVariant(it) => it.variant_data(db), | ||
619 | } | ||
620 | } | ||
621 | } | ||
622 | |||
623 | /// The defs which have a body. | ||
624 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
625 | pub enum DefWithBody { | ||
626 | Function(Function), | ||
627 | Static(Static), | ||
628 | Const(Const), | ||
629 | } | ||
630 | impl_from!(Function, Const, Static for DefWithBody); | ||
631 | |||
632 | impl DefWithBody { | ||
633 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
634 | match self { | ||
635 | DefWithBody::Const(c) => c.module(db), | ||
636 | DefWithBody::Function(f) => f.module(db), | ||
637 | DefWithBody::Static(s) => s.module(db), | ||
638 | } | ||
639 | } | ||
640 | |||
641 | pub fn name(self, db: &dyn HirDatabase) -> Option<Name> { | ||
642 | match self { | ||
643 | DefWithBody::Function(f) => Some(f.name(db)), | ||
644 | DefWithBody::Static(s) => s.name(db), | ||
645 | DefWithBody::Const(c) => c.name(db), | ||
646 | } | ||
647 | } | ||
648 | } | ||
649 | |||
650 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
651 | pub struct Function { | ||
652 | pub(crate) id: FunctionId, | ||
653 | } | ||
654 | |||
655 | impl Function { | ||
656 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
657 | self.id.lookup(db.upcast()).module(db.upcast()).into() | ||
658 | } | ||
659 | |||
660 | pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> { | ||
661 | Some(self.module(db).krate()) | ||
662 | } | ||
663 | |||
664 | pub fn name(self, db: &dyn HirDatabase) -> Name { | ||
665 | db.function_data(self.id).name.clone() | ||
666 | } | ||
667 | |||
668 | pub fn has_self_param(self, db: &dyn HirDatabase) -> bool { | ||
669 | db.function_data(self.id).has_self_param | ||
670 | } | ||
671 | |||
672 | pub fn params(self, db: &dyn HirDatabase) -> Vec<TypeRef> { | ||
673 | db.function_data(self.id).params.clone() | ||
674 | } | ||
675 | |||
676 | pub fn is_unsafe(self, db: &dyn HirDatabase) -> bool { | ||
677 | db.function_data(self.id).is_unsafe | ||
678 | } | ||
679 | |||
680 | pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) { | ||
681 | hir_ty::diagnostics::validate_body(db, self.id.into(), sink) | ||
682 | } | ||
683 | } | ||
684 | |||
685 | impl HasVisibility for Function { | ||
686 | fn visibility(&self, db: &dyn HirDatabase) -> Visibility { | ||
687 | let function_data = db.function_data(self.id); | ||
688 | let visibility = &function_data.visibility; | ||
689 | visibility.resolve(db.upcast(), &self.id.resolver(db.upcast())) | ||
690 | } | ||
691 | } | ||
692 | |||
693 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
694 | pub struct Const { | ||
695 | pub(crate) id: ConstId, | ||
696 | } | ||
697 | |||
698 | impl Const { | ||
699 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
700 | Module { id: self.id.lookup(db.upcast()).module(db.upcast()) } | ||
701 | } | ||
702 | |||
703 | pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> { | ||
704 | Some(self.module(db).krate()) | ||
705 | } | ||
706 | |||
707 | pub fn name(self, db: &dyn HirDatabase) -> Option<Name> { | ||
708 | db.const_data(self.id).name.clone() | ||
709 | } | ||
710 | } | ||
711 | |||
712 | impl HasVisibility for Const { | ||
713 | fn visibility(&self, db: &dyn HirDatabase) -> Visibility { | ||
714 | let function_data = db.const_data(self.id); | ||
715 | let visibility = &function_data.visibility; | ||
716 | visibility.resolve(db.upcast(), &self.id.resolver(db.upcast())) | ||
717 | } | ||
718 | } | ||
719 | |||
720 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
721 | pub struct Static { | ||
722 | pub(crate) id: StaticId, | ||
723 | } | ||
724 | |||
725 | impl Static { | ||
726 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
727 | Module { id: self.id.lookup(db.upcast()).module(db.upcast()) } | ||
728 | } | ||
729 | |||
730 | pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> { | ||
731 | Some(self.module(db).krate()) | ||
732 | } | ||
733 | |||
734 | pub fn name(self, db: &dyn HirDatabase) -> Option<Name> { | ||
735 | db.static_data(self.id).name.clone() | ||
736 | } | ||
737 | |||
738 | pub fn is_mut(self, db: &dyn HirDatabase) -> bool { | ||
739 | db.static_data(self.id).mutable | ||
740 | } | ||
741 | } | ||
742 | |||
743 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
744 | pub struct Trait { | ||
745 | pub(crate) id: TraitId, | ||
746 | } | ||
747 | |||
748 | impl Trait { | ||
749 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
750 | Module { id: self.id.lookup(db.upcast()).container.module(db.upcast()) } | ||
751 | } | ||
752 | |||
753 | pub fn name(self, db: &dyn HirDatabase) -> Name { | ||
754 | db.trait_data(self.id).name.clone() | ||
755 | } | ||
756 | |||
757 | pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> { | ||
758 | db.trait_data(self.id).items.iter().map(|(_name, it)| (*it).into()).collect() | ||
759 | } | ||
760 | |||
761 | pub fn is_auto(self, db: &dyn HirDatabase) -> bool { | ||
762 | db.trait_data(self.id).auto | ||
763 | } | ||
764 | } | ||
765 | |||
766 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
767 | pub struct TypeAlias { | ||
768 | pub(crate) id: TypeAliasId, | ||
769 | } | ||
770 | |||
771 | impl TypeAlias { | ||
772 | pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool { | ||
773 | let subst = db.generic_defaults(self.id.into()); | ||
774 | subst.iter().any(|ty| &ty.value == &Ty::Unknown) | ||
775 | } | ||
776 | |||
777 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
778 | Module { id: self.id.lookup(db.upcast()).module(db.upcast()) } | ||
779 | } | ||
780 | |||
781 | pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> { | ||
782 | Some(self.module(db).krate()) | ||
783 | } | ||
784 | |||
785 | pub fn type_ref(self, db: &dyn HirDatabase) -> Option<TypeRef> { | ||
786 | db.type_alias_data(self.id).type_ref.clone() | ||
787 | } | ||
788 | |||
789 | pub fn ty(self, db: &dyn HirDatabase) -> Type { | ||
790 | Type::from_def(db, self.id.lookup(db.upcast()).module(db.upcast()).krate, self.id) | ||
791 | } | ||
792 | |||
793 | pub fn name(self, db: &dyn HirDatabase) -> Name { | ||
794 | db.type_alias_data(self.id).name.clone() | ||
795 | } | ||
796 | } | ||
797 | |||
798 | impl HasVisibility for TypeAlias { | ||
799 | fn visibility(&self, db: &dyn HirDatabase) -> Visibility { | ||
800 | let function_data = db.type_alias_data(self.id); | ||
801 | let visibility = &function_data.visibility; | ||
802 | visibility.resolve(db.upcast(), &self.id.resolver(db.upcast())) | ||
803 | } | ||
804 | } | ||
805 | |||
806 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
807 | pub struct MacroDef { | ||
808 | pub(crate) id: MacroDefId, | ||
809 | } | ||
810 | |||
811 | impl MacroDef { | ||
812 | /// FIXME: right now, this just returns the root module of the crate that | ||
813 | /// defines this macro. The reasons for this is that macros are expanded | ||
814 | /// early, in `ra_hir_expand`, where modules simply do not exist yet. | ||
815 | pub fn module(self, db: &dyn HirDatabase) -> Option<Module> { | ||
816 | let krate = self.id.krate?; | ||
817 | let module_id = db.crate_def_map(krate).root; | ||
818 | Some(Module::new(Crate { id: krate }, module_id)) | ||
819 | } | ||
820 | |||
821 | /// XXX: this parses the file | ||
822 | pub fn name(self, db: &dyn HirDatabase) -> Option<Name> { | ||
823 | self.source(db).value.name().map(|it| it.as_name()) | ||
824 | } | ||
825 | |||
826 | /// Indicate it is a proc-macro | ||
827 | pub fn is_proc_macro(&self) -> bool { | ||
828 | matches!(self.id.kind, MacroDefKind::CustomDerive(_)) | ||
829 | } | ||
830 | |||
831 | /// Indicate it is a derive macro | ||
832 | pub fn is_derive_macro(&self) -> bool { | ||
833 | matches!(self.id.kind, MacroDefKind::CustomDerive(_) | MacroDefKind::BuiltInDerive(_)) | ||
834 | } | ||
835 | } | ||
836 | |||
837 | /// Invariant: `inner.as_assoc_item(db).is_some()` | ||
838 | /// We do not actively enforce this invariant. | ||
839 | #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] | ||
840 | pub enum AssocItem { | ||
841 | Function(Function), | ||
842 | Const(Const), | ||
843 | TypeAlias(TypeAlias), | ||
844 | } | ||
845 | pub enum AssocItemContainer { | ||
846 | Trait(Trait), | ||
847 | ImplDef(ImplDef), | ||
848 | } | ||
849 | pub trait AsAssocItem { | ||
850 | fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem>; | ||
851 | } | ||
852 | |||
853 | impl AsAssocItem for Function { | ||
854 | fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> { | ||
855 | as_assoc_item(db, AssocItem::Function, self.id) | ||
856 | } | ||
857 | } | ||
858 | impl AsAssocItem for Const { | ||
859 | fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> { | ||
860 | as_assoc_item(db, AssocItem::Const, self.id) | ||
861 | } | ||
862 | } | ||
863 | impl AsAssocItem for TypeAlias { | ||
864 | fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> { | ||
865 | as_assoc_item(db, AssocItem::TypeAlias, self.id) | ||
866 | } | ||
867 | } | ||
868 | fn as_assoc_item<ID, DEF, CTOR, AST>(db: &dyn HirDatabase, ctor: CTOR, id: ID) -> Option<AssocItem> | ||
869 | where | ||
870 | ID: Lookup<Data = AssocItemLoc<AST>>, | ||
871 | DEF: From<ID>, | ||
872 | CTOR: FnOnce(DEF) -> AssocItem, | ||
873 | AST: ItemTreeNode, | ||
874 | { | ||
875 | match id.lookup(db.upcast()).container { | ||
876 | AssocContainerId::TraitId(_) | AssocContainerId::ImplId(_) => Some(ctor(DEF::from(id))), | ||
877 | AssocContainerId::ContainerId(_) => None, | ||
878 | } | ||
879 | } | ||
880 | |||
881 | impl AssocItem { | ||
882 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
883 | match self { | ||
884 | AssocItem::Function(f) => f.module(db), | ||
885 | AssocItem::Const(c) => c.module(db), | ||
886 | AssocItem::TypeAlias(t) => t.module(db), | ||
887 | } | ||
888 | } | ||
889 | pub fn container(self, db: &dyn HirDatabase) -> AssocItemContainer { | ||
890 | let container = match self { | ||
891 | AssocItem::Function(it) => it.id.lookup(db.upcast()).container, | ||
892 | AssocItem::Const(it) => it.id.lookup(db.upcast()).container, | ||
893 | AssocItem::TypeAlias(it) => it.id.lookup(db.upcast()).container, | ||
894 | }; | ||
895 | match container { | ||
896 | AssocContainerId::TraitId(id) => AssocItemContainer::Trait(id.into()), | ||
897 | AssocContainerId::ImplId(id) => AssocItemContainer::ImplDef(id.into()), | ||
898 | AssocContainerId::ContainerId(_) => panic!("invalid AssocItem"), | ||
899 | } | ||
900 | } | ||
901 | } | ||
902 | |||
903 | impl HasVisibility for AssocItem { | ||
904 | fn visibility(&self, db: &dyn HirDatabase) -> Visibility { | ||
905 | match self { | ||
906 | AssocItem::Function(f) => f.visibility(db), | ||
907 | AssocItem::Const(c) => c.visibility(db), | ||
908 | AssocItem::TypeAlias(t) => t.visibility(db), | ||
909 | } | ||
910 | } | ||
911 | } | ||
912 | |||
913 | #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] | ||
914 | pub enum GenericDef { | ||
915 | Function(Function), | ||
916 | Adt(Adt), | ||
917 | Trait(Trait), | ||
918 | TypeAlias(TypeAlias), | ||
919 | ImplDef(ImplDef), | ||
920 | // enum variants cannot have generics themselves, but their parent enums | ||
921 | // can, and this makes some code easier to write | ||
922 | EnumVariant(EnumVariant), | ||
923 | // consts can have type parameters from their parents (i.e. associated consts of traits) | ||
924 | Const(Const), | ||
925 | } | ||
926 | impl_from!( | ||
927 | Function, | ||
928 | Adt(Struct, Enum, Union), | ||
929 | Trait, | ||
930 | TypeAlias, | ||
931 | ImplDef, | ||
932 | EnumVariant, | ||
933 | Const | ||
934 | for GenericDef | ||
935 | ); | ||
936 | |||
937 | impl GenericDef { | ||
938 | pub fn params(self, db: &dyn HirDatabase) -> Vec<TypeParam> { | ||
939 | let generics: Arc<hir_def::generics::GenericParams> = db.generic_params(self.into()); | ||
940 | generics | ||
941 | .types | ||
942 | .iter() | ||
943 | .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } }) | ||
944 | .collect() | ||
945 | } | ||
946 | } | ||
947 | |||
948 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] | ||
949 | pub struct Local { | ||
950 | pub(crate) parent: DefWithBodyId, | ||
951 | pub(crate) pat_id: PatId, | ||
952 | } | ||
953 | |||
954 | impl Local { | ||
955 | pub fn is_param(self, db: &dyn HirDatabase) -> bool { | ||
956 | let src = self.source(db); | ||
957 | match src.value { | ||
958 | Either::Left(bind_pat) => { | ||
959 | bind_pat.syntax().ancestors().any(|it| ast::Param::can_cast(it.kind())) | ||
960 | } | ||
961 | Either::Right(_self_param) => true, | ||
962 | } | ||
963 | } | ||
964 | |||
965 | // FIXME: why is this an option? It shouldn't be? | ||
966 | pub fn name(self, db: &dyn HirDatabase) -> Option<Name> { | ||
967 | let body = db.body(self.parent.into()); | ||
968 | match &body[self.pat_id] { | ||
969 | Pat::Bind { name, .. } => Some(name.clone()), | ||
970 | _ => None, | ||
971 | } | ||
972 | } | ||
973 | |||
974 | pub fn is_self(self, db: &dyn HirDatabase) -> bool { | ||
975 | self.name(db) == Some(name![self]) | ||
976 | } | ||
977 | |||
978 | pub fn is_mut(self, db: &dyn HirDatabase) -> bool { | ||
979 | let body = db.body(self.parent.into()); | ||
980 | match &body[self.pat_id] { | ||
981 | Pat::Bind { mode, .. } => match mode { | ||
982 | BindingAnnotation::Mutable | BindingAnnotation::RefMut => true, | ||
983 | _ => false, | ||
984 | }, | ||
985 | _ => false, | ||
986 | } | ||
987 | } | ||
988 | |||
989 | pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody { | ||
990 | self.parent.into() | ||
991 | } | ||
992 | |||
993 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
994 | self.parent(db).module(db) | ||
995 | } | ||
996 | |||
997 | pub fn ty(self, db: &dyn HirDatabase) -> Type { | ||
998 | let def = DefWithBodyId::from(self.parent); | ||
999 | let infer = db.infer(def); | ||
1000 | let ty = infer[self.pat_id].clone(); | ||
1001 | let krate = def.module(db.upcast()).krate; | ||
1002 | Type::new(db, krate, def, ty) | ||
1003 | } | ||
1004 | |||
1005 | pub fn source(self, db: &dyn HirDatabase) -> InFile<Either<ast::IdentPat, ast::SelfParam>> { | ||
1006 | let (_body, source_map) = db.body_with_source_map(self.parent.into()); | ||
1007 | let src = source_map.pat_syntax(self.pat_id).unwrap(); // Hmm... | ||
1008 | let root = src.file_syntax(db.upcast()); | ||
1009 | src.map(|ast| { | ||
1010 | ast.map_left(|it| it.cast().unwrap().to_node(&root)).map_right(|it| it.to_node(&root)) | ||
1011 | }) | ||
1012 | } | ||
1013 | } | ||
1014 | |||
1015 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] | ||
1016 | pub struct TypeParam { | ||
1017 | pub(crate) id: TypeParamId, | ||
1018 | } | ||
1019 | |||
1020 | impl TypeParam { | ||
1021 | pub fn name(self, db: &dyn HirDatabase) -> Name { | ||
1022 | let params = db.generic_params(self.id.parent); | ||
1023 | params.types[self.id.local_id].name.clone().unwrap_or_else(Name::missing) | ||
1024 | } | ||
1025 | |||
1026 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
1027 | self.id.parent.module(db.upcast()).into() | ||
1028 | } | ||
1029 | |||
1030 | pub fn ty(self, db: &dyn HirDatabase) -> Type { | ||
1031 | let resolver = self.id.parent.resolver(db.upcast()); | ||
1032 | let environment = TraitEnvironment::lower(db, &resolver); | ||
1033 | let ty = Ty::Placeholder(self.id); | ||
1034 | Type { | ||
1035 | krate: self.id.parent.module(db.upcast()).krate, | ||
1036 | ty: InEnvironment { value: ty, environment }, | ||
1037 | } | ||
1038 | } | ||
1039 | |||
1040 | pub fn default(self, db: &dyn HirDatabase) -> Option<Type> { | ||
1041 | let params = db.generic_defaults(self.id.parent); | ||
1042 | let local_idx = hir_ty::param_idx(db, self.id)?; | ||
1043 | let resolver = self.id.parent.resolver(db.upcast()); | ||
1044 | let environment = TraitEnvironment::lower(db, &resolver); | ||
1045 | let ty = params.get(local_idx)?.clone(); | ||
1046 | let subst = Substs::type_params(db, self.id.parent); | ||
1047 | let ty = ty.subst(&subst.prefix(local_idx)); | ||
1048 | Some(Type { | ||
1049 | krate: self.id.parent.module(db.upcast()).krate, | ||
1050 | ty: InEnvironment { value: ty, environment }, | ||
1051 | }) | ||
1052 | } | ||
1053 | } | ||
1054 | |||
1055 | // FIXME: rename from `ImplDef` to `Impl` | ||
1056 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
1057 | pub struct ImplDef { | ||
1058 | pub(crate) id: ImplId, | ||
1059 | } | ||
1060 | |||
1061 | impl ImplDef { | ||
1062 | pub fn all_in_crate(db: &dyn HirDatabase, krate: Crate) -> Vec<ImplDef> { | ||
1063 | let inherent = db.inherent_impls_in_crate(krate.id); | ||
1064 | let trait_ = db.trait_impls_in_crate(krate.id); | ||
1065 | |||
1066 | inherent.all_impls().chain(trait_.all_impls()).map(Self::from).collect() | ||
1067 | } | ||
1068 | pub fn for_trait(db: &dyn HirDatabase, krate: Crate, trait_: Trait) -> Vec<ImplDef> { | ||
1069 | let impls = db.trait_impls_in_crate(krate.id); | ||
1070 | impls.for_trait(trait_.id).map(Self::from).collect() | ||
1071 | } | ||
1072 | |||
1073 | pub fn target_trait(self, db: &dyn HirDatabase) -> Option<TypeRef> { | ||
1074 | db.impl_data(self.id).target_trait.clone() | ||
1075 | } | ||
1076 | |||
1077 | pub fn target_type(self, db: &dyn HirDatabase) -> TypeRef { | ||
1078 | db.impl_data(self.id).target_type.clone() | ||
1079 | } | ||
1080 | |||
1081 | pub fn target_ty(self, db: &dyn HirDatabase) -> Type { | ||
1082 | let impl_data = db.impl_data(self.id); | ||
1083 | let resolver = self.id.resolver(db.upcast()); | ||
1084 | let ctx = hir_ty::TyLoweringContext::new(db, &resolver); | ||
1085 | let environment = TraitEnvironment::lower(db, &resolver); | ||
1086 | let ty = Ty::from_hir(&ctx, &impl_data.target_type); | ||
1087 | Type { | ||
1088 | krate: self.id.lookup(db.upcast()).container.module(db.upcast()).krate, | ||
1089 | ty: InEnvironment { value: ty, environment }, | ||
1090 | } | ||
1091 | } | ||
1092 | |||
1093 | pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> { | ||
1094 | db.impl_data(self.id).items.iter().map(|it| (*it).into()).collect() | ||
1095 | } | ||
1096 | |||
1097 | pub fn is_negative(self, db: &dyn HirDatabase) -> bool { | ||
1098 | db.impl_data(self.id).is_negative | ||
1099 | } | ||
1100 | |||
1101 | pub fn module(self, db: &dyn HirDatabase) -> Module { | ||
1102 | self.id.lookup(db.upcast()).container.module(db.upcast()).into() | ||
1103 | } | ||
1104 | |||
1105 | pub fn krate(self, db: &dyn HirDatabase) -> Crate { | ||
1106 | Crate { id: self.module(db).id.krate } | ||
1107 | } | ||
1108 | |||
1109 | pub fn is_builtin_derive(self, db: &dyn HirDatabase) -> Option<InFile<ast::Attr>> { | ||
1110 | let src = self.source(db); | ||
1111 | let item = src.file_id.is_builtin_derive(db.upcast())?; | ||
1112 | let hygenic = hir_expand::hygiene::Hygiene::new(db.upcast(), item.file_id); | ||
1113 | |||
1114 | let attr = item | ||
1115 | .value | ||
1116 | .attrs() | ||
1117 | .filter_map(|it| { | ||
1118 | let path = hir_def::path::ModPath::from_src(it.path()?, &hygenic)?; | ||
1119 | if path.as_ident()?.to_string() == "derive" { | ||
1120 | Some(it) | ||
1121 | } else { | ||
1122 | None | ||
1123 | } | ||
1124 | }) | ||
1125 | .last()?; | ||
1126 | |||
1127 | Some(item.with_value(attr)) | ||
1128 | } | ||
1129 | } | ||
1130 | |||
1131 | #[derive(Clone, PartialEq, Eq, Debug)] | ||
1132 | pub struct Type { | ||
1133 | krate: CrateId, | ||
1134 | ty: InEnvironment<Ty>, | ||
1135 | } | ||
1136 | |||
1137 | impl Type { | ||
1138 | pub(crate) fn new_with_resolver( | ||
1139 | db: &dyn HirDatabase, | ||
1140 | resolver: &Resolver, | ||
1141 | ty: Ty, | ||
1142 | ) -> Option<Type> { | ||
1143 | let krate = resolver.krate()?; | ||
1144 | Some(Type::new_with_resolver_inner(db, krate, resolver, ty)) | ||
1145 | } | ||
1146 | pub(crate) fn new_with_resolver_inner( | ||
1147 | db: &dyn HirDatabase, | ||
1148 | krate: CrateId, | ||
1149 | resolver: &Resolver, | ||
1150 | ty: Ty, | ||
1151 | ) -> Type { | ||
1152 | let environment = TraitEnvironment::lower(db, &resolver); | ||
1153 | Type { krate, ty: InEnvironment { value: ty, environment } } | ||
1154 | } | ||
1155 | |||
1156 | fn new(db: &dyn HirDatabase, krate: CrateId, lexical_env: impl HasResolver, ty: Ty) -> Type { | ||
1157 | let resolver = lexical_env.resolver(db.upcast()); | ||
1158 | let environment = TraitEnvironment::lower(db, &resolver); | ||
1159 | Type { krate, ty: InEnvironment { value: ty, environment } } | ||
1160 | } | ||
1161 | |||
1162 | fn from_def( | ||
1163 | db: &dyn HirDatabase, | ||
1164 | krate: CrateId, | ||
1165 | def: impl HasResolver + Into<TyDefId> + Into<GenericDefId>, | ||
1166 | ) -> Type { | ||
1167 | let substs = Substs::build_for_def(db, def).fill_with_unknown().build(); | ||
1168 | let ty = db.ty(def.into()).subst(&substs); | ||
1169 | Type::new(db, krate, def, ty) | ||
1170 | } | ||
1171 | |||
1172 | pub fn is_unit(&self) -> bool { | ||
1173 | matches!( | ||
1174 | self.ty.value, | ||
1175 | Ty::Apply(ApplicationTy { ctor: TypeCtor::Tuple { cardinality: 0 }, .. }) | ||
1176 | ) | ||
1177 | } | ||
1178 | pub fn is_bool(&self) -> bool { | ||
1179 | matches!(self.ty.value, Ty::Apply(ApplicationTy { ctor: TypeCtor::Bool, .. })) | ||
1180 | } | ||
1181 | |||
1182 | pub fn is_mutable_reference(&self) -> bool { | ||
1183 | matches!( | ||
1184 | self.ty.value, | ||
1185 | Ty::Apply(ApplicationTy { ctor: TypeCtor::Ref(Mutability::Mut), .. }) | ||
1186 | ) | ||
1187 | } | ||
1188 | |||
1189 | pub fn is_unknown(&self) -> bool { | ||
1190 | matches!(self.ty.value, Ty::Unknown) | ||
1191 | } | ||
1192 | |||
1193 | /// Checks that particular type `ty` implements `std::future::Future`. | ||
1194 | /// This function is used in `.await` syntax completion. | ||
1195 | pub fn impls_future(&self, db: &dyn HirDatabase) -> bool { | ||
1196 | let krate = self.krate; | ||
1197 | |||
1198 | let std_future_trait = | ||
1199 | db.lang_item(krate, "future_trait".into()).and_then(|it| it.as_trait()); | ||
1200 | let std_future_trait = match std_future_trait { | ||
1201 | Some(it) => it, | ||
1202 | None => return false, | ||
1203 | }; | ||
1204 | |||
1205 | let canonical_ty = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) }; | ||
1206 | method_resolution::implements_trait( | ||
1207 | &canonical_ty, | ||
1208 | db, | ||
1209 | self.ty.environment.clone(), | ||
1210 | krate, | ||
1211 | std_future_trait, | ||
1212 | ) | ||
1213 | } | ||
1214 | |||
1215 | pub fn impls_trait(&self, db: &dyn HirDatabase, trait_: Trait, args: &[Type]) -> bool { | ||
1216 | let trait_ref = hir_ty::TraitRef { | ||
1217 | trait_: trait_.id, | ||
1218 | substs: Substs::build_for_def(db, trait_.id) | ||
1219 | .push(self.ty.value.clone()) | ||
1220 | .fill(args.iter().map(|t| t.ty.value.clone())) | ||
1221 | .build(), | ||
1222 | }; | ||
1223 | |||
1224 | let goal = Canonical { | ||
1225 | value: hir_ty::InEnvironment::new( | ||
1226 | self.ty.environment.clone(), | ||
1227 | hir_ty::Obligation::Trait(trait_ref), | ||
1228 | ), | ||
1229 | kinds: Arc::new([]), | ||
1230 | }; | ||
1231 | |||
1232 | db.trait_solve(self.krate, goal).is_some() | ||
1233 | } | ||
1234 | |||
1235 | pub fn as_callable(&self, db: &dyn HirDatabase) -> Option<Callable> { | ||
1236 | let def = match self.ty.value { | ||
1237 | Ty::Apply(ApplicationTy { ctor: TypeCtor::FnDef(def), parameters: _ }) => Some(def), | ||
1238 | _ => None, | ||
1239 | }; | ||
1240 | |||
1241 | let sig = self.ty.value.callable_sig(db)?; | ||
1242 | Some(Callable { ty: self.clone(), sig, def, is_bound_method: false }) | ||
1243 | } | ||
1244 | |||
1245 | pub fn is_closure(&self) -> bool { | ||
1246 | matches!(&self.ty.value, Ty::Apply(ApplicationTy { ctor: TypeCtor::Closure { .. }, .. })) | ||
1247 | } | ||
1248 | |||
1249 | pub fn is_fn(&self) -> bool { | ||
1250 | matches!(&self.ty.value, | ||
1251 | Ty::Apply(ApplicationTy { ctor: TypeCtor::FnDef(..), .. }) | | ||
1252 | Ty::Apply(ApplicationTy { ctor: TypeCtor::FnPtr { .. }, .. }) | ||
1253 | ) | ||
1254 | } | ||
1255 | |||
1256 | pub fn is_raw_ptr(&self) -> bool { | ||
1257 | matches!(&self.ty.value, Ty::Apply(ApplicationTy { ctor: TypeCtor::RawPtr(..), .. })) | ||
1258 | } | ||
1259 | |||
1260 | pub fn contains_unknown(&self) -> bool { | ||
1261 | return go(&self.ty.value); | ||
1262 | |||
1263 | fn go(ty: &Ty) -> bool { | ||
1264 | match ty { | ||
1265 | Ty::Unknown => true, | ||
1266 | Ty::Apply(a_ty) => a_ty.parameters.iter().any(go), | ||
1267 | _ => false, | ||
1268 | } | ||
1269 | } | ||
1270 | } | ||
1271 | |||
1272 | pub fn fields(&self, db: &dyn HirDatabase) -> Vec<(Field, Type)> { | ||
1273 | if let Ty::Apply(a_ty) = &self.ty.value { | ||
1274 | let variant_id = match a_ty.ctor { | ||
1275 | TypeCtor::Adt(AdtId::StructId(s)) => s.into(), | ||
1276 | TypeCtor::Adt(AdtId::UnionId(u)) => u.into(), | ||
1277 | _ => return Vec::new(), | ||
1278 | }; | ||
1279 | |||
1280 | return db | ||
1281 | .field_types(variant_id) | ||
1282 | .iter() | ||
1283 | .map(|(local_id, ty)| { | ||
1284 | let def = Field { parent: variant_id.into(), id: local_id }; | ||
1285 | let ty = ty.clone().subst(&a_ty.parameters); | ||
1286 | (def, self.derived(ty)) | ||
1287 | }) | ||
1288 | .collect(); | ||
1289 | }; | ||
1290 | Vec::new() | ||
1291 | } | ||
1292 | |||
1293 | pub fn tuple_fields(&self, _db: &dyn HirDatabase) -> Vec<Type> { | ||
1294 | let mut res = Vec::new(); | ||
1295 | if let Ty::Apply(a_ty) = &self.ty.value { | ||
1296 | if let TypeCtor::Tuple { .. } = a_ty.ctor { | ||
1297 | for ty in a_ty.parameters.iter() { | ||
1298 | let ty = ty.clone(); | ||
1299 | res.push(self.derived(ty)); | ||
1300 | } | ||
1301 | } | ||
1302 | }; | ||
1303 | res | ||
1304 | } | ||
1305 | |||
1306 | pub fn autoderef<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Type> + 'a { | ||
1307 | // There should be no inference vars in types passed here | ||
1308 | // FIXME check that? | ||
1309 | let canonical = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) }; | ||
1310 | let environment = self.ty.environment.clone(); | ||
1311 | let ty = InEnvironment { value: canonical, environment }; | ||
1312 | autoderef(db, Some(self.krate), ty) | ||
1313 | .map(|canonical| canonical.value) | ||
1314 | .map(move |ty| self.derived(ty)) | ||
1315 | } | ||
1316 | |||
1317 | // This would be nicer if it just returned an iterator, but that runs into | ||
1318 | // lifetime problems, because we need to borrow temp `CrateImplDefs`. | ||
1319 | pub fn iterate_assoc_items<T>( | ||
1320 | self, | ||
1321 | db: &dyn HirDatabase, | ||
1322 | krate: Crate, | ||
1323 | mut callback: impl FnMut(AssocItem) -> Option<T>, | ||
1324 | ) -> Option<T> { | ||
1325 | for krate in self.ty.value.def_crates(db, krate.id)? { | ||
1326 | let impls = db.inherent_impls_in_crate(krate); | ||
1327 | |||
1328 | for impl_def in impls.for_self_ty(&self.ty.value) { | ||
1329 | for &item in db.impl_data(*impl_def).items.iter() { | ||
1330 | if let Some(result) = callback(item.into()) { | ||
1331 | return Some(result); | ||
1332 | } | ||
1333 | } | ||
1334 | } | ||
1335 | } | ||
1336 | None | ||
1337 | } | ||
1338 | |||
1339 | pub fn iterate_method_candidates<T>( | ||
1340 | &self, | ||
1341 | db: &dyn HirDatabase, | ||
1342 | krate: Crate, | ||
1343 | traits_in_scope: &FxHashSet<TraitId>, | ||
1344 | name: Option<&Name>, | ||
1345 | mut callback: impl FnMut(&Ty, Function) -> Option<T>, | ||
1346 | ) -> Option<T> { | ||
1347 | // There should be no inference vars in types passed here | ||
1348 | // FIXME check that? | ||
1349 | // FIXME replace Unknown by bound vars here | ||
1350 | let canonical = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) }; | ||
1351 | |||
1352 | let env = self.ty.environment.clone(); | ||
1353 | let krate = krate.id; | ||
1354 | |||
1355 | method_resolution::iterate_method_candidates( | ||
1356 | &canonical, | ||
1357 | db, | ||
1358 | env, | ||
1359 | krate, | ||
1360 | traits_in_scope, | ||
1361 | name, | ||
1362 | method_resolution::LookupMode::MethodCall, | ||
1363 | |ty, it| match it { | ||
1364 | AssocItemId::FunctionId(f) => callback(ty, f.into()), | ||
1365 | _ => None, | ||
1366 | }, | ||
1367 | ) | ||
1368 | } | ||
1369 | |||
1370 | pub fn iterate_path_candidates<T>( | ||
1371 | &self, | ||
1372 | db: &dyn HirDatabase, | ||
1373 | krate: Crate, | ||
1374 | traits_in_scope: &FxHashSet<TraitId>, | ||
1375 | name: Option<&Name>, | ||
1376 | mut callback: impl FnMut(&Ty, AssocItem) -> Option<T>, | ||
1377 | ) -> Option<T> { | ||
1378 | // There should be no inference vars in types passed here | ||
1379 | // FIXME check that? | ||
1380 | // FIXME replace Unknown by bound vars here | ||
1381 | let canonical = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) }; | ||
1382 | |||
1383 | let env = self.ty.environment.clone(); | ||
1384 | let krate = krate.id; | ||
1385 | |||
1386 | method_resolution::iterate_method_candidates( | ||
1387 | &canonical, | ||
1388 | db, | ||
1389 | env, | ||
1390 | krate, | ||
1391 | traits_in_scope, | ||
1392 | name, | ||
1393 | method_resolution::LookupMode::Path, | ||
1394 | |ty, it| callback(ty, it.into()), | ||
1395 | ) | ||
1396 | } | ||
1397 | |||
1398 | pub fn as_adt(&self) -> Option<Adt> { | ||
1399 | let (adt, _subst) = self.ty.value.as_adt()?; | ||
1400 | Some(adt.into()) | ||
1401 | } | ||
1402 | |||
1403 | pub fn as_dyn_trait(&self) -> Option<Trait> { | ||
1404 | self.ty.value.dyn_trait().map(Into::into) | ||
1405 | } | ||
1406 | |||
1407 | pub fn as_impl_traits(&self, db: &dyn HirDatabase) -> Option<Vec<Trait>> { | ||
1408 | self.ty.value.impl_trait_bounds(db).map(|it| { | ||
1409 | it.into_iter() | ||
1410 | .filter_map(|pred| match pred { | ||
1411 | hir_ty::GenericPredicate::Implemented(trait_ref) => { | ||
1412 | Some(Trait::from(trait_ref.trait_)) | ||
1413 | } | ||
1414 | _ => None, | ||
1415 | }) | ||
1416 | .collect() | ||
1417 | }) | ||
1418 | } | ||
1419 | |||
1420 | pub fn as_associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<Trait> { | ||
1421 | self.ty.value.associated_type_parent_trait(db).map(Into::into) | ||
1422 | } | ||
1423 | |||
1424 | // FIXME: provide required accessors such that it becomes implementable from outside. | ||
1425 | pub fn is_equal_for_find_impls(&self, other: &Type) -> bool { | ||
1426 | match (&self.ty.value, &other.ty.value) { | ||
1427 | (Ty::Apply(a_original_ty), Ty::Apply(ApplicationTy { ctor, parameters })) => match ctor | ||
1428 | { | ||
1429 | TypeCtor::Ref(..) => match parameters.as_single() { | ||
1430 | Ty::Apply(a_ty) => a_original_ty.ctor == a_ty.ctor, | ||
1431 | _ => false, | ||
1432 | }, | ||
1433 | _ => a_original_ty.ctor == *ctor, | ||
1434 | }, | ||
1435 | _ => false, | ||
1436 | } | ||
1437 | } | ||
1438 | |||
1439 | fn derived(&self, ty: Ty) -> Type { | ||
1440 | Type { | ||
1441 | krate: self.krate, | ||
1442 | ty: InEnvironment { value: ty, environment: self.ty.environment.clone() }, | ||
1443 | } | ||
1444 | } | ||
1445 | |||
1446 | pub fn walk(&self, db: &dyn HirDatabase, mut cb: impl FnMut(Type)) { | ||
1447 | // TypeWalk::walk for a Ty at first visits parameters and only after that the Ty itself. | ||
1448 | // We need a different order here. | ||
1449 | |||
1450 | fn walk_substs( | ||
1451 | db: &dyn HirDatabase, | ||
1452 | type_: &Type, | ||
1453 | substs: &Substs, | ||
1454 | cb: &mut impl FnMut(Type), | ||
1455 | ) { | ||
1456 | for ty in substs.iter() { | ||
1457 | walk_type(db, &type_.derived(ty.clone()), cb); | ||
1458 | } | ||
1459 | } | ||
1460 | |||
1461 | fn walk_bounds( | ||
1462 | db: &dyn HirDatabase, | ||
1463 | type_: &Type, | ||
1464 | bounds: &[GenericPredicate], | ||
1465 | cb: &mut impl FnMut(Type), | ||
1466 | ) { | ||
1467 | for pred in bounds { | ||
1468 | match pred { | ||
1469 | GenericPredicate::Implemented(trait_ref) => { | ||
1470 | cb(type_.clone()); | ||
1471 | walk_substs(db, type_, &trait_ref.substs, cb); | ||
1472 | } | ||
1473 | _ => (), | ||
1474 | } | ||
1475 | } | ||
1476 | } | ||
1477 | |||
1478 | fn walk_type(db: &dyn HirDatabase, type_: &Type, cb: &mut impl FnMut(Type)) { | ||
1479 | let ty = type_.ty.value.strip_references(); | ||
1480 | match ty { | ||
1481 | Ty::Apply(ApplicationTy { ctor, parameters }) => { | ||
1482 | match ctor { | ||
1483 | TypeCtor::Adt(_) => { | ||
1484 | cb(type_.derived(ty.clone())); | ||
1485 | } | ||
1486 | TypeCtor::AssociatedType(_) => { | ||
1487 | if let Some(_) = ty.associated_type_parent_trait(db) { | ||
1488 | cb(type_.derived(ty.clone())); | ||
1489 | } | ||
1490 | } | ||
1491 | _ => (), | ||
1492 | } | ||
1493 | |||
1494 | // adt params, tuples, etc... | ||
1495 | walk_substs(db, type_, parameters, cb); | ||
1496 | } | ||
1497 | Ty::Opaque(opaque_ty) => { | ||
1498 | if let Some(bounds) = ty.impl_trait_bounds(db) { | ||
1499 | walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb); | ||
1500 | } | ||
1501 | |||
1502 | walk_substs(db, type_, &opaque_ty.parameters, cb); | ||
1503 | } | ||
1504 | Ty::Placeholder(_) => { | ||
1505 | if let Some(bounds) = ty.impl_trait_bounds(db) { | ||
1506 | walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb); | ||
1507 | } | ||
1508 | } | ||
1509 | Ty::Dyn(bounds) => { | ||
1510 | walk_bounds(db, &type_.derived(ty.clone()), bounds.as_ref(), cb); | ||
1511 | } | ||
1512 | |||
1513 | _ => (), | ||
1514 | } | ||
1515 | } | ||
1516 | |||
1517 | walk_type(db, self, &mut cb); | ||
1518 | } | ||
1519 | } | ||
1520 | |||
1521 | impl HirDisplay for Type { | ||
1522 | fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> { | ||
1523 | self.ty.value.hir_fmt(f) | ||
1524 | } | ||
1525 | } | ||
1526 | |||
1527 | // FIXME: closures | ||
1528 | #[derive(Debug)] | ||
1529 | pub struct Callable { | ||
1530 | ty: Type, | ||
1531 | sig: FnSig, | ||
1532 | def: Option<CallableDefId>, | ||
1533 | pub(crate) is_bound_method: bool, | ||
1534 | } | ||
1535 | |||
1536 | pub enum CallableKind { | ||
1537 | Function(Function), | ||
1538 | TupleStruct(Struct), | ||
1539 | TupleEnumVariant(EnumVariant), | ||
1540 | Closure, | ||
1541 | } | ||
1542 | |||
1543 | impl Callable { | ||
1544 | pub fn kind(&self) -> CallableKind { | ||
1545 | match self.def { | ||
1546 | Some(CallableDefId::FunctionId(it)) => CallableKind::Function(it.into()), | ||
1547 | Some(CallableDefId::StructId(it)) => CallableKind::TupleStruct(it.into()), | ||
1548 | Some(CallableDefId::EnumVariantId(it)) => CallableKind::TupleEnumVariant(it.into()), | ||
1549 | None => CallableKind::Closure, | ||
1550 | } | ||
1551 | } | ||
1552 | pub fn receiver_param(&self, db: &dyn HirDatabase) -> Option<ast::SelfParam> { | ||
1553 | let func = match self.def { | ||
1554 | Some(CallableDefId::FunctionId(it)) if self.is_bound_method => it, | ||
1555 | _ => return None, | ||
1556 | }; | ||
1557 | let src = func.lookup(db.upcast()).source(db.upcast()); | ||
1558 | let param_list = src.value.param_list()?; | ||
1559 | param_list.self_param() | ||
1560 | } | ||
1561 | pub fn n_params(&self) -> usize { | ||
1562 | self.sig.params().len() - if self.is_bound_method { 1 } else { 0 } | ||
1563 | } | ||
1564 | pub fn params( | ||
1565 | &self, | ||
1566 | db: &dyn HirDatabase, | ||
1567 | ) -> Vec<(Option<Either<ast::SelfParam, ast::Pat>>, Type)> { | ||
1568 | let types = self | ||
1569 | .sig | ||
1570 | .params() | ||
1571 | .iter() | ||
1572 | .skip(if self.is_bound_method { 1 } else { 0 }) | ||
1573 | .map(|ty| self.ty.derived(ty.clone())); | ||
1574 | let patterns = match self.def { | ||
1575 | Some(CallableDefId::FunctionId(func)) => { | ||
1576 | let src = func.lookup(db.upcast()).source(db.upcast()); | ||
1577 | src.value.param_list().map(|param_list| { | ||
1578 | param_list | ||
1579 | .self_param() | ||
1580 | .map(|it| Some(Either::Left(it))) | ||
1581 | .filter(|_| !self.is_bound_method) | ||
1582 | .into_iter() | ||
1583 | .chain(param_list.params().map(|it| it.pat().map(Either::Right))) | ||
1584 | }) | ||
1585 | } | ||
1586 | _ => None, | ||
1587 | }; | ||
1588 | patterns.into_iter().flatten().chain(iter::repeat(None)).zip(types).collect() | ||
1589 | } | ||
1590 | pub fn return_type(&self) -> Type { | ||
1591 | self.ty.derived(self.sig.ret().clone()) | ||
1592 | } | ||
1593 | } | ||
1594 | |||
1595 | /// For IDE only | ||
1596 | #[derive(Debug)] | ||
1597 | pub enum ScopeDef { | ||
1598 | ModuleDef(ModuleDef), | ||
1599 | MacroDef(MacroDef), | ||
1600 | GenericParam(TypeParam), | ||
1601 | ImplSelfType(ImplDef), | ||
1602 | AdtSelfType(Adt), | ||
1603 | Local(Local), | ||
1604 | Unknown, | ||
1605 | } | ||
1606 | |||
1607 | impl ScopeDef { | ||
1608 | pub fn all_items(def: PerNs) -> ArrayVec<[Self; 3]> { | ||
1609 | let mut items = ArrayVec::new(); | ||
1610 | |||
1611 | match (def.take_types(), def.take_values()) { | ||
1612 | (Some(m1), None) => items.push(ScopeDef::ModuleDef(m1.into())), | ||
1613 | (None, Some(m2)) => items.push(ScopeDef::ModuleDef(m2.into())), | ||
1614 | (Some(m1), Some(m2)) => { | ||
1615 | // Some items, like unit structs and enum variants, are | ||
1616 | // returned as both a type and a value. Here we want | ||
1617 | // to de-duplicate them. | ||
1618 | if m1 != m2 { | ||
1619 | items.push(ScopeDef::ModuleDef(m1.into())); | ||
1620 | items.push(ScopeDef::ModuleDef(m2.into())); | ||
1621 | } else { | ||
1622 | items.push(ScopeDef::ModuleDef(m1.into())); | ||
1623 | } | ||
1624 | } | ||
1625 | (None, None) => {} | ||
1626 | }; | ||
1627 | |||
1628 | if let Some(macro_def_id) = def.take_macros() { | ||
1629 | items.push(ScopeDef::MacroDef(macro_def_id.into())); | ||
1630 | } | ||
1631 | |||
1632 | if items.is_empty() { | ||
1633 | items.push(ScopeDef::Unknown); | ||
1634 | } | ||
1635 | |||
1636 | items | ||
1637 | } | ||
1638 | } | ||
1639 | |||
1640 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] | ||
1641 | pub enum AttrDef { | ||
1642 | Module(Module), | ||
1643 | Field(Field), | ||
1644 | Adt(Adt), | ||
1645 | Function(Function), | ||
1646 | EnumVariant(EnumVariant), | ||
1647 | Static(Static), | ||
1648 | Const(Const), | ||
1649 | Trait(Trait), | ||
1650 | TypeAlias(TypeAlias), | ||
1651 | MacroDef(MacroDef), | ||
1652 | } | ||
1653 | |||
1654 | impl_from!( | ||
1655 | Module, | ||
1656 | Field, | ||
1657 | Adt(Struct, Enum, Union), | ||
1658 | EnumVariant, | ||
1659 | Static, | ||
1660 | Const, | ||
1661 | Function, | ||
1662 | Trait, | ||
1663 | TypeAlias, | ||
1664 | MacroDef | ||
1665 | for AttrDef | ||
1666 | ); | ||
1667 | |||
1668 | pub trait HasAttrs { | ||
1669 | fn attrs(self, db: &dyn HirDatabase) -> Attrs; | ||
1670 | } | ||
1671 | |||
1672 | impl<T: Into<AttrDef>> HasAttrs for T { | ||
1673 | fn attrs(self, db: &dyn HirDatabase) -> Attrs { | ||
1674 | let def: AttrDef = self.into(); | ||
1675 | db.attrs(def.into()) | ||
1676 | } | ||
1677 | } | ||
1678 | |||
1679 | pub trait Docs { | ||
1680 | fn docs(&self, db: &dyn HirDatabase) -> Option<Documentation>; | ||
1681 | } | ||
1682 | impl<T: Into<AttrDef> + Copy> Docs for T { | ||
1683 | fn docs(&self, db: &dyn HirDatabase) -> Option<Documentation> { | ||
1684 | let def: AttrDef = (*self).into(); | ||
1685 | db.documentation(def.into()) | ||
1686 | } | ||
1687 | } | ||
1688 | |||
1689 | pub trait HasVisibility { | ||
1690 | fn visibility(&self, db: &dyn HirDatabase) -> Visibility; | ||
1691 | fn is_visible_from(&self, db: &dyn HirDatabase, module: Module) -> bool { | ||
1692 | let vis = self.visibility(db); | ||
1693 | vis.is_visible_from(db.upcast(), module.id) | ||
1694 | } | ||
1695 | } | ||