aboutsummaryrefslogtreecommitdiff
path: root/crates/hir/src
diff options
context:
space:
mode:
Diffstat (limited to 'crates/hir/src')
-rw-r--r--crates/hir/src/code_model.rs2128
-rw-r--r--crates/hir/src/diagnostics.rs4
-rw-r--r--crates/hir/src/from_id.rs5
-rw-r--r--crates/hir/src/lib.rs2127
-rw-r--r--crates/hir/src/semantics.rs13
-rw-r--r--crates/hir/src/source_analyzer.rs21
6 files changed, 2114 insertions, 2184 deletions
diff --git a/crates/hir/src/code_model.rs b/crates/hir/src/code_model.rs
deleted file mode 100644
index b3218833d..000000000
--- a/crates/hir/src/code_model.rs
+++ /dev/null
@@ -1,2128 +0,0 @@
1//! FIXME: write short doc here
2use std::{iter, sync::Arc};
3
4use arrayvec::ArrayVec;
5use base_db::{CrateDisplayName, CrateId, Edition, FileId};
6use either::Either;
7use hir_def::{
8 adt::{ReprKind, StructKind, VariantData},
9 expr::{BindingAnnotation, LabelId, Pat, PatId},
10 import_map,
11 item_tree::ItemTreeNode,
12 lang_item::LangItemTarget,
13 path::ModPath,
14 per_ns::PerNs,
15 resolver::{HasResolver, Resolver},
16 src::HasSource as _,
17 type_ref::{Mutability, TypeRef},
18 AdtId, AssocContainerId, AssocItemId, AssocItemLoc, AttrDefId, ConstId, ConstParamId,
19 DefWithBodyId, EnumId, FunctionId, GenericDefId, HasModule, ImplId, LifetimeParamId,
20 LocalEnumVariantId, LocalFieldId, Lookup, ModuleId, StaticId, StructId, TraitId, TypeAliasId,
21 TypeParamId, UnionId,
22};
23use hir_def::{find_path::PrefixKind, item_scope::ItemInNs, visibility::Visibility};
24use hir_expand::{
25 diagnostics::DiagnosticSink,
26 name::{name, AsName},
27 MacroDefId, MacroDefKind,
28};
29use hir_ty::{
30 autoderef,
31 display::{write_bounds_like_dyn_trait_with_prefix, HirDisplayError, HirFormatter},
32 method_resolution,
33 traits::{FnTrait, Solution, SolutionVariables},
34 ApplicationTy, BoundVar, CallableDefId, Canonical, DebruijnIndex, FnSig, GenericPredicate,
35 InEnvironment, Obligation, ProjectionPredicate, ProjectionTy, Substs, TraitEnvironment, Ty,
36 TyDefId, TyKind, TypeCtor,
37};
38use rustc_hash::FxHashSet;
39use stdx::{format_to, impl_from};
40use syntax::{
41 ast::{self, AttrsOwner, NameOwner},
42 AstNode, SmolStr,
43};
44use tt::{Ident, Leaf, Literal, TokenTree};
45
46use crate::{
47 db::{DefDatabase, HirDatabase},
48 has_source::HasSource,
49 HirDisplay, InFile, Name,
50};
51
52/// hir::Crate describes a single crate. It's the main interface with which
53/// a crate's dependencies interact. Mostly, it should be just a proxy for the
54/// root module.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
56pub struct Crate {
57 pub(crate) id: CrateId,
58}
59
60#[derive(Debug)]
61pub struct CrateDependency {
62 pub krate: Crate,
63 pub name: Name,
64}
65
66impl Crate {
67 pub fn dependencies(self, db: &dyn HirDatabase) -> Vec<CrateDependency> {
68 db.crate_graph()[self.id]
69 .dependencies
70 .iter()
71 .map(|dep| {
72 let krate = Crate { id: dep.crate_id };
73 let name = dep.as_name();
74 CrateDependency { krate, name }
75 })
76 .collect()
77 }
78
79 // FIXME: add `transitive_reverse_dependencies`.
80 pub fn reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
81 let crate_graph = db.crate_graph();
82 crate_graph
83 .iter()
84 .filter(|&krate| {
85 crate_graph[krate].dependencies.iter().any(|it| it.crate_id == self.id)
86 })
87 .map(|id| Crate { id })
88 .collect()
89 }
90
91 pub fn root_module(self, db: &dyn HirDatabase) -> Module {
92 let def_map = db.crate_def_map(self.id);
93 Module { id: def_map.module_id(def_map.root()) }
94 }
95
96 pub fn root_file(self, db: &dyn HirDatabase) -> FileId {
97 db.crate_graph()[self.id].root_file_id
98 }
99
100 pub fn edition(self, db: &dyn HirDatabase) -> Edition {
101 db.crate_graph()[self.id].edition
102 }
103
104 pub fn display_name(self, db: &dyn HirDatabase) -> Option<CrateDisplayName> {
105 db.crate_graph()[self.id].display_name.clone()
106 }
107
108 pub fn query_external_importables(
109 self,
110 db: &dyn DefDatabase,
111 query: import_map::Query,
112 ) -> impl Iterator<Item = Either<ModuleDef, MacroDef>> {
113 import_map::search_dependencies(db, self.into(), query).into_iter().map(|item| match item {
114 ItemInNs::Types(mod_id) | ItemInNs::Values(mod_id) => Either::Left(mod_id.into()),
115 ItemInNs::Macros(mac_id) => Either::Right(mac_id.into()),
116 })
117 }
118
119 pub fn all(db: &dyn HirDatabase) -> Vec<Crate> {
120 db.crate_graph().iter().map(|id| Crate { id }).collect()
121 }
122
123 /// Try to get the root URL of the documentation of a crate.
124 pub fn get_html_root_url(self: &Crate, db: &dyn HirDatabase) -> Option<String> {
125 // Look for #![doc(html_root_url = "...")]
126 let attrs = db.attrs(AttrDefId::ModuleId(self.root_module(db).into()));
127 let doc_attr_q = attrs.by_key("doc");
128
129 if !doc_attr_q.exists() {
130 return None;
131 }
132
133 let doc_url = doc_attr_q.tt_values().map(|tt| {
134 let name = tt.token_trees.iter()
135 .skip_while(|tt| !matches!(tt, TokenTree::Leaf(Leaf::Ident(Ident{text: ref ident, ..})) if ident == "html_root_url"))
136 .skip(2)
137 .next();
138
139 match name {
140 Some(TokenTree::Leaf(Leaf::Literal(Literal{ref text, ..}))) => Some(text),
141 _ => None
142 }
143 }).flat_map(|t| t).next();
144
145 doc_url.map(|s| s.trim_matches('"').trim_end_matches('/').to_owned() + "/")
146 }
147}
148
149#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
150pub struct Module {
151 pub(crate) id: ModuleId,
152}
153
154/// The defs which can be visible in the module.
155#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
156pub enum ModuleDef {
157 Module(Module),
158 Function(Function),
159 Adt(Adt),
160 // Can't be directly declared, but can be imported.
161 Variant(Variant),
162 Const(Const),
163 Static(Static),
164 Trait(Trait),
165 TypeAlias(TypeAlias),
166 BuiltinType(BuiltinType),
167}
168impl_from!(
169 Module,
170 Function,
171 Adt(Struct, Enum, Union),
172 Variant,
173 Const,
174 Static,
175 Trait,
176 TypeAlias,
177 BuiltinType
178 for ModuleDef
179);
180
181impl From<VariantDef> for ModuleDef {
182 fn from(var: VariantDef) -> Self {
183 match var {
184 VariantDef::Struct(t) => Adt::from(t).into(),
185 VariantDef::Union(t) => Adt::from(t).into(),
186 VariantDef::Variant(t) => t.into(),
187 }
188 }
189}
190
191impl ModuleDef {
192 pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
193 match self {
194 ModuleDef::Module(it) => it.parent(db),
195 ModuleDef::Function(it) => Some(it.module(db)),
196 ModuleDef::Adt(it) => Some(it.module(db)),
197 ModuleDef::Variant(it) => Some(it.module(db)),
198 ModuleDef::Const(it) => Some(it.module(db)),
199 ModuleDef::Static(it) => Some(it.module(db)),
200 ModuleDef::Trait(it) => Some(it.module(db)),
201 ModuleDef::TypeAlias(it) => Some(it.module(db)),
202 ModuleDef::BuiltinType(_) => None,
203 }
204 }
205
206 pub fn canonical_path(&self, db: &dyn HirDatabase) -> Option<String> {
207 let mut segments = Vec::new();
208 segments.push(self.name(db)?.to_string());
209 for m in self.module(db)?.path_to_root(db) {
210 segments.extend(m.name(db).map(|it| it.to_string()))
211 }
212 segments.reverse();
213 Some(segments.join("::"))
214 }
215
216 pub fn definition_visibility(&self, db: &dyn HirDatabase) -> Option<Visibility> {
217 let module = match self {
218 ModuleDef::Module(it) => it.parent(db)?,
219 ModuleDef::Function(it) => return Some(it.visibility(db)),
220 ModuleDef::Adt(it) => it.module(db),
221 ModuleDef::Variant(it) => {
222 let parent = it.parent_enum(db);
223 let module = it.module(db);
224 return module.visibility_of(db, &ModuleDef::Adt(Adt::Enum(parent)));
225 }
226 ModuleDef::Const(it) => return Some(it.visibility(db)),
227 ModuleDef::Static(it) => it.module(db),
228 ModuleDef::Trait(it) => it.module(db),
229 ModuleDef::TypeAlias(it) => return Some(it.visibility(db)),
230 ModuleDef::BuiltinType(_) => return None,
231 };
232
233 module.visibility_of(db, self)
234 }
235
236 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
237 match self {
238 ModuleDef::Adt(it) => Some(it.name(db)),
239 ModuleDef::Trait(it) => Some(it.name(db)),
240 ModuleDef::Function(it) => Some(it.name(db)),
241 ModuleDef::Variant(it) => Some(it.name(db)),
242 ModuleDef::TypeAlias(it) => Some(it.name(db)),
243 ModuleDef::Module(it) => it.name(db),
244 ModuleDef::Const(it) => it.name(db),
245 ModuleDef::Static(it) => it.name(db),
246
247 ModuleDef::BuiltinType(it) => Some(it.name()),
248 }
249 }
250
251 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
252 let id = match self {
253 ModuleDef::Adt(it) => match it {
254 Adt::Struct(it) => it.id.into(),
255 Adt::Enum(it) => it.id.into(),
256 Adt::Union(it) => it.id.into(),
257 },
258 ModuleDef::Trait(it) => it.id.into(),
259 ModuleDef::Function(it) => it.id.into(),
260 ModuleDef::TypeAlias(it) => it.id.into(),
261 ModuleDef::Module(it) => it.id.into(),
262 ModuleDef::Const(it) => it.id.into(),
263 ModuleDef::Static(it) => it.id.into(),
264 _ => return,
265 };
266
267 let module = match self.module(db) {
268 Some(it) => it,
269 None => return,
270 };
271
272 hir_ty::diagnostics::validate_module_item(db, module.id.krate(), id, sink)
273 }
274}
275
276impl Module {
277 /// Name of this module.
278 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
279 let def_map = self.id.def_map(db.upcast());
280 let parent = def_map[self.id.local_id].parent?;
281 def_map[parent].children.iter().find_map(|(name, module_id)| {
282 if *module_id == self.id.local_id {
283 Some(name.clone())
284 } else {
285 None
286 }
287 })
288 }
289
290 /// Returns the crate this module is part of.
291 pub fn krate(self) -> Crate {
292 Crate { id: self.id.krate() }
293 }
294
295 /// Topmost parent of this module. Every module has a `crate_root`, but some
296 /// might be missing `krate`. This can happen if a module's file is not included
297 /// in the module tree of any target in `Cargo.toml`.
298 pub fn crate_root(self, db: &dyn HirDatabase) -> Module {
299 let def_map = db.crate_def_map(self.id.krate());
300 Module { id: def_map.module_id(def_map.root()) }
301 }
302
303 /// Iterates over all child modules.
304 pub fn children(self, db: &dyn HirDatabase) -> impl Iterator<Item = Module> {
305 let def_map = self.id.def_map(db.upcast());
306 let children = def_map[self.id.local_id]
307 .children
308 .iter()
309 .map(|(_, module_id)| Module { id: def_map.module_id(*module_id) })
310 .collect::<Vec<_>>();
311 children.into_iter()
312 }
313
314 /// Finds a parent module.
315 pub fn parent(self, db: &dyn HirDatabase) -> Option<Module> {
316 // FIXME: handle block expressions as modules (their parent is in a different DefMap)
317 let def_map = self.id.def_map(db.upcast());
318 let parent_id = def_map[self.id.local_id].parent?;
319 Some(Module { id: def_map.module_id(parent_id) })
320 }
321
322 pub fn path_to_root(self, db: &dyn HirDatabase) -> Vec<Module> {
323 let mut res = vec![self];
324 let mut curr = self;
325 while let Some(next) = curr.parent(db) {
326 res.push(next);
327 curr = next
328 }
329 res
330 }
331
332 /// Returns a `ModuleScope`: a set of items, visible in this module.
333 pub fn scope(
334 self,
335 db: &dyn HirDatabase,
336 visible_from: Option<Module>,
337 ) -> Vec<(Name, ScopeDef)> {
338 self.id.def_map(db.upcast())[self.id.local_id]
339 .scope
340 .entries()
341 .filter_map(|(name, def)| {
342 if let Some(m) = visible_from {
343 let filtered =
344 def.filter_visibility(|vis| vis.is_visible_from(db.upcast(), m.id));
345 if filtered.is_none() && !def.is_none() {
346 None
347 } else {
348 Some((name, filtered))
349 }
350 } else {
351 Some((name, def))
352 }
353 })
354 .flat_map(|(name, def)| {
355 ScopeDef::all_items(def).into_iter().map(move |item| (name.clone(), item))
356 })
357 .collect()
358 }
359
360 pub fn visibility_of(self, db: &dyn HirDatabase, def: &ModuleDef) -> Option<Visibility> {
361 self.id.def_map(db.upcast())[self.id.local_id].scope.visibility_of(def.clone().into())
362 }
363
364 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
365 let _p = profile::span("Module::diagnostics").detail(|| {
366 format!("{:?}", self.name(db).map_or("<unknown>".into(), |name| name.to_string()))
367 });
368 let crate_def_map = self.id.def_map(db.upcast());
369 crate_def_map.add_diagnostics(db.upcast(), self.id.local_id, sink);
370 for decl in self.declarations(db) {
371 match decl {
372 crate::ModuleDef::Function(f) => f.diagnostics(db, sink),
373 crate::ModuleDef::Module(m) => {
374 // Only add diagnostics from inline modules
375 if crate_def_map[m.id.local_id].origin.is_inline() {
376 m.diagnostics(db, sink)
377 }
378 }
379 _ => {
380 decl.diagnostics(db, sink);
381 }
382 }
383 }
384
385 for impl_def in self.impl_defs(db) {
386 for item in impl_def.items(db) {
387 if let AssocItem::Function(f) = item {
388 f.diagnostics(db, sink);
389 }
390 }
391 }
392 }
393
394 pub fn declarations(self, db: &dyn HirDatabase) -> Vec<ModuleDef> {
395 let def_map = self.id.def_map(db.upcast());
396 def_map[self.id.local_id].scope.declarations().map(ModuleDef::from).collect()
397 }
398
399 pub fn impl_defs(self, db: &dyn HirDatabase) -> Vec<Impl> {
400 let def_map = self.id.def_map(db.upcast());
401 def_map[self.id.local_id].scope.impls().map(Impl::from).collect()
402 }
403
404 /// Finds a path that can be used to refer to the given item from within
405 /// this module, if possible.
406 pub fn find_use_path(self, db: &dyn DefDatabase, item: impl Into<ItemInNs>) -> Option<ModPath> {
407 hir_def::find_path::find_path(db, item.into(), self.into())
408 }
409
410 /// Finds a path that can be used to refer to the given item from within
411 /// this module, if possible. This is used for returning import paths for use-statements.
412 pub fn find_use_path_prefixed(
413 self,
414 db: &dyn DefDatabase,
415 item: impl Into<ItemInNs>,
416 prefix_kind: PrefixKind,
417 ) -> Option<ModPath> {
418 hir_def::find_path::find_path_prefixed(db, item.into(), self.into(), prefix_kind)
419 }
420}
421
422#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
423pub struct Field {
424 pub(crate) parent: VariantDef,
425 pub(crate) id: LocalFieldId,
426}
427
428#[derive(Debug, PartialEq, Eq)]
429pub enum FieldSource {
430 Named(ast::RecordField),
431 Pos(ast::TupleField),
432}
433
434impl Field {
435 pub fn name(&self, db: &dyn HirDatabase) -> Name {
436 self.parent.variant_data(db).fields()[self.id].name.clone()
437 }
438
439 /// Returns the type as in the signature of the struct (i.e., with
440 /// placeholder types for type parameters). This is good for showing
441 /// signature help, but not so good to actually get the type of the field
442 /// when you actually have a variable of the struct.
443 pub fn signature_ty(&self, db: &dyn HirDatabase) -> Type {
444 let var_id = self.parent.into();
445 let generic_def_id: GenericDefId = match self.parent {
446 VariantDef::Struct(it) => it.id.into(),
447 VariantDef::Union(it) => it.id.into(),
448 VariantDef::Variant(it) => it.parent.id.into(),
449 };
450 let substs = Substs::type_params(db, generic_def_id);
451 let ty = db.field_types(var_id)[self.id].clone().subst(&substs);
452 Type::new(db, self.parent.module(db).id.krate(), var_id, ty)
453 }
454
455 pub fn parent_def(&self, _db: &dyn HirDatabase) -> VariantDef {
456 self.parent
457 }
458}
459
460impl HasVisibility for Field {
461 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
462 let variant_data = self.parent.variant_data(db);
463 let visibility = &variant_data.fields()[self.id].visibility;
464 let parent_id: hir_def::VariantId = self.parent.into();
465 visibility.resolve(db.upcast(), &parent_id.resolver(db.upcast()))
466 }
467}
468
469#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
470pub struct Struct {
471 pub(crate) id: StructId,
472}
473
474impl Struct {
475 pub fn module(self, db: &dyn HirDatabase) -> Module {
476 Module { id: self.id.lookup(db.upcast()).container.module(db.upcast()) }
477 }
478
479 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
480 Some(self.module(db).krate())
481 }
482
483 pub fn name(self, db: &dyn HirDatabase) -> Name {
484 db.struct_data(self.id).name.clone()
485 }
486
487 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
488 db.struct_data(self.id)
489 .variant_data
490 .fields()
491 .iter()
492 .map(|(id, _)| Field { parent: self.into(), id })
493 .collect()
494 }
495
496 pub fn ty(self, db: &dyn HirDatabase) -> Type {
497 Type::from_def(
498 db,
499 self.id.lookup(db.upcast()).container.module(db.upcast()).krate(),
500 self.id,
501 )
502 }
503
504 pub fn repr(self, db: &dyn HirDatabase) -> Option<ReprKind> {
505 db.struct_data(self.id).repr.clone()
506 }
507
508 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
509 self.variant_data(db).kind()
510 }
511
512 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
513 db.struct_data(self.id).variant_data.clone()
514 }
515}
516
517#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
518pub struct Union {
519 pub(crate) id: UnionId,
520}
521
522impl Union {
523 pub fn name(self, db: &dyn HirDatabase) -> Name {
524 db.union_data(self.id).name.clone()
525 }
526
527 pub fn module(self, db: &dyn HirDatabase) -> Module {
528 Module { id: self.id.lookup(db.upcast()).container.module(db.upcast()) }
529 }
530
531 pub fn ty(self, db: &dyn HirDatabase) -> Type {
532 Type::from_def(
533 db,
534 self.id.lookup(db.upcast()).container.module(db.upcast()).krate(),
535 self.id,
536 )
537 }
538
539 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
540 db.union_data(self.id)
541 .variant_data
542 .fields()
543 .iter()
544 .map(|(id, _)| Field { parent: self.into(), id })
545 .collect()
546 }
547
548 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
549 db.union_data(self.id).variant_data.clone()
550 }
551}
552
553#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
554pub struct Enum {
555 pub(crate) id: EnumId,
556}
557
558impl Enum {
559 pub fn module(self, db: &dyn HirDatabase) -> Module {
560 Module { id: self.id.lookup(db.upcast()).container.module(db.upcast()) }
561 }
562
563 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
564 Some(self.module(db).krate())
565 }
566
567 pub fn name(self, db: &dyn HirDatabase) -> Name {
568 db.enum_data(self.id).name.clone()
569 }
570
571 pub fn variants(self, db: &dyn HirDatabase) -> Vec<Variant> {
572 db.enum_data(self.id).variants.iter().map(|(id, _)| Variant { parent: self, id }).collect()
573 }
574
575 pub fn ty(self, db: &dyn HirDatabase) -> Type {
576 Type::from_def(
577 db,
578 self.id.lookup(db.upcast()).container.module(db.upcast()).krate(),
579 self.id,
580 )
581 }
582}
583
584#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
585pub struct Variant {
586 pub(crate) parent: Enum,
587 pub(crate) id: LocalEnumVariantId,
588}
589
590impl Variant {
591 pub fn module(self, db: &dyn HirDatabase) -> Module {
592 self.parent.module(db)
593 }
594 pub fn parent_enum(self, _db: &dyn HirDatabase) -> Enum {
595 self.parent
596 }
597
598 pub fn name(self, db: &dyn HirDatabase) -> Name {
599 db.enum_data(self.parent.id).variants[self.id].name.clone()
600 }
601
602 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
603 self.variant_data(db)
604 .fields()
605 .iter()
606 .map(|(id, _)| Field { parent: self.into(), id })
607 .collect()
608 }
609
610 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
611 self.variant_data(db).kind()
612 }
613
614 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
615 db.enum_data(self.parent.id).variants[self.id].variant_data.clone()
616 }
617}
618
619/// A Data Type
620#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
621pub enum Adt {
622 Struct(Struct),
623 Union(Union),
624 Enum(Enum),
625}
626impl_from!(Struct, Union, Enum for Adt);
627
628impl Adt {
629 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
630 let subst = db.generic_defaults(self.into());
631 subst.iter().any(|ty| &ty.value == &Ty::Unknown)
632 }
633
634 /// Turns this ADT into a type. Any type parameters of the ADT will be
635 /// turned into unknown types, which is good for e.g. finding the most
636 /// general set of completions, but will not look very nice when printed.
637 pub fn ty(self, db: &dyn HirDatabase) -> Type {
638 let id = AdtId::from(self);
639 Type::from_def(db, id.module(db.upcast()).krate(), id)
640 }
641
642 pub fn module(self, db: &dyn HirDatabase) -> Module {
643 match self {
644 Adt::Struct(s) => s.module(db),
645 Adt::Union(s) => s.module(db),
646 Adt::Enum(e) => e.module(db),
647 }
648 }
649
650 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
651 Some(self.module(db).krate())
652 }
653
654 pub fn name(self, db: &dyn HirDatabase) -> Name {
655 match self {
656 Adt::Struct(s) => s.name(db),
657 Adt::Union(u) => u.name(db),
658 Adt::Enum(e) => e.name(db),
659 }
660 }
661}
662
663#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
664pub enum VariantDef {
665 Struct(Struct),
666 Union(Union),
667 Variant(Variant),
668}
669impl_from!(Struct, Union, Variant for VariantDef);
670
671impl VariantDef {
672 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
673 match self {
674 VariantDef::Struct(it) => it.fields(db),
675 VariantDef::Union(it) => it.fields(db),
676 VariantDef::Variant(it) => it.fields(db),
677 }
678 }
679
680 pub fn module(self, db: &dyn HirDatabase) -> Module {
681 match self {
682 VariantDef::Struct(it) => it.module(db),
683 VariantDef::Union(it) => it.module(db),
684 VariantDef::Variant(it) => it.module(db),
685 }
686 }
687
688 pub fn name(&self, db: &dyn HirDatabase) -> Name {
689 match self {
690 VariantDef::Struct(s) => s.name(db),
691 VariantDef::Union(u) => u.name(db),
692 VariantDef::Variant(e) => e.name(db),
693 }
694 }
695
696 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
697 match self {
698 VariantDef::Struct(it) => it.variant_data(db),
699 VariantDef::Union(it) => it.variant_data(db),
700 VariantDef::Variant(it) => it.variant_data(db),
701 }
702 }
703}
704
705/// The defs which have a body.
706#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
707pub enum DefWithBody {
708 Function(Function),
709 Static(Static),
710 Const(Const),
711}
712impl_from!(Function, Const, Static for DefWithBody);
713
714impl DefWithBody {
715 pub fn module(self, db: &dyn HirDatabase) -> Module {
716 match self {
717 DefWithBody::Const(c) => c.module(db),
718 DefWithBody::Function(f) => f.module(db),
719 DefWithBody::Static(s) => s.module(db),
720 }
721 }
722
723 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
724 match self {
725 DefWithBody::Function(f) => Some(f.name(db)),
726 DefWithBody::Static(s) => s.name(db),
727 DefWithBody::Const(c) => c.name(db),
728 }
729 }
730}
731
732#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
733pub struct Function {
734 pub(crate) id: FunctionId,
735}
736
737impl Function {
738 pub fn module(self, db: &dyn HirDatabase) -> Module {
739 self.id.lookup(db.upcast()).module(db.upcast()).into()
740 }
741
742 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
743 Some(self.module(db).krate())
744 }
745
746 pub fn name(self, db: &dyn HirDatabase) -> Name {
747 db.function_data(self.id).name.clone()
748 }
749
750 /// Get this function's return type
751 pub fn ret_type(self, db: &dyn HirDatabase) -> Type {
752 let resolver = self.id.resolver(db.upcast());
753 let ret_type = &db.function_data(self.id).ret_type;
754 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
755 let environment = TraitEnvironment::lower(db, &resolver);
756 Type {
757 krate: self.id.lookup(db.upcast()).container.module(db.upcast()).krate(),
758 ty: InEnvironment { value: Ty::from_hir_ext(&ctx, ret_type).0, environment },
759 }
760 }
761
762 pub fn self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
763 if !db.function_data(self.id).has_self_param {
764 return None;
765 }
766 Some(SelfParam { func: self.id })
767 }
768
769 pub fn assoc_fn_params(self, db: &dyn HirDatabase) -> Vec<Param> {
770 let resolver = self.id.resolver(db.upcast());
771 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
772 let environment = TraitEnvironment::lower(db, &resolver);
773 db.function_data(self.id)
774 .params
775 .iter()
776 .map(|type_ref| {
777 let ty = Type {
778 krate: self.id.lookup(db.upcast()).container.module(db.upcast()).krate(),
779 ty: InEnvironment {
780 value: Ty::from_hir_ext(&ctx, type_ref).0,
781 environment: environment.clone(),
782 },
783 };
784 Param { ty }
785 })
786 .collect()
787 }
788 pub fn method_params(self, db: &dyn HirDatabase) -> Option<Vec<Param>> {
789 if self.self_param(db).is_none() {
790 return None;
791 }
792 let mut res = self.assoc_fn_params(db);
793 res.remove(0);
794 Some(res)
795 }
796
797 pub fn is_unsafe(self, db: &dyn HirDatabase) -> bool {
798 db.function_data(self.id).is_unsafe
799 }
800
801 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
802 let krate = self.module(db).id.krate();
803 hir_def::diagnostics::validate_body(db.upcast(), self.id.into(), sink);
804 hir_ty::diagnostics::validate_module_item(db, krate, self.id.into(), sink);
805 hir_ty::diagnostics::validate_body(db, self.id.into(), sink);
806 }
807
808 /// Whether this function declaration has a definition.
809 ///
810 /// This is false in the case of required (not provided) trait methods.
811 pub fn has_body(self, db: &dyn HirDatabase) -> bool {
812 db.function_data(self.id).has_body
813 }
814
815 /// A textual representation of the HIR of this function for debugging purposes.
816 pub fn debug_hir(self, db: &dyn HirDatabase) -> String {
817 let body = db.body(self.id.into());
818
819 let mut result = String::new();
820 format_to!(result, "HIR expressions in the body of `{}`:\n", self.name(db));
821 for (id, expr) in body.exprs.iter() {
822 format_to!(result, "{:?}: {:?}\n", id, expr);
823 }
824
825 result
826 }
827}
828
829// Note: logically, this belongs to `hir_ty`, but we are not using it there yet.
830pub enum Access {
831 Shared,
832 Exclusive,
833 Owned,
834}
835
836impl From<Mutability> for Access {
837 fn from(mutability: Mutability) -> Access {
838 match mutability {
839 Mutability::Shared => Access::Shared,
840 Mutability::Mut => Access::Exclusive,
841 }
842 }
843}
844
845#[derive(Debug)]
846pub struct Param {
847 ty: Type,
848}
849
850impl Param {
851 pub fn ty(&self) -> &Type {
852 &self.ty
853 }
854}
855
856#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
857pub struct SelfParam {
858 func: FunctionId,
859}
860
861impl SelfParam {
862 pub fn access(self, db: &dyn HirDatabase) -> Access {
863 let func_data = db.function_data(self.func);
864 func_data
865 .params
866 .first()
867 .map(|param| match *param {
868 TypeRef::Reference(.., mutability) => mutability.into(),
869 _ => Access::Owned,
870 })
871 .unwrap_or(Access::Owned)
872 }
873}
874
875impl HasVisibility for Function {
876 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
877 let function_data = db.function_data(self.id);
878 let visibility = &function_data.visibility;
879 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
880 }
881}
882
883#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
884pub struct Const {
885 pub(crate) id: ConstId,
886}
887
888impl Const {
889 pub fn module(self, db: &dyn HirDatabase) -> Module {
890 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
891 }
892
893 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
894 Some(self.module(db).krate())
895 }
896
897 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
898 db.const_data(self.id).name.clone()
899 }
900}
901
902impl HasVisibility for Const {
903 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
904 let function_data = db.const_data(self.id);
905 let visibility = &function_data.visibility;
906 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
907 }
908}
909
910#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
911pub struct Static {
912 pub(crate) id: StaticId,
913}
914
915impl Static {
916 pub fn module(self, db: &dyn HirDatabase) -> Module {
917 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
918 }
919
920 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
921 Some(self.module(db).krate())
922 }
923
924 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
925 db.static_data(self.id).name.clone()
926 }
927
928 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
929 db.static_data(self.id).mutable
930 }
931}
932
933#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
934pub struct Trait {
935 pub(crate) id: TraitId,
936}
937
938impl Trait {
939 pub fn module(self, db: &dyn HirDatabase) -> Module {
940 Module { id: self.id.lookup(db.upcast()).container.module(db.upcast()) }
941 }
942
943 pub fn name(self, db: &dyn HirDatabase) -> Name {
944 db.trait_data(self.id).name.clone()
945 }
946
947 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
948 db.trait_data(self.id).items.iter().map(|(_name, it)| (*it).into()).collect()
949 }
950
951 pub fn is_auto(self, db: &dyn HirDatabase) -> bool {
952 db.trait_data(self.id).auto
953 }
954}
955
956#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
957pub struct TypeAlias {
958 pub(crate) id: TypeAliasId,
959}
960
961impl TypeAlias {
962 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
963 let subst = db.generic_defaults(self.id.into());
964 subst.iter().any(|ty| &ty.value == &Ty::Unknown)
965 }
966
967 pub fn module(self, db: &dyn HirDatabase) -> Module {
968 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
969 }
970
971 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
972 Some(self.module(db).krate())
973 }
974
975 pub fn type_ref(self, db: &dyn HirDatabase) -> Option<TypeRef> {
976 db.type_alias_data(self.id).type_ref.clone()
977 }
978
979 pub fn ty(self, db: &dyn HirDatabase) -> Type {
980 Type::from_def(db, self.id.lookup(db.upcast()).module(db.upcast()).krate(), self.id)
981 }
982
983 pub fn name(self, db: &dyn HirDatabase) -> Name {
984 db.type_alias_data(self.id).name.clone()
985 }
986}
987
988impl HasVisibility for TypeAlias {
989 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
990 let function_data = db.type_alias_data(self.id);
991 let visibility = &function_data.visibility;
992 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
993 }
994}
995
996#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
997pub struct BuiltinType {
998 pub(crate) inner: hir_def::builtin_type::BuiltinType,
999}
1000
1001impl BuiltinType {
1002 pub fn ty(self, db: &dyn HirDatabase, module: Module) -> Type {
1003 let resolver = module.id.resolver(db.upcast());
1004 Type::new_with_resolver(db, &resolver, Ty::builtin(self.inner))
1005 .expect("crate not present in resolver")
1006 }
1007
1008 pub fn name(self) -> Name {
1009 self.inner.as_name()
1010 }
1011}
1012
1013#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1014pub struct MacroDef {
1015 pub(crate) id: MacroDefId,
1016}
1017
1018impl MacroDef {
1019 /// FIXME: right now, this just returns the root module of the crate that
1020 /// defines this macro. The reasons for this is that macros are expanded
1021 /// early, in `hir_expand`, where modules simply do not exist yet.
1022 pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
1023 let krate = self.id.krate;
1024 let def_map = db.crate_def_map(krate);
1025 let module_id = def_map.root();
1026 Some(Module { id: def_map.module_id(module_id) })
1027 }
1028
1029 /// XXX: this parses the file
1030 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1031 self.source(db)?.value.name().map(|it| it.as_name())
1032 }
1033
1034 /// Indicate it is a proc-macro
1035 pub fn is_proc_macro(&self) -> bool {
1036 matches!(self.id.kind, MacroDefKind::ProcMacro(_))
1037 }
1038
1039 /// Indicate it is a derive macro
1040 pub fn is_derive_macro(&self) -> bool {
1041 matches!(self.id.kind, MacroDefKind::ProcMacro(_) | MacroDefKind::BuiltInDerive(_))
1042 }
1043}
1044
1045/// Invariant: `inner.as_assoc_item(db).is_some()`
1046/// We do not actively enforce this invariant.
1047#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1048pub enum AssocItem {
1049 Function(Function),
1050 Const(Const),
1051 TypeAlias(TypeAlias),
1052}
1053pub enum AssocItemContainer {
1054 Trait(Trait),
1055 Impl(Impl),
1056}
1057pub trait AsAssocItem {
1058 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem>;
1059}
1060
1061impl AsAssocItem for Function {
1062 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1063 as_assoc_item(db, AssocItem::Function, self.id)
1064 }
1065}
1066impl AsAssocItem for Const {
1067 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1068 as_assoc_item(db, AssocItem::Const, self.id)
1069 }
1070}
1071impl AsAssocItem for TypeAlias {
1072 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1073 as_assoc_item(db, AssocItem::TypeAlias, self.id)
1074 }
1075}
1076impl AsAssocItem for ModuleDef {
1077 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1078 match self {
1079 ModuleDef::Function(it) => it.as_assoc_item(db),
1080 ModuleDef::Const(it) => it.as_assoc_item(db),
1081 ModuleDef::TypeAlias(it) => it.as_assoc_item(db),
1082 _ => None,
1083 }
1084 }
1085}
1086fn as_assoc_item<ID, DEF, CTOR, AST>(db: &dyn HirDatabase, ctor: CTOR, id: ID) -> Option<AssocItem>
1087where
1088 ID: Lookup<Data = AssocItemLoc<AST>>,
1089 DEF: From<ID>,
1090 CTOR: FnOnce(DEF) -> AssocItem,
1091 AST: ItemTreeNode,
1092{
1093 match id.lookup(db.upcast()).container {
1094 AssocContainerId::TraitId(_) | AssocContainerId::ImplId(_) => Some(ctor(DEF::from(id))),
1095 AssocContainerId::ContainerId(_) => None,
1096 }
1097}
1098
1099impl AssocItem {
1100 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1101 match self {
1102 AssocItem::Function(it) => Some(it.name(db)),
1103 AssocItem::Const(it) => it.name(db),
1104 AssocItem::TypeAlias(it) => Some(it.name(db)),
1105 }
1106 }
1107 pub fn module(self, db: &dyn HirDatabase) -> Module {
1108 match self {
1109 AssocItem::Function(f) => f.module(db),
1110 AssocItem::Const(c) => c.module(db),
1111 AssocItem::TypeAlias(t) => t.module(db),
1112 }
1113 }
1114 pub fn container(self, db: &dyn HirDatabase) -> AssocItemContainer {
1115 let container = match self {
1116 AssocItem::Function(it) => it.id.lookup(db.upcast()).container,
1117 AssocItem::Const(it) => it.id.lookup(db.upcast()).container,
1118 AssocItem::TypeAlias(it) => it.id.lookup(db.upcast()).container,
1119 };
1120 match container {
1121 AssocContainerId::TraitId(id) => AssocItemContainer::Trait(id.into()),
1122 AssocContainerId::ImplId(id) => AssocItemContainer::Impl(id.into()),
1123 AssocContainerId::ContainerId(_) => panic!("invalid AssocItem"),
1124 }
1125 }
1126
1127 pub fn containing_trait(self, db: &dyn HirDatabase) -> Option<Trait> {
1128 match self.container(db) {
1129 AssocItemContainer::Trait(t) => Some(t),
1130 _ => None,
1131 }
1132 }
1133}
1134
1135impl HasVisibility for AssocItem {
1136 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1137 match self {
1138 AssocItem::Function(f) => f.visibility(db),
1139 AssocItem::Const(c) => c.visibility(db),
1140 AssocItem::TypeAlias(t) => t.visibility(db),
1141 }
1142 }
1143}
1144
1145#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
1146pub enum GenericDef {
1147 Function(Function),
1148 Adt(Adt),
1149 Trait(Trait),
1150 TypeAlias(TypeAlias),
1151 Impl(Impl),
1152 // enum variants cannot have generics themselves, but their parent enums
1153 // can, and this makes some code easier to write
1154 Variant(Variant),
1155 // consts can have type parameters from their parents (i.e. associated consts of traits)
1156 Const(Const),
1157}
1158impl_from!(
1159 Function,
1160 Adt(Struct, Enum, Union),
1161 Trait,
1162 TypeAlias,
1163 Impl,
1164 Variant,
1165 Const
1166 for GenericDef
1167);
1168
1169impl GenericDef {
1170 pub fn params(self, db: &dyn HirDatabase) -> Vec<GenericParam> {
1171 let generics = db.generic_params(self.into());
1172 let ty_params = generics
1173 .types
1174 .iter()
1175 .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
1176 .map(GenericParam::TypeParam);
1177 let lt_params = generics
1178 .lifetimes
1179 .iter()
1180 .map(|(local_id, _)| LifetimeParam {
1181 id: LifetimeParamId { parent: self.into(), local_id },
1182 })
1183 .map(GenericParam::LifetimeParam);
1184 let const_params = generics
1185 .consts
1186 .iter()
1187 .map(|(local_id, _)| ConstParam { id: ConstParamId { parent: self.into(), local_id } })
1188 .map(GenericParam::ConstParam);
1189 ty_params.chain(lt_params).chain(const_params).collect()
1190 }
1191
1192 pub fn type_params(self, db: &dyn HirDatabase) -> Vec<TypeParam> {
1193 let generics = db.generic_params(self.into());
1194 generics
1195 .types
1196 .iter()
1197 .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
1198 .collect()
1199 }
1200}
1201
1202#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1203pub struct Local {
1204 pub(crate) parent: DefWithBodyId,
1205 pub(crate) pat_id: PatId,
1206}
1207
1208impl Local {
1209 pub fn is_param(self, db: &dyn HirDatabase) -> bool {
1210 let src = self.source(db);
1211 match src.value {
1212 Either::Left(bind_pat) => {
1213 bind_pat.syntax().ancestors().any(|it| ast::Param::can_cast(it.kind()))
1214 }
1215 Either::Right(_self_param) => true,
1216 }
1217 }
1218
1219 // FIXME: why is this an option? It shouldn't be?
1220 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1221 let body = db.body(self.parent.into());
1222 match &body[self.pat_id] {
1223 Pat::Bind { name, .. } => Some(name.clone()),
1224 _ => None,
1225 }
1226 }
1227
1228 pub fn is_self(self, db: &dyn HirDatabase) -> bool {
1229 self.name(db) == Some(name![self])
1230 }
1231
1232 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
1233 let body = db.body(self.parent.into());
1234 match &body[self.pat_id] {
1235 Pat::Bind { mode, .. } => match mode {
1236 BindingAnnotation::Mutable | BindingAnnotation::RefMut => true,
1237 _ => false,
1238 },
1239 _ => false,
1240 }
1241 }
1242
1243 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
1244 self.parent.into()
1245 }
1246
1247 pub fn module(self, db: &dyn HirDatabase) -> Module {
1248 self.parent(db).module(db)
1249 }
1250
1251 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1252 let def = DefWithBodyId::from(self.parent);
1253 let infer = db.infer(def);
1254 let ty = infer[self.pat_id].clone();
1255 let krate = def.module(db.upcast()).krate();
1256 Type::new(db, krate, def, ty)
1257 }
1258
1259 pub fn source(self, db: &dyn HirDatabase) -> InFile<Either<ast::IdentPat, ast::SelfParam>> {
1260 let (_body, source_map) = db.body_with_source_map(self.parent.into());
1261 let src = source_map.pat_syntax(self.pat_id).unwrap(); // Hmm...
1262 let root = src.file_syntax(db.upcast());
1263 src.map(|ast| {
1264 ast.map_left(|it| it.cast().unwrap().to_node(&root)).map_right(|it| it.to_node(&root))
1265 })
1266 }
1267}
1268
1269#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1270pub struct Label {
1271 pub(crate) parent: DefWithBodyId,
1272 pub(crate) label_id: LabelId,
1273}
1274
1275impl Label {
1276 pub fn module(self, db: &dyn HirDatabase) -> Module {
1277 self.parent(db).module(db)
1278 }
1279
1280 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
1281 self.parent.into()
1282 }
1283
1284 pub fn name(self, db: &dyn HirDatabase) -> Name {
1285 let body = db.body(self.parent.into());
1286 body[self.label_id].name.clone()
1287 }
1288
1289 pub fn source(self, db: &dyn HirDatabase) -> InFile<ast::Label> {
1290 let (_body, source_map) = db.body_with_source_map(self.parent.into());
1291 let src = source_map.label_syntax(self.label_id);
1292 let root = src.file_syntax(db.upcast());
1293 src.map(|ast| ast.to_node(&root))
1294 }
1295}
1296
1297#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1298pub enum GenericParam {
1299 TypeParam(TypeParam),
1300 LifetimeParam(LifetimeParam),
1301 ConstParam(ConstParam),
1302}
1303impl_from!(TypeParam, LifetimeParam, ConstParam for GenericParam);
1304
1305impl GenericParam {
1306 pub fn module(self, db: &dyn HirDatabase) -> Module {
1307 match self {
1308 GenericParam::TypeParam(it) => it.module(db),
1309 GenericParam::LifetimeParam(it) => it.module(db),
1310 GenericParam::ConstParam(it) => it.module(db),
1311 }
1312 }
1313
1314 pub fn name(self, db: &dyn HirDatabase) -> Name {
1315 match self {
1316 GenericParam::TypeParam(it) => it.name(db),
1317 GenericParam::LifetimeParam(it) => it.name(db),
1318 GenericParam::ConstParam(it) => it.name(db),
1319 }
1320 }
1321}
1322
1323#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1324pub struct TypeParam {
1325 pub(crate) id: TypeParamId,
1326}
1327
1328impl TypeParam {
1329 pub fn name(self, db: &dyn HirDatabase) -> Name {
1330 let params = db.generic_params(self.id.parent);
1331 params.types[self.id.local_id].name.clone().unwrap_or_else(Name::missing)
1332 }
1333
1334 pub fn module(self, db: &dyn HirDatabase) -> Module {
1335 self.id.parent.module(db.upcast()).into()
1336 }
1337
1338 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1339 let resolver = self.id.parent.resolver(db.upcast());
1340 let environment = TraitEnvironment::lower(db, &resolver);
1341 let ty = Ty::Placeholder(self.id);
1342 Type {
1343 krate: self.id.parent.module(db.upcast()).krate(),
1344 ty: InEnvironment { value: ty, environment },
1345 }
1346 }
1347
1348 pub fn trait_bounds(self, db: &dyn HirDatabase) -> Vec<Trait> {
1349 db.generic_predicates_for_param(self.id)
1350 .into_iter()
1351 .filter_map(|pred| match &pred.value {
1352 hir_ty::GenericPredicate::Implemented(trait_ref) => {
1353 Some(Trait::from(trait_ref.trait_))
1354 }
1355 _ => None,
1356 })
1357 .collect()
1358 }
1359
1360 pub fn default(self, db: &dyn HirDatabase) -> Option<Type> {
1361 let params = db.generic_defaults(self.id.parent);
1362 let local_idx = hir_ty::param_idx(db, self.id)?;
1363 let resolver = self.id.parent.resolver(db.upcast());
1364 let environment = TraitEnvironment::lower(db, &resolver);
1365 let ty = params.get(local_idx)?.clone();
1366 let subst = Substs::type_params(db, self.id.parent);
1367 let ty = ty.subst(&subst.prefix(local_idx));
1368 Some(Type {
1369 krate: self.id.parent.module(db.upcast()).krate(),
1370 ty: InEnvironment { value: ty, environment },
1371 })
1372 }
1373}
1374
1375impl HirDisplay for TypeParam {
1376 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1377 write!(f, "{}", self.name(f.db))?;
1378 let bounds = f.db.generic_predicates_for_param(self.id);
1379 let substs = Substs::type_params(f.db, self.id.parent);
1380 let predicates = bounds.iter().cloned().map(|b| b.subst(&substs)).collect::<Vec<_>>();
1381 if !(predicates.is_empty() || f.omit_verbose_types()) {
1382 write_bounds_like_dyn_trait_with_prefix(":", &predicates, f)?;
1383 }
1384 Ok(())
1385 }
1386}
1387
1388#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1389pub struct LifetimeParam {
1390 pub(crate) id: LifetimeParamId,
1391}
1392
1393impl LifetimeParam {
1394 pub fn name(self, db: &dyn HirDatabase) -> Name {
1395 let params = db.generic_params(self.id.parent);
1396 params.lifetimes[self.id.local_id].name.clone()
1397 }
1398
1399 pub fn module(self, db: &dyn HirDatabase) -> Module {
1400 self.id.parent.module(db.upcast()).into()
1401 }
1402
1403 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
1404 self.id.parent.into()
1405 }
1406}
1407
1408#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1409pub struct ConstParam {
1410 pub(crate) id: ConstParamId,
1411}
1412
1413impl ConstParam {
1414 pub fn name(self, db: &dyn HirDatabase) -> Name {
1415 let params = db.generic_params(self.id.parent);
1416 params.consts[self.id.local_id].name.clone()
1417 }
1418
1419 pub fn module(self, db: &dyn HirDatabase) -> Module {
1420 self.id.parent.module(db.upcast()).into()
1421 }
1422
1423 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
1424 self.id.parent.into()
1425 }
1426
1427 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1428 let def = self.id.parent;
1429 let krate = def.module(db.upcast()).krate();
1430 Type::new(db, krate, def, db.const_param_ty(self.id))
1431 }
1432}
1433
1434#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1435pub struct Impl {
1436 pub(crate) id: ImplId,
1437}
1438
1439impl Impl {
1440 pub fn all_in_crate(db: &dyn HirDatabase, krate: Crate) -> Vec<Impl> {
1441 let inherent = db.inherent_impls_in_crate(krate.id);
1442 let trait_ = db.trait_impls_in_crate(krate.id);
1443
1444 inherent.all_impls().chain(trait_.all_impls()).map(Self::from).collect()
1445 }
1446 pub fn for_trait(db: &dyn HirDatabase, krate: Crate, trait_: Trait) -> Vec<Impl> {
1447 let impls = db.trait_impls_in_crate(krate.id);
1448 impls.for_trait(trait_.id).map(Self::from).collect()
1449 }
1450
1451 // FIXME: the return type is wrong. This should be a hir version of
1452 // `TraitRef` (ie, resolved `TypeRef`).
1453 pub fn target_trait(self, db: &dyn HirDatabase) -> Option<TypeRef> {
1454 db.impl_data(self.id).target_trait.clone()
1455 }
1456
1457 pub fn target_ty(self, db: &dyn HirDatabase) -> Type {
1458 let impl_data = db.impl_data(self.id);
1459 let resolver = self.id.resolver(db.upcast());
1460 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1461 let environment = TraitEnvironment::lower(db, &resolver);
1462 let ty = Ty::from_hir(&ctx, &impl_data.target_type);
1463 Type {
1464 krate: self.id.lookup(db.upcast()).container.module(db.upcast()).krate(),
1465 ty: InEnvironment { value: ty, environment },
1466 }
1467 }
1468
1469 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
1470 db.impl_data(self.id).items.iter().map(|it| (*it).into()).collect()
1471 }
1472
1473 pub fn is_negative(self, db: &dyn HirDatabase) -> bool {
1474 db.impl_data(self.id).is_negative
1475 }
1476
1477 pub fn module(self, db: &dyn HirDatabase) -> Module {
1478 self.id.lookup(db.upcast()).container.module(db.upcast()).into()
1479 }
1480
1481 pub fn krate(self, db: &dyn HirDatabase) -> Crate {
1482 Crate { id: self.module(db).id.krate() }
1483 }
1484
1485 pub fn is_builtin_derive(self, db: &dyn HirDatabase) -> Option<InFile<ast::Attr>> {
1486 let src = self.source(db)?;
1487 let item = src.file_id.is_builtin_derive(db.upcast())?;
1488 let hygenic = hir_expand::hygiene::Hygiene::new(db.upcast(), item.file_id);
1489
1490 // FIXME: handle `cfg_attr`
1491 let attr = item
1492 .value
1493 .attrs()
1494 .filter_map(|it| {
1495 let path = ModPath::from_src(it.path()?, &hygenic)?;
1496 if path.as_ident()?.to_string() == "derive" {
1497 Some(it)
1498 } else {
1499 None
1500 }
1501 })
1502 .last()?;
1503
1504 Some(item.with_value(attr))
1505 }
1506}
1507
1508#[derive(Clone, PartialEq, Eq, Debug)]
1509pub struct Type {
1510 krate: CrateId,
1511 ty: InEnvironment<Ty>,
1512}
1513
1514impl Type {
1515 pub(crate) fn new_with_resolver(
1516 db: &dyn HirDatabase,
1517 resolver: &Resolver,
1518 ty: Ty,
1519 ) -> Option<Type> {
1520 let krate = resolver.krate()?;
1521 Some(Type::new_with_resolver_inner(db, krate, resolver, ty))
1522 }
1523 pub(crate) fn new_with_resolver_inner(
1524 db: &dyn HirDatabase,
1525 krate: CrateId,
1526 resolver: &Resolver,
1527 ty: Ty,
1528 ) -> Type {
1529 let environment = TraitEnvironment::lower(db, &resolver);
1530 Type { krate, ty: InEnvironment { value: ty, environment } }
1531 }
1532
1533 fn new(db: &dyn HirDatabase, krate: CrateId, lexical_env: impl HasResolver, ty: Ty) -> Type {
1534 let resolver = lexical_env.resolver(db.upcast());
1535 let environment = TraitEnvironment::lower(db, &resolver);
1536 Type { krate, ty: InEnvironment { value: ty, environment } }
1537 }
1538
1539 fn from_def(
1540 db: &dyn HirDatabase,
1541 krate: CrateId,
1542 def: impl HasResolver + Into<TyDefId> + Into<GenericDefId>,
1543 ) -> Type {
1544 let substs = Substs::build_for_def(db, def).fill_with_unknown().build();
1545 let ty = db.ty(def.into()).subst(&substs);
1546 Type::new(db, krate, def, ty)
1547 }
1548
1549 pub fn is_unit(&self) -> bool {
1550 matches!(
1551 self.ty.value,
1552 Ty::Apply(ApplicationTy { ctor: TypeCtor::Tuple { cardinality: 0 }, .. })
1553 )
1554 }
1555 pub fn is_bool(&self) -> bool {
1556 matches!(self.ty.value, Ty::Apply(ApplicationTy { ctor: TypeCtor::Bool, .. }))
1557 }
1558
1559 pub fn is_mutable_reference(&self) -> bool {
1560 matches!(
1561 self.ty.value,
1562 Ty::Apply(ApplicationTy { ctor: TypeCtor::Ref(Mutability::Mut), .. })
1563 )
1564 }
1565
1566 pub fn remove_ref(&self) -> Option<Type> {
1567 if let Ty::Apply(ApplicationTy { ctor: TypeCtor::Ref(_), .. }) = self.ty.value {
1568 self.ty.value.substs().map(|substs| self.derived(substs[0].clone()))
1569 } else {
1570 None
1571 }
1572 }
1573
1574 pub fn is_unknown(&self) -> bool {
1575 matches!(self.ty.value, Ty::Unknown)
1576 }
1577
1578 /// Checks that particular type `ty` implements `std::future::Future`.
1579 /// This function is used in `.await` syntax completion.
1580 pub fn impls_future(&self, db: &dyn HirDatabase) -> bool {
1581 // No special case for the type of async block, since Chalk can figure it out.
1582
1583 let krate = self.krate;
1584
1585 let std_future_trait =
1586 db.lang_item(krate, "future_trait".into()).and_then(|it| it.as_trait());
1587 let std_future_trait = match std_future_trait {
1588 Some(it) => it,
1589 None => return false,
1590 };
1591
1592 let canonical_ty = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1593 method_resolution::implements_trait(
1594 &canonical_ty,
1595 db,
1596 self.ty.environment.clone(),
1597 krate,
1598 std_future_trait,
1599 )
1600 }
1601
1602 /// Checks that particular type `ty` implements `std::ops::FnOnce`.
1603 ///
1604 /// This function can be used to check if a particular type is callable, since FnOnce is a
1605 /// supertrait of Fn and FnMut, so all callable types implements at least FnOnce.
1606 pub fn impls_fnonce(&self, db: &dyn HirDatabase) -> bool {
1607 let krate = self.krate;
1608
1609 let fnonce_trait = match FnTrait::FnOnce.get_id(db, krate) {
1610 Some(it) => it,
1611 None => return false,
1612 };
1613
1614 let canonical_ty = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1615 method_resolution::implements_trait_unique(
1616 &canonical_ty,
1617 db,
1618 self.ty.environment.clone(),
1619 krate,
1620 fnonce_trait,
1621 )
1622 }
1623
1624 pub fn impls_trait(&self, db: &dyn HirDatabase, trait_: Trait, args: &[Type]) -> bool {
1625 let trait_ref = hir_ty::TraitRef {
1626 trait_: trait_.id,
1627 substs: Substs::build_for_def(db, trait_.id)
1628 .push(self.ty.value.clone())
1629 .fill(args.iter().map(|t| t.ty.value.clone()))
1630 .build(),
1631 };
1632
1633 let goal = Canonical {
1634 value: hir_ty::InEnvironment::new(
1635 self.ty.environment.clone(),
1636 hir_ty::Obligation::Trait(trait_ref),
1637 ),
1638 kinds: Arc::new([]),
1639 };
1640
1641 db.trait_solve(self.krate, goal).is_some()
1642 }
1643
1644 pub fn normalize_trait_assoc_type(
1645 &self,
1646 db: &dyn HirDatabase,
1647 trait_: Trait,
1648 args: &[Type],
1649 alias: TypeAlias,
1650 ) -> Option<Type> {
1651 let subst = Substs::build_for_def(db, trait_.id)
1652 .push(self.ty.value.clone())
1653 .fill(args.iter().map(|t| t.ty.value.clone()))
1654 .build();
1655 let predicate = ProjectionPredicate {
1656 projection_ty: ProjectionTy { associated_ty: alias.id, parameters: subst },
1657 ty: Ty::Bound(BoundVar::new(DebruijnIndex::INNERMOST, 0)),
1658 };
1659 let goal = Canonical {
1660 value: InEnvironment::new(
1661 self.ty.environment.clone(),
1662 Obligation::Projection(predicate),
1663 ),
1664 kinds: Arc::new([TyKind::General]),
1665 };
1666
1667 match db.trait_solve(self.krate, goal)? {
1668 Solution::Unique(SolutionVariables(subst)) => subst.value.first().cloned(),
1669 Solution::Ambig(_) => None,
1670 }
1671 .map(|ty| Type {
1672 krate: self.krate,
1673 ty: InEnvironment { value: ty, environment: Arc::clone(&self.ty.environment) },
1674 })
1675 }
1676
1677 pub fn is_copy(&self, db: &dyn HirDatabase) -> bool {
1678 let lang_item = db.lang_item(self.krate, SmolStr::new("copy"));
1679 let copy_trait = match lang_item {
1680 Some(LangItemTarget::TraitId(it)) => it,
1681 _ => return false,
1682 };
1683 self.impls_trait(db, copy_trait.into(), &[])
1684 }
1685
1686 pub fn as_callable(&self, db: &dyn HirDatabase) -> Option<Callable> {
1687 let def = match self.ty.value {
1688 Ty::Apply(ApplicationTy { ctor: TypeCtor::FnDef(def), parameters: _ }) => Some(def),
1689 _ => None,
1690 };
1691
1692 let sig = self.ty.value.callable_sig(db)?;
1693 Some(Callable { ty: self.clone(), sig, def, is_bound_method: false })
1694 }
1695
1696 pub fn is_closure(&self) -> bool {
1697 matches!(&self.ty.value, Ty::Apply(ApplicationTy { ctor: TypeCtor::Closure { .. }, .. }))
1698 }
1699
1700 pub fn is_fn(&self) -> bool {
1701 matches!(
1702 &self.ty.value,
1703 Ty::Apply(ApplicationTy { ctor: TypeCtor::FnDef(..), .. })
1704 | Ty::Apply(ApplicationTy { ctor: TypeCtor::FnPtr { .. }, .. })
1705 )
1706 }
1707
1708 pub fn is_packed(&self, db: &dyn HirDatabase) -> bool {
1709 let adt_id = match self.ty.value {
1710 Ty::Apply(ApplicationTy { ctor: TypeCtor::Adt(adt_id), .. }) => adt_id,
1711 _ => return false,
1712 };
1713
1714 let adt = adt_id.into();
1715 match adt {
1716 Adt::Struct(s) => matches!(s.repr(db), Some(ReprKind::Packed)),
1717 _ => false,
1718 }
1719 }
1720
1721 pub fn is_raw_ptr(&self) -> bool {
1722 matches!(&self.ty.value, Ty::Apply(ApplicationTy { ctor: TypeCtor::RawPtr(..), .. }))
1723 }
1724
1725 pub fn contains_unknown(&self) -> bool {
1726 return go(&self.ty.value);
1727
1728 fn go(ty: &Ty) -> bool {
1729 match ty {
1730 Ty::Unknown => true,
1731 Ty::Apply(a_ty) => a_ty.parameters.iter().any(go),
1732 _ => false,
1733 }
1734 }
1735 }
1736
1737 pub fn fields(&self, db: &dyn HirDatabase) -> Vec<(Field, Type)> {
1738 if let Ty::Apply(a_ty) = &self.ty.value {
1739 let variant_id = match a_ty.ctor {
1740 TypeCtor::Adt(AdtId::StructId(s)) => s.into(),
1741 TypeCtor::Adt(AdtId::UnionId(u)) => u.into(),
1742 _ => return Vec::new(),
1743 };
1744
1745 return db
1746 .field_types(variant_id)
1747 .iter()
1748 .map(|(local_id, ty)| {
1749 let def = Field { parent: variant_id.into(), id: local_id };
1750 let ty = ty.clone().subst(&a_ty.parameters);
1751 (def, self.derived(ty))
1752 })
1753 .collect();
1754 };
1755 Vec::new()
1756 }
1757
1758 pub fn tuple_fields(&self, _db: &dyn HirDatabase) -> Vec<Type> {
1759 let mut res = Vec::new();
1760 if let Ty::Apply(a_ty) = &self.ty.value {
1761 if let TypeCtor::Tuple { .. } = a_ty.ctor {
1762 for ty in a_ty.parameters.iter() {
1763 let ty = ty.clone();
1764 res.push(self.derived(ty));
1765 }
1766 }
1767 };
1768 res
1769 }
1770
1771 pub fn autoderef<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Type> + 'a {
1772 // There should be no inference vars in types passed here
1773 // FIXME check that?
1774 let canonical = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1775 let environment = self.ty.environment.clone();
1776 let ty = InEnvironment { value: canonical, environment };
1777 autoderef(db, Some(self.krate), ty)
1778 .map(|canonical| canonical.value)
1779 .map(move |ty| self.derived(ty))
1780 }
1781
1782 // This would be nicer if it just returned an iterator, but that runs into
1783 // lifetime problems, because we need to borrow temp `CrateImplDefs`.
1784 pub fn iterate_assoc_items<T>(
1785 self,
1786 db: &dyn HirDatabase,
1787 krate: Crate,
1788 mut callback: impl FnMut(AssocItem) -> Option<T>,
1789 ) -> Option<T> {
1790 for krate in self.ty.value.def_crates(db, krate.id)? {
1791 let impls = db.inherent_impls_in_crate(krate);
1792
1793 for impl_def in impls.for_self_ty(&self.ty.value) {
1794 for &item in db.impl_data(*impl_def).items.iter() {
1795 if let Some(result) = callback(item.into()) {
1796 return Some(result);
1797 }
1798 }
1799 }
1800 }
1801 None
1802 }
1803
1804 pub fn type_parameters(&self) -> impl Iterator<Item = Type> + '_ {
1805 let ty = self.ty.value.strip_references();
1806 let substs = match ty {
1807 Ty::Apply(apply_ty) => &apply_ty.parameters,
1808 Ty::Opaque(opaque_ty) => &opaque_ty.parameters,
1809 _ => return Either::Left(iter::empty()),
1810 };
1811
1812 let iter = substs.iter().map(move |ty| self.derived(ty.clone()));
1813 Either::Right(iter)
1814 }
1815
1816 pub fn iterate_method_candidates<T>(
1817 &self,
1818 db: &dyn HirDatabase,
1819 krate: Crate,
1820 traits_in_scope: &FxHashSet<TraitId>,
1821 name: Option<&Name>,
1822 mut callback: impl FnMut(&Ty, Function) -> Option<T>,
1823 ) -> Option<T> {
1824 // There should be no inference vars in types passed here
1825 // FIXME check that?
1826 // FIXME replace Unknown by bound vars here
1827 let canonical = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1828
1829 let env = self.ty.environment.clone();
1830 let krate = krate.id;
1831
1832 method_resolution::iterate_method_candidates(
1833 &canonical,
1834 db,
1835 env,
1836 krate,
1837 traits_in_scope,
1838 name,
1839 method_resolution::LookupMode::MethodCall,
1840 |ty, it| match it {
1841 AssocItemId::FunctionId(f) => callback(ty, f.into()),
1842 _ => None,
1843 },
1844 )
1845 }
1846
1847 pub fn iterate_path_candidates<T>(
1848 &self,
1849 db: &dyn HirDatabase,
1850 krate: Crate,
1851 traits_in_scope: &FxHashSet<TraitId>,
1852 name: Option<&Name>,
1853 mut callback: impl FnMut(&Ty, AssocItem) -> Option<T>,
1854 ) -> Option<T> {
1855 // There should be no inference vars in types passed here
1856 // FIXME check that?
1857 // FIXME replace Unknown by bound vars here
1858 let canonical = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1859
1860 let env = self.ty.environment.clone();
1861 let krate = krate.id;
1862
1863 method_resolution::iterate_method_candidates(
1864 &canonical,
1865 db,
1866 env,
1867 krate,
1868 traits_in_scope,
1869 name,
1870 method_resolution::LookupMode::Path,
1871 |ty, it| callback(ty, it.into()),
1872 )
1873 }
1874
1875 pub fn as_adt(&self) -> Option<Adt> {
1876 let (adt, _subst) = self.ty.value.as_adt()?;
1877 Some(adt.into())
1878 }
1879
1880 pub fn as_dyn_trait(&self) -> Option<Trait> {
1881 self.ty.value.dyn_trait().map(Into::into)
1882 }
1883
1884 pub fn as_impl_traits(&self, db: &dyn HirDatabase) -> Option<Vec<Trait>> {
1885 self.ty.value.impl_trait_bounds(db).map(|it| {
1886 it.into_iter()
1887 .filter_map(|pred| match pred {
1888 hir_ty::GenericPredicate::Implemented(trait_ref) => {
1889 Some(Trait::from(trait_ref.trait_))
1890 }
1891 _ => None,
1892 })
1893 .collect()
1894 })
1895 }
1896
1897 pub fn as_associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<Trait> {
1898 self.ty.value.associated_type_parent_trait(db).map(Into::into)
1899 }
1900
1901 // FIXME: provide required accessors such that it becomes implementable from outside.
1902 pub fn is_equal_for_find_impls(&self, other: &Type) -> bool {
1903 match (&self.ty.value, &other.ty.value) {
1904 (Ty::Apply(a_original_ty), Ty::Apply(ApplicationTy { ctor, parameters })) => match ctor
1905 {
1906 TypeCtor::Ref(..) => match parameters.as_single() {
1907 Ty::Apply(a_ty) => a_original_ty.ctor == a_ty.ctor,
1908 _ => false,
1909 },
1910 _ => a_original_ty.ctor == *ctor,
1911 },
1912 _ => false,
1913 }
1914 }
1915
1916 fn derived(&self, ty: Ty) -> Type {
1917 Type {
1918 krate: self.krate,
1919 ty: InEnvironment { value: ty, environment: self.ty.environment.clone() },
1920 }
1921 }
1922
1923 pub fn walk(&self, db: &dyn HirDatabase, mut cb: impl FnMut(Type)) {
1924 // TypeWalk::walk for a Ty at first visits parameters and only after that the Ty itself.
1925 // We need a different order here.
1926
1927 fn walk_substs(
1928 db: &dyn HirDatabase,
1929 type_: &Type,
1930 substs: &Substs,
1931 cb: &mut impl FnMut(Type),
1932 ) {
1933 for ty in substs.iter() {
1934 walk_type(db, &type_.derived(ty.clone()), cb);
1935 }
1936 }
1937
1938 fn walk_bounds(
1939 db: &dyn HirDatabase,
1940 type_: &Type,
1941 bounds: &[GenericPredicate],
1942 cb: &mut impl FnMut(Type),
1943 ) {
1944 for pred in bounds {
1945 match pred {
1946 GenericPredicate::Implemented(trait_ref) => {
1947 cb(type_.clone());
1948 walk_substs(db, type_, &trait_ref.substs, cb);
1949 }
1950 _ => (),
1951 }
1952 }
1953 }
1954
1955 fn walk_type(db: &dyn HirDatabase, type_: &Type, cb: &mut impl FnMut(Type)) {
1956 let ty = type_.ty.value.strip_references();
1957 match ty {
1958 Ty::Apply(ApplicationTy { ctor, parameters }) => {
1959 match ctor {
1960 TypeCtor::Adt(_) => {
1961 cb(type_.derived(ty.clone()));
1962 }
1963 TypeCtor::AssociatedType(_) => {
1964 if let Some(_) = ty.associated_type_parent_trait(db) {
1965 cb(type_.derived(ty.clone()));
1966 }
1967 }
1968 TypeCtor::OpaqueType(..) => {
1969 if let Some(bounds) = ty.impl_trait_bounds(db) {
1970 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
1971 }
1972 }
1973 _ => (),
1974 }
1975
1976 // adt params, tuples, etc...
1977 walk_substs(db, type_, parameters, cb);
1978 }
1979 Ty::Opaque(opaque_ty) => {
1980 if let Some(bounds) = ty.impl_trait_bounds(db) {
1981 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
1982 }
1983
1984 walk_substs(db, type_, &opaque_ty.parameters, cb);
1985 }
1986 Ty::Placeholder(_) => {
1987 if let Some(bounds) = ty.impl_trait_bounds(db) {
1988 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
1989 }
1990 }
1991 Ty::Dyn(bounds) => {
1992 walk_bounds(db, &type_.derived(ty.clone()), bounds.as_ref(), cb);
1993 }
1994
1995 _ => (),
1996 }
1997 }
1998
1999 walk_type(db, self, &mut cb);
2000 }
2001}
2002
2003impl HirDisplay for Type {
2004 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
2005 self.ty.value.hir_fmt(f)
2006 }
2007}
2008
2009// FIXME: closures
2010#[derive(Debug)]
2011pub struct Callable {
2012 ty: Type,
2013 sig: FnSig,
2014 def: Option<CallableDefId>,
2015 pub(crate) is_bound_method: bool,
2016}
2017
2018pub enum CallableKind {
2019 Function(Function),
2020 TupleStruct(Struct),
2021 TupleEnumVariant(Variant),
2022 Closure,
2023}
2024
2025impl Callable {
2026 pub fn kind(&self) -> CallableKind {
2027 match self.def {
2028 Some(CallableDefId::FunctionId(it)) => CallableKind::Function(it.into()),
2029 Some(CallableDefId::StructId(it)) => CallableKind::TupleStruct(it.into()),
2030 Some(CallableDefId::EnumVariantId(it)) => CallableKind::TupleEnumVariant(it.into()),
2031 None => CallableKind::Closure,
2032 }
2033 }
2034 pub fn receiver_param(&self, db: &dyn HirDatabase) -> Option<ast::SelfParam> {
2035 let func = match self.def {
2036 Some(CallableDefId::FunctionId(it)) if self.is_bound_method => it,
2037 _ => return None,
2038 };
2039 let src = func.lookup(db.upcast()).source(db.upcast());
2040 let param_list = src.value.param_list()?;
2041 param_list.self_param()
2042 }
2043 pub fn n_params(&self) -> usize {
2044 self.sig.params().len() - if self.is_bound_method { 1 } else { 0 }
2045 }
2046 pub fn params(
2047 &self,
2048 db: &dyn HirDatabase,
2049 ) -> Vec<(Option<Either<ast::SelfParam, ast::Pat>>, Type)> {
2050 let types = self
2051 .sig
2052 .params()
2053 .iter()
2054 .skip(if self.is_bound_method { 1 } else { 0 })
2055 .map(|ty| self.ty.derived(ty.clone()));
2056 let patterns = match self.def {
2057 Some(CallableDefId::FunctionId(func)) => {
2058 let src = func.lookup(db.upcast()).source(db.upcast());
2059 src.value.param_list().map(|param_list| {
2060 param_list
2061 .self_param()
2062 .map(|it| Some(Either::Left(it)))
2063 .filter(|_| !self.is_bound_method)
2064 .into_iter()
2065 .chain(param_list.params().map(|it| it.pat().map(Either::Right)))
2066 })
2067 }
2068 _ => None,
2069 };
2070 patterns.into_iter().flatten().chain(iter::repeat(None)).zip(types).collect()
2071 }
2072 pub fn return_type(&self) -> Type {
2073 self.ty.derived(self.sig.ret().clone())
2074 }
2075}
2076
2077/// For IDE only
2078#[derive(Debug, PartialEq, Eq, Hash)]
2079pub enum ScopeDef {
2080 ModuleDef(ModuleDef),
2081 MacroDef(MacroDef),
2082 GenericParam(GenericParam),
2083 ImplSelfType(Impl),
2084 AdtSelfType(Adt),
2085 Local(Local),
2086 Unknown,
2087}
2088
2089impl ScopeDef {
2090 pub fn all_items(def: PerNs) -> ArrayVec<[Self; 3]> {
2091 let mut items = ArrayVec::new();
2092
2093 match (def.take_types(), def.take_values()) {
2094 (Some(m1), None) => items.push(ScopeDef::ModuleDef(m1.into())),
2095 (None, Some(m2)) => items.push(ScopeDef::ModuleDef(m2.into())),
2096 (Some(m1), Some(m2)) => {
2097 // Some items, like unit structs and enum variants, are
2098 // returned as both a type and a value. Here we want
2099 // to de-duplicate them.
2100 if m1 != m2 {
2101 items.push(ScopeDef::ModuleDef(m1.into()));
2102 items.push(ScopeDef::ModuleDef(m2.into()));
2103 } else {
2104 items.push(ScopeDef::ModuleDef(m1.into()));
2105 }
2106 }
2107 (None, None) => {}
2108 };
2109
2110 if let Some(macro_def_id) = def.take_macros() {
2111 items.push(ScopeDef::MacroDef(macro_def_id.into()));
2112 }
2113
2114 if items.is_empty() {
2115 items.push(ScopeDef::Unknown);
2116 }
2117
2118 items
2119 }
2120}
2121
2122pub trait HasVisibility {
2123 fn visibility(&self, db: &dyn HirDatabase) -> Visibility;
2124 fn is_visible_from(&self, db: &dyn HirDatabase, module: Module) -> bool {
2125 let vis = self.visibility(db);
2126 vis.is_visible_from(db.upcast(), module.id)
2127 }
2128}
diff --git a/crates/hir/src/diagnostics.rs b/crates/hir/src/diagnostics.rs
index 5343a036c..b1ebba516 100644
--- a/crates/hir/src/diagnostics.rs
+++ b/crates/hir/src/diagnostics.rs
@@ -1,5 +1,7 @@
1//! FIXME: write short doc here 1//! FIXME: write short doc here
2pub use hir_def::diagnostics::{InactiveCode, UnresolvedModule, UnresolvedProcMacro}; 2pub use hir_def::diagnostics::{
3 InactiveCode, UnresolvedMacroCall, UnresolvedModule, UnresolvedProcMacro,
4};
3pub use hir_expand::diagnostics::{ 5pub use hir_expand::diagnostics::{
4 Diagnostic, DiagnosticCode, DiagnosticSink, DiagnosticSinkBuilder, 6 Diagnostic, DiagnosticCode, DiagnosticSink, DiagnosticSinkBuilder,
5}; 7};
diff --git a/crates/hir/src/from_id.rs b/crates/hir/src/from_id.rs
index b5814da11..179b9d51e 100644
--- a/crates/hir/src/from_id.rs
+++ b/crates/hir/src/from_id.rs
@@ -11,9 +11,8 @@ use hir_def::{
11}; 11};
12 12
13use crate::{ 13use crate::{
14 code_model::{BuiltinType, GenericParam}, 14 Adt, AssocItem, BuiltinType, DefWithBody, Field, GenericDef, GenericParam, Label, Local,
15 Adt, AssocItem, DefWithBody, Field, GenericDef, Label, Local, MacroDef, ModuleDef, Variant, 15 MacroDef, ModuleDef, Variant, VariantDef,
16 VariantDef,
17}; 16};
18 17
19macro_rules! from_id { 18macro_rules! from_id {
diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs
index 769945c47..58adc8fd3 100644
--- a/crates/hir/src/lib.rs
+++ b/crates/hir/src/lib.rs
@@ -20,50 +20,2117 @@
20#![recursion_limit = "512"] 20#![recursion_limit = "512"]
21 21
22mod semantics; 22mod semantics;
23pub mod db;
24mod source_analyzer; 23mod source_analyzer;
25 24
26pub mod diagnostics;
27
28mod from_id; 25mod from_id;
29mod code_model;
30mod attrs; 26mod attrs;
31mod has_source; 27mod has_source;
32 28
29pub mod diagnostics;
30pub mod db;
31
32use std::{iter, sync::Arc};
33
34use arrayvec::ArrayVec;
35use base_db::{CrateDisplayName, CrateId, Edition, FileId};
36use either::Either;
37use hir_def::{
38 adt::{ReprKind, VariantData},
39 expr::{BindingAnnotation, LabelId, Pat, PatId},
40 item_tree::ItemTreeNode,
41 lang_item::LangItemTarget,
42 per_ns::PerNs,
43 resolver::{HasResolver, Resolver},
44 src::HasSource as _,
45 AdtId, AssocContainerId, AssocItemId, AssocItemLoc, AttrDefId, ConstId, ConstParamId,
46 DefWithBodyId, EnumId, FunctionId, GenericDefId, HasModule, ImplId, LifetimeParamId,
47 LocalEnumVariantId, LocalFieldId, Lookup, ModuleId, StaticId, StructId, TraitId, TypeAliasId,
48 TypeParamId, UnionId,
49};
50use hir_expand::{diagnostics::DiagnosticSink, name::name, MacroDefKind};
51use hir_ty::{
52 autoderef,
53 display::{write_bounds_like_dyn_trait_with_prefix, HirDisplayError, HirFormatter},
54 method_resolution,
55 traits::{FnTrait, Solution, SolutionVariables},
56 AliasTy, BoundVar, CallableDefId, CallableSig, Canonical, DebruijnIndex, GenericPredicate,
57 InEnvironment, Obligation, ProjectionPredicate, ProjectionTy, Scalar, Substs, TraitEnvironment,
58 Ty, TyDefId, TyVariableKind,
59};
60use rustc_hash::FxHashSet;
61use stdx::{format_to, impl_from};
62use syntax::{
63 ast::{self, AttrsOwner, NameOwner},
64 AstNode, SmolStr,
65};
66use tt::{Ident, Leaf, Literal, TokenTree};
67
68use crate::db::{DefDatabase, HirDatabase};
69
33pub use crate::{ 70pub use crate::{
34 attrs::{HasAttrs, Namespace}, 71 attrs::{HasAttrs, Namespace},
35 code_model::{
36 Access, Adt, AsAssocItem, AssocItem, AssocItemContainer, Callable, CallableKind, Const,
37 ConstParam, Crate, CrateDependency, DefWithBody, Enum, Field, FieldSource, Function,
38 GenericDef, GenericParam, HasVisibility, Impl, Label, LifetimeParam, Local, MacroDef,
39 Module, ModuleDef, ScopeDef, Static, Struct, Trait, Type, TypeAlias, TypeParam, Union,
40 Variant, VariantDef,
41 },
42 has_source::HasSource, 72 has_source::HasSource,
43 semantics::{PathResolution, Semantics, SemanticsScope}, 73 semantics::{PathResolution, Semantics, SemanticsScope},
44}; 74};
45 75
46pub use hir_def::{ 76// Be careful with these re-exports.
47 adt::StructKind, 77//
48 attr::{Attrs, Documentation}, 78// `hir` is the boundary between the compiler and the IDE. It should try hard to
49 body::scope::ExprScopes, 79// isolate the compiler from the ide, to allow the two to be refactored
50 builtin_type::BuiltinType, 80// independently. Re-exporting something from the compiler is the sure way to
51 find_path::PrefixKind, 81// breach the boundary.
52 import_map, 82//
53 item_scope::ItemInNs, 83// Generally, a refactoring which *removes* a name from this list is a good
54 nameres::ModuleSource, 84// idea!
55 path::{ModPath, PathKind}, 85pub use {
56 type_ref::{Mutability, TypeRef}, 86 hir_def::{
57 visibility::Visibility, 87 adt::StructKind,
58}; 88 attr::{Attrs, Documentation},
59pub use hir_expand::{ 89 body::scope::ExprScopes,
60 name::{known, AsName, Name}, 90 find_path::PrefixKind,
61 ExpandResult, HirFileId, InFile, MacroCallId, MacroCallLoc, /* FIXME */ MacroDefId, 91 import_map,
62 MacroFile, Origin, 92 item_scope::ItemInNs,
93 nameres::ModuleSource,
94 path::{ModPath, PathKind},
95 type_ref::{Mutability, TypeRef},
96 visibility::Visibility,
97 },
98 hir_expand::{
99 name::{known, Name},
100 ExpandResult, HirFileId, InFile, MacroCallId, MacroCallLoc, /* FIXME */ MacroDefId,
101 MacroFile, Origin,
102 },
103 hir_ty::display::HirDisplay,
63}; 104};
64pub use hir_ty::display::HirDisplay;
65 105
66// These are negative re-exports: pub using these names is forbidden, they 106// These are negative re-exports: pub using these names is forbidden, they
67// should remain private to hir internals. 107// should remain private to hir internals.
68#[allow(unused)] 108#[allow(unused)]
69use {hir_def::path::Path, hir_expand::hygiene::Hygiene}; 109use {
110 hir_def::path::Path,
111 hir_expand::{hygiene::Hygiene, name::AsName},
112};
113
114/// hir::Crate describes a single crate. It's the main interface with which
115/// a crate's dependencies interact. Mostly, it should be just a proxy for the
116/// root module.
117#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
118pub struct Crate {
119 pub(crate) id: CrateId,
120}
121
122#[derive(Debug)]
123pub struct CrateDependency {
124 pub krate: Crate,
125 pub name: Name,
126}
127
128impl Crate {
129 pub fn dependencies(self, db: &dyn HirDatabase) -> Vec<CrateDependency> {
130 db.crate_graph()[self.id]
131 .dependencies
132 .iter()
133 .map(|dep| {
134 let krate = Crate { id: dep.crate_id };
135 let name = dep.as_name();
136 CrateDependency { krate, name }
137 })
138 .collect()
139 }
140
141 // FIXME: add `transitive_reverse_dependencies`.
142 pub fn reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
143 let crate_graph = db.crate_graph();
144 crate_graph
145 .iter()
146 .filter(|&krate| {
147 crate_graph[krate].dependencies.iter().any(|it| it.crate_id == self.id)
148 })
149 .map(|id| Crate { id })
150 .collect()
151 }
152
153 pub fn root_module(self, db: &dyn HirDatabase) -> Module {
154 let def_map = db.crate_def_map(self.id);
155 Module { id: def_map.module_id(def_map.root()) }
156 }
157
158 pub fn root_file(self, db: &dyn HirDatabase) -> FileId {
159 db.crate_graph()[self.id].root_file_id
160 }
161
162 pub fn edition(self, db: &dyn HirDatabase) -> Edition {
163 db.crate_graph()[self.id].edition
164 }
165
166 pub fn display_name(self, db: &dyn HirDatabase) -> Option<CrateDisplayName> {
167 db.crate_graph()[self.id].display_name.clone()
168 }
169
170 pub fn query_external_importables(
171 self,
172 db: &dyn DefDatabase,
173 query: import_map::Query,
174 ) -> impl Iterator<Item = Either<ModuleDef, MacroDef>> {
175 import_map::search_dependencies(db, self.into(), query).into_iter().map(|item| match item {
176 ItemInNs::Types(mod_id) | ItemInNs::Values(mod_id) => Either::Left(mod_id.into()),
177 ItemInNs::Macros(mac_id) => Either::Right(mac_id.into()),
178 })
179 }
180
181 pub fn all(db: &dyn HirDatabase) -> Vec<Crate> {
182 db.crate_graph().iter().map(|id| Crate { id }).collect()
183 }
184
185 /// Try to get the root URL of the documentation of a crate.
186 pub fn get_html_root_url(self: &Crate, db: &dyn HirDatabase) -> Option<String> {
187 // Look for #![doc(html_root_url = "...")]
188 let attrs = db.attrs(AttrDefId::ModuleId(self.root_module(db).into()));
189 let doc_attr_q = attrs.by_key("doc");
190
191 if !doc_attr_q.exists() {
192 return None;
193 }
194
195 let doc_url = doc_attr_q.tt_values().map(|tt| {
196 let name = tt.token_trees.iter()
197 .skip_while(|tt| !matches!(tt, TokenTree::Leaf(Leaf::Ident(Ident{text: ref ident, ..})) if ident == "html_root_url"))
198 .skip(2)
199 .next();
200
201 match name {
202 Some(TokenTree::Leaf(Leaf::Literal(Literal{ref text, ..}))) => Some(text),
203 _ => None
204 }
205 }).flat_map(|t| t).next();
206
207 doc_url.map(|s| s.trim_matches('"').trim_end_matches('/').to_owned() + "/")
208 }
209}
210
211#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
212pub struct Module {
213 pub(crate) id: ModuleId,
214}
215
216/// The defs which can be visible in the module.
217#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
218pub enum ModuleDef {
219 Module(Module),
220 Function(Function),
221 Adt(Adt),
222 // Can't be directly declared, but can be imported.
223 Variant(Variant),
224 Const(Const),
225 Static(Static),
226 Trait(Trait),
227 TypeAlias(TypeAlias),
228 BuiltinType(BuiltinType),
229}
230impl_from!(
231 Module,
232 Function,
233 Adt(Struct, Enum, Union),
234 Variant,
235 Const,
236 Static,
237 Trait,
238 TypeAlias,
239 BuiltinType
240 for ModuleDef
241);
242
243impl From<VariantDef> for ModuleDef {
244 fn from(var: VariantDef) -> Self {
245 match var {
246 VariantDef::Struct(t) => Adt::from(t).into(),
247 VariantDef::Union(t) => Adt::from(t).into(),
248 VariantDef::Variant(t) => t.into(),
249 }
250 }
251}
252
253impl ModuleDef {
254 pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
255 match self {
256 ModuleDef::Module(it) => it.parent(db),
257 ModuleDef::Function(it) => Some(it.module(db)),
258 ModuleDef::Adt(it) => Some(it.module(db)),
259 ModuleDef::Variant(it) => Some(it.module(db)),
260 ModuleDef::Const(it) => Some(it.module(db)),
261 ModuleDef::Static(it) => Some(it.module(db)),
262 ModuleDef::Trait(it) => Some(it.module(db)),
263 ModuleDef::TypeAlias(it) => Some(it.module(db)),
264 ModuleDef::BuiltinType(_) => None,
265 }
266 }
267
268 pub fn canonical_path(&self, db: &dyn HirDatabase) -> Option<String> {
269 let mut segments = Vec::new();
270 segments.push(self.name(db)?.to_string());
271 for m in self.module(db)?.path_to_root(db) {
272 segments.extend(m.name(db).map(|it| it.to_string()))
273 }
274 segments.reverse();
275 Some(segments.join("::"))
276 }
277
278 pub fn definition_visibility(&self, db: &dyn HirDatabase) -> Option<Visibility> {
279 let module = match self {
280 ModuleDef::Module(it) => it.parent(db)?,
281 ModuleDef::Function(it) => return Some(it.visibility(db)),
282 ModuleDef::Adt(it) => it.module(db),
283 ModuleDef::Variant(it) => {
284 let parent = it.parent_enum(db);
285 let module = it.module(db);
286 return module.visibility_of(db, &ModuleDef::Adt(Adt::Enum(parent)));
287 }
288 ModuleDef::Const(it) => return Some(it.visibility(db)),
289 ModuleDef::Static(it) => it.module(db),
290 ModuleDef::Trait(it) => it.module(db),
291 ModuleDef::TypeAlias(it) => return Some(it.visibility(db)),
292 ModuleDef::BuiltinType(_) => return None,
293 };
294
295 module.visibility_of(db, self)
296 }
297
298 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
299 match self {
300 ModuleDef::Adt(it) => Some(it.name(db)),
301 ModuleDef::Trait(it) => Some(it.name(db)),
302 ModuleDef::Function(it) => Some(it.name(db)),
303 ModuleDef::Variant(it) => Some(it.name(db)),
304 ModuleDef::TypeAlias(it) => Some(it.name(db)),
305 ModuleDef::Module(it) => it.name(db),
306 ModuleDef::Const(it) => it.name(db),
307 ModuleDef::Static(it) => it.name(db),
308 ModuleDef::BuiltinType(it) => Some(it.name()),
309 }
310 }
311
312 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
313 let id = match self {
314 ModuleDef::Adt(it) => match it {
315 Adt::Struct(it) => it.id.into(),
316 Adt::Enum(it) => it.id.into(),
317 Adt::Union(it) => it.id.into(),
318 },
319 ModuleDef::Trait(it) => it.id.into(),
320 ModuleDef::Function(it) => it.id.into(),
321 ModuleDef::TypeAlias(it) => it.id.into(),
322 ModuleDef::Module(it) => it.id.into(),
323 ModuleDef::Const(it) => it.id.into(),
324 ModuleDef::Static(it) => it.id.into(),
325 _ => return,
326 };
327
328 let module = match self.module(db) {
329 Some(it) => it,
330 None => return,
331 };
332
333 hir_ty::diagnostics::validate_module_item(db, module.id.krate(), id, sink)
334 }
335}
336
337impl Module {
338 /// Name of this module.
339 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
340 let def_map = self.id.def_map(db.upcast());
341 let parent = def_map[self.id.local_id].parent?;
342 def_map[parent].children.iter().find_map(|(name, module_id)| {
343 if *module_id == self.id.local_id {
344 Some(name.clone())
345 } else {
346 None
347 }
348 })
349 }
350
351 /// Returns the crate this module is part of.
352 pub fn krate(self) -> Crate {
353 Crate { id: self.id.krate() }
354 }
355
356 /// Topmost parent of this module. Every module has a `crate_root`, but some
357 /// might be missing `krate`. This can happen if a module's file is not included
358 /// in the module tree of any target in `Cargo.toml`.
359 pub fn crate_root(self, db: &dyn HirDatabase) -> Module {
360 let def_map = db.crate_def_map(self.id.krate());
361 Module { id: def_map.module_id(def_map.root()) }
362 }
363
364 /// Iterates over all child modules.
365 pub fn children(self, db: &dyn HirDatabase) -> impl Iterator<Item = Module> {
366 let def_map = self.id.def_map(db.upcast());
367 let children = def_map[self.id.local_id]
368 .children
369 .iter()
370 .map(|(_, module_id)| Module { id: def_map.module_id(*module_id) })
371 .collect::<Vec<_>>();
372 children.into_iter()
373 }
374
375 /// Finds a parent module.
376 pub fn parent(self, db: &dyn HirDatabase) -> Option<Module> {
377 // FIXME: handle block expressions as modules (their parent is in a different DefMap)
378 let def_map = self.id.def_map(db.upcast());
379 let parent_id = def_map[self.id.local_id].parent?;
380 Some(Module { id: def_map.module_id(parent_id) })
381 }
382
383 pub fn path_to_root(self, db: &dyn HirDatabase) -> Vec<Module> {
384 let mut res = vec![self];
385 let mut curr = self;
386 while let Some(next) = curr.parent(db) {
387 res.push(next);
388 curr = next
389 }
390 res
391 }
392
393 /// Returns a `ModuleScope`: a set of items, visible in this module.
394 pub fn scope(
395 self,
396 db: &dyn HirDatabase,
397 visible_from: Option<Module>,
398 ) -> Vec<(Name, ScopeDef)> {
399 self.id.def_map(db.upcast())[self.id.local_id]
400 .scope
401 .entries()
402 .filter_map(|(name, def)| {
403 if let Some(m) = visible_from {
404 let filtered =
405 def.filter_visibility(|vis| vis.is_visible_from(db.upcast(), m.id));
406 if filtered.is_none() && !def.is_none() {
407 None
408 } else {
409 Some((name, filtered))
410 }
411 } else {
412 Some((name, def))
413 }
414 })
415 .flat_map(|(name, def)| {
416 ScopeDef::all_items(def).into_iter().map(move |item| (name.clone(), item))
417 })
418 .collect()
419 }
420
421 pub fn visibility_of(self, db: &dyn HirDatabase, def: &ModuleDef) -> Option<Visibility> {
422 self.id.def_map(db.upcast())[self.id.local_id].scope.visibility_of(def.clone().into())
423 }
424
425 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
426 let _p = profile::span("Module::diagnostics").detail(|| {
427 format!("{:?}", self.name(db).map_or("<unknown>".into(), |name| name.to_string()))
428 });
429 let def_map = self.id.def_map(db.upcast());
430 def_map.add_diagnostics(db.upcast(), self.id.local_id, sink);
431 for decl in self.declarations(db) {
432 match decl {
433 crate::ModuleDef::Function(f) => f.diagnostics(db, sink),
434 crate::ModuleDef::Module(m) => {
435 // Only add diagnostics from inline modules
436 if def_map[m.id.local_id].origin.is_inline() {
437 m.diagnostics(db, sink)
438 }
439 }
440 _ => {
441 decl.diagnostics(db, sink);
442 }
443 }
444 }
445
446 for impl_def in self.impl_defs(db) {
447 for item in impl_def.items(db) {
448 if let AssocItem::Function(f) = item {
449 f.diagnostics(db, sink);
450 }
451 }
452 }
453 }
454
455 pub fn declarations(self, db: &dyn HirDatabase) -> Vec<ModuleDef> {
456 let def_map = self.id.def_map(db.upcast());
457 def_map[self.id.local_id].scope.declarations().map(ModuleDef::from).collect()
458 }
459
460 pub fn impl_defs(self, db: &dyn HirDatabase) -> Vec<Impl> {
461 let def_map = self.id.def_map(db.upcast());
462 def_map[self.id.local_id].scope.impls().map(Impl::from).collect()
463 }
464
465 /// Finds a path that can be used to refer to the given item from within
466 /// this module, if possible.
467 pub fn find_use_path(self, db: &dyn DefDatabase, item: impl Into<ItemInNs>) -> Option<ModPath> {
468 hir_def::find_path::find_path(db, item.into(), self.into())
469 }
470
471 /// Finds a path that can be used to refer to the given item from within
472 /// this module, if possible. This is used for returning import paths for use-statements.
473 pub fn find_use_path_prefixed(
474 self,
475 db: &dyn DefDatabase,
476 item: impl Into<ItemInNs>,
477 prefix_kind: PrefixKind,
478 ) -> Option<ModPath> {
479 hir_def::find_path::find_path_prefixed(db, item.into(), self.into(), prefix_kind)
480 }
481}
482
483#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
484pub struct Field {
485 pub(crate) parent: VariantDef,
486 pub(crate) id: LocalFieldId,
487}
488
489#[derive(Debug, PartialEq, Eq)]
490pub enum FieldSource {
491 Named(ast::RecordField),
492 Pos(ast::TupleField),
493}
494
495impl Field {
496 pub fn name(&self, db: &dyn HirDatabase) -> Name {
497 self.parent.variant_data(db).fields()[self.id].name.clone()
498 }
499
500 /// Returns the type as in the signature of the struct (i.e., with
501 /// placeholder types for type parameters). This is good for showing
502 /// signature help, but not so good to actually get the type of the field
503 /// when you actually have a variable of the struct.
504 pub fn signature_ty(&self, db: &dyn HirDatabase) -> Type {
505 let var_id = self.parent.into();
506 let generic_def_id: GenericDefId = match self.parent {
507 VariantDef::Struct(it) => it.id.into(),
508 VariantDef::Union(it) => it.id.into(),
509 VariantDef::Variant(it) => it.parent.id.into(),
510 };
511 let substs = Substs::type_params(db, generic_def_id);
512 let ty = db.field_types(var_id)[self.id].clone().subst(&substs);
513 Type::new(db, self.parent.module(db).id.krate(), var_id, ty)
514 }
515
516 pub fn parent_def(&self, _db: &dyn HirDatabase) -> VariantDef {
517 self.parent
518 }
519}
520
521impl HasVisibility for Field {
522 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
523 let variant_data = self.parent.variant_data(db);
524 let visibility = &variant_data.fields()[self.id].visibility;
525 let parent_id: hir_def::VariantId = self.parent.into();
526 visibility.resolve(db.upcast(), &parent_id.resolver(db.upcast()))
527 }
528}
529
530#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
531pub struct Struct {
532 pub(crate) id: StructId,
533}
534
535impl Struct {
536 pub fn module(self, db: &dyn HirDatabase) -> Module {
537 Module { id: self.id.lookup(db.upcast()).container }
538 }
539
540 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
541 Some(self.module(db).krate())
542 }
543
544 pub fn name(self, db: &dyn HirDatabase) -> Name {
545 db.struct_data(self.id).name.clone()
546 }
547
548 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
549 db.struct_data(self.id)
550 .variant_data
551 .fields()
552 .iter()
553 .map(|(id, _)| Field { parent: self.into(), id })
554 .collect()
555 }
556
557 pub fn ty(self, db: &dyn HirDatabase) -> Type {
558 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
559 }
560
561 pub fn repr(self, db: &dyn HirDatabase) -> Option<ReprKind> {
562 db.struct_data(self.id).repr.clone()
563 }
564
565 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
566 self.variant_data(db).kind()
567 }
568
569 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
570 db.struct_data(self.id).variant_data.clone()
571 }
572}
573
574#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
575pub struct Union {
576 pub(crate) id: UnionId,
577}
578
579impl Union {
580 pub fn name(self, db: &dyn HirDatabase) -> Name {
581 db.union_data(self.id).name.clone()
582 }
583
584 pub fn module(self, db: &dyn HirDatabase) -> Module {
585 Module { id: self.id.lookup(db.upcast()).container }
586 }
587
588 pub fn ty(self, db: &dyn HirDatabase) -> Type {
589 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
590 }
591
592 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
593 db.union_data(self.id)
594 .variant_data
595 .fields()
596 .iter()
597 .map(|(id, _)| Field { parent: self.into(), id })
598 .collect()
599 }
600
601 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
602 db.union_data(self.id).variant_data.clone()
603 }
604}
605
606#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
607pub struct Enum {
608 pub(crate) id: EnumId,
609}
610
611impl Enum {
612 pub fn module(self, db: &dyn HirDatabase) -> Module {
613 Module { id: self.id.lookup(db.upcast()).container }
614 }
615
616 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
617 Some(self.module(db).krate())
618 }
619
620 pub fn name(self, db: &dyn HirDatabase) -> Name {
621 db.enum_data(self.id).name.clone()
622 }
623
624 pub fn variants(self, db: &dyn HirDatabase) -> Vec<Variant> {
625 db.enum_data(self.id).variants.iter().map(|(id, _)| Variant { parent: self, id }).collect()
626 }
627
628 pub fn ty(self, db: &dyn HirDatabase) -> Type {
629 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
630 }
631}
632
633#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
634pub struct Variant {
635 pub(crate) parent: Enum,
636 pub(crate) id: LocalEnumVariantId,
637}
638
639impl Variant {
640 pub fn module(self, db: &dyn HirDatabase) -> Module {
641 self.parent.module(db)
642 }
643 pub fn parent_enum(self, _db: &dyn HirDatabase) -> Enum {
644 self.parent
645 }
646
647 pub fn name(self, db: &dyn HirDatabase) -> Name {
648 db.enum_data(self.parent.id).variants[self.id].name.clone()
649 }
650
651 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
652 self.variant_data(db)
653 .fields()
654 .iter()
655 .map(|(id, _)| Field { parent: self.into(), id })
656 .collect()
657 }
658
659 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
660 self.variant_data(db).kind()
661 }
662
663 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
664 db.enum_data(self.parent.id).variants[self.id].variant_data.clone()
665 }
666}
667
668/// A Data Type
669#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
670pub enum Adt {
671 Struct(Struct),
672 Union(Union),
673 Enum(Enum),
674}
675impl_from!(Struct, Union, Enum for Adt);
676
677impl Adt {
678 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
679 let subst = db.generic_defaults(self.into());
680 subst.iter().any(|ty| &ty.value == &Ty::Unknown)
681 }
682
683 /// Turns this ADT into a type. Any type parameters of the ADT will be
684 /// turned into unknown types, which is good for e.g. finding the most
685 /// general set of completions, but will not look very nice when printed.
686 pub fn ty(self, db: &dyn HirDatabase) -> Type {
687 let id = AdtId::from(self);
688 Type::from_def(db, id.module(db.upcast()).krate(), id)
689 }
690
691 pub fn module(self, db: &dyn HirDatabase) -> Module {
692 match self {
693 Adt::Struct(s) => s.module(db),
694 Adt::Union(s) => s.module(db),
695 Adt::Enum(e) => e.module(db),
696 }
697 }
698
699 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
700 Some(self.module(db).krate())
701 }
702
703 pub fn name(self, db: &dyn HirDatabase) -> Name {
704 match self {
705 Adt::Struct(s) => s.name(db),
706 Adt::Union(u) => u.name(db),
707 Adt::Enum(e) => e.name(db),
708 }
709 }
710}
711
712#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
713pub enum VariantDef {
714 Struct(Struct),
715 Union(Union),
716 Variant(Variant),
717}
718impl_from!(Struct, Union, Variant for VariantDef);
719
720impl VariantDef {
721 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
722 match self {
723 VariantDef::Struct(it) => it.fields(db),
724 VariantDef::Union(it) => it.fields(db),
725 VariantDef::Variant(it) => it.fields(db),
726 }
727 }
728
729 pub fn module(self, db: &dyn HirDatabase) -> Module {
730 match self {
731 VariantDef::Struct(it) => it.module(db),
732 VariantDef::Union(it) => it.module(db),
733 VariantDef::Variant(it) => it.module(db),
734 }
735 }
736
737 pub fn name(&self, db: &dyn HirDatabase) -> Name {
738 match self {
739 VariantDef::Struct(s) => s.name(db),
740 VariantDef::Union(u) => u.name(db),
741 VariantDef::Variant(e) => e.name(db),
742 }
743 }
744
745 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
746 match self {
747 VariantDef::Struct(it) => it.variant_data(db),
748 VariantDef::Union(it) => it.variant_data(db),
749 VariantDef::Variant(it) => it.variant_data(db),
750 }
751 }
752}
753
754/// The defs which have a body.
755#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
756pub enum DefWithBody {
757 Function(Function),
758 Static(Static),
759 Const(Const),
760}
761impl_from!(Function, Const, Static for DefWithBody);
762
763impl DefWithBody {
764 pub fn module(self, db: &dyn HirDatabase) -> Module {
765 match self {
766 DefWithBody::Const(c) => c.module(db),
767 DefWithBody::Function(f) => f.module(db),
768 DefWithBody::Static(s) => s.module(db),
769 }
770 }
771
772 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
773 match self {
774 DefWithBody::Function(f) => Some(f.name(db)),
775 DefWithBody::Static(s) => s.name(db),
776 DefWithBody::Const(c) => c.name(db),
777 }
778 }
779}
780
781#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
782pub struct Function {
783 pub(crate) id: FunctionId,
784}
785
786impl Function {
787 pub fn module(self, db: &dyn HirDatabase) -> Module {
788 self.id.lookup(db.upcast()).module(db.upcast()).into()
789 }
790
791 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
792 Some(self.module(db).krate())
793 }
794
795 pub fn name(self, db: &dyn HirDatabase) -> Name {
796 db.function_data(self.id).name.clone()
797 }
798
799 /// Get this function's return type
800 pub fn ret_type(self, db: &dyn HirDatabase) -> Type {
801 let resolver = self.id.resolver(db.upcast());
802 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
803 let ret_type = &db.function_data(self.id).ret_type;
804 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
805 let ty = Ty::from_hir_ext(&ctx, ret_type).0;
806 Type::new_with_resolver_inner(db, krate, &resolver, ty)
807 }
808
809 pub fn self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
810 if !db.function_data(self.id).has_self_param {
811 return None;
812 }
813 Some(SelfParam { func: self.id })
814 }
815
816 pub fn assoc_fn_params(self, db: &dyn HirDatabase) -> Vec<Param> {
817 let resolver = self.id.resolver(db.upcast());
818 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
819 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
820 let environment = TraitEnvironment::lower(db, &resolver);
821 db.function_data(self.id)
822 .params
823 .iter()
824 .map(|type_ref| {
825 let ty = Type {
826 krate,
827 ty: InEnvironment {
828 value: Ty::from_hir_ext(&ctx, type_ref).0,
829 environment: environment.clone(),
830 },
831 };
832 Param { ty }
833 })
834 .collect()
835 }
836 pub fn method_params(self, db: &dyn HirDatabase) -> Option<Vec<Param>> {
837 if self.self_param(db).is_none() {
838 return None;
839 }
840 let mut res = self.assoc_fn_params(db);
841 res.remove(0);
842 Some(res)
843 }
844
845 pub fn is_unsafe(self, db: &dyn HirDatabase) -> bool {
846 db.function_data(self.id).is_unsafe
847 }
848
849 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
850 let krate = self.module(db).id.krate();
851 hir_def::diagnostics::validate_body(db.upcast(), self.id.into(), sink);
852 hir_ty::diagnostics::validate_module_item(db, krate, self.id.into(), sink);
853 hir_ty::diagnostics::validate_body(db, self.id.into(), sink);
854 }
855
856 /// Whether this function declaration has a definition.
857 ///
858 /// This is false in the case of required (not provided) trait methods.
859 pub fn has_body(self, db: &dyn HirDatabase) -> bool {
860 db.function_data(self.id).has_body
861 }
862
863 /// A textual representation of the HIR of this function for debugging purposes.
864 pub fn debug_hir(self, db: &dyn HirDatabase) -> String {
865 let body = db.body(self.id.into());
866
867 let mut result = String::new();
868 format_to!(result, "HIR expressions in the body of `{}`:\n", self.name(db));
869 for (id, expr) in body.exprs.iter() {
870 format_to!(result, "{:?}: {:?}\n", id, expr);
871 }
872
873 result
874 }
875}
876
877// Note: logically, this belongs to `hir_ty`, but we are not using it there yet.
878pub enum Access {
879 Shared,
880 Exclusive,
881 Owned,
882}
883
884impl From<hir_ty::Mutability> for Access {
885 fn from(mutability: hir_ty::Mutability) -> Access {
886 match mutability {
887 hir_ty::Mutability::Not => Access::Shared,
888 hir_ty::Mutability::Mut => Access::Exclusive,
889 }
890 }
891}
892
893#[derive(Debug)]
894pub struct Param {
895 ty: Type,
896}
897
898impl Param {
899 pub fn ty(&self) -> &Type {
900 &self.ty
901 }
902}
903
904#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
905pub struct SelfParam {
906 func: FunctionId,
907}
908
909impl SelfParam {
910 pub fn access(self, db: &dyn HirDatabase) -> Access {
911 let func_data = db.function_data(self.func);
912 func_data
913 .params
914 .first()
915 .map(|param| match *param {
916 TypeRef::Reference(.., mutability) => match mutability {
917 hir_def::type_ref::Mutability::Shared => Access::Shared,
918 hir_def::type_ref::Mutability::Mut => Access::Exclusive,
919 },
920 _ => Access::Owned,
921 })
922 .unwrap_or(Access::Owned)
923 }
924}
925
926impl HasVisibility for Function {
927 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
928 let function_data = db.function_data(self.id);
929 let visibility = &function_data.visibility;
930 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
931 }
932}
933
934#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
935pub struct Const {
936 pub(crate) id: ConstId,
937}
938
939impl Const {
940 pub fn module(self, db: &dyn HirDatabase) -> Module {
941 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
942 }
943
944 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
945 Some(self.module(db).krate())
946 }
947
948 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
949 db.const_data(self.id).name.clone()
950 }
951}
952
953impl HasVisibility for Const {
954 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
955 let function_data = db.const_data(self.id);
956 let visibility = &function_data.visibility;
957 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
958 }
959}
960
961#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
962pub struct Static {
963 pub(crate) id: StaticId,
964}
965
966impl Static {
967 pub fn module(self, db: &dyn HirDatabase) -> Module {
968 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
969 }
970
971 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
972 Some(self.module(db).krate())
973 }
974
975 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
976 db.static_data(self.id).name.clone()
977 }
978
979 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
980 db.static_data(self.id).mutable
981 }
982}
983
984#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
985pub struct Trait {
986 pub(crate) id: TraitId,
987}
988
989impl Trait {
990 pub fn module(self, db: &dyn HirDatabase) -> Module {
991 Module { id: self.id.lookup(db.upcast()).container }
992 }
993
994 pub fn name(self, db: &dyn HirDatabase) -> Name {
995 db.trait_data(self.id).name.clone()
996 }
997
998 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
999 db.trait_data(self.id).items.iter().map(|(_name, it)| (*it).into()).collect()
1000 }
1001
1002 pub fn is_auto(self, db: &dyn HirDatabase) -> bool {
1003 db.trait_data(self.id).auto
1004 }
1005}
1006
1007#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1008pub struct TypeAlias {
1009 pub(crate) id: TypeAliasId,
1010}
1011
1012impl TypeAlias {
1013 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
1014 let subst = db.generic_defaults(self.id.into());
1015 subst.iter().any(|ty| &ty.value == &Ty::Unknown)
1016 }
1017
1018 pub fn module(self, db: &dyn HirDatabase) -> Module {
1019 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1020 }
1021
1022 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
1023 Some(self.module(db).krate())
1024 }
1025
1026 pub fn type_ref(self, db: &dyn HirDatabase) -> Option<TypeRef> {
1027 db.type_alias_data(self.id).type_ref.clone()
1028 }
1029
1030 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1031 Type::from_def(db, self.id.lookup(db.upcast()).module(db.upcast()).krate(), self.id)
1032 }
1033
1034 pub fn name(self, db: &dyn HirDatabase) -> Name {
1035 db.type_alias_data(self.id).name.clone()
1036 }
1037}
1038
1039impl HasVisibility for TypeAlias {
1040 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1041 let function_data = db.type_alias_data(self.id);
1042 let visibility = &function_data.visibility;
1043 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1044 }
1045}
1046
1047#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1048pub struct BuiltinType {
1049 pub(crate) inner: hir_def::builtin_type::BuiltinType,
1050}
1051
1052impl BuiltinType {
1053 pub fn ty(self, db: &dyn HirDatabase, module: Module) -> Type {
1054 let resolver = module.id.resolver(db.upcast());
1055 Type::new_with_resolver(db, &resolver, Ty::builtin(self.inner))
1056 .expect("crate not present in resolver")
1057 }
1058
1059 pub fn name(self) -> Name {
1060 self.inner.as_name()
1061 }
1062}
1063
1064#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1065pub struct MacroDef {
1066 pub(crate) id: MacroDefId,
1067}
1068
1069impl MacroDef {
1070 /// FIXME: right now, this just returns the root module of the crate that
1071 /// defines this macro. The reasons for this is that macros are expanded
1072 /// early, in `hir_expand`, where modules simply do not exist yet.
1073 pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
1074 let krate = self.id.krate;
1075 let def_map = db.crate_def_map(krate);
1076 let module_id = def_map.root();
1077 Some(Module { id: def_map.module_id(module_id) })
1078 }
1079
1080 /// XXX: this parses the file
1081 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1082 self.source(db)?.value.name().map(|it| it.as_name())
1083 }
1084
1085 /// Indicate it is a proc-macro
1086 pub fn is_proc_macro(&self) -> bool {
1087 matches!(self.id.kind, MacroDefKind::ProcMacro(_))
1088 }
1089
1090 /// Indicate it is a derive macro
1091 pub fn is_derive_macro(&self) -> bool {
1092 matches!(self.id.kind, MacroDefKind::ProcMacro(_) | MacroDefKind::BuiltInDerive(_))
1093 }
1094}
1095
1096/// Invariant: `inner.as_assoc_item(db).is_some()`
1097/// We do not actively enforce this invariant.
1098#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1099pub enum AssocItem {
1100 Function(Function),
1101 Const(Const),
1102 TypeAlias(TypeAlias),
1103}
1104#[derive(Debug)]
1105pub enum AssocItemContainer {
1106 Trait(Trait),
1107 Impl(Impl),
1108}
1109pub trait AsAssocItem {
1110 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem>;
1111}
1112
1113impl AsAssocItem for Function {
1114 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1115 as_assoc_item(db, AssocItem::Function, self.id)
1116 }
1117}
1118impl AsAssocItem for Const {
1119 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1120 as_assoc_item(db, AssocItem::Const, self.id)
1121 }
1122}
1123impl AsAssocItem for TypeAlias {
1124 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1125 as_assoc_item(db, AssocItem::TypeAlias, self.id)
1126 }
1127}
1128impl AsAssocItem for ModuleDef {
1129 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1130 match self {
1131 ModuleDef::Function(it) => it.as_assoc_item(db),
1132 ModuleDef::Const(it) => it.as_assoc_item(db),
1133 ModuleDef::TypeAlias(it) => it.as_assoc_item(db),
1134 _ => None,
1135 }
1136 }
1137}
1138fn as_assoc_item<ID, DEF, CTOR, AST>(db: &dyn HirDatabase, ctor: CTOR, id: ID) -> Option<AssocItem>
1139where
1140 ID: Lookup<Data = AssocItemLoc<AST>>,
1141 DEF: From<ID>,
1142 CTOR: FnOnce(DEF) -> AssocItem,
1143 AST: ItemTreeNode,
1144{
1145 match id.lookup(db.upcast()).container {
1146 AssocContainerId::TraitId(_) | AssocContainerId::ImplId(_) => Some(ctor(DEF::from(id))),
1147 AssocContainerId::ModuleId(_) => None,
1148 }
1149}
1150
1151impl AssocItem {
1152 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1153 match self {
1154 AssocItem::Function(it) => Some(it.name(db)),
1155 AssocItem::Const(it) => it.name(db),
1156 AssocItem::TypeAlias(it) => Some(it.name(db)),
1157 }
1158 }
1159 pub fn module(self, db: &dyn HirDatabase) -> Module {
1160 match self {
1161 AssocItem::Function(f) => f.module(db),
1162 AssocItem::Const(c) => c.module(db),
1163 AssocItem::TypeAlias(t) => t.module(db),
1164 }
1165 }
1166 pub fn container(self, db: &dyn HirDatabase) -> AssocItemContainer {
1167 let container = match self {
1168 AssocItem::Function(it) => it.id.lookup(db.upcast()).container,
1169 AssocItem::Const(it) => it.id.lookup(db.upcast()).container,
1170 AssocItem::TypeAlias(it) => it.id.lookup(db.upcast()).container,
1171 };
1172 match container {
1173 AssocContainerId::TraitId(id) => AssocItemContainer::Trait(id.into()),
1174 AssocContainerId::ImplId(id) => AssocItemContainer::Impl(id.into()),
1175 AssocContainerId::ModuleId(_) => panic!("invalid AssocItem"),
1176 }
1177 }
1178
1179 pub fn containing_trait(self, db: &dyn HirDatabase) -> Option<Trait> {
1180 match self.container(db) {
1181 AssocItemContainer::Trait(t) => Some(t),
1182 _ => None,
1183 }
1184 }
1185}
1186
1187impl HasVisibility for AssocItem {
1188 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1189 match self {
1190 AssocItem::Function(f) => f.visibility(db),
1191 AssocItem::Const(c) => c.visibility(db),
1192 AssocItem::TypeAlias(t) => t.visibility(db),
1193 }
1194 }
1195}
1196
1197#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
1198pub enum GenericDef {
1199 Function(Function),
1200 Adt(Adt),
1201 Trait(Trait),
1202 TypeAlias(TypeAlias),
1203 Impl(Impl),
1204 // enum variants cannot have generics themselves, but their parent enums
1205 // can, and this makes some code easier to write
1206 Variant(Variant),
1207 // consts can have type parameters from their parents (i.e. associated consts of traits)
1208 Const(Const),
1209}
1210impl_from!(
1211 Function,
1212 Adt(Struct, Enum, Union),
1213 Trait,
1214 TypeAlias,
1215 Impl,
1216 Variant,
1217 Const
1218 for GenericDef
1219);
1220
1221impl GenericDef {
1222 pub fn params(self, db: &dyn HirDatabase) -> Vec<GenericParam> {
1223 let generics = db.generic_params(self.into());
1224 let ty_params = generics
1225 .types
1226 .iter()
1227 .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
1228 .map(GenericParam::TypeParam);
1229 let lt_params = generics
1230 .lifetimes
1231 .iter()
1232 .map(|(local_id, _)| LifetimeParam {
1233 id: LifetimeParamId { parent: self.into(), local_id },
1234 })
1235 .map(GenericParam::LifetimeParam);
1236 let const_params = generics
1237 .consts
1238 .iter()
1239 .map(|(local_id, _)| ConstParam { id: ConstParamId { parent: self.into(), local_id } })
1240 .map(GenericParam::ConstParam);
1241 ty_params.chain(lt_params).chain(const_params).collect()
1242 }
1243
1244 pub fn type_params(self, db: &dyn HirDatabase) -> Vec<TypeParam> {
1245 let generics = db.generic_params(self.into());
1246 generics
1247 .types
1248 .iter()
1249 .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
1250 .collect()
1251 }
1252}
1253
1254#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1255pub struct Local {
1256 pub(crate) parent: DefWithBodyId,
1257 pub(crate) pat_id: PatId,
1258}
1259
1260impl Local {
1261 pub fn is_param(self, db: &dyn HirDatabase) -> bool {
1262 let src = self.source(db);
1263 match src.value {
1264 Either::Left(bind_pat) => {
1265 bind_pat.syntax().ancestors().any(|it| ast::Param::can_cast(it.kind()))
1266 }
1267 Either::Right(_self_param) => true,
1268 }
1269 }
1270
1271 // FIXME: why is this an option? It shouldn't be?
1272 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1273 let body = db.body(self.parent.into());
1274 match &body[self.pat_id] {
1275 Pat::Bind { name, .. } => Some(name.clone()),
1276 _ => None,
1277 }
1278 }
1279
1280 pub fn is_self(self, db: &dyn HirDatabase) -> bool {
1281 self.name(db) == Some(name![self])
1282 }
1283
1284 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
1285 let body = db.body(self.parent.into());
1286 matches!(&body[self.pat_id], Pat::Bind { mode: BindingAnnotation::Mutable, .. })
1287 }
1288
1289 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
1290 self.parent.into()
1291 }
1292
1293 pub fn module(self, db: &dyn HirDatabase) -> Module {
1294 self.parent(db).module(db)
1295 }
1296
1297 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1298 let def = DefWithBodyId::from(self.parent);
1299 let infer = db.infer(def);
1300 let ty = infer[self.pat_id].clone();
1301 let krate = def.module(db.upcast()).krate();
1302 Type::new(db, krate, def, ty)
1303 }
1304
1305 pub fn source(self, db: &dyn HirDatabase) -> InFile<Either<ast::IdentPat, ast::SelfParam>> {
1306 let (_body, source_map) = db.body_with_source_map(self.parent.into());
1307 let src = source_map.pat_syntax(self.pat_id).unwrap(); // Hmm...
1308 let root = src.file_syntax(db.upcast());
1309 src.map(|ast| {
1310 ast.map_left(|it| it.cast().unwrap().to_node(&root)).map_right(|it| it.to_node(&root))
1311 })
1312 }
1313}
1314
1315#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1316pub struct Label {
1317 pub(crate) parent: DefWithBodyId,
1318 pub(crate) label_id: LabelId,
1319}
1320
1321impl Label {
1322 pub fn module(self, db: &dyn HirDatabase) -> Module {
1323 self.parent(db).module(db)
1324 }
1325
1326 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
1327 self.parent.into()
1328 }
1329
1330 pub fn name(self, db: &dyn HirDatabase) -> Name {
1331 let body = db.body(self.parent.into());
1332 body[self.label_id].name.clone()
1333 }
1334
1335 pub fn source(self, db: &dyn HirDatabase) -> InFile<ast::Label> {
1336 let (_body, source_map) = db.body_with_source_map(self.parent.into());
1337 let src = source_map.label_syntax(self.label_id);
1338 let root = src.file_syntax(db.upcast());
1339 src.map(|ast| ast.to_node(&root))
1340 }
1341}
1342
1343#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1344pub enum GenericParam {
1345 TypeParam(TypeParam),
1346 LifetimeParam(LifetimeParam),
1347 ConstParam(ConstParam),
1348}
1349impl_from!(TypeParam, LifetimeParam, ConstParam for GenericParam);
1350
1351impl GenericParam {
1352 pub fn module(self, db: &dyn HirDatabase) -> Module {
1353 match self {
1354 GenericParam::TypeParam(it) => it.module(db),
1355 GenericParam::LifetimeParam(it) => it.module(db),
1356 GenericParam::ConstParam(it) => it.module(db),
1357 }
1358 }
1359
1360 pub fn name(self, db: &dyn HirDatabase) -> Name {
1361 match self {
1362 GenericParam::TypeParam(it) => it.name(db),
1363 GenericParam::LifetimeParam(it) => it.name(db),
1364 GenericParam::ConstParam(it) => it.name(db),
1365 }
1366 }
1367}
1368
1369#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1370pub struct TypeParam {
1371 pub(crate) id: TypeParamId,
1372}
1373
1374impl TypeParam {
1375 pub fn name(self, db: &dyn HirDatabase) -> Name {
1376 let params = db.generic_params(self.id.parent);
1377 params.types[self.id.local_id].name.clone().unwrap_or_else(Name::missing)
1378 }
1379
1380 pub fn module(self, db: &dyn HirDatabase) -> Module {
1381 self.id.parent.module(db.upcast()).into()
1382 }
1383
1384 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1385 let resolver = self.id.parent.resolver(db.upcast());
1386 let krate = self.id.parent.module(db.upcast()).krate();
1387 let ty = Ty::Placeholder(self.id);
1388 Type::new_with_resolver_inner(db, krate, &resolver, ty)
1389 }
1390
1391 pub fn trait_bounds(self, db: &dyn HirDatabase) -> Vec<Trait> {
1392 db.generic_predicates_for_param(self.id)
1393 .into_iter()
1394 .filter_map(|pred| match &pred.value {
1395 hir_ty::GenericPredicate::Implemented(trait_ref) => {
1396 Some(Trait::from(trait_ref.trait_))
1397 }
1398 _ => None,
1399 })
1400 .collect()
1401 }
1402
1403 pub fn default(self, db: &dyn HirDatabase) -> Option<Type> {
1404 let params = db.generic_defaults(self.id.parent);
1405 let local_idx = hir_ty::param_idx(db, self.id)?;
1406 let resolver = self.id.parent.resolver(db.upcast());
1407 let krate = self.id.parent.module(db.upcast()).krate();
1408 let ty = params.get(local_idx)?.clone();
1409 let subst = Substs::type_params(db, self.id.parent);
1410 let ty = ty.subst(&subst.prefix(local_idx));
1411 Some(Type::new_with_resolver_inner(db, krate, &resolver, ty))
1412 }
1413}
1414
1415impl HirDisplay for TypeParam {
1416 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1417 write!(f, "{}", self.name(f.db))?;
1418 let bounds = f.db.generic_predicates_for_param(self.id);
1419 let substs = Substs::type_params(f.db, self.id.parent);
1420 let predicates = bounds.iter().cloned().map(|b| b.subst(&substs)).collect::<Vec<_>>();
1421 if !(predicates.is_empty() || f.omit_verbose_types()) {
1422 write_bounds_like_dyn_trait_with_prefix(":", &predicates, f)?;
1423 }
1424 Ok(())
1425 }
1426}
1427
1428#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1429pub struct LifetimeParam {
1430 pub(crate) id: LifetimeParamId,
1431}
1432
1433impl LifetimeParam {
1434 pub fn name(self, db: &dyn HirDatabase) -> Name {
1435 let params = db.generic_params(self.id.parent);
1436 params.lifetimes[self.id.local_id].name.clone()
1437 }
1438
1439 pub fn module(self, db: &dyn HirDatabase) -> Module {
1440 self.id.parent.module(db.upcast()).into()
1441 }
1442
1443 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
1444 self.id.parent.into()
1445 }
1446}
1447
1448#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1449pub struct ConstParam {
1450 pub(crate) id: ConstParamId,
1451}
1452
1453impl ConstParam {
1454 pub fn name(self, db: &dyn HirDatabase) -> Name {
1455 let params = db.generic_params(self.id.parent);
1456 params.consts[self.id.local_id].name.clone()
1457 }
1458
1459 pub fn module(self, db: &dyn HirDatabase) -> Module {
1460 self.id.parent.module(db.upcast()).into()
1461 }
1462
1463 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
1464 self.id.parent.into()
1465 }
1466
1467 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1468 let def = self.id.parent;
1469 let krate = def.module(db.upcast()).krate();
1470 Type::new(db, krate, def, db.const_param_ty(self.id))
1471 }
1472}
1473
1474#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1475pub struct Impl {
1476 pub(crate) id: ImplId,
1477}
1478
1479impl Impl {
1480 pub fn all_in_crate(db: &dyn HirDatabase, krate: Crate) -> Vec<Impl> {
1481 let inherent = db.inherent_impls_in_crate(krate.id);
1482 let trait_ = db.trait_impls_in_crate(krate.id);
1483
1484 inherent.all_impls().chain(trait_.all_impls()).map(Self::from).collect()
1485 }
1486 pub fn for_trait(db: &dyn HirDatabase, krate: Crate, trait_: Trait) -> Vec<Impl> {
1487 let impls = db.trait_impls_in_crate(krate.id);
1488 impls.for_trait(trait_.id).map(Self::from).collect()
1489 }
1490
1491 // FIXME: the return type is wrong. This should be a hir version of
1492 // `TraitRef` (ie, resolved `TypeRef`).
1493 pub fn target_trait(self, db: &dyn HirDatabase) -> Option<TypeRef> {
1494 db.impl_data(self.id).target_trait.clone()
1495 }
1496
1497 pub fn target_ty(self, db: &dyn HirDatabase) -> Type {
1498 let impl_data = db.impl_data(self.id);
1499 let resolver = self.id.resolver(db.upcast());
1500 let krate = self.id.lookup(db.upcast()).container.krate();
1501 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1502 let ty = Ty::from_hir(&ctx, &impl_data.target_type);
1503 Type::new_with_resolver_inner(db, krate, &resolver, ty)
1504 }
1505
1506 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
1507 db.impl_data(self.id).items.iter().map(|it| (*it).into()).collect()
1508 }
1509
1510 pub fn is_negative(self, db: &dyn HirDatabase) -> bool {
1511 db.impl_data(self.id).is_negative
1512 }
1513
1514 pub fn module(self, db: &dyn HirDatabase) -> Module {
1515 self.id.lookup(db.upcast()).container.into()
1516 }
1517
1518 pub fn krate(self, db: &dyn HirDatabase) -> Crate {
1519 Crate { id: self.module(db).id.krate() }
1520 }
1521
1522 pub fn is_builtin_derive(self, db: &dyn HirDatabase) -> Option<InFile<ast::Attr>> {
1523 let src = self.source(db)?;
1524 let item = src.file_id.is_builtin_derive(db.upcast())?;
1525 let hygenic = hir_expand::hygiene::Hygiene::new(db.upcast(), item.file_id);
1526
1527 // FIXME: handle `cfg_attr`
1528 let attr = item
1529 .value
1530 .attrs()
1531 .filter_map(|it| {
1532 let path = ModPath::from_src(it.path()?, &hygenic)?;
1533 if path.as_ident()?.to_string() == "derive" {
1534 Some(it)
1535 } else {
1536 None
1537 }
1538 })
1539 .last()?;
1540
1541 Some(item.with_value(attr))
1542 }
1543}
1544
1545#[derive(Clone, PartialEq, Eq, Debug)]
1546pub struct Type {
1547 krate: CrateId,
1548 ty: InEnvironment<Ty>,
1549}
1550
1551impl Type {
1552 pub(crate) fn new_with_resolver(
1553 db: &dyn HirDatabase,
1554 resolver: &Resolver,
1555 ty: Ty,
1556 ) -> Option<Type> {
1557 let krate = resolver.krate()?;
1558 Some(Type::new_with_resolver_inner(db, krate, resolver, ty))
1559 }
1560 pub(crate) fn new_with_resolver_inner(
1561 db: &dyn HirDatabase,
1562 krate: CrateId,
1563 resolver: &Resolver,
1564 ty: Ty,
1565 ) -> Type {
1566 let environment = TraitEnvironment::lower(db, &resolver);
1567 Type { krate, ty: InEnvironment { value: ty, environment } }
1568 }
1569
1570 fn new(db: &dyn HirDatabase, krate: CrateId, lexical_env: impl HasResolver, ty: Ty) -> Type {
1571 let resolver = lexical_env.resolver(db.upcast());
1572 let environment = TraitEnvironment::lower(db, &resolver);
1573 Type { krate, ty: InEnvironment { value: ty, environment } }
1574 }
1575
1576 fn from_def(
1577 db: &dyn HirDatabase,
1578 krate: CrateId,
1579 def: impl HasResolver + Into<TyDefId> + Into<GenericDefId>,
1580 ) -> Type {
1581 let substs = Substs::build_for_def(db, def).fill_with_unknown().build();
1582 let ty = db.ty(def.into()).subst(&substs);
1583 Type::new(db, krate, def, ty)
1584 }
1585
1586 pub fn is_unit(&self) -> bool {
1587 matches!(self.ty.value, Ty::Tuple(0, ..))
1588 }
1589 pub fn is_bool(&self) -> bool {
1590 matches!(self.ty.value, Ty::Scalar(Scalar::Bool))
1591 }
1592
1593 pub fn is_mutable_reference(&self) -> bool {
1594 matches!(self.ty.value, Ty::Ref(hir_ty::Mutability::Mut, ..))
1595 }
1596
1597 pub fn remove_ref(&self) -> Option<Type> {
1598 match &self.ty.value {
1599 Ty::Ref(.., substs) => Some(self.derived(substs[0].clone())),
1600 _ => None,
1601 }
1602 }
1603
1604 pub fn is_unknown(&self) -> bool {
1605 matches!(self.ty.value, Ty::Unknown)
1606 }
1607
1608 /// Checks that particular type `ty` implements `std::future::Future`.
1609 /// This function is used in `.await` syntax completion.
1610 pub fn impls_future(&self, db: &dyn HirDatabase) -> bool {
1611 // No special case for the type of async block, since Chalk can figure it out.
1612
1613 let krate = self.krate;
1614
1615 let std_future_trait =
1616 db.lang_item(krate, "future_trait".into()).and_then(|it| it.as_trait());
1617 let std_future_trait = match std_future_trait {
1618 Some(it) => it,
1619 None => return false,
1620 };
1621
1622 let canonical_ty = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1623 method_resolution::implements_trait(
1624 &canonical_ty,
1625 db,
1626 self.ty.environment.clone(),
1627 krate,
1628 std_future_trait,
1629 )
1630 }
1631
1632 /// Checks that particular type `ty` implements `std::ops::FnOnce`.
1633 ///
1634 /// This function can be used to check if a particular type is callable, since FnOnce is a
1635 /// supertrait of Fn and FnMut, so all callable types implements at least FnOnce.
1636 pub fn impls_fnonce(&self, db: &dyn HirDatabase) -> bool {
1637 let krate = self.krate;
1638
1639 let fnonce_trait = match FnTrait::FnOnce.get_id(db, krate) {
1640 Some(it) => it,
1641 None => return false,
1642 };
1643
1644 let canonical_ty = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1645 method_resolution::implements_trait_unique(
1646 &canonical_ty,
1647 db,
1648 self.ty.environment.clone(),
1649 krate,
1650 fnonce_trait,
1651 )
1652 }
1653
1654 pub fn impls_trait(&self, db: &dyn HirDatabase, trait_: Trait, args: &[Type]) -> bool {
1655 let trait_ref = hir_ty::TraitRef {
1656 trait_: trait_.id,
1657 substs: Substs::build_for_def(db, trait_.id)
1658 .push(self.ty.value.clone())
1659 .fill(args.iter().map(|t| t.ty.value.clone()))
1660 .build(),
1661 };
1662
1663 let goal = Canonical {
1664 value: hir_ty::InEnvironment::new(
1665 self.ty.environment.clone(),
1666 hir_ty::Obligation::Trait(trait_ref),
1667 ),
1668 kinds: Arc::new([]),
1669 };
1670
1671 db.trait_solve(self.krate, goal).is_some()
1672 }
1673
1674 pub fn normalize_trait_assoc_type(
1675 &self,
1676 db: &dyn HirDatabase,
1677 trait_: Trait,
1678 args: &[Type],
1679 alias: TypeAlias,
1680 ) -> Option<Type> {
1681 let subst = Substs::build_for_def(db, trait_.id)
1682 .push(self.ty.value.clone())
1683 .fill(args.iter().map(|t| t.ty.value.clone()))
1684 .build();
1685 let predicate = ProjectionPredicate {
1686 projection_ty: ProjectionTy { associated_ty: alias.id, parameters: subst },
1687 ty: Ty::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)),
1688 };
1689 let goal = Canonical {
1690 value: InEnvironment::new(
1691 self.ty.environment.clone(),
1692 Obligation::Projection(predicate),
1693 ),
1694 kinds: Arc::new([TyVariableKind::General]),
1695 };
1696
1697 match db.trait_solve(self.krate, goal)? {
1698 Solution::Unique(SolutionVariables(subst)) => {
1699 subst.value.first().map(|ty| self.derived(ty.clone()))
1700 }
1701 Solution::Ambig(_) => None,
1702 }
1703 }
1704
1705 pub fn is_copy(&self, db: &dyn HirDatabase) -> bool {
1706 let lang_item = db.lang_item(self.krate, SmolStr::new("copy"));
1707 let copy_trait = match lang_item {
1708 Some(LangItemTarget::TraitId(it)) => it,
1709 _ => return false,
1710 };
1711 self.impls_trait(db, copy_trait.into(), &[])
1712 }
1713
1714 pub fn as_callable(&self, db: &dyn HirDatabase) -> Option<Callable> {
1715 let def = match self.ty.value {
1716 Ty::FnDef(def, _) => Some(def),
1717 _ => None,
1718 };
1719
1720 let sig = self.ty.value.callable_sig(db)?;
1721 Some(Callable { ty: self.clone(), sig, def, is_bound_method: false })
1722 }
1723
1724 pub fn is_closure(&self) -> bool {
1725 matches!(&self.ty.value, Ty::Closure { .. })
1726 }
1727
1728 pub fn is_fn(&self) -> bool {
1729 matches!(&self.ty.value, Ty::FnDef(..) | Ty::Function { .. })
1730 }
1731
1732 pub fn is_packed(&self, db: &dyn HirDatabase) -> bool {
1733 let adt_id = match self.ty.value {
1734 Ty::Adt(hir_ty::AdtId(adt_id), ..) => adt_id,
1735 _ => return false,
1736 };
1737
1738 let adt = adt_id.into();
1739 match adt {
1740 Adt::Struct(s) => matches!(s.repr(db), Some(ReprKind::Packed)),
1741 _ => false,
1742 }
1743 }
1744
1745 pub fn is_raw_ptr(&self) -> bool {
1746 matches!(&self.ty.value, Ty::Raw(..))
1747 }
1748
1749 pub fn contains_unknown(&self) -> bool {
1750 return go(&self.ty.value);
1751
1752 fn go(ty: &Ty) -> bool {
1753 match ty {
1754 Ty::Unknown => true,
1755 _ => ty.substs().map_or(false, |substs| substs.iter().any(go)),
1756 }
1757 }
1758 }
1759
1760 pub fn fields(&self, db: &dyn HirDatabase) -> Vec<(Field, Type)> {
1761 let (variant_id, substs) = match self.ty.value {
1762 Ty::Adt(hir_ty::AdtId(AdtId::StructId(s)), ref substs) => (s.into(), substs),
1763 Ty::Adt(hir_ty::AdtId(AdtId::UnionId(u)), ref substs) => (u.into(), substs),
1764 _ => return Vec::new(),
1765 };
1766
1767 db.field_types(variant_id)
1768 .iter()
1769 .map(|(local_id, ty)| {
1770 let def = Field { parent: variant_id.into(), id: local_id };
1771 let ty = ty.clone().subst(substs);
1772 (def, self.derived(ty))
1773 })
1774 .collect()
1775 }
1776
1777 pub fn tuple_fields(&self, _db: &dyn HirDatabase) -> Vec<Type> {
1778 if let Ty::Tuple(_, substs) = &self.ty.value {
1779 substs.iter().map(|ty| self.derived(ty.clone())).collect()
1780 } else {
1781 Vec::new()
1782 }
1783 }
1784
1785 pub fn autoderef<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Type> + 'a {
1786 // There should be no inference vars in types passed here
1787 // FIXME check that?
1788 let canonical = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1789 let environment = self.ty.environment.clone();
1790 let ty = InEnvironment { value: canonical, environment };
1791 autoderef(db, Some(self.krate), ty)
1792 .map(|canonical| canonical.value)
1793 .map(move |ty| self.derived(ty))
1794 }
1795
1796 // This would be nicer if it just returned an iterator, but that runs into
1797 // lifetime problems, because we need to borrow temp `CrateImplDefs`.
1798 pub fn iterate_assoc_items<T>(
1799 self,
1800 db: &dyn HirDatabase,
1801 krate: Crate,
1802 mut callback: impl FnMut(AssocItem) -> Option<T>,
1803 ) -> Option<T> {
1804 for krate in self.ty.value.def_crates(db, krate.id)? {
1805 let impls = db.inherent_impls_in_crate(krate);
1806
1807 for impl_def in impls.for_self_ty(&self.ty.value) {
1808 for &item in db.impl_data(*impl_def).items.iter() {
1809 if let Some(result) = callback(item.into()) {
1810 return Some(result);
1811 }
1812 }
1813 }
1814 }
1815 None
1816 }
1817
1818 pub fn type_parameters(&self) -> impl Iterator<Item = Type> + '_ {
1819 self.ty
1820 .value
1821 .strip_references()
1822 .substs()
1823 .into_iter()
1824 .flat_map(|substs| substs.iter())
1825 .map(move |ty| self.derived(ty.clone()))
1826 }
1827
1828 pub fn iterate_method_candidates<T>(
1829 &self,
1830 db: &dyn HirDatabase,
1831 krate: Crate,
1832 traits_in_scope: &FxHashSet<TraitId>,
1833 name: Option<&Name>,
1834 mut callback: impl FnMut(&Ty, Function) -> Option<T>,
1835 ) -> Option<T> {
1836 // There should be no inference vars in types passed here
1837 // FIXME check that?
1838 // FIXME replace Unknown by bound vars here
1839 let canonical = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1840
1841 let env = self.ty.environment.clone();
1842 let krate = krate.id;
1843
1844 method_resolution::iterate_method_candidates(
1845 &canonical,
1846 db,
1847 env,
1848 krate,
1849 traits_in_scope,
1850 name,
1851 method_resolution::LookupMode::MethodCall,
1852 |ty, it| match it {
1853 AssocItemId::FunctionId(f) => callback(ty, f.into()),
1854 _ => None,
1855 },
1856 )
1857 }
1858
1859 pub fn iterate_path_candidates<T>(
1860 &self,
1861 db: &dyn HirDatabase,
1862 krate: Crate,
1863 traits_in_scope: &FxHashSet<TraitId>,
1864 name: Option<&Name>,
1865 mut callback: impl FnMut(&Ty, AssocItem) -> Option<T>,
1866 ) -> Option<T> {
1867 // There should be no inference vars in types passed here
1868 // FIXME check that?
1869 // FIXME replace Unknown by bound vars here
1870 let canonical = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1871
1872 let env = self.ty.environment.clone();
1873 let krate = krate.id;
1874
1875 method_resolution::iterate_method_candidates(
1876 &canonical,
1877 db,
1878 env,
1879 krate,
1880 traits_in_scope,
1881 name,
1882 method_resolution::LookupMode::Path,
1883 |ty, it| callback(ty, it.into()),
1884 )
1885 }
1886
1887 pub fn as_adt(&self) -> Option<Adt> {
1888 let (adt, _subst) = self.ty.value.as_adt()?;
1889 Some(adt.into())
1890 }
1891
1892 pub fn as_dyn_trait(&self) -> Option<Trait> {
1893 self.ty.value.dyn_trait().map(Into::into)
1894 }
1895
1896 pub fn as_impl_traits(&self, db: &dyn HirDatabase) -> Option<Vec<Trait>> {
1897 self.ty.value.impl_trait_bounds(db).map(|it| {
1898 it.into_iter()
1899 .filter_map(|pred| match pred {
1900 hir_ty::GenericPredicate::Implemented(trait_ref) => {
1901 Some(Trait::from(trait_ref.trait_))
1902 }
1903 _ => None,
1904 })
1905 .collect()
1906 })
1907 }
1908
1909 pub fn as_associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<Trait> {
1910 self.ty.value.associated_type_parent_trait(db).map(Into::into)
1911 }
1912
1913 // FIXME: provide required accessors such that it becomes implementable from outside.
1914 pub fn is_equal_for_find_impls(&self, other: &Type) -> bool {
1915 let rref = other.remove_ref();
1916 self.ty.value.equals_ctor(rref.as_ref().map_or(&other.ty.value, |it| &it.ty.value))
1917 }
1918
1919 fn derived(&self, ty: Ty) -> Type {
1920 Type {
1921 krate: self.krate,
1922 ty: InEnvironment { value: ty, environment: self.ty.environment.clone() },
1923 }
1924 }
1925
1926 pub fn walk(&self, db: &dyn HirDatabase, mut cb: impl FnMut(Type)) {
1927 // TypeWalk::walk for a Ty at first visits parameters and only after that the Ty itself.
1928 // We need a different order here.
1929
1930 fn walk_substs(
1931 db: &dyn HirDatabase,
1932 type_: &Type,
1933 substs: &Substs,
1934 cb: &mut impl FnMut(Type),
1935 ) {
1936 for ty in substs.iter() {
1937 walk_type(db, &type_.derived(ty.clone()), cb);
1938 }
1939 }
1940
1941 fn walk_bounds(
1942 db: &dyn HirDatabase,
1943 type_: &Type,
1944 bounds: &[GenericPredicate],
1945 cb: &mut impl FnMut(Type),
1946 ) {
1947 for pred in bounds {
1948 match pred {
1949 GenericPredicate::Implemented(trait_ref) => {
1950 cb(type_.clone());
1951 walk_substs(db, type_, &trait_ref.substs, cb);
1952 }
1953 _ => (),
1954 }
1955 }
1956 }
1957
1958 fn walk_type(db: &dyn HirDatabase, type_: &Type, cb: &mut impl FnMut(Type)) {
1959 let ty = type_.ty.value.strip_references();
1960 match ty {
1961 Ty::Adt(..) => {
1962 cb(type_.derived(ty.clone()));
1963 }
1964 Ty::AssociatedType(..) => {
1965 if let Some(_) = ty.associated_type_parent_trait(db) {
1966 cb(type_.derived(ty.clone()));
1967 }
1968 }
1969 Ty::OpaqueType(..) => {
1970 if let Some(bounds) = ty.impl_trait_bounds(db) {
1971 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
1972 }
1973 }
1974 Ty::Alias(AliasTy::Opaque(opaque_ty)) => {
1975 if let Some(bounds) = ty.impl_trait_bounds(db) {
1976 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
1977 }
1978
1979 walk_substs(db, type_, &opaque_ty.parameters, cb);
1980 }
1981 Ty::Placeholder(_) => {
1982 if let Some(bounds) = ty.impl_trait_bounds(db) {
1983 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
1984 }
1985 }
1986 Ty::Dyn(bounds) => {
1987 walk_bounds(db, &type_.derived(ty.clone()), bounds.as_ref(), cb);
1988 }
1989
1990 _ => {}
1991 }
1992 if let Some(substs) = ty.substs() {
1993 walk_substs(db, type_, &substs, cb);
1994 }
1995 }
1996
1997 walk_type(db, self, &mut cb);
1998 }
1999}
2000
2001impl HirDisplay for Type {
2002 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
2003 self.ty.value.hir_fmt(f)
2004 }
2005}
2006
2007// FIXME: closures
2008#[derive(Debug)]
2009pub struct Callable {
2010 ty: Type,
2011 sig: CallableSig,
2012 def: Option<CallableDefId>,
2013 pub(crate) is_bound_method: bool,
2014}
2015
2016pub enum CallableKind {
2017 Function(Function),
2018 TupleStruct(Struct),
2019 TupleEnumVariant(Variant),
2020 Closure,
2021}
2022
2023impl Callable {
2024 pub fn kind(&self) -> CallableKind {
2025 match self.def {
2026 Some(CallableDefId::FunctionId(it)) => CallableKind::Function(it.into()),
2027 Some(CallableDefId::StructId(it)) => CallableKind::TupleStruct(it.into()),
2028 Some(CallableDefId::EnumVariantId(it)) => CallableKind::TupleEnumVariant(it.into()),
2029 None => CallableKind::Closure,
2030 }
2031 }
2032 pub fn receiver_param(&self, db: &dyn HirDatabase) -> Option<ast::SelfParam> {
2033 let func = match self.def {
2034 Some(CallableDefId::FunctionId(it)) if self.is_bound_method => it,
2035 _ => return None,
2036 };
2037 let src = func.lookup(db.upcast()).source(db.upcast());
2038 let param_list = src.value.param_list()?;
2039 param_list.self_param()
2040 }
2041 pub fn n_params(&self) -> usize {
2042 self.sig.params().len() - if self.is_bound_method { 1 } else { 0 }
2043 }
2044 pub fn params(
2045 &self,
2046 db: &dyn HirDatabase,
2047 ) -> Vec<(Option<Either<ast::SelfParam, ast::Pat>>, Type)> {
2048 let types = self
2049 .sig
2050 .params()
2051 .iter()
2052 .skip(if self.is_bound_method { 1 } else { 0 })
2053 .map(|ty| self.ty.derived(ty.clone()));
2054 let patterns = match self.def {
2055 Some(CallableDefId::FunctionId(func)) => {
2056 let src = func.lookup(db.upcast()).source(db.upcast());
2057 src.value.param_list().map(|param_list| {
2058 param_list
2059 .self_param()
2060 .map(|it| Some(Either::Left(it)))
2061 .filter(|_| !self.is_bound_method)
2062 .into_iter()
2063 .chain(param_list.params().map(|it| it.pat().map(Either::Right)))
2064 })
2065 }
2066 _ => None,
2067 };
2068 patterns.into_iter().flatten().chain(iter::repeat(None)).zip(types).collect()
2069 }
2070 pub fn return_type(&self) -> Type {
2071 self.ty.derived(self.sig.ret().clone())
2072 }
2073}
2074
2075/// For IDE only
2076#[derive(Debug, PartialEq, Eq, Hash)]
2077pub enum ScopeDef {
2078 ModuleDef(ModuleDef),
2079 MacroDef(MacroDef),
2080 GenericParam(GenericParam),
2081 ImplSelfType(Impl),
2082 AdtSelfType(Adt),
2083 Local(Local),
2084 Unknown,
2085}
2086
2087impl ScopeDef {
2088 pub fn all_items(def: PerNs) -> ArrayVec<[Self; 3]> {
2089 let mut items = ArrayVec::new();
2090
2091 match (def.take_types(), def.take_values()) {
2092 (Some(m1), None) => items.push(ScopeDef::ModuleDef(m1.into())),
2093 (None, Some(m2)) => items.push(ScopeDef::ModuleDef(m2.into())),
2094 (Some(m1), Some(m2)) => {
2095 // Some items, like unit structs and enum variants, are
2096 // returned as both a type and a value. Here we want
2097 // to de-duplicate them.
2098 if m1 != m2 {
2099 items.push(ScopeDef::ModuleDef(m1.into()));
2100 items.push(ScopeDef::ModuleDef(m2.into()));
2101 } else {
2102 items.push(ScopeDef::ModuleDef(m1.into()));
2103 }
2104 }
2105 (None, None) => {}
2106 };
2107
2108 if let Some(macro_def_id) = def.take_macros() {
2109 items.push(ScopeDef::MacroDef(macro_def_id.into()));
2110 }
2111
2112 if items.is_empty() {
2113 items.push(ScopeDef::Unknown);
2114 }
2115
2116 items
2117 }
2118}
2119
2120impl From<ItemInNs> for ScopeDef {
2121 fn from(item: ItemInNs) -> Self {
2122 match item {
2123 ItemInNs::Types(id) => ScopeDef::ModuleDef(id.into()),
2124 ItemInNs::Values(id) => ScopeDef::ModuleDef(id.into()),
2125 ItemInNs::Macros(id) => ScopeDef::MacroDef(id.into()),
2126 }
2127 }
2128}
2129
2130pub trait HasVisibility {
2131 fn visibility(&self, db: &dyn HirDatabase) -> Visibility;
2132 fn is_visible_from(&self, db: &dyn HirDatabase, module: Module) -> bool {
2133 let vis = self.visibility(db);
2134 vis.is_visible_from(db.upcast(), module.id)
2135 }
2136}
diff --git a/crates/hir/src/semantics.rs b/crates/hir/src/semantics.rs
index 59292d5a2..945638cc5 100644
--- a/crates/hir/src/semantics.rs
+++ b/crates/hir/src/semantics.rs
@@ -16,17 +16,15 @@ use rustc_hash::{FxHashMap, FxHashSet};
16use syntax::{ 16use syntax::{
17 algo::find_node_at_offset, 17 algo::find_node_at_offset,
18 ast::{self, GenericParamsOwner, LoopBodyOwner}, 18 ast::{self, GenericParamsOwner, LoopBodyOwner},
19 match_ast, AstNode, SyntaxNode, SyntaxToken, TextSize, 19 match_ast, AstNode, SyntaxNode, SyntaxNodePtr, SyntaxToken, TextSize,
20}; 20};
21 21
22use crate::{ 22use crate::{
23 code_model::Access,
24 db::HirDatabase, 23 db::HirDatabase,
25 diagnostics::Diagnostic,
26 semantics::source_to_def::{ChildContainer, SourceToDefCache, SourceToDefCtx}, 24 semantics::source_to_def::{ChildContainer, SourceToDefCache, SourceToDefCtx},
27 source_analyzer::{resolve_hir_path, SourceAnalyzer}, 25 source_analyzer::{resolve_hir_path, SourceAnalyzer},
28 AssocItem, Callable, ConstParam, Crate, Field, Function, HirFileId, Impl, InFile, Label, 26 Access, AssocItem, Callable, ConstParam, Crate, Field, Function, HirFileId, Impl, InFile,
29 LifetimeParam, Local, MacroDef, Module, ModuleDef, Name, Path, ScopeDef, Trait, Type, 27 Label, LifetimeParam, Local, MacroDef, Module, ModuleDef, Name, Path, ScopeDef, Trait, Type,
30 TypeAlias, TypeParam, VariantDef, 28 TypeAlias, TypeParam, VariantDef,
31}; 29};
32 30
@@ -141,7 +139,7 @@ impl<'db, DB: HirDatabase> Semantics<'db, DB> {
141 self.imp.original_range(node) 139 self.imp.original_range(node)
142 } 140 }
143 141
144 pub fn diagnostics_display_range(&self, diagnostics: &dyn Diagnostic) -> FileRange { 142 pub fn diagnostics_display_range(&self, diagnostics: InFile<SyntaxNodePtr>) -> FileRange {
145 self.imp.diagnostics_display_range(diagnostics) 143 self.imp.diagnostics_display_range(diagnostics)
146 } 144 }
147 145
@@ -385,8 +383,7 @@ impl<'db> SemanticsImpl<'db> {
385 node.as_ref().original_file_range(self.db.upcast()) 383 node.as_ref().original_file_range(self.db.upcast())
386 } 384 }
387 385
388 fn diagnostics_display_range(&self, diagnostics: &dyn Diagnostic) -> FileRange { 386 fn diagnostics_display_range(&self, src: InFile<SyntaxNodePtr>) -> FileRange {
389 let src = diagnostics.display_source();
390 let root = self.db.parse_or_expand(src.file_id).unwrap(); 387 let root = self.db.parse_or_expand(src.file_id).unwrap();
391 let node = src.value.to_node(&root); 388 let node = src.value.to_node(&root);
392 self.cache(root, src.file_id); 389 self.cache(root, src.file_id);
diff --git a/crates/hir/src/source_analyzer.rs b/crates/hir/src/source_analyzer.rs
index dc21f6051..d546512cb 100644
--- a/crates/hir/src/source_analyzer.rs
+++ b/crates/hir/src/source_analyzer.rs
@@ -20,7 +20,7 @@ use hir_def::{
20use hir_expand::{hygiene::Hygiene, name::AsName, HirFileId, InFile}; 20use hir_expand::{hygiene::Hygiene, name::AsName, HirFileId, InFile};
21use hir_ty::{ 21use hir_ty::{
22 diagnostics::{record_literal_missing_fields, record_pattern_missing_fields}, 22 diagnostics::{record_literal_missing_fields, record_pattern_missing_fields},
23 InferenceResult, Substs, Ty, 23 InferenceResult, Substs,
24}; 24};
25use syntax::{ 25use syntax::{
26 ast::{self, AstNode}, 26 ast::{self, AstNode},
@@ -28,9 +28,8 @@ use syntax::{
28}; 28};
29 29
30use crate::{ 30use crate::{
31 code_model::BuiltinType, db::HirDatabase, semantics::PathResolution, Adt, Const, Field, 31 db::HirDatabase, semantics::PathResolution, Adt, BuiltinType, Const, Field, Function, Local,
32 Function, Local, MacroDef, ModuleDef, Static, Struct, Trait, Type, TypeAlias, TypeParam, 32 MacroDef, ModuleDef, Static, Struct, Trait, Type, TypeAlias, TypeParam, Variant,
33 Variant,
34}; 33};
35use base_db::CrateId; 34use base_db::CrateId;
36 35
@@ -299,14 +298,11 @@ impl SourceAnalyzer {
299 let infer = self.infer.as_ref()?; 298 let infer = self.infer.as_ref()?;
300 299
301 let expr_id = self.expr_id(db, &literal.clone().into())?; 300 let expr_id = self.expr_id(db, &literal.clone().into())?;
302 let substs = match &infer.type_of_expr[expr_id] { 301 let substs = infer.type_of_expr[expr_id].substs()?;
303 Ty::Apply(a_ty) => &a_ty.parameters,
304 _ => return None,
305 };
306 302
307 let (variant, missing_fields, _exhaustive) = 303 let (variant, missing_fields, _exhaustive) =
308 record_literal_missing_fields(db, infer, expr_id, &body[expr_id])?; 304 record_literal_missing_fields(db, infer, expr_id, &body[expr_id])?;
309 let res = self.missing_fields(db, krate, substs, variant, missing_fields); 305 let res = self.missing_fields(db, krate, &substs, variant, missing_fields);
310 Some(res) 306 Some(res)
311 } 307 }
312 308
@@ -320,14 +316,11 @@ impl SourceAnalyzer {
320 let infer = self.infer.as_ref()?; 316 let infer = self.infer.as_ref()?;
321 317
322 let pat_id = self.pat_id(&pattern.clone().into())?; 318 let pat_id = self.pat_id(&pattern.clone().into())?;
323 let substs = match &infer.type_of_pat[pat_id] { 319 let substs = infer.type_of_pat[pat_id].substs()?;
324 Ty::Apply(a_ty) => &a_ty.parameters,
325 _ => return None,
326 };
327 320
328 let (variant, missing_fields, _exhaustive) = 321 let (variant, missing_fields, _exhaustive) =
329 record_pattern_missing_fields(db, infer, pat_id, &body[pat_id])?; 322 record_pattern_missing_fields(db, infer, pat_id, &body[pat_id])?;
330 let res = self.missing_fields(db, krate, substs, variant, missing_fields); 323 let res = self.missing_fields(db, krate, &substs, variant, missing_fields);
331 Some(res) 324 Some(res)
332 } 325 }
333 326