1 //! FIXME: write short doc here
2 use std::{iter, sync::Arc};
4 use arrayvec::ArrayVec;
5 use base_db::{CrateDisplayName, CrateId, Edition, FileId};
8 adt::{ReprKind, StructKind, VariantData},
9 builtin_type::BuiltinType,
10 expr::{BindingAnnotation, LabelId, Pat, PatId},
12 item_tree::ItemTreeNode,
13 lang_item::LangItemTarget,
16 resolver::{HasResolver, Resolver},
18 type_ref::{Mutability, TypeRef},
19 AdtId, AssocContainerId, AssocItemId, AssocItemLoc, AttrDefId, ConstId, ConstParamId,
20 DefWithBodyId, EnumId, FunctionId, GenericDefId, HasModule, ImplId, LifetimeParamId,
21 LocalEnumVariantId, LocalFieldId, LocalModuleId, Lookup, ModuleId, StaticId, StructId, TraitId,
22 TypeAliasId, TypeParamId, UnionId,
24 use hir_def::{find_path::PrefixKind, item_scope::ItemInNs, visibility::Visibility};
26 diagnostics::DiagnosticSink,
28 MacroDefId, MacroDefKind,
32 display::{write_bounds_like_dyn_trait, HirDisplayError, HirFormatter},
34 traits::{FnTrait, Solution, SolutionVariables},
35 ApplicationTy, BoundVar, CallableDefId, Canonical, DebruijnIndex, FnSig, GenericPredicate,
36 InEnvironment, Obligation, ProjectionPredicate, ProjectionTy, Substs, TraitEnvironment, Ty,
37 TyDefId, TyKind, TypeCtor,
39 use rustc_hash::FxHashSet;
40 use stdx::{format_to, impl_from};
42 ast::{self, AttrsOwner, NameOwner},
45 use tt::{Ident, Leaf, Literal, TokenTree};
48 db::{DefDatabase, HirDatabase},
49 has_source::HasSource,
50 HirDisplay, InFile, Name,
53 /// hir::Crate describes a single crate. It's the main interface with which
54 /// a crate's dependencies interact. Mostly, it should be just a proxy for the
56 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
58 pub(crate) id: CrateId,
62 pub struct CrateDependency {
68 pub fn dependencies(self, db: &dyn HirDatabase) -> Vec<CrateDependency> {
69 db.crate_graph()[self.id]
73 let krate = Crate { id: dep.crate_id };
74 let name = dep.as_name();
75 CrateDependency { krate, name }
80 // FIXME: add `transitive_reverse_dependencies`.
81 pub fn reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
82 let crate_graph = db.crate_graph();
86 crate_graph[krate].dependencies.iter().any(|it| it.crate_id == self.id)
88 .map(|id| Crate { id })
92 pub fn root_module(self, db: &dyn HirDatabase) -> Module {
93 let module_id = db.crate_def_map(self.id).root;
94 Module::new(self, module_id)
97 pub fn root_file(self, db: &dyn HirDatabase) -> FileId {
98 db.crate_graph()[self.id].root_file_id
101 pub fn edition(self, db: &dyn HirDatabase) -> Edition {
102 db.crate_graph()[self.id].edition
105 pub fn display_name(self, db: &dyn HirDatabase) -> Option<CrateDisplayName> {
106 db.crate_graph()[self.id].display_name.clone()
109 pub fn query_external_importables(
111 db: &dyn DefDatabase,
112 query: import_map::Query,
113 ) -> impl Iterator<Item = Either<ModuleDef, MacroDef>> {
114 import_map::search_dependencies(db, self.into(), query).into_iter().map(|item| match item {
115 ItemInNs::Types(mod_id) | ItemInNs::Values(mod_id) => Either::Left(mod_id.into()),
116 ItemInNs::Macros(mac_id) => Either::Right(mac_id.into()),
120 pub fn all(db: &dyn HirDatabase) -> Vec<Crate> {
121 db.crate_graph().iter().map(|id| Crate { id }).collect()
124 /// Try to get the root URL of the documentation of a crate.
125 pub fn get_html_root_url(self: &Crate, db: &dyn HirDatabase) -> Option<String> {
126 // Look for #![doc(html_root_url = "...")]
127 let attrs = db.attrs(AttrDefId::ModuleId(self.root_module(db).into()));
128 let doc_attr_q = attrs.by_key("doc");
130 if !doc_attr_q.exists() {
134 let doc_url = doc_attr_q.tt_values().map(|tt| {
135 let name = tt.token_trees.iter()
136 .skip_while(|tt| !matches!(tt, TokenTree::Leaf(Leaf::Ident(Ident{text: ref ident, ..})) if ident == "html_root_url"))
141 Some(TokenTree::Leaf(Leaf::Literal(Literal{ref text, ..}))) => Some(text),
144 }).flat_map(|t| t).next();
146 doc_url.map(|s| s.trim_matches('"').trim_end_matches('/').to_owned() + "/")
150 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
152 pub(crate) id: ModuleId,
155 /// The defs which can be visible in the module.
156 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
161 // Can't be directly declared, but can be imported.
166 TypeAlias(TypeAlias),
167 BuiltinType(BuiltinType),
172 Adt(Struct, Enum, Union),
182 impl From<VariantDef> for ModuleDef {
183 fn from(var: VariantDef) -> Self {
185 VariantDef::Struct(t) => Adt::from(t).into(),
186 VariantDef::Union(t) => Adt::from(t).into(),
187 VariantDef::Variant(t) => t.into(),
193 pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
195 ModuleDef::Module(it) => it.parent(db),
196 ModuleDef::Function(it) => Some(it.module(db)),
197 ModuleDef::Adt(it) => Some(it.module(db)),
198 ModuleDef::Variant(it) => Some(it.module(db)),
199 ModuleDef::Const(it) => Some(it.module(db)),
200 ModuleDef::Static(it) => Some(it.module(db)),
201 ModuleDef::Trait(it) => Some(it.module(db)),
202 ModuleDef::TypeAlias(it) => Some(it.module(db)),
203 ModuleDef::BuiltinType(_) => None,
207 pub fn canonical_path(&self, db: &dyn HirDatabase) -> Option<String> {
208 let mut segments = Vec::new();
209 segments.push(self.name(db)?.to_string());
210 for m in self.module(db)?.path_to_root(db) {
211 segments.extend(m.name(db).map(|it| it.to_string()))
214 Some(segments.join("::"))
217 pub fn definition_visibility(&self, db: &dyn HirDatabase) -> Option<Visibility> {
218 let module = match self {
219 ModuleDef::Module(it) => it.parent(db)?,
220 ModuleDef::Function(it) => return Some(it.visibility(db)),
221 ModuleDef::Adt(it) => it.module(db),
222 ModuleDef::Variant(it) => {
223 let parent = it.parent_enum(db);
224 let module = it.module(db);
225 return module.visibility_of(db, &ModuleDef::Adt(Adt::Enum(parent)));
227 ModuleDef::Const(it) => return Some(it.visibility(db)),
228 ModuleDef::Static(it) => it.module(db),
229 ModuleDef::Trait(it) => it.module(db),
230 ModuleDef::TypeAlias(it) => return Some(it.visibility(db)),
231 ModuleDef::BuiltinType(_) => return None,
234 module.visibility_of(db, self)
237 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
239 ModuleDef::Adt(it) => Some(it.name(db)),
240 ModuleDef::Trait(it) => Some(it.name(db)),
241 ModuleDef::Function(it) => Some(it.name(db)),
242 ModuleDef::Variant(it) => Some(it.name(db)),
243 ModuleDef::TypeAlias(it) => Some(it.name(db)),
244 ModuleDef::Module(it) => it.name(db),
245 ModuleDef::Const(it) => it.name(db),
246 ModuleDef::Static(it) => it.name(db),
248 ModuleDef::BuiltinType(it) => Some(it.as_name()),
252 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
253 let id = match self {
254 ModuleDef::Adt(it) => match it {
255 Adt::Struct(it) => it.id.into(),
256 Adt::Enum(it) => it.id.into(),
257 Adt::Union(it) => it.id.into(),
259 ModuleDef::Trait(it) => it.id.into(),
260 ModuleDef::Function(it) => it.id.into(),
261 ModuleDef::TypeAlias(it) => it.id.into(),
262 ModuleDef::Module(it) => it.id.into(),
263 ModuleDef::Const(it) => it.id.into(),
264 ModuleDef::Static(it) => it.id.into(),
268 let module = match self.module(db) {
273 hir_ty::diagnostics::validate_module_item(db, module.id.krate, id, sink)
278 pub(crate) fn new(krate: Crate, crate_module_id: LocalModuleId) -> Module {
279 Module { id: ModuleId { krate: krate.id, local_id: crate_module_id } }
282 /// Name of this module.
283 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
284 let def_map = db.crate_def_map(self.id.krate);
285 let parent = def_map[self.id.local_id].parent?;
286 def_map[parent].children.iter().find_map(|(name, module_id)| {
287 if *module_id == self.id.local_id {
295 /// Returns the crate this module is part of.
296 pub fn krate(self) -> Crate {
297 Crate { id: self.id.krate }
300 /// Topmost parent of this module. Every module has a `crate_root`, but some
301 /// might be missing `krate`. This can happen if a module's file is not included
302 /// in the module tree of any target in `Cargo.toml`.
303 pub fn crate_root(self, db: &dyn HirDatabase) -> Module {
304 let def_map = db.crate_def_map(self.id.krate);
305 self.with_module_id(def_map.root)
308 /// Iterates over all child modules.
309 pub fn children(self, db: &dyn HirDatabase) -> impl Iterator<Item = Module> {
310 let def_map = db.crate_def_map(self.id.krate);
311 let children = def_map[self.id.local_id]
314 .map(|(_, module_id)| self.with_module_id(*module_id))
315 .collect::<Vec<_>>();
319 /// Finds a parent module.
320 pub fn parent(self, db: &dyn HirDatabase) -> Option<Module> {
321 let def_map = db.crate_def_map(self.id.krate);
322 let parent_id = def_map[self.id.local_id].parent?;
323 Some(self.with_module_id(parent_id))
326 pub fn path_to_root(self, db: &dyn HirDatabase) -> Vec<Module> {
327 let mut res = vec![self];
329 while let Some(next) = curr.parent(db) {
336 /// Returns a `ModuleScope`: a set of items, visible in this module.
339 db: &dyn HirDatabase,
340 visible_from: Option<Module>,
341 ) -> Vec<(Name, ScopeDef)> {
342 db.crate_def_map(self.id.krate)[self.id.local_id]
345 .filter_map(|(name, def)| {
346 if let Some(m) = visible_from {
348 def.filter_visibility(|vis| vis.is_visible_from(db.upcast(), m.id));
349 if filtered.is_none() && !def.is_none() {
352 Some((name, filtered))
358 .flat_map(|(name, def)| {
359 ScopeDef::all_items(def).into_iter().map(move |item| (name.clone(), item))
364 pub fn visibility_of(self, db: &dyn HirDatabase, def: &ModuleDef) -> Option<Visibility> {
365 db.crate_def_map(self.id.krate)[self.id.local_id].scope.visibility_of(def.clone().into())
368 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
369 let _p = profile::span("Module::diagnostics").detail(|| {
370 format!("{:?}", self.name(db).map_or("<unknown>".into(), |name| name.to_string()))
372 let crate_def_map = db.crate_def_map(self.id.krate);
373 crate_def_map.add_diagnostics(db.upcast(), self.id.local_id, sink);
374 for decl in self.declarations(db) {
376 crate::ModuleDef::Function(f) => f.diagnostics(db, sink),
377 crate::ModuleDef::Module(m) => {
378 // Only add diagnostics from inline modules
379 if crate_def_map[m.id.local_id].origin.is_inline() {
380 m.diagnostics(db, sink)
384 decl.diagnostics(db, sink);
389 for impl_def in self.impl_defs(db) {
390 for item in impl_def.items(db) {
391 if let AssocItem::Function(f) = item {
392 f.diagnostics(db, sink);
398 pub fn declarations(self, db: &dyn HirDatabase) -> Vec<ModuleDef> {
399 let def_map = db.crate_def_map(self.id.krate);
400 def_map[self.id.local_id].scope.declarations().map(ModuleDef::from).collect()
403 pub fn impl_defs(self, db: &dyn HirDatabase) -> Vec<Impl> {
404 let def_map = db.crate_def_map(self.id.krate);
405 def_map[self.id.local_id].scope.impls().map(Impl::from).collect()
408 pub(crate) fn with_module_id(self, module_id: LocalModuleId) -> Module {
409 Module::new(self.krate(), module_id)
412 /// Finds a path that can be used to refer to the given item from within
413 /// this module, if possible.
414 pub fn find_use_path(self, db: &dyn DefDatabase, item: impl Into<ItemInNs>) -> Option<ModPath> {
415 hir_def::find_path::find_path(db, item.into(), self.into())
418 /// Finds a path that can be used to refer to the given item from within
419 /// this module, if possible. This is used for returning import paths for use-statements.
420 pub fn find_use_path_prefixed(
422 db: &dyn DefDatabase,
423 item: impl Into<ItemInNs>,
424 prefix_kind: PrefixKind,
425 ) -> Option<ModPath> {
426 hir_def::find_path::find_path_prefixed(db, item.into(), self.into(), prefix_kind)
430 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
432 pub(crate) parent: VariantDef,
433 pub(crate) id: LocalFieldId,
436 #[derive(Debug, PartialEq, Eq)]
437 pub enum FieldSource {
438 Named(ast::RecordField),
439 Pos(ast::TupleField),
443 pub fn name(&self, db: &dyn HirDatabase) -> Name {
444 self.parent.variant_data(db).fields()[self.id].name.clone()
447 /// Returns the type as in the signature of the struct (i.e., with
448 /// placeholder types for type parameters). This is good for showing
449 /// signature help, but not so good to actually get the type of the field
450 /// when you actually have a variable of the struct.
451 pub fn signature_ty(&self, db: &dyn HirDatabase) -> Type {
452 let var_id = self.parent.into();
453 let generic_def_id: GenericDefId = match self.parent {
454 VariantDef::Struct(it) => it.id.into(),
455 VariantDef::Union(it) => it.id.into(),
456 VariantDef::Variant(it) => it.parent.id.into(),
458 let substs = Substs::type_params(db, generic_def_id);
459 let ty = db.field_types(var_id)[self.id].clone().subst(&substs);
460 Type::new(db, self.parent.module(db).id.krate, var_id, ty)
463 pub fn parent_def(&self, _db: &dyn HirDatabase) -> VariantDef {
468 impl HasVisibility for Field {
469 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
470 let variant_data = self.parent.variant_data(db);
471 let visibility = &variant_data.fields()[self.id].visibility;
472 let parent_id: hir_def::VariantId = self.parent.into();
473 visibility.resolve(db.upcast(), &parent_id.resolver(db.upcast()))
477 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
479 pub(crate) id: StructId,
483 pub fn module(self, db: &dyn HirDatabase) -> Module {
484 Module { id: self.id.lookup(db.upcast()).container.module(db.upcast()) }
487 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
488 Some(self.module(db).krate())
491 pub fn name(self, db: &dyn HirDatabase) -> Name {
492 db.struct_data(self.id).name.clone()
495 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
496 db.struct_data(self.id)
500 .map(|(id, _)| Field { parent: self.into(), id })
504 pub fn ty(self, db: &dyn HirDatabase) -> Type {
505 Type::from_def(db, self.id.lookup(db.upcast()).container.module(db.upcast()).krate, self.id)
508 pub fn repr(self, db: &dyn HirDatabase) -> Option<ReprKind> {
509 db.struct_data(self.id).repr.clone()
512 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
513 self.variant_data(db).kind()
516 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
517 db.struct_data(self.id).variant_data.clone()
521 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
523 pub(crate) id: UnionId,
527 pub fn name(self, db: &dyn HirDatabase) -> Name {
528 db.union_data(self.id).name.clone()
531 pub fn module(self, db: &dyn HirDatabase) -> Module {
532 Module { id: self.id.lookup(db.upcast()).container.module(db.upcast()) }
535 pub fn ty(self, db: &dyn HirDatabase) -> Type {
536 Type::from_def(db, self.id.lookup(db.upcast()).container.module(db.upcast()).krate, self.id)
539 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
540 db.union_data(self.id)
544 .map(|(id, _)| Field { parent: self.into(), id })
548 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
549 db.union_data(self.id).variant_data.clone()
553 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
555 pub(crate) id: EnumId,
559 pub fn module(self, db: &dyn HirDatabase) -> Module {
560 Module { id: self.id.lookup(db.upcast()).container.module(db.upcast()) }
563 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
564 Some(self.module(db).krate())
567 pub fn name(self, db: &dyn HirDatabase) -> Name {
568 db.enum_data(self.id).name.clone()
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()
575 pub fn ty(self, db: &dyn HirDatabase) -> Type {
576 Type::from_def(db, self.id.lookup(db.upcast()).container.module(db.upcast()).krate, self.id)
580 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
582 pub(crate) parent: Enum,
583 pub(crate) id: LocalEnumVariantId,
587 pub fn module(self, db: &dyn HirDatabase) -> Module {
588 self.parent.module(db)
590 pub fn parent_enum(self, _db: &dyn HirDatabase) -> Enum {
594 pub fn name(self, db: &dyn HirDatabase) -> Name {
595 db.enum_data(self.parent.id).variants[self.id].name.clone()
598 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
599 self.variant_data(db)
602 .map(|(id, _)| Field { parent: self.into(), id })
606 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
607 self.variant_data(db).kind()
610 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
611 db.enum_data(self.parent.id).variants[self.id].variant_data.clone()
616 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
622 impl_from!(Struct, Union, Enum for Adt);
625 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
626 let subst = db.generic_defaults(self.into());
627 subst.iter().any(|ty| &ty.value == &Ty::Unknown)
630 /// Turns this ADT into a type. Any type parameters of the ADT will be
631 /// turned into unknown types, which is good for e.g. finding the most
632 /// general set of completions, but will not look very nice when printed.
633 pub fn ty(self, db: &dyn HirDatabase) -> Type {
634 let id = AdtId::from(self);
635 Type::from_def(db, id.module(db.upcast()).krate, id)
638 pub fn module(self, db: &dyn HirDatabase) -> Module {
640 Adt::Struct(s) => s.module(db),
641 Adt::Union(s) => s.module(db),
642 Adt::Enum(e) => e.module(db),
646 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
647 Some(self.module(db).krate())
650 pub fn name(self, db: &dyn HirDatabase) -> Name {
652 Adt::Struct(s) => s.name(db),
653 Adt::Union(u) => u.name(db),
654 Adt::Enum(e) => e.name(db),
659 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
660 pub enum VariantDef {
665 impl_from!(Struct, Union, Variant for VariantDef);
668 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
670 VariantDef::Struct(it) => it.fields(db),
671 VariantDef::Union(it) => it.fields(db),
672 VariantDef::Variant(it) => it.fields(db),
676 pub fn module(self, db: &dyn HirDatabase) -> Module {
678 VariantDef::Struct(it) => it.module(db),
679 VariantDef::Union(it) => it.module(db),
680 VariantDef::Variant(it) => it.module(db),
684 pub fn name(&self, db: &dyn HirDatabase) -> Name {
686 VariantDef::Struct(s) => s.name(db),
687 VariantDef::Union(u) => u.name(db),
688 VariantDef::Variant(e) => e.name(db),
692 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
694 VariantDef::Struct(it) => it.variant_data(db),
695 VariantDef::Union(it) => it.variant_data(db),
696 VariantDef::Variant(it) => it.variant_data(db),
701 /// The defs which have a body.
702 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
703 pub enum DefWithBody {
708 impl_from!(Function, Const, Static for DefWithBody);
711 pub fn module(self, db: &dyn HirDatabase) -> Module {
713 DefWithBody::Const(c) => c.module(db),
714 DefWithBody::Function(f) => f.module(db),
715 DefWithBody::Static(s) => s.module(db),
719 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
721 DefWithBody::Function(f) => Some(f.name(db)),
722 DefWithBody::Static(s) => s.name(db),
723 DefWithBody::Const(c) => c.name(db),
728 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
729 pub struct Function {
730 pub(crate) id: FunctionId,
734 pub fn module(self, db: &dyn HirDatabase) -> Module {
735 self.id.lookup(db.upcast()).module(db.upcast()).into()
738 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
739 Some(self.module(db).krate())
742 pub fn name(self, db: &dyn HirDatabase) -> Name {
743 db.function_data(self.id).name.clone()
746 /// Get this function's return type
747 pub fn ret_type(self, db: &dyn HirDatabase) -> Type {
748 let resolver = self.id.resolver(db.upcast());
749 let ret_type = &db.function_data(self.id).ret_type;
750 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
751 let environment = TraitEnvironment::lower(db, &resolver);
753 krate: self.id.lookup(db.upcast()).container.module(db.upcast()).krate,
754 ty: InEnvironment { value: Ty::from_hir_ext(&ctx, ret_type).0, environment },
758 pub fn self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
759 if !db.function_data(self.id).has_self_param {
762 Some(SelfParam { func: self.id })
765 pub fn assoc_fn_params(self, db: &dyn HirDatabase) -> Vec<Param> {
766 let resolver = self.id.resolver(db.upcast());
767 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
768 let environment = TraitEnvironment::lower(db, &resolver);
769 db.function_data(self.id)
774 krate: self.id.lookup(db.upcast()).container.module(db.upcast()).krate,
776 value: Ty::from_hir_ext(&ctx, type_ref).0,
777 environment: environment.clone(),
784 pub fn method_params(self, db: &dyn HirDatabase) -> Option<Vec<Param>> {
785 if self.self_param(db).is_none() {
788 let mut res = self.assoc_fn_params(db);
793 pub fn is_unsafe(self, db: &dyn HirDatabase) -> bool {
794 db.function_data(self.id).is_unsafe
797 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
798 let krate = self.module(db).id.krate;
799 hir_def::diagnostics::validate_body(db.upcast(), self.id.into(), sink);
800 hir_ty::diagnostics::validate_module_item(db, krate, self.id.into(), sink);
801 hir_ty::diagnostics::validate_body(db, self.id.into(), sink);
804 /// Whether this function declaration has a definition.
806 /// This is false in the case of required (not provided) trait methods.
807 pub fn has_body(self, db: &dyn HirDatabase) -> bool {
808 db.function_data(self.id).has_body
811 /// A textual representation of the HIR of this function for debugging purposes.
812 pub fn debug_hir(self, db: &dyn HirDatabase) -> String {
813 let body = db.body(self.id.into());
815 let mut result = String::new();
816 format_to!(result, "HIR expressions in the body of `{}`:\n", self.name(db));
817 for (id, expr) in body.exprs.iter() {
818 format_to!(result, "{:?}: {:?}\n", id, expr);
825 // Note: logically, this belongs to `hir_ty`, but we are not using it there yet.
832 impl From<Mutability> for Access {
833 fn from(mutability: Mutability) -> Access {
835 Mutability::Shared => Access::Shared,
836 Mutability::Mut => Access::Exclusive,
847 pub fn ty(&self) -> &Type {
852 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
853 pub struct SelfParam {
858 pub fn access(self, db: &dyn HirDatabase) -> Access {
859 let func_data = db.function_data(self.func);
863 .map(|param| match *param {
864 TypeRef::Reference(.., mutability) => mutability.into(),
867 .unwrap_or(Access::Owned)
871 impl HasVisibility for Function {
872 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
873 let function_data = db.function_data(self.id);
874 let visibility = &function_data.visibility;
875 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
879 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
881 pub(crate) id: ConstId,
885 pub fn module(self, db: &dyn HirDatabase) -> Module {
886 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
889 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
890 Some(self.module(db).krate())
893 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
894 db.const_data(self.id).name.clone()
898 impl HasVisibility for Const {
899 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
900 let function_data = db.const_data(self.id);
901 let visibility = &function_data.visibility;
902 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
906 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
908 pub(crate) id: StaticId,
912 pub fn module(self, db: &dyn HirDatabase) -> Module {
913 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
916 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
917 Some(self.module(db).krate())
920 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
921 db.static_data(self.id).name.clone()
924 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
925 db.static_data(self.id).mutable
929 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
931 pub(crate) id: TraitId,
935 pub fn module(self, db: &dyn HirDatabase) -> Module {
936 Module { id: self.id.lookup(db.upcast()).container.module(db.upcast()) }
939 pub fn name(self, db: &dyn HirDatabase) -> Name {
940 db.trait_data(self.id).name.clone()
943 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
944 db.trait_data(self.id).items.iter().map(|(_name, it)| (*it).into()).collect()
947 pub fn is_auto(self, db: &dyn HirDatabase) -> bool {
948 db.trait_data(self.id).auto
952 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
953 pub struct TypeAlias {
954 pub(crate) id: TypeAliasId,
958 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
959 let subst = db.generic_defaults(self.id.into());
960 subst.iter().any(|ty| &ty.value == &Ty::Unknown)
963 pub fn module(self, db: &dyn HirDatabase) -> Module {
964 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
967 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
968 Some(self.module(db).krate())
971 pub fn type_ref(self, db: &dyn HirDatabase) -> Option<TypeRef> {
972 db.type_alias_data(self.id).type_ref.clone()
975 pub fn ty(self, db: &dyn HirDatabase) -> Type {
976 Type::from_def(db, self.id.lookup(db.upcast()).module(db.upcast()).krate, self.id)
979 pub fn name(self, db: &dyn HirDatabase) -> Name {
980 db.type_alias_data(self.id).name.clone()
984 impl HasVisibility for TypeAlias {
985 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
986 let function_data = db.type_alias_data(self.id);
987 let visibility = &function_data.visibility;
988 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
992 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
993 pub struct MacroDef {
994 pub(crate) id: MacroDefId,
998 /// FIXME: right now, this just returns the root module of the crate that
999 /// defines this macro. The reasons for this is that macros are expanded
1000 /// early, in `hir_expand`, where modules simply do not exist yet.
1001 pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
1002 let krate = self.id.krate;
1003 let module_id = db.crate_def_map(krate).root;
1004 Some(Module::new(Crate { id: krate }, module_id))
1007 /// XXX: this parses the file
1008 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1009 self.source(db)?.value.name().map(|it| it.as_name())
1012 /// Indicate it is a proc-macro
1013 pub fn is_proc_macro(&self) -> bool {
1014 matches!(self.id.kind, MacroDefKind::ProcMacro(_))
1017 /// Indicate it is a derive macro
1018 pub fn is_derive_macro(&self) -> bool {
1019 matches!(self.id.kind, MacroDefKind::ProcMacro(_) | MacroDefKind::BuiltInDerive(_))
1023 /// Invariant: `inner.as_assoc_item(db).is_some()`
1024 /// We do not actively enforce this invariant.
1025 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1026 pub enum AssocItem {
1029 TypeAlias(TypeAlias),
1031 pub enum AssocItemContainer {
1035 pub trait AsAssocItem {
1036 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem>;
1039 impl AsAssocItem for Function {
1040 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1041 as_assoc_item(db, AssocItem::Function, self.id)
1044 impl AsAssocItem for Const {
1045 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1046 as_assoc_item(db, AssocItem::Const, self.id)
1049 impl AsAssocItem for TypeAlias {
1050 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1051 as_assoc_item(db, AssocItem::TypeAlias, self.id)
1054 impl AsAssocItem for ModuleDef {
1055 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1057 ModuleDef::Function(it) => it.as_assoc_item(db),
1058 ModuleDef::Const(it) => it.as_assoc_item(db),
1059 ModuleDef::TypeAlias(it) => it.as_assoc_item(db),
1064 fn as_assoc_item<ID, DEF, CTOR, AST>(db: &dyn HirDatabase, ctor: CTOR, id: ID) -> Option<AssocItem>
1066 ID: Lookup<Data = AssocItemLoc<AST>>,
1068 CTOR: FnOnce(DEF) -> AssocItem,
1071 match id.lookup(db.upcast()).container {
1072 AssocContainerId::TraitId(_) | AssocContainerId::ImplId(_) => Some(ctor(DEF::from(id))),
1073 AssocContainerId::ContainerId(_) => None,
1078 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1080 AssocItem::Function(it) => Some(it.name(db)),
1081 AssocItem::Const(it) => it.name(db),
1082 AssocItem::TypeAlias(it) => Some(it.name(db)),
1085 pub fn module(self, db: &dyn HirDatabase) -> Module {
1087 AssocItem::Function(f) => f.module(db),
1088 AssocItem::Const(c) => c.module(db),
1089 AssocItem::TypeAlias(t) => t.module(db),
1092 pub fn container(self, db: &dyn HirDatabase) -> AssocItemContainer {
1093 let container = match self {
1094 AssocItem::Function(it) => it.id.lookup(db.upcast()).container,
1095 AssocItem::Const(it) => it.id.lookup(db.upcast()).container,
1096 AssocItem::TypeAlias(it) => it.id.lookup(db.upcast()).container,
1099 AssocContainerId::TraitId(id) => AssocItemContainer::Trait(id.into()),
1100 AssocContainerId::ImplId(id) => AssocItemContainer::Impl(id.into()),
1101 AssocContainerId::ContainerId(_) => panic!("invalid AssocItem"),
1105 pub fn containing_trait(self, db: &dyn HirDatabase) -> Option<Trait> {
1106 match self.container(db) {
1107 AssocItemContainer::Trait(t) => Some(t),
1113 impl HasVisibility for AssocItem {
1114 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1116 AssocItem::Function(f) => f.visibility(db),
1117 AssocItem::Const(c) => c.visibility(db),
1118 AssocItem::TypeAlias(t) => t.visibility(db),
1123 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
1124 pub enum GenericDef {
1128 TypeAlias(TypeAlias),
1130 // enum variants cannot have generics themselves, but their parent enums
1131 // can, and this makes some code easier to write
1133 // consts can have type parameters from their parents (i.e. associated consts of traits)
1138 Adt(Struct, Enum, Union),
1148 pub fn params(self, db: &dyn HirDatabase) -> Vec<GenericParam> {
1149 let generics = db.generic_params(self.into());
1150 let ty_params = generics
1153 .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
1154 .map(GenericParam::TypeParam);
1155 let lt_params = generics
1158 .map(|(local_id, _)| LifetimeParam {
1159 id: LifetimeParamId { parent: self.into(), local_id },
1161 .map(GenericParam::LifetimeParam);
1162 let const_params = generics
1165 .map(|(local_id, _)| ConstParam { id: ConstParamId { parent: self.into(), local_id } })
1166 .map(GenericParam::ConstParam);
1167 ty_params.chain(lt_params).chain(const_params).collect()
1170 pub fn type_params(self, db: &dyn HirDatabase) -> Vec<TypeParam> {
1171 let generics = db.generic_params(self.into());
1175 .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
1180 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1182 pub(crate) parent: DefWithBodyId,
1183 pub(crate) pat_id: PatId,
1187 pub fn is_param(self, db: &dyn HirDatabase) -> bool {
1188 let src = self.source(db);
1190 Either::Left(bind_pat) => {
1191 bind_pat.syntax().ancestors().any(|it| ast::Param::can_cast(it.kind()))
1193 Either::Right(_self_param) => true,
1197 // FIXME: why is this an option? It shouldn't be?
1198 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1199 let body = db.body(self.parent.into());
1200 match &body[self.pat_id] {
1201 Pat::Bind { name, .. } => Some(name.clone()),
1206 pub fn is_self(self, db: &dyn HirDatabase) -> bool {
1207 self.name(db) == Some(name![self])
1210 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
1211 let body = db.body(self.parent.into());
1212 match &body[self.pat_id] {
1213 Pat::Bind { mode, .. } => match mode {
1214 BindingAnnotation::Mutable | BindingAnnotation::RefMut => true,
1221 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
1225 pub fn module(self, db: &dyn HirDatabase) -> Module {
1226 self.parent(db).module(db)
1229 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1230 let def = DefWithBodyId::from(self.parent);
1231 let infer = db.infer(def);
1232 let ty = infer[self.pat_id].clone();
1233 let krate = def.module(db.upcast()).krate;
1234 Type::new(db, krate, def, ty)
1237 pub fn source(self, db: &dyn HirDatabase) -> InFile<Either<ast::IdentPat, ast::SelfParam>> {
1238 let (_body, source_map) = db.body_with_source_map(self.parent.into());
1239 let src = source_map.pat_syntax(self.pat_id).unwrap(); // Hmm...
1240 let root = src.file_syntax(db.upcast());
1242 ast.map_left(|it| it.cast().unwrap().to_node(&root)).map_right(|it| it.to_node(&root))
1247 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1249 pub(crate) parent: DefWithBodyId,
1250 pub(crate) label_id: LabelId,
1254 pub fn module(self, db: &dyn HirDatabase) -> Module {
1255 self.parent(db).module(db)
1258 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
1262 pub fn name(self, db: &dyn HirDatabase) -> Name {
1263 let body = db.body(self.parent.into());
1264 body[self.label_id].name.clone()
1267 pub fn source(self, db: &dyn HirDatabase) -> InFile<ast::Label> {
1268 let (_body, source_map) = db.body_with_source_map(self.parent.into());
1269 let src = source_map.label_syntax(self.label_id);
1270 let root = src.file_syntax(db.upcast());
1271 src.map(|ast| ast.to_node(&root))
1275 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1276 pub enum GenericParam {
1277 TypeParam(TypeParam),
1278 LifetimeParam(LifetimeParam),
1279 ConstParam(ConstParam),
1281 impl_from!(TypeParam, LifetimeParam, ConstParam for GenericParam);
1284 pub fn module(self, db: &dyn HirDatabase) -> Module {
1286 GenericParam::TypeParam(it) => it.module(db),
1287 GenericParam::LifetimeParam(it) => it.module(db),
1288 GenericParam::ConstParam(it) => it.module(db),
1292 pub fn name(self, db: &dyn HirDatabase) -> Name {
1294 GenericParam::TypeParam(it) => it.name(db),
1295 GenericParam::LifetimeParam(it) => it.name(db),
1296 GenericParam::ConstParam(it) => it.name(db),
1301 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1302 pub struct TypeParam {
1303 pub(crate) id: TypeParamId,
1307 pub fn name(self, db: &dyn HirDatabase) -> Name {
1308 let params = db.generic_params(self.id.parent);
1309 params.types[self.id.local_id].name.clone().unwrap_or_else(Name::missing)
1312 pub fn module(self, db: &dyn HirDatabase) -> Module {
1313 self.id.parent.module(db.upcast()).into()
1316 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1317 let resolver = self.id.parent.resolver(db.upcast());
1318 let environment = TraitEnvironment::lower(db, &resolver);
1319 let ty = Ty::Placeholder(self.id);
1321 krate: self.id.parent.module(db.upcast()).krate,
1322 ty: InEnvironment { value: ty, environment },
1326 pub fn trait_bounds(self, db: &dyn HirDatabase) -> Vec<Trait> {
1327 db.generic_predicates_for_param(self.id)
1329 .filter_map(|pred| match &pred.value {
1330 hir_ty::GenericPredicate::Implemented(trait_ref) => {
1331 Some(Trait::from(trait_ref.trait_))
1338 pub fn default(self, db: &dyn HirDatabase) -> Option<Type> {
1339 let params = db.generic_defaults(self.id.parent);
1340 let local_idx = hir_ty::param_idx(db, self.id)?;
1341 let resolver = self.id.parent.resolver(db.upcast());
1342 let environment = TraitEnvironment::lower(db, &resolver);
1343 let ty = params.get(local_idx)?.clone();
1344 let subst = Substs::type_params(db, self.id.parent);
1345 let ty = ty.subst(&subst.prefix(local_idx));
1347 krate: self.id.parent.module(db.upcast()).krate,
1348 ty: InEnvironment { value: ty, environment },
1353 impl HirDisplay for TypeParam {
1354 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1355 write!(f, "{}", self.name(f.db))?;
1356 let bounds = f.db.generic_predicates_for_param(self.id);
1357 let substs = Substs::type_params(f.db, self.id.parent);
1358 let predicates = bounds.iter().cloned().map(|b| b.subst(&substs)).collect::<Vec<_>>();
1359 if !(predicates.is_empty() || f.omit_verbose_types()) {
1361 write_bounds_like_dyn_trait(&predicates, f)?;
1367 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1368 pub struct LifetimeParam {
1369 pub(crate) id: LifetimeParamId,
1372 impl LifetimeParam {
1373 pub fn name(self, db: &dyn HirDatabase) -> Name {
1374 let params = db.generic_params(self.id.parent);
1375 params.lifetimes[self.id.local_id].name.clone()
1378 pub fn module(self, db: &dyn HirDatabase) -> Module {
1379 self.id.parent.module(db.upcast()).into()
1382 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
1383 self.id.parent.into()
1387 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1388 pub struct ConstParam {
1389 pub(crate) id: ConstParamId,
1393 pub fn name(self, db: &dyn HirDatabase) -> Name {
1394 let params = db.generic_params(self.id.parent);
1395 params.consts[self.id.local_id].name.clone()
1398 pub fn module(self, db: &dyn HirDatabase) -> Module {
1399 self.id.parent.module(db.upcast()).into()
1402 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
1403 self.id.parent.into()
1406 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1407 let def = self.id.parent;
1408 let krate = def.module(db.upcast()).krate;
1409 Type::new(db, krate, def, db.const_param_ty(self.id))
1413 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1415 pub(crate) id: ImplId,
1419 pub fn all_in_crate(db: &dyn HirDatabase, krate: Crate) -> Vec<Impl> {
1420 let inherent = db.inherent_impls_in_crate(krate.id);
1421 let trait_ = db.trait_impls_in_crate(krate.id);
1423 inherent.all_impls().chain(trait_.all_impls()).map(Self::from).collect()
1425 pub fn for_trait(db: &dyn HirDatabase, krate: Crate, trait_: Trait) -> Vec<Impl> {
1426 let impls = db.trait_impls_in_crate(krate.id);
1427 impls.for_trait(trait_.id).map(Self::from).collect()
1430 // FIXME: the return type is wrong. This should be a hir version of
1431 // `TraitRef` (ie, resolved `TypeRef`).
1432 pub fn target_trait(self, db: &dyn HirDatabase) -> Option<TypeRef> {
1433 db.impl_data(self.id).target_trait.clone()
1436 pub fn target_ty(self, db: &dyn HirDatabase) -> Type {
1437 let impl_data = db.impl_data(self.id);
1438 let resolver = self.id.resolver(db.upcast());
1439 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1440 let environment = TraitEnvironment::lower(db, &resolver);
1441 let ty = Ty::from_hir(&ctx, &impl_data.target_type);
1443 krate: self.id.lookup(db.upcast()).container.module(db.upcast()).krate,
1444 ty: InEnvironment { value: ty, environment },
1448 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
1449 db.impl_data(self.id).items.iter().map(|it| (*it).into()).collect()
1452 pub fn is_negative(self, db: &dyn HirDatabase) -> bool {
1453 db.impl_data(self.id).is_negative
1456 pub fn module(self, db: &dyn HirDatabase) -> Module {
1457 self.id.lookup(db.upcast()).container.module(db.upcast()).into()
1460 pub fn krate(self, db: &dyn HirDatabase) -> Crate {
1461 Crate { id: self.module(db).id.krate }
1464 pub fn is_builtin_derive(self, db: &dyn HirDatabase) -> Option<InFile<ast::Attr>> {
1465 let src = self.source(db)?;
1466 let item = src.file_id.is_builtin_derive(db.upcast())?;
1467 let hygenic = hir_expand::hygiene::Hygiene::new(db.upcast(), item.file_id);
1469 // FIXME: handle `cfg_attr`
1474 let path = ModPath::from_src(it.path()?, &hygenic)?;
1475 if path.as_ident()?.to_string() == "derive" {
1483 Some(item.with_value(attr))
1487 #[derive(Clone, PartialEq, Eq, Debug)]
1490 ty: InEnvironment<Ty>,
1494 pub(crate) fn new_with_resolver(
1495 db: &dyn HirDatabase,
1496 resolver: &Resolver,
1499 let krate = resolver.krate()?;
1500 Some(Type::new_with_resolver_inner(db, krate, resolver, ty))
1502 pub(crate) fn new_with_resolver_inner(
1503 db: &dyn HirDatabase,
1505 resolver: &Resolver,
1508 let environment = TraitEnvironment::lower(db, &resolver);
1509 Type { krate, ty: InEnvironment { value: ty, environment } }
1512 fn new(db: &dyn HirDatabase, krate: CrateId, lexical_env: impl HasResolver, ty: Ty) -> Type {
1513 let resolver = lexical_env.resolver(db.upcast());
1514 let environment = TraitEnvironment::lower(db, &resolver);
1515 Type { krate, ty: InEnvironment { value: ty, environment } }
1519 db: &dyn HirDatabase,
1521 def: impl HasResolver + Into<TyDefId> + Into<GenericDefId>,
1523 let substs = Substs::build_for_def(db, def).fill_with_unknown().build();
1524 let ty = db.ty(def.into()).subst(&substs);
1525 Type::new(db, krate, def, ty)
1528 pub fn is_unit(&self) -> bool {
1531 Ty::Apply(ApplicationTy { ctor: TypeCtor::Tuple { cardinality: 0 }, .. })
1534 pub fn is_bool(&self) -> bool {
1535 matches!(self.ty.value, Ty::Apply(ApplicationTy { ctor: TypeCtor::Bool, .. }))
1538 pub fn is_mutable_reference(&self) -> bool {
1541 Ty::Apply(ApplicationTy { ctor: TypeCtor::Ref(Mutability::Mut), .. })
1545 pub fn remove_ref(&self) -> Option<Type> {
1546 if let Ty::Apply(ApplicationTy { ctor: TypeCtor::Ref(_), .. }) = self.ty.value {
1547 self.ty.value.substs().map(|substs| self.derived(substs[0].clone()))
1553 pub fn is_unknown(&self) -> bool {
1554 matches!(self.ty.value, Ty::Unknown)
1557 /// Checks that particular type `ty` implements `std::future::Future`.
1558 /// This function is used in `.await` syntax completion.
1559 pub fn impls_future(&self, db: &dyn HirDatabase) -> bool {
1560 // No special case for the type of async block, since Chalk can figure it out.
1562 let krate = self.krate;
1564 let std_future_trait =
1565 db.lang_item(krate, "future_trait".into()).and_then(|it| it.as_trait());
1566 let std_future_trait = match std_future_trait {
1568 None => return false,
1571 let canonical_ty = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1572 method_resolution::implements_trait(
1575 self.ty.environment.clone(),
1581 /// Checks that particular type `ty` implements `std::ops::FnOnce`.
1583 /// This function can be used to check if a particular type is callable, since FnOnce is a
1584 /// supertrait of Fn and FnMut, so all callable types implements at least FnOnce.
1585 pub fn impls_fnonce(&self, db: &dyn HirDatabase) -> bool {
1586 let krate = self.krate;
1588 let fnonce_trait = match FnTrait::FnOnce.get_id(db, krate) {
1590 None => return false,
1593 let canonical_ty = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1594 method_resolution::implements_trait_unique(
1597 self.ty.environment.clone(),
1603 pub fn impls_trait(&self, db: &dyn HirDatabase, trait_: Trait, args: &[Type]) -> bool {
1604 let trait_ref = hir_ty::TraitRef {
1606 substs: Substs::build_for_def(db, trait_.id)
1607 .push(self.ty.value.clone())
1608 .fill(args.iter().map(|t| t.ty.value.clone()))
1612 let goal = Canonical {
1613 value: hir_ty::InEnvironment::new(
1614 self.ty.environment.clone(),
1615 hir_ty::Obligation::Trait(trait_ref),
1617 kinds: Arc::new([]),
1620 db.trait_solve(self.krate, goal).is_some()
1623 pub fn normalize_trait_assoc_type(
1625 db: &dyn HirDatabase,
1630 let subst = Substs::build_for_def(db, trait_.id)
1631 .push(self.ty.value.clone())
1632 .fill(args.iter().map(|t| t.ty.value.clone()))
1634 let predicate = ProjectionPredicate {
1635 projection_ty: ProjectionTy { associated_ty: alias.id, parameters: subst },
1636 ty: Ty::Bound(BoundVar::new(DebruijnIndex::INNERMOST, 0)),
1638 let goal = Canonical {
1639 value: InEnvironment::new(
1640 self.ty.environment.clone(),
1641 Obligation::Projection(predicate),
1643 kinds: Arc::new([TyKind::General]),
1646 match db.trait_solve(self.krate, goal)? {
1647 Solution::Unique(SolutionVariables(subst)) => subst.value.first().cloned(),
1648 Solution::Ambig(_) => None,
1652 ty: InEnvironment { value: ty, environment: Arc::clone(&self.ty.environment) },
1656 pub fn is_copy(&self, db: &dyn HirDatabase) -> bool {
1657 let lang_item = db.lang_item(self.krate, SmolStr::new("copy"));
1658 let copy_trait = match lang_item {
1659 Some(LangItemTarget::TraitId(it)) => it,
1662 self.impls_trait(db, copy_trait.into(), &[])
1665 pub fn as_callable(&self, db: &dyn HirDatabase) -> Option<Callable> {
1666 let def = match self.ty.value {
1667 Ty::Apply(ApplicationTy { ctor: TypeCtor::FnDef(def), parameters: _ }) => Some(def),
1671 let sig = self.ty.value.callable_sig(db)?;
1672 Some(Callable { ty: self.clone(), sig, def, is_bound_method: false })
1675 pub fn is_closure(&self) -> bool {
1676 matches!(&self.ty.value, Ty::Apply(ApplicationTy { ctor: TypeCtor::Closure { .. }, .. }))
1679 pub fn is_fn(&self) -> bool {
1682 Ty::Apply(ApplicationTy { ctor: TypeCtor::FnDef(..), .. })
1683 | Ty::Apply(ApplicationTy { ctor: TypeCtor::FnPtr { .. }, .. })
1687 pub fn is_packed(&self, db: &dyn HirDatabase) -> bool {
1688 let adt_id = match self.ty.value {
1689 Ty::Apply(ApplicationTy { ctor: TypeCtor::Adt(adt_id), .. }) => adt_id,
1693 let adt = adt_id.into();
1695 Adt::Struct(s) => matches!(s.repr(db), Some(ReprKind::Packed)),
1700 pub fn is_raw_ptr(&self) -> bool {
1701 matches!(&self.ty.value, Ty::Apply(ApplicationTy { ctor: TypeCtor::RawPtr(..), .. }))
1704 pub fn contains_unknown(&self) -> bool {
1705 return go(&self.ty.value);
1707 fn go(ty: &Ty) -> bool {
1709 Ty::Unknown => true,
1710 Ty::Apply(a_ty) => a_ty.parameters.iter().any(go),
1716 pub fn fields(&self, db: &dyn HirDatabase) -> Vec<(Field, Type)> {
1717 if let Ty::Apply(a_ty) = &self.ty.value {
1718 let variant_id = match a_ty.ctor {
1719 TypeCtor::Adt(AdtId::StructId(s)) => s.into(),
1720 TypeCtor::Adt(AdtId::UnionId(u)) => u.into(),
1721 _ => return Vec::new(),
1725 .field_types(variant_id)
1727 .map(|(local_id, ty)| {
1728 let def = Field { parent: variant_id.into(), id: local_id };
1729 let ty = ty.clone().subst(&a_ty.parameters);
1730 (def, self.derived(ty))
1737 pub fn tuple_fields(&self, _db: &dyn HirDatabase) -> Vec<Type> {
1738 let mut res = Vec::new();
1739 if let Ty::Apply(a_ty) = &self.ty.value {
1740 if let TypeCtor::Tuple { .. } = a_ty.ctor {
1741 for ty in a_ty.parameters.iter() {
1742 let ty = ty.clone();
1743 res.push(self.derived(ty));
1750 pub fn autoderef<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Type> + 'a {
1751 // There should be no inference vars in types passed here
1752 // FIXME check that?
1753 let canonical = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1754 let environment = self.ty.environment.clone();
1755 let ty = InEnvironment { value: canonical, environment };
1756 autoderef(db, Some(self.krate), ty)
1757 .map(|canonical| canonical.value)
1758 .map(move |ty| self.derived(ty))
1761 // This would be nicer if it just returned an iterator, but that runs into
1762 // lifetime problems, because we need to borrow temp `CrateImplDefs`.
1763 pub fn iterate_assoc_items<T>(
1765 db: &dyn HirDatabase,
1767 mut callback: impl FnMut(AssocItem) -> Option<T>,
1769 for krate in self.ty.value.def_crates(db, krate.id)? {
1770 let impls = db.inherent_impls_in_crate(krate);
1772 for impl_def in impls.for_self_ty(&self.ty.value) {
1773 for &item in db.impl_data(*impl_def).items.iter() {
1774 if let Some(result) = callback(item.into()) {
1775 return Some(result);
1783 pub fn iterate_method_candidates<T>(
1785 db: &dyn HirDatabase,
1787 traits_in_scope: &FxHashSet<TraitId>,
1788 name: Option<&Name>,
1789 mut callback: impl FnMut(&Ty, Function) -> Option<T>,
1791 // There should be no inference vars in types passed here
1792 // FIXME check that?
1793 // FIXME replace Unknown by bound vars here
1794 let canonical = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1796 let env = self.ty.environment.clone();
1797 let krate = krate.id;
1799 method_resolution::iterate_method_candidates(
1806 method_resolution::LookupMode::MethodCall,
1808 AssocItemId::FunctionId(f) => callback(ty, f.into()),
1814 pub fn iterate_path_candidates<T>(
1816 db: &dyn HirDatabase,
1818 traits_in_scope: &FxHashSet<TraitId>,
1819 name: Option<&Name>,
1820 mut callback: impl FnMut(&Ty, AssocItem) -> Option<T>,
1822 // There should be no inference vars in types passed here
1823 // FIXME check that?
1824 // FIXME replace Unknown by bound vars here
1825 let canonical = Canonical { value: self.ty.value.clone(), kinds: Arc::new([]) };
1827 let env = self.ty.environment.clone();
1828 let krate = krate.id;
1830 method_resolution::iterate_method_candidates(
1837 method_resolution::LookupMode::Path,
1838 |ty, it| callback(ty, it.into()),
1842 pub fn as_adt(&self) -> Option<Adt> {
1843 let (adt, _subst) = self.ty.value.as_adt()?;
1847 pub fn as_dyn_trait(&self) -> Option<Trait> {
1848 self.ty.value.dyn_trait().map(Into::into)
1851 pub fn as_impl_traits(&self, db: &dyn HirDatabase) -> Option<Vec<Trait>> {
1852 self.ty.value.impl_trait_bounds(db).map(|it| {
1854 .filter_map(|pred| match pred {
1855 hir_ty::GenericPredicate::Implemented(trait_ref) => {
1856 Some(Trait::from(trait_ref.trait_))
1864 pub fn as_associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<Trait> {
1865 self.ty.value.associated_type_parent_trait(db).map(Into::into)
1868 // FIXME: provide required accessors such that it becomes implementable from outside.
1869 pub fn is_equal_for_find_impls(&self, other: &Type) -> bool {
1870 match (&self.ty.value, &other.ty.value) {
1871 (Ty::Apply(a_original_ty), Ty::Apply(ApplicationTy { ctor, parameters })) => match ctor
1873 TypeCtor::Ref(..) => match parameters.as_single() {
1874 Ty::Apply(a_ty) => a_original_ty.ctor == a_ty.ctor,
1877 _ => a_original_ty.ctor == *ctor,
1883 fn derived(&self, ty: Ty) -> Type {
1886 ty: InEnvironment { value: ty, environment: self.ty.environment.clone() },
1890 pub fn walk(&self, db: &dyn HirDatabase, mut cb: impl FnMut(Type)) {
1891 // TypeWalk::walk for a Ty at first visits parameters and only after that the Ty itself.
1892 // We need a different order here.
1895 db: &dyn HirDatabase,
1898 cb: &mut impl FnMut(Type),
1900 for ty in substs.iter() {
1901 walk_type(db, &type_.derived(ty.clone()), cb);
1906 db: &dyn HirDatabase,
1908 bounds: &[GenericPredicate],
1909 cb: &mut impl FnMut(Type),
1911 for pred in bounds {
1913 GenericPredicate::Implemented(trait_ref) => {
1915 walk_substs(db, type_, &trait_ref.substs, cb);
1922 fn walk_type(db: &dyn HirDatabase, type_: &Type, cb: &mut impl FnMut(Type)) {
1923 let ty = type_.ty.value.strip_references();
1925 Ty::Apply(ApplicationTy { ctor, parameters }) => {
1927 TypeCtor::Adt(_) => {
1928 cb(type_.derived(ty.clone()));
1930 TypeCtor::AssociatedType(_) => {
1931 if let Some(_) = ty.associated_type_parent_trait(db) {
1932 cb(type_.derived(ty.clone()));
1935 TypeCtor::OpaqueType(..) => {
1936 if let Some(bounds) = ty.impl_trait_bounds(db) {
1937 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
1943 // adt params, tuples, etc...
1944 walk_substs(db, type_, parameters, cb);
1946 Ty::Opaque(opaque_ty) => {
1947 if let Some(bounds) = ty.impl_trait_bounds(db) {
1948 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
1951 walk_substs(db, type_, &opaque_ty.parameters, cb);
1953 Ty::Placeholder(_) => {
1954 if let Some(bounds) = ty.impl_trait_bounds(db) {
1955 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
1958 Ty::Dyn(bounds) => {
1959 walk_bounds(db, &type_.derived(ty.clone()), bounds.as_ref(), cb);
1966 walk_type(db, self, &mut cb);
1970 impl HirDisplay for Type {
1971 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1972 self.ty.value.hir_fmt(f)
1978 pub struct Callable {
1981 def: Option<CallableDefId>,
1982 pub(crate) is_bound_method: bool,
1985 pub enum CallableKind {
1987 TupleStruct(Struct),
1988 TupleEnumVariant(Variant),
1993 pub fn kind(&self) -> CallableKind {
1995 Some(CallableDefId::FunctionId(it)) => CallableKind::Function(it.into()),
1996 Some(CallableDefId::StructId(it)) => CallableKind::TupleStruct(it.into()),
1997 Some(CallableDefId::EnumVariantId(it)) => CallableKind::TupleEnumVariant(it.into()),
1998 None => CallableKind::Closure,
2001 pub fn receiver_param(&self, db: &dyn HirDatabase) -> Option<ast::SelfParam> {
2002 let func = match self.def {
2003 Some(CallableDefId::FunctionId(it)) if self.is_bound_method => it,
2006 let src = func.lookup(db.upcast()).source(db.upcast());
2007 let param_list = src.value.param_list()?;
2008 param_list.self_param()
2010 pub fn n_params(&self) -> usize {
2011 self.sig.params().len() - if self.is_bound_method { 1 } else { 0 }
2015 db: &dyn HirDatabase,
2016 ) -> Vec<(Option<Either<ast::SelfParam, ast::Pat>>, Type)> {
2021 .skip(if self.is_bound_method { 1 } else { 0 })
2022 .map(|ty| self.ty.derived(ty.clone()));
2023 let patterns = match self.def {
2024 Some(CallableDefId::FunctionId(func)) => {
2025 let src = func.lookup(db.upcast()).source(db.upcast());
2026 src.value.param_list().map(|param_list| {
2029 .map(|it| Some(Either::Left(it)))
2030 .filter(|_| !self.is_bound_method)
2032 .chain(param_list.params().map(|it| it.pat().map(Either::Right)))
2037 patterns.into_iter().flatten().chain(iter::repeat(None)).zip(types).collect()
2039 pub fn return_type(&self) -> Type {
2040 self.ty.derived(self.sig.ret().clone())
2047 ModuleDef(ModuleDef),
2049 GenericParam(GenericParam),
2057 pub fn all_items(def: PerNs) -> ArrayVec<[Self; 3]> {
2058 let mut items = ArrayVec::new();
2060 match (def.take_types(), def.take_values()) {
2061 (Some(m1), None) => items.push(ScopeDef::ModuleDef(m1.into())),
2062 (None, Some(m2)) => items.push(ScopeDef::ModuleDef(m2.into())),
2063 (Some(m1), Some(m2)) => {
2064 // Some items, like unit structs and enum variants, are
2065 // returned as both a type and a value. Here we want
2066 // to de-duplicate them.
2068 items.push(ScopeDef::ModuleDef(m1.into()));
2069 items.push(ScopeDef::ModuleDef(m2.into()));
2071 items.push(ScopeDef::ModuleDef(m1.into()));
2077 if let Some(macro_def_id) = def.take_macros() {
2078 items.push(ScopeDef::MacroDef(macro_def_id.into()));
2081 if items.is_empty() {
2082 items.push(ScopeDef::Unknown);
2089 pub trait HasVisibility {
2090 fn visibility(&self, db: &dyn HirDatabase) -> Visibility;
2091 fn is_visible_from(&self, db: &dyn HirDatabase, module: Module) -> bool {
2092 let vis = self.visibility(db);
2093 vis.is_visible_from(db.upcast(), module.id)