1 //! HIR (previously known as descriptors) provides a high-level object oriented
2 //! access to Rust code.
4 //! The principal difference between HIR and syntax trees is that HIR is bound
5 //! to a particular crate instance. That is, it has cfg flags and features
6 //! applied. So, the relation between syntax and HIR is many-to-one.
8 //! HIR is the public API of the all of the compiler logic above syntax trees.
9 //! It is written in "OO" style. Each type is self contained (as in, it knows it's
10 //! parents and full context). It should be "clean code".
12 //! `hir_*` crates are the implementation of the compiler logic.
13 //! They are written in "ECS" style, with relatively little abstractions.
14 //! Many types are not self-contained, and explicitly use local indexes, arenas, etc.
16 //! `hir` is what insulates the "we don't know how to actually write an incremental compiler"
17 //! from the ide with completions, hovers, etc. It is a (soft, internal) boundary:
18 //! https://www.tedinski.com/2018/02/06/system-boundaries.html.
20 #![recursion_limit = "512"]
34 use std::{iter, sync::Arc};
36 use arrayvec::ArrayVec;
37 use base_db::{CrateDisplayName, CrateId, Edition, FileId};
40 adt::{ReprKind, VariantData},
41 expr::{BindingAnnotation, LabelId, Pat, PatId},
42 item_tree::ItemTreeNode,
43 lang_item::LangItemTarget,
45 resolver::{HasResolver, Resolver},
48 AdtId, AssocContainerId, AssocItemId, AssocItemLoc, AttrDefId, ConstId, ConstParamId,
49 DefWithBodyId, EnumId, FunctionId, GenericDefId, HasModule, ImplId, LifetimeParamId,
50 LocalEnumVariantId, LocalFieldId, Lookup, ModuleId, StaticId, StructId, TraitId, TypeAliasId,
53 use hir_expand::{diagnostics::DiagnosticSink, name::name, MacroDefKind};
58 method_resolution::{self, def_crates, TyFingerprint},
62 AliasEq, AliasTy, BoundVar, CallableDefId, CallableSig, Canonical, CanonicalVarKinds, Cast,
63 DebruijnIndex, InEnvironment, Interner, QuantifiedWhereClause, Scalar, Solution, Substitution,
64 TraitEnvironment, TraitRefExt, Ty, TyBuilder, TyDefId, TyExt, TyKind, TyVariableKind,
67 use itertools::Itertools;
68 use rustc_hash::FxHashSet;
69 use stdx::{format_to, impl_from};
71 ast::{self, AttrsOwner, NameOwner},
74 use tt::{Ident, Leaf, Literal, TokenTree};
76 use crate::db::{DefDatabase, HirDatabase};
79 attrs::{HasAttrs, Namespace},
80 has_source::HasSource,
81 semantics::{PathResolution, Semantics, SemanticsScope},
84 // Be careful with these re-exports.
86 // `hir` is the boundary between the compiler and the IDE. It should try hard to
87 // isolate the compiler from the ide, to allow the two to be refactored
88 // independently. Re-exporting something from the compiler is the sure way to
89 // breach the boundary.
91 // Generally, a refactoring which *removes* a name from this list is a good
94 cfg::{CfgAtom, CfgExpr, CfgOptions},
97 attr::{Attr, Attrs, AttrsWithOwner, Documentation},
98 body::scope::ExprScopes,
99 find_path::PrefixKind,
101 item_scope::ItemInNs,
102 nameres::ModuleSource,
103 path::{ModPath, PathKind},
104 type_ref::{Mutability, TypeRef},
105 visibility::Visibility,
109 ExpandResult, HirFileId, InFile, MacroCallId, MacroCallLoc, /* FIXME */ MacroDefId,
112 hir_ty::display::HirDisplay,
115 // These are negative re-exports: pub using these names is forbidden, they
116 // should remain private to hir internals.
120 hir_expand::{hygiene::Hygiene, name::AsName},
123 /// hir::Crate describes a single crate. It's the main interface with which
124 /// a crate's dependencies interact. Mostly, it should be just a proxy for the
126 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
128 pub(crate) id: CrateId,
132 pub struct CrateDependency {
138 pub fn dependencies(self, db: &dyn HirDatabase) -> Vec<CrateDependency> {
139 db.crate_graph()[self.id]
143 let krate = Crate { id: dep.crate_id };
144 let name = dep.as_name();
145 CrateDependency { krate, name }
150 pub fn reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
151 let crate_graph = db.crate_graph();
155 crate_graph[krate].dependencies.iter().any(|it| it.crate_id == self.id)
157 .map(|id| Crate { id })
161 pub fn transitive_reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
162 db.crate_graph().transitive_rev_deps(self.id).into_iter().map(|id| Crate { id }).collect()
165 pub fn root_module(self, db: &dyn HirDatabase) -> Module {
166 let def_map = db.crate_def_map(self.id);
167 Module { id: def_map.module_id(def_map.root()) }
170 pub fn root_file(self, db: &dyn HirDatabase) -> FileId {
171 db.crate_graph()[self.id].root_file_id
174 pub fn edition(self, db: &dyn HirDatabase) -> Edition {
175 db.crate_graph()[self.id].edition
178 pub fn display_name(self, db: &dyn HirDatabase) -> Option<CrateDisplayName> {
179 db.crate_graph()[self.id].display_name.clone()
182 pub fn query_external_importables(
184 db: &dyn DefDatabase,
185 query: import_map::Query,
186 ) -> impl Iterator<Item = Either<ModuleDef, MacroDef>> {
187 import_map::search_dependencies(db, self.into(), query).into_iter().map(|item| match item {
188 ItemInNs::Types(mod_id) | ItemInNs::Values(mod_id) => Either::Left(mod_id.into()),
189 ItemInNs::Macros(mac_id) => Either::Right(mac_id.into()),
193 pub fn all(db: &dyn HirDatabase) -> Vec<Crate> {
194 db.crate_graph().iter().map(|id| Crate { id }).collect()
197 /// Try to get the root URL of the documentation of a crate.
198 pub fn get_html_root_url(self: &Crate, db: &dyn HirDatabase) -> Option<String> {
199 // Look for #![doc(html_root_url = "...")]
200 let attrs = db.attrs(AttrDefId::ModuleId(self.root_module(db).into()));
201 let doc_attr_q = attrs.by_key("doc");
203 if !doc_attr_q.exists() {
207 let doc_url = doc_attr_q.tt_values().map(|tt| {
208 let name = tt.token_trees.iter()
209 .skip_while(|tt| !matches!(tt, TokenTree::Leaf(Leaf::Ident(Ident{text: ref ident, ..})) if ident == "html_root_url"))
214 Some(TokenTree::Leaf(Leaf::Literal(Literal{ref text, ..}))) => Some(text),
219 doc_url.map(|s| s.trim_matches('"').trim_end_matches('/').to_owned() + "/")
222 pub fn cfg(&self, db: &dyn HirDatabase) -> CfgOptions {
223 db.crate_graph()[self.id].cfg_options.clone()
227 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
229 pub(crate) id: ModuleId,
232 /// The defs which can be visible in the module.
233 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
238 // Can't be directly declared, but can be imported.
243 TypeAlias(TypeAlias),
244 BuiltinType(BuiltinType),
249 Adt(Struct, Enum, Union),
259 impl From<VariantDef> for ModuleDef {
260 fn from(var: VariantDef) -> Self {
262 VariantDef::Struct(t) => Adt::from(t).into(),
263 VariantDef::Union(t) => Adt::from(t).into(),
264 VariantDef::Variant(t) => t.into(),
270 pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
272 ModuleDef::Module(it) => it.parent(db),
273 ModuleDef::Function(it) => Some(it.module(db)),
274 ModuleDef::Adt(it) => Some(it.module(db)),
275 ModuleDef::Variant(it) => Some(it.module(db)),
276 ModuleDef::Const(it) => Some(it.module(db)),
277 ModuleDef::Static(it) => Some(it.module(db)),
278 ModuleDef::Trait(it) => Some(it.module(db)),
279 ModuleDef::TypeAlias(it) => Some(it.module(db)),
280 ModuleDef::BuiltinType(_) => None,
284 pub fn canonical_path(&self, db: &dyn HirDatabase) -> Option<String> {
285 let mut segments = vec![self.name(db)?.to_string()];
286 for m in self.module(db)?.path_to_root(db) {
287 segments.extend(m.name(db).map(|it| it.to_string()))
290 Some(segments.join("::"))
293 pub fn definition_visibility(&self, db: &dyn HirDatabase) -> Option<Visibility> {
294 let module = match self {
295 ModuleDef::Module(it) => it.parent(db)?,
296 ModuleDef::Function(it) => return Some(it.visibility(db)),
297 ModuleDef::Adt(it) => it.module(db),
298 ModuleDef::Variant(it) => {
299 let parent = it.parent_enum(db);
300 let module = it.module(db);
301 return module.visibility_of(db, &ModuleDef::Adt(Adt::Enum(parent)));
303 ModuleDef::Const(it) => return Some(it.visibility(db)),
304 ModuleDef::Static(it) => it.module(db),
305 ModuleDef::Trait(it) => it.module(db),
306 ModuleDef::TypeAlias(it) => return Some(it.visibility(db)),
307 ModuleDef::BuiltinType(_) => return None,
310 module.visibility_of(db, self)
313 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
315 ModuleDef::Adt(it) => Some(it.name(db)),
316 ModuleDef::Trait(it) => Some(it.name(db)),
317 ModuleDef::Function(it) => Some(it.name(db)),
318 ModuleDef::Variant(it) => Some(it.name(db)),
319 ModuleDef::TypeAlias(it) => Some(it.name(db)),
320 ModuleDef::Module(it) => it.name(db),
321 ModuleDef::Const(it) => it.name(db),
322 ModuleDef::Static(it) => it.name(db),
323 ModuleDef::BuiltinType(it) => Some(it.name()),
327 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
328 let id = match self {
329 ModuleDef::Adt(it) => match it {
330 Adt::Struct(it) => it.id.into(),
331 Adt::Enum(it) => it.id.into(),
332 Adt::Union(it) => it.id.into(),
334 ModuleDef::Trait(it) => it.id.into(),
335 ModuleDef::Function(it) => it.id.into(),
336 ModuleDef::TypeAlias(it) => it.id.into(),
337 ModuleDef::Module(it) => it.id.into(),
338 ModuleDef::Const(it) => it.id.into(),
339 ModuleDef::Static(it) => it.id.into(),
343 let module = match self.module(db) {
348 hir_ty::diagnostics::validate_module_item(db, module.id.krate(), id, sink)
353 /// Name of this module.
354 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
355 let def_map = self.id.def_map(db.upcast());
356 let parent = def_map[self.id.local_id].parent?;
357 def_map[parent].children.iter().find_map(|(name, module_id)| {
358 if *module_id == self.id.local_id {
366 /// Returns the crate this module is part of.
367 pub fn krate(self) -> Crate {
368 Crate { id: self.id.krate() }
371 /// Topmost parent of this module. Every module has a `crate_root`, but some
372 /// might be missing `krate`. This can happen if a module's file is not included
373 /// in the module tree of any target in `Cargo.toml`.
374 pub fn crate_root(self, db: &dyn HirDatabase) -> Module {
375 let def_map = db.crate_def_map(self.id.krate());
376 Module { id: def_map.module_id(def_map.root()) }
379 /// Iterates over all child modules.
380 pub fn children(self, db: &dyn HirDatabase) -> impl Iterator<Item = Module> {
381 let def_map = self.id.def_map(db.upcast());
382 let children = def_map[self.id.local_id]
385 .map(|(_, module_id)| Module { id: def_map.module_id(*module_id) })
386 .collect::<Vec<_>>();
390 /// Finds a parent module.
391 pub fn parent(self, db: &dyn HirDatabase) -> Option<Module> {
392 // FIXME: handle block expressions as modules (their parent is in a different DefMap)
393 let def_map = self.id.def_map(db.upcast());
394 let parent_id = def_map[self.id.local_id].parent?;
395 Some(Module { id: def_map.module_id(parent_id) })
398 pub fn path_to_root(self, db: &dyn HirDatabase) -> Vec<Module> {
399 let mut res = vec![self];
401 while let Some(next) = curr.parent(db) {
408 /// Returns a `ModuleScope`: a set of items, visible in this module.
411 db: &dyn HirDatabase,
412 visible_from: Option<Module>,
413 ) -> Vec<(Name, ScopeDef)> {
414 self.id.def_map(db.upcast())[self.id.local_id]
417 .filter_map(|(name, def)| {
418 if let Some(m) = visible_from {
420 def.filter_visibility(|vis| vis.is_visible_from(db.upcast(), m.id));
421 if filtered.is_none() && !def.is_none() {
424 Some((name, filtered))
430 .flat_map(|(name, def)| {
431 ScopeDef::all_items(def).into_iter().map(move |item| (name.clone(), item))
436 pub fn visibility_of(self, db: &dyn HirDatabase, def: &ModuleDef) -> Option<Visibility> {
437 self.id.def_map(db.upcast())[self.id.local_id].scope.visibility_of(def.clone().into())
440 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
441 let _p = profile::span("Module::diagnostics").detail(|| {
442 format!("{:?}", self.name(db).map_or("<unknown>".into(), |name| name.to_string()))
444 let def_map = self.id.def_map(db.upcast());
445 def_map.add_diagnostics(db.upcast(), self.id.local_id, sink);
446 for decl in self.declarations(db) {
448 crate::ModuleDef::Function(f) => f.diagnostics(db, sink),
449 crate::ModuleDef::Module(m) => {
450 // Only add diagnostics from inline modules
451 if def_map[m.id.local_id].origin.is_inline() {
452 m.diagnostics(db, sink)
456 decl.diagnostics(db, sink);
461 for impl_def in self.impl_defs(db) {
462 for item in impl_def.items(db) {
463 if let AssocItem::Function(f) = item {
464 f.diagnostics(db, sink);
470 pub fn declarations(self, db: &dyn HirDatabase) -> Vec<ModuleDef> {
471 let def_map = self.id.def_map(db.upcast());
472 def_map[self.id.local_id].scope.declarations().map(ModuleDef::from).collect()
475 pub fn impl_defs(self, db: &dyn HirDatabase) -> Vec<Impl> {
476 let def_map = self.id.def_map(db.upcast());
477 def_map[self.id.local_id].scope.impls().map(Impl::from).collect()
480 /// Finds a path that can be used to refer to the given item from within
481 /// this module, if possible.
482 pub fn find_use_path(self, db: &dyn DefDatabase, item: impl Into<ItemInNs>) -> Option<ModPath> {
483 hir_def::find_path::find_path(db, item.into(), self.into())
486 /// Finds a path that can be used to refer to the given item from within
487 /// this module, if possible. This is used for returning import paths for use-statements.
488 pub fn find_use_path_prefixed(
490 db: &dyn DefDatabase,
491 item: impl Into<ItemInNs>,
492 prefix_kind: PrefixKind,
493 ) -> Option<ModPath> {
494 hir_def::find_path::find_path_prefixed(db, item.into(), self.into(), prefix_kind)
498 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
500 pub(crate) parent: VariantDef,
501 pub(crate) id: LocalFieldId,
504 #[derive(Debug, PartialEq, Eq)]
505 pub enum FieldSource {
506 Named(ast::RecordField),
507 Pos(ast::TupleField),
511 pub fn name(&self, db: &dyn HirDatabase) -> Name {
512 self.parent.variant_data(db).fields()[self.id].name.clone()
515 /// Returns the type as in the signature of the struct (i.e., with
516 /// placeholder types for type parameters). This is good for showing
517 /// signature help, but not so good to actually get the type of the field
518 /// when you actually have a variable of the struct.
519 pub fn ty(&self, db: &dyn HirDatabase) -> Type {
520 let var_id = self.parent.into();
521 let generic_def_id: GenericDefId = match self.parent {
522 VariantDef::Struct(it) => it.id.into(),
523 VariantDef::Union(it) => it.id.into(),
524 VariantDef::Variant(it) => it.parent.id.into(),
526 let substs = TyBuilder::type_params_subst(db, generic_def_id);
527 let ty = db.field_types(var_id)[self.id].clone().substitute(&Interner, &substs);
528 Type::new(db, self.parent.module(db).id.krate(), var_id, ty)
531 pub fn parent_def(&self, _db: &dyn HirDatabase) -> VariantDef {
536 impl HasVisibility for Field {
537 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
538 let variant_data = self.parent.variant_data(db);
539 let visibility = &variant_data.fields()[self.id].visibility;
540 let parent_id: hir_def::VariantId = self.parent.into();
541 visibility.resolve(db.upcast(), &parent_id.resolver(db.upcast()))
545 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
547 pub(crate) id: StructId,
551 pub fn module(self, db: &dyn HirDatabase) -> Module {
552 Module { id: self.id.lookup(db.upcast()).container }
555 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
556 Some(self.module(db).krate())
559 pub fn name(self, db: &dyn HirDatabase) -> Name {
560 db.struct_data(self.id).name.clone()
563 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
564 db.struct_data(self.id)
568 .map(|(id, _)| Field { parent: self.into(), id })
572 pub fn ty(self, db: &dyn HirDatabase) -> Type {
573 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
576 pub fn repr(self, db: &dyn HirDatabase) -> Option<ReprKind> {
577 db.struct_data(self.id).repr.clone()
580 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
581 self.variant_data(db).kind()
584 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
585 db.struct_data(self.id).variant_data.clone()
589 impl HasVisibility for Struct {
590 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
591 db.struct_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
595 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
597 pub(crate) id: UnionId,
601 pub fn name(self, db: &dyn HirDatabase) -> Name {
602 db.union_data(self.id).name.clone()
605 pub fn module(self, db: &dyn HirDatabase) -> Module {
606 Module { id: self.id.lookup(db.upcast()).container }
609 pub fn ty(self, db: &dyn HirDatabase) -> Type {
610 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
613 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
614 db.union_data(self.id)
618 .map(|(id, _)| Field { parent: self.into(), id })
622 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
623 db.union_data(self.id).variant_data.clone()
627 impl HasVisibility for Union {
628 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
629 db.union_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
633 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
635 pub(crate) id: EnumId,
639 pub fn module(self, db: &dyn HirDatabase) -> Module {
640 Module { id: self.id.lookup(db.upcast()).container }
643 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
644 Some(self.module(db).krate())
647 pub fn name(self, db: &dyn HirDatabase) -> Name {
648 db.enum_data(self.id).name.clone()
651 pub fn variants(self, db: &dyn HirDatabase) -> Vec<Variant> {
652 db.enum_data(self.id).variants.iter().map(|(id, _)| Variant { parent: self, id }).collect()
655 pub fn ty(self, db: &dyn HirDatabase) -> Type {
656 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
660 impl HasVisibility for Enum {
661 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
662 db.enum_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
666 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
668 pub(crate) parent: Enum,
669 pub(crate) id: LocalEnumVariantId,
673 pub fn module(self, db: &dyn HirDatabase) -> Module {
674 self.parent.module(db)
676 pub fn parent_enum(self, _db: &dyn HirDatabase) -> Enum {
680 pub fn name(self, db: &dyn HirDatabase) -> Name {
681 db.enum_data(self.parent.id).variants[self.id].name.clone()
684 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
685 self.variant_data(db)
688 .map(|(id, _)| Field { parent: self.into(), id })
692 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
693 self.variant_data(db).kind()
696 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
697 db.enum_data(self.parent.id).variants[self.id].variant_data.clone()
702 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
708 impl_from!(Struct, Union, Enum for Adt);
711 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
712 let subst = db.generic_defaults(self.into());
713 subst.iter().any(|ty| ty.skip_binders().is_unknown())
716 /// Turns this ADT into a type. Any type parameters of the ADT will be
717 /// turned into unknown types, which is good for e.g. finding the most
718 /// general set of completions, but will not look very nice when printed.
719 pub fn ty(self, db: &dyn HirDatabase) -> Type {
720 let id = AdtId::from(self);
721 Type::from_def(db, id.module(db.upcast()).krate(), id)
724 pub fn module(self, db: &dyn HirDatabase) -> Module {
726 Adt::Struct(s) => s.module(db),
727 Adt::Union(s) => s.module(db),
728 Adt::Enum(e) => e.module(db),
732 pub fn krate(self, db: &dyn HirDatabase) -> Crate {
733 self.module(db).krate()
736 pub fn name(self, db: &dyn HirDatabase) -> Name {
738 Adt::Struct(s) => s.name(db),
739 Adt::Union(u) => u.name(db),
740 Adt::Enum(e) => e.name(db),
745 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
746 pub enum VariantDef {
751 impl_from!(Struct, Union, Variant for VariantDef);
754 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
756 VariantDef::Struct(it) => it.fields(db),
757 VariantDef::Union(it) => it.fields(db),
758 VariantDef::Variant(it) => it.fields(db),
762 pub fn module(self, db: &dyn HirDatabase) -> Module {
764 VariantDef::Struct(it) => it.module(db),
765 VariantDef::Union(it) => it.module(db),
766 VariantDef::Variant(it) => it.module(db),
770 pub fn name(&self, db: &dyn HirDatabase) -> Name {
772 VariantDef::Struct(s) => s.name(db),
773 VariantDef::Union(u) => u.name(db),
774 VariantDef::Variant(e) => e.name(db),
778 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
780 VariantDef::Struct(it) => it.variant_data(db),
781 VariantDef::Union(it) => it.variant_data(db),
782 VariantDef::Variant(it) => it.variant_data(db),
787 /// The defs which have a body.
788 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
789 pub enum DefWithBody {
794 impl_from!(Function, Const, Static for DefWithBody);
797 pub fn module(self, db: &dyn HirDatabase) -> Module {
799 DefWithBody::Const(c) => c.module(db),
800 DefWithBody::Function(f) => f.module(db),
801 DefWithBody::Static(s) => s.module(db),
805 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
807 DefWithBody::Function(f) => Some(f.name(db)),
808 DefWithBody::Static(s) => s.name(db),
809 DefWithBody::Const(c) => c.name(db),
814 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
815 pub struct Function {
816 pub(crate) id: FunctionId,
820 pub fn module(self, db: &dyn HirDatabase) -> Module {
821 self.id.lookup(db.upcast()).module(db.upcast()).into()
824 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
825 Some(self.module(db).krate())
828 pub fn name(self, db: &dyn HirDatabase) -> Name {
829 db.function_data(self.id).name.clone()
832 /// Get this function's return type
833 pub fn ret_type(self, db: &dyn HirDatabase) -> Type {
834 let resolver = self.id.resolver(db.upcast());
835 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
836 let ret_type = &db.function_data(self.id).ret_type;
837 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
838 let ty = ctx.lower_ty(ret_type);
839 Type::new_with_resolver_inner(db, krate, &resolver, ty)
842 pub fn self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
843 if !db.function_data(self.id).has_self_param() {
846 Some(SelfParam { func: self.id })
849 pub fn assoc_fn_params(self, db: &dyn HirDatabase) -> Vec<Param> {
850 let resolver = self.id.resolver(db.upcast());
851 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
852 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
853 let environment = db.trait_environment(self.id.into());
854 db.function_data(self.id)
858 .map(|(idx, type_ref)| {
859 let ty = Type { krate, env: environment.clone(), ty: ctx.lower_ty(type_ref) };
860 Param { func: self, ty, idx }
865 pub fn method_params(self, db: &dyn HirDatabase) -> Option<Vec<Param>> {
866 if self.self_param(db).is_none() {
869 let mut res = self.assoc_fn_params(db);
874 pub fn is_unsafe(self, db: &dyn HirDatabase) -> bool {
875 db.function_data(self.id).is_unsafe()
878 pub fn is_async(self, db: &dyn HirDatabase) -> bool {
879 db.function_data(self.id).is_async()
882 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
883 let krate = self.module(db).id.krate();
884 hir_def::diagnostics::validate_body(db.upcast(), self.id.into(), sink);
885 hir_ty::diagnostics::validate_module_item(db, krate, self.id.into(), sink);
886 hir_ty::diagnostics::validate_body(db, self.id.into(), sink);
889 /// Whether this function declaration has a definition.
891 /// This is false in the case of required (not provided) trait methods.
892 pub fn has_body(self, db: &dyn HirDatabase) -> bool {
893 db.function_data(self.id).has_body()
896 /// A textual representation of the HIR of this function for debugging purposes.
897 pub fn debug_hir(self, db: &dyn HirDatabase) -> String {
898 let body = db.body(self.id.into());
900 let mut result = String::new();
901 format_to!(result, "HIR expressions in the body of `{}`:\n", self.name(db));
902 for (id, expr) in body.exprs.iter() {
903 format_to!(result, "{:?}: {:?}\n", id, expr);
910 // Note: logically, this belongs to `hir_ty`, but we are not using it there yet.
917 impl From<hir_ty::Mutability> for Access {
918 fn from(mutability: hir_ty::Mutability) -> Access {
920 hir_ty::Mutability::Not => Access::Shared,
921 hir_ty::Mutability::Mut => Access::Exclusive,
926 #[derive(Clone, Debug)]
929 /// The index in parameter list, including self parameter.
935 pub fn ty(&self) -> &Type {
939 pub fn as_local(&self, db: &dyn HirDatabase) -> Local {
940 let parent = DefWithBodyId::FunctionId(self.func.into());
941 let body = db.body(parent);
942 Local { parent, pat_id: body.params[self.idx] }
945 pub fn pattern_source(&self, db: &dyn HirDatabase) -> Option<ast::Pat> {
946 self.source(db).and_then(|p| p.value.pat())
949 pub fn source(&self, db: &dyn HirDatabase) -> Option<InFile<ast::Param>> {
950 let InFile { file_id, value } = self.func.source(db)?;
951 let params = value.param_list()?;
952 if params.self_param().is_some() {
953 params.params().nth(self.idx.checked_sub(1)?)
955 params.params().nth(self.idx)
957 .map(|value| InFile { file_id, value })
961 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
962 pub struct SelfParam {
967 pub fn access(self, db: &dyn HirDatabase) -> Access {
968 let func_data = db.function_data(self.func);
972 .map(|param| match &**param {
973 TypeRef::Reference(.., mutability) => match mutability {
974 hir_def::type_ref::Mutability::Shared => Access::Shared,
975 hir_def::type_ref::Mutability::Mut => Access::Exclusive,
979 .unwrap_or(Access::Owned)
982 pub fn display(self, db: &dyn HirDatabase) -> &'static str {
983 match self.access(db) {
984 Access::Shared => "&self",
985 Access::Exclusive => "&mut self",
986 Access::Owned => "self",
990 pub fn source(&self, db: &dyn HirDatabase) -> Option<InFile<ast::SelfParam>> {
991 let InFile { file_id, value } = Function::from(self.func).source(db)?;
994 .and_then(|params| params.self_param())
995 .map(|value| InFile { file_id, value })
999 impl HasVisibility for Function {
1000 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1001 let function_data = db.function_data(self.id);
1002 let visibility = &function_data.visibility;
1003 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1007 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1009 pub(crate) id: ConstId,
1013 pub fn module(self, db: &dyn HirDatabase) -> Module {
1014 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1017 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
1018 Some(self.module(db).krate())
1021 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1022 db.const_data(self.id).name.clone()
1025 pub fn type_ref(self, db: &dyn HirDatabase) -> TypeRef {
1026 db.const_data(self.id).type_ref.as_ref().clone()
1030 impl HasVisibility for Const {
1031 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1032 let function_data = db.const_data(self.id);
1033 let visibility = &function_data.visibility;
1034 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1038 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1040 pub(crate) id: StaticId,
1044 pub fn module(self, db: &dyn HirDatabase) -> Module {
1045 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1048 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
1049 Some(self.module(db).krate())
1052 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1053 db.static_data(self.id).name.clone()
1056 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
1057 db.static_data(self.id).mutable
1061 impl HasVisibility for Static {
1062 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1063 db.static_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1067 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1069 pub(crate) id: TraitId,
1073 pub fn module(self, db: &dyn HirDatabase) -> Module {
1074 Module { id: self.id.lookup(db.upcast()).container }
1077 pub fn name(self, db: &dyn HirDatabase) -> Name {
1078 db.trait_data(self.id).name.clone()
1081 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
1082 db.trait_data(self.id).items.iter().map(|(_name, it)| (*it).into()).collect()
1085 pub fn is_auto(self, db: &dyn HirDatabase) -> bool {
1086 db.trait_data(self.id).is_auto
1089 pub fn is_unsafe(&self, db: &dyn HirDatabase) -> bool {
1090 db.trait_data(self.id).is_unsafe
1094 impl HasVisibility for Trait {
1095 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1096 db.trait_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1100 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1101 pub struct TypeAlias {
1102 pub(crate) id: TypeAliasId,
1106 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
1107 let subst = db.generic_defaults(self.id.into());
1108 subst.iter().any(|ty| ty.skip_binders().is_unknown())
1111 pub fn module(self, db: &dyn HirDatabase) -> Module {
1112 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1115 pub fn krate(self, db: &dyn HirDatabase) -> Crate {
1116 self.module(db).krate()
1119 pub fn type_ref(self, db: &dyn HirDatabase) -> Option<TypeRef> {
1120 db.type_alias_data(self.id).type_ref.as_deref().cloned()
1123 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1124 Type::from_def(db, self.id.lookup(db.upcast()).module(db.upcast()).krate(), self.id)
1127 pub fn name(self, db: &dyn HirDatabase) -> Name {
1128 db.type_alias_data(self.id).name.clone()
1132 impl HasVisibility for TypeAlias {
1133 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1134 let function_data = db.type_alias_data(self.id);
1135 let visibility = &function_data.visibility;
1136 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1140 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1141 pub struct BuiltinType {
1142 pub(crate) inner: hir_def::builtin_type::BuiltinType,
1146 pub fn ty(self, db: &dyn HirDatabase, module: Module) -> Type {
1147 let resolver = module.id.resolver(db.upcast());
1148 Type::new_with_resolver(db, &resolver, TyBuilder::builtin(self.inner))
1149 .expect("crate not present in resolver")
1152 pub fn name(self) -> Name {
1153 self.inner.as_name()
1157 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1158 pub enum MacroKind {
1165 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1166 pub struct MacroDef {
1167 pub(crate) id: MacroDefId,
1171 /// FIXME: right now, this just returns the root module of the crate that
1172 /// defines this macro. The reasons for this is that macros are expanded
1173 /// early, in `hir_expand`, where modules simply do not exist yet.
1174 pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
1175 let krate = self.id.krate;
1176 let def_map = db.crate_def_map(krate);
1177 let module_id = def_map.root();
1178 Some(Module { id: def_map.module_id(module_id) })
1181 /// XXX: this parses the file
1182 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1183 match self.source(db)?.value {
1184 Either::Left(it) => it.name().map(|it| it.as_name()),
1185 Either::Right(it) => it.name().map(|it| it.as_name()),
1189 pub fn kind(&self) -> MacroKind {
1190 match self.id.kind {
1191 MacroDefKind::Declarative(_) => MacroKind::Declarative,
1192 MacroDefKind::BuiltIn(_, _) => MacroKind::BuiltIn,
1193 MacroDefKind::BuiltInDerive(_, _) => MacroKind::Derive,
1194 MacroDefKind::BuiltInEager(_, _) => MacroKind::BuiltIn,
1195 // FIXME might be a derive
1196 MacroDefKind::ProcMacro(_, _) => MacroKind::ProcMacro,
1201 /// Invariant: `inner.as_assoc_item(db).is_some()`
1202 /// We do not actively enforce this invariant.
1203 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1204 pub enum AssocItem {
1207 TypeAlias(TypeAlias),
1210 pub enum AssocItemContainer {
1214 pub trait AsAssocItem {
1215 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem>;
1218 impl AsAssocItem for Function {
1219 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1220 as_assoc_item(db, AssocItem::Function, self.id)
1223 impl AsAssocItem for Const {
1224 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1225 as_assoc_item(db, AssocItem::Const, self.id)
1228 impl AsAssocItem for TypeAlias {
1229 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1230 as_assoc_item(db, AssocItem::TypeAlias, self.id)
1233 impl AsAssocItem for ModuleDef {
1234 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1236 ModuleDef::Function(it) => it.as_assoc_item(db),
1237 ModuleDef::Const(it) => it.as_assoc_item(db),
1238 ModuleDef::TypeAlias(it) => it.as_assoc_item(db),
1243 fn as_assoc_item<ID, DEF, CTOR, AST>(db: &dyn HirDatabase, ctor: CTOR, id: ID) -> Option<AssocItem>
1245 ID: Lookup<Data = AssocItemLoc<AST>>,
1247 CTOR: FnOnce(DEF) -> AssocItem,
1250 match id.lookup(db.upcast()).container {
1251 AssocContainerId::TraitId(_) | AssocContainerId::ImplId(_) => Some(ctor(DEF::from(id))),
1252 AssocContainerId::ModuleId(_) => None,
1257 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1259 AssocItem::Function(it) => Some(it.name(db)),
1260 AssocItem::Const(it) => it.name(db),
1261 AssocItem::TypeAlias(it) => Some(it.name(db)),
1264 pub fn module(self, db: &dyn HirDatabase) -> Module {
1266 AssocItem::Function(f) => f.module(db),
1267 AssocItem::Const(c) => c.module(db),
1268 AssocItem::TypeAlias(t) => t.module(db),
1271 pub fn container(self, db: &dyn HirDatabase) -> AssocItemContainer {
1272 let container = match self {
1273 AssocItem::Function(it) => it.id.lookup(db.upcast()).container,
1274 AssocItem::Const(it) => it.id.lookup(db.upcast()).container,
1275 AssocItem::TypeAlias(it) => it.id.lookup(db.upcast()).container,
1278 AssocContainerId::TraitId(id) => AssocItemContainer::Trait(id.into()),
1279 AssocContainerId::ImplId(id) => AssocItemContainer::Impl(id.into()),
1280 AssocContainerId::ModuleId(_) => panic!("invalid AssocItem"),
1284 pub fn containing_trait(self, db: &dyn HirDatabase) -> Option<Trait> {
1285 match self.container(db) {
1286 AssocItemContainer::Trait(t) => Some(t),
1292 impl HasVisibility for AssocItem {
1293 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1295 AssocItem::Function(f) => f.visibility(db),
1296 AssocItem::Const(c) => c.visibility(db),
1297 AssocItem::TypeAlias(t) => t.visibility(db),
1302 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
1303 pub enum GenericDef {
1307 TypeAlias(TypeAlias),
1309 // enum variants cannot have generics themselves, but their parent enums
1310 // can, and this makes some code easier to write
1312 // consts can have type parameters from their parents (i.e. associated consts of traits)
1317 Adt(Struct, Enum, Union),
1327 pub fn params(self, db: &dyn HirDatabase) -> Vec<GenericParam> {
1328 let generics = db.generic_params(self.into());
1329 let ty_params = generics
1332 .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
1333 .map(GenericParam::TypeParam);
1334 let lt_params = generics
1337 .map(|(local_id, _)| LifetimeParam {
1338 id: LifetimeParamId { parent: self.into(), local_id },
1340 .map(GenericParam::LifetimeParam);
1341 let const_params = generics
1344 .map(|(local_id, _)| ConstParam { id: ConstParamId { parent: self.into(), local_id } })
1345 .map(GenericParam::ConstParam);
1346 ty_params.chain(lt_params).chain(const_params).collect()
1349 pub fn type_params(self, db: &dyn HirDatabase) -> Vec<TypeParam> {
1350 let generics = db.generic_params(self.into());
1354 .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
1359 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1361 pub(crate) parent: DefWithBodyId,
1362 pub(crate) pat_id: PatId,
1366 pub fn is_param(self, db: &dyn HirDatabase) -> bool {
1367 let src = self.source(db);
1369 Either::Left(bind_pat) => {
1370 bind_pat.syntax().ancestors().any(|it| ast::Param::can_cast(it.kind()))
1372 Either::Right(_self_param) => true,
1376 pub fn as_self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
1378 DefWithBodyId::FunctionId(func) if self.is_self(db) => Some(SelfParam { func }),
1383 // FIXME: why is this an option? It shouldn't be?
1384 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1385 let body = db.body(self.parent);
1386 match &body[self.pat_id] {
1387 Pat::Bind { name, .. } => Some(name.clone()),
1392 pub fn is_self(self, db: &dyn HirDatabase) -> bool {
1393 self.name(db) == Some(name![self])
1396 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
1397 let body = db.body(self.parent);
1398 matches!(&body[self.pat_id], Pat::Bind { mode: BindingAnnotation::Mutable, .. })
1401 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
1405 pub fn module(self, db: &dyn HirDatabase) -> Module {
1406 self.parent(db).module(db)
1409 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1410 let def = self.parent;
1411 let infer = db.infer(def);
1412 let ty = infer[self.pat_id].clone();
1413 let krate = def.module(db.upcast()).krate();
1414 Type::new(db, krate, def, ty)
1417 pub fn source(self, db: &dyn HirDatabase) -> InFile<Either<ast::IdentPat, ast::SelfParam>> {
1418 let (_body, source_map) = db.body_with_source_map(self.parent);
1419 let src = source_map.pat_syntax(self.pat_id).unwrap(); // Hmm...
1420 let root = src.file_syntax(db.upcast());
1422 ast.map_left(|it| it.cast().unwrap().to_node(&root)).map_right(|it| it.to_node(&root))
1427 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1429 pub(crate) parent: DefWithBodyId,
1430 pub(crate) label_id: LabelId,
1434 pub fn module(self, db: &dyn HirDatabase) -> Module {
1435 self.parent(db).module(db)
1438 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
1442 pub fn name(self, db: &dyn HirDatabase) -> Name {
1443 let body = db.body(self.parent);
1444 body[self.label_id].name.clone()
1447 pub fn source(self, db: &dyn HirDatabase) -> InFile<ast::Label> {
1448 let (_body, source_map) = db.body_with_source_map(self.parent);
1449 let src = source_map.label_syntax(self.label_id);
1450 let root = src.file_syntax(db.upcast());
1451 src.map(|ast| ast.to_node(&root))
1455 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1456 pub enum GenericParam {
1457 TypeParam(TypeParam),
1458 LifetimeParam(LifetimeParam),
1459 ConstParam(ConstParam),
1461 impl_from!(TypeParam, LifetimeParam, ConstParam for GenericParam);
1464 pub fn module(self, db: &dyn HirDatabase) -> Module {
1466 GenericParam::TypeParam(it) => it.module(db),
1467 GenericParam::LifetimeParam(it) => it.module(db),
1468 GenericParam::ConstParam(it) => it.module(db),
1472 pub fn name(self, db: &dyn HirDatabase) -> Name {
1474 GenericParam::TypeParam(it) => it.name(db),
1475 GenericParam::LifetimeParam(it) => it.name(db),
1476 GenericParam::ConstParam(it) => it.name(db),
1481 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1482 pub struct TypeParam {
1483 pub(crate) id: TypeParamId,
1487 pub fn name(self, db: &dyn HirDatabase) -> Name {
1488 let params = db.generic_params(self.id.parent);
1489 params.types[self.id.local_id].name.clone().unwrap_or_else(Name::missing)
1492 pub fn module(self, db: &dyn HirDatabase) -> Module {
1493 self.id.parent.module(db.upcast()).into()
1496 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1497 let resolver = self.id.parent.resolver(db.upcast());
1498 let krate = self.id.parent.module(db.upcast()).krate();
1499 let ty = TyKind::Placeholder(hir_ty::to_placeholder_idx(db, self.id)).intern(&Interner);
1500 Type::new_with_resolver_inner(db, krate, &resolver, ty)
1503 pub fn trait_bounds(self, db: &dyn HirDatabase) -> Vec<Trait> {
1504 db.generic_predicates_for_param(self.id)
1506 .filter_map(|pred| match &pred.skip_binders().skip_binders() {
1507 hir_ty::WhereClause::Implemented(trait_ref) => {
1508 Some(Trait::from(trait_ref.hir_trait_id()))
1515 pub fn default(self, db: &dyn HirDatabase) -> Option<Type> {
1516 let params = db.generic_defaults(self.id.parent);
1517 let local_idx = hir_ty::param_idx(db, self.id)?;
1518 let resolver = self.id.parent.resolver(db.upcast());
1519 let krate = self.id.parent.module(db.upcast()).krate();
1520 let ty = params.get(local_idx)?.clone();
1521 let subst = TyBuilder::type_params_subst(db, self.id.parent);
1522 let ty = ty.substitute(&Interner, &subst_prefix(&subst, local_idx));
1523 Some(Type::new_with_resolver_inner(db, krate, &resolver, ty))
1527 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1528 pub struct LifetimeParam {
1529 pub(crate) id: LifetimeParamId,
1532 impl LifetimeParam {
1533 pub fn name(self, db: &dyn HirDatabase) -> Name {
1534 let params = db.generic_params(self.id.parent);
1535 params.lifetimes[self.id.local_id].name.clone()
1538 pub fn module(self, db: &dyn HirDatabase) -> Module {
1539 self.id.parent.module(db.upcast()).into()
1542 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
1543 self.id.parent.into()
1547 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1548 pub struct ConstParam {
1549 pub(crate) id: ConstParamId,
1553 pub fn name(self, db: &dyn HirDatabase) -> Name {
1554 let params = db.generic_params(self.id.parent);
1555 params.consts[self.id.local_id].name.clone()
1558 pub fn module(self, db: &dyn HirDatabase) -> Module {
1559 self.id.parent.module(db.upcast()).into()
1562 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
1563 self.id.parent.into()
1566 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1567 let def = self.id.parent;
1568 let krate = def.module(db.upcast()).krate();
1569 Type::new(db, krate, def, db.const_param_ty(self.id))
1573 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1575 pub(crate) id: ImplId,
1579 pub fn all_in_crate(db: &dyn HirDatabase, krate: Crate) -> Vec<Impl> {
1580 let inherent = db.inherent_impls_in_crate(krate.id);
1581 let trait_ = db.trait_impls_in_crate(krate.id);
1583 inherent.all_impls().chain(trait_.all_impls()).map(Self::from).collect()
1586 pub fn all_for_type(db: &dyn HirDatabase, Type { krate, ty, .. }: Type) -> Vec<Impl> {
1587 let def_crates = match def_crates(db, &ty, krate) {
1588 Some(def_crates) => def_crates,
1589 None => return Vec::new(),
1592 let filter = |impl_def: &Impl| {
1593 let self_ty = impl_def.self_ty(db);
1594 let rref = self_ty.remove_ref();
1595 ty.equals_ctor(rref.as_ref().map_or(&self_ty.ty, |it| &it.ty))
1598 let fp = TyFingerprint::for_inherent_impl(&ty);
1599 let fp = if let Some(fp) = fp {
1605 let mut all = Vec::new();
1606 def_crates.iter().for_each(|&id| {
1608 db.inherent_impls_in_crate(id)
1616 for id in def_crates
1618 .flat_map(|&id| Crate { id }.transitive_reverse_dependencies(db))
1619 .map(|Crate { id }| id)
1620 .chain(def_crates.iter().copied())
1624 db.trait_impls_in_crate(id)
1625 .for_self_ty_without_blanket_impls(fp)
1633 pub fn all_for_trait(db: &dyn HirDatabase, trait_: Trait) -> Vec<Impl> {
1634 let krate = trait_.module(db).krate();
1635 let mut all = Vec::new();
1636 for Crate { id } in krate.transitive_reverse_dependencies(db).into_iter() {
1637 let impls = db.trait_impls_in_crate(id);
1638 all.extend(impls.for_trait(trait_.id).map(Self::from))
1643 // FIXME: the return type is wrong. This should be a hir version of
1644 // `TraitRef` (ie, resolved `TypeRef`).
1645 pub fn trait_(self, db: &dyn HirDatabase) -> Option<TraitRef> {
1646 db.impl_data(self.id).target_trait.as_deref().cloned()
1649 pub fn self_ty(self, db: &dyn HirDatabase) -> Type {
1650 let impl_data = db.impl_data(self.id);
1651 let resolver = self.id.resolver(db.upcast());
1652 let krate = self.id.lookup(db.upcast()).container.krate();
1653 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1654 let ty = ctx.lower_ty(&impl_data.self_ty);
1655 Type::new_with_resolver_inner(db, krate, &resolver, ty)
1658 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
1659 db.impl_data(self.id).items.iter().map(|it| (*it).into()).collect()
1662 pub fn is_negative(self, db: &dyn HirDatabase) -> bool {
1663 db.impl_data(self.id).is_negative
1666 pub fn module(self, db: &dyn HirDatabase) -> Module {
1667 self.id.lookup(db.upcast()).container.into()
1670 pub fn krate(self, db: &dyn HirDatabase) -> Crate {
1671 Crate { id: self.module(db).id.krate() }
1674 pub fn is_builtin_derive(self, db: &dyn HirDatabase) -> Option<InFile<ast::Attr>> {
1675 let src = self.source(db)?;
1676 let item = src.file_id.is_builtin_derive(db.upcast())?;
1677 let hygenic = hir_expand::hygiene::Hygiene::new(db.upcast(), item.file_id);
1679 // FIXME: handle `cfg_attr`
1684 let path = ModPath::from_src(db.upcast(), it.path()?, &hygenic)?;
1685 if path.as_ident()?.to_string() == "derive" {
1693 Some(item.with_value(attr))
1697 #[derive(Clone, PartialEq, Eq, Debug)]
1700 env: Arc<TraitEnvironment>,
1705 pub(crate) fn new_with_resolver(
1706 db: &dyn HirDatabase,
1707 resolver: &Resolver,
1710 let krate = resolver.krate()?;
1711 Some(Type::new_with_resolver_inner(db, krate, resolver, ty))
1713 pub(crate) fn new_with_resolver_inner(
1714 db: &dyn HirDatabase,
1716 resolver: &Resolver,
1719 let environment = resolver
1721 .map_or_else(|| Arc::new(TraitEnvironment::empty(krate)), |d| db.trait_environment(d));
1722 Type { krate, env: environment, ty }
1725 fn new(db: &dyn HirDatabase, krate: CrateId, lexical_env: impl HasResolver, ty: Ty) -> Type {
1726 let resolver = lexical_env.resolver(db.upcast());
1727 let environment = resolver
1729 .map_or_else(|| Arc::new(TraitEnvironment::empty(krate)), |d| db.trait_environment(d));
1730 Type { krate, env: environment, ty }
1734 db: &dyn HirDatabase,
1736 def: impl HasResolver + Into<TyDefId>,
1738 let ty = TyBuilder::def_ty(db, def.into()).fill_with_unknown().build();
1739 Type::new(db, krate, def, ty)
1742 pub fn is_unit(&self) -> bool {
1743 matches!(self.ty.kind(&Interner), TyKind::Tuple(0, ..))
1745 pub fn is_bool(&self) -> bool {
1746 matches!(self.ty.kind(&Interner), TyKind::Scalar(Scalar::Bool))
1749 pub fn is_mutable_reference(&self) -> bool {
1750 matches!(self.ty.kind(&Interner), TyKind::Ref(hir_ty::Mutability::Mut, ..))
1753 pub fn is_usize(&self) -> bool {
1754 matches!(self.ty.kind(&Interner), TyKind::Scalar(Scalar::Uint(UintTy::Usize)))
1757 pub fn remove_ref(&self) -> Option<Type> {
1758 match &self.ty.kind(&Interner) {
1759 TyKind::Ref(.., ty) => Some(self.derived(ty.clone())),
1764 pub fn strip_references(&self) -> Type {
1765 self.derived(self.ty.strip_references().clone())
1768 pub fn is_unknown(&self) -> bool {
1769 self.ty.is_unknown()
1772 /// Checks that particular type `ty` implements `std::future::Future`.
1773 /// This function is used in `.await` syntax completion.
1774 pub fn impls_future(&self, db: &dyn HirDatabase) -> bool {
1775 // No special case for the type of async block, since Chalk can figure it out.
1777 let krate = self.krate;
1779 let std_future_trait =
1780 db.lang_item(krate, "future_trait".into()).and_then(|it| it.as_trait());
1781 let std_future_trait = match std_future_trait {
1783 None => return false,
1787 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(&Interner) };
1788 method_resolution::implements_trait(
1797 /// Checks that particular type `ty` implements `std::ops::FnOnce`.
1799 /// This function can be used to check if a particular type is callable, since FnOnce is a
1800 /// supertrait of Fn and FnMut, so all callable types implements at least FnOnce.
1801 pub fn impls_fnonce(&self, db: &dyn HirDatabase) -> bool {
1802 let krate = self.krate;
1804 let fnonce_trait = match FnTrait::FnOnce.get_id(db, krate) {
1806 None => return false,
1810 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(&Interner) };
1811 method_resolution::implements_trait_unique(
1820 pub fn impls_trait(&self, db: &dyn HirDatabase, trait_: Trait, args: &[Type]) -> bool {
1821 let trait_ref = TyBuilder::trait_ref(db, trait_.id)
1822 .push(self.ty.clone())
1823 .fill(args.iter().map(|t| t.ty.clone()))
1826 let goal = Canonical {
1827 value: hir_ty::InEnvironment::new(&self.env.env, trait_ref.cast(&Interner)),
1828 binders: CanonicalVarKinds::empty(&Interner),
1831 db.trait_solve(self.krate, goal).is_some()
1834 pub fn normalize_trait_assoc_type(
1836 db: &dyn HirDatabase,
1840 let projection = TyBuilder::assoc_type_projection(db, alias.id)
1841 .push(self.ty.clone())
1842 .fill(args.iter().map(|t| t.ty.clone()))
1844 let goal = hir_ty::make_canonical(
1848 alias: AliasTy::Projection(projection),
1849 ty: TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0))
1854 [TyVariableKind::General].iter().copied(),
1857 match db.trait_solve(self.krate, goal)? {
1858 Solution::Unique(s) => s
1861 .as_slice(&Interner)
1863 .map(|ty| self.derived(ty.assert_ty_ref(&Interner).clone())),
1864 Solution::Ambig(_) => None,
1868 pub fn is_copy(&self, db: &dyn HirDatabase) -> bool {
1869 let lang_item = db.lang_item(self.krate, SmolStr::new("copy"));
1870 let copy_trait = match lang_item {
1871 Some(LangItemTarget::TraitId(it)) => it,
1874 self.impls_trait(db, copy_trait.into(), &[])
1877 pub fn as_callable(&self, db: &dyn HirDatabase) -> Option<Callable> {
1878 let def = self.ty.callable_def(db);
1880 let sig = self.ty.callable_sig(db)?;
1881 Some(Callable { ty: self.clone(), sig, def, is_bound_method: false })
1884 pub fn is_closure(&self) -> bool {
1885 matches!(&self.ty.kind(&Interner), TyKind::Closure { .. })
1888 pub fn is_fn(&self) -> bool {
1889 matches!(&self.ty.kind(&Interner), TyKind::FnDef(..) | TyKind::Function { .. })
1892 pub fn is_packed(&self, db: &dyn HirDatabase) -> bool {
1893 let adt_id = match self.ty.kind(&Interner) {
1894 &TyKind::Adt(hir_ty::AdtId(adt_id), ..) => adt_id,
1898 let adt = adt_id.into();
1900 Adt::Struct(s) => matches!(s.repr(db), Some(ReprKind::Packed)),
1905 pub fn is_raw_ptr(&self) -> bool {
1906 matches!(&self.ty.kind(&Interner), TyKind::Raw(..))
1909 pub fn contains_unknown(&self) -> bool {
1910 return go(&self.ty);
1912 fn go(ty: &Ty) -> bool {
1913 match ty.kind(&Interner) {
1914 TyKind::Error => true,
1916 TyKind::Adt(_, substs)
1917 | TyKind::AssociatedType(_, substs)
1918 | TyKind::Tuple(_, substs)
1919 | TyKind::OpaqueType(_, substs)
1920 | TyKind::FnDef(_, substs)
1921 | TyKind::Closure(_, substs) => {
1922 substs.iter(&Interner).filter_map(|a| a.ty(&Interner)).any(go)
1925 TyKind::Array(_ty, len) if len.is_unknown() => true,
1926 TyKind::Array(ty, _)
1928 | TyKind::Raw(_, ty)
1929 | TyKind::Ref(_, _, ty) => go(ty),
1934 | TyKind::Placeholder(_)
1935 | TyKind::BoundVar(_)
1936 | TyKind::InferenceVar(_, _)
1938 | TyKind::Function(_)
1940 | TyKind::Foreign(_)
1941 | TyKind::Generator(..)
1942 | TyKind::GeneratorWitness(..) => false,
1947 pub fn fields(&self, db: &dyn HirDatabase) -> Vec<(Field, Type)> {
1948 let (variant_id, substs) = match self.ty.kind(&Interner) {
1949 &TyKind::Adt(hir_ty::AdtId(AdtId::StructId(s)), ref substs) => (s.into(), substs),
1950 &TyKind::Adt(hir_ty::AdtId(AdtId::UnionId(u)), ref substs) => (u.into(), substs),
1951 _ => return Vec::new(),
1954 db.field_types(variant_id)
1956 .map(|(local_id, ty)| {
1957 let def = Field { parent: variant_id.into(), id: local_id };
1958 let ty = ty.clone().substitute(&Interner, substs);
1959 (def, self.derived(ty))
1964 pub fn tuple_fields(&self, _db: &dyn HirDatabase) -> Vec<Type> {
1965 if let TyKind::Tuple(_, substs) = &self.ty.kind(&Interner) {
1968 .map(|ty| self.derived(ty.assert_ty_ref(&Interner).clone()))
1975 pub fn autoderef<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Type> + 'a {
1976 // There should be no inference vars in types passed here
1977 // FIXME check that?
1979 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(&Interner) };
1980 let environment = self.env.env.clone();
1981 let ty = InEnvironment { goal: canonical, environment };
1982 autoderef(db, Some(self.krate), ty)
1983 .map(|canonical| canonical.value)
1984 .map(move |ty| self.derived(ty))
1987 // This would be nicer if it just returned an iterator, but that runs into
1988 // lifetime problems, because we need to borrow temp `CrateImplDefs`.
1989 pub fn iterate_assoc_items<T>(
1991 db: &dyn HirDatabase,
1993 mut callback: impl FnMut(AssocItem) -> Option<T>,
1995 for krate in def_crates(db, &self.ty, krate.id)? {
1996 let impls = db.inherent_impls_in_crate(krate);
1998 for impl_def in impls.for_self_ty(&self.ty) {
1999 for &item in db.impl_data(*impl_def).items.iter() {
2000 if let Some(result) = callback(item.into()) {
2001 return Some(result);
2009 pub fn type_arguments(&self) -> impl Iterator<Item = Type> + '_ {
2014 .flat_map(|(_, substs)| substs.iter(&Interner))
2015 .filter_map(|arg| arg.ty(&Interner).cloned())
2016 .map(move |ty| self.derived(ty))
2019 pub fn iterate_method_candidates<T>(
2021 db: &dyn HirDatabase,
2023 traits_in_scope: &FxHashSet<TraitId>,
2024 name: Option<&Name>,
2025 mut callback: impl FnMut(&Ty, Function) -> Option<T>,
2027 // There should be no inference vars in types passed here
2028 // FIXME check that?
2029 // FIXME replace Unknown by bound vars here
2031 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(&Interner) };
2033 let env = self.env.clone();
2034 let krate = krate.id;
2036 method_resolution::iterate_method_candidates(
2044 method_resolution::LookupMode::MethodCall,
2046 AssocItemId::FunctionId(f) => callback(ty, f.into()),
2052 pub fn iterate_path_candidates<T>(
2054 db: &dyn HirDatabase,
2056 traits_in_scope: &FxHashSet<TraitId>,
2057 name: Option<&Name>,
2058 mut callback: impl FnMut(&Ty, AssocItem) -> Option<T>,
2060 let canonical = hir_ty::replace_errors_with_variables(&self.ty);
2062 let env = self.env.clone();
2063 let krate = krate.id;
2065 method_resolution::iterate_method_candidates(
2073 method_resolution::LookupMode::Path,
2074 |ty, it| callback(ty, it.into()),
2078 pub fn as_adt(&self) -> Option<Adt> {
2079 let (adt, _subst) = self.ty.as_adt()?;
2083 pub fn as_builtin(&self) -> Option<BuiltinType> {
2084 self.ty.as_builtin().map(|inner| BuiltinType { inner })
2087 pub fn as_dyn_trait(&self) -> Option<Trait> {
2088 self.ty.dyn_trait().map(Into::into)
2091 /// If a type can be represented as `dyn Trait`, returns all traits accessible via this type,
2092 /// or an empty iterator otherwise.
2093 pub fn applicable_inherent_traits<'a>(
2095 db: &'a dyn HirDatabase,
2096 ) -> impl Iterator<Item = Trait> + 'a {
2098 .filter_map(|derefed_type| derefed_type.ty.dyn_trait())
2099 .flat_map(move |dyn_trait_id| hir_ty::all_super_traits(db.upcast(), dyn_trait_id))
2103 pub fn as_impl_traits(&self, db: &dyn HirDatabase) -> Option<Vec<Trait>> {
2104 self.ty.impl_trait_bounds(db).map(|it| {
2106 .filter_map(|pred| match pred.skip_binders() {
2107 hir_ty::WhereClause::Implemented(trait_ref) => {
2108 Some(Trait::from(trait_ref.hir_trait_id()))
2116 pub fn as_associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<Trait> {
2117 self.ty.associated_type_parent_trait(db).map(Into::into)
2120 fn derived(&self, ty: Ty) -> Type {
2121 Type { krate: self.krate, env: self.env.clone(), ty }
2124 pub fn walk(&self, db: &dyn HirDatabase, mut cb: impl FnMut(Type)) {
2125 // TypeWalk::walk for a Ty at first visits parameters and only after that the Ty itself.
2126 // We need a different order here.
2129 db: &dyn HirDatabase,
2131 substs: &Substitution,
2132 cb: &mut impl FnMut(Type),
2134 for ty in substs.iter(&Interner).filter_map(|a| a.ty(&Interner)) {
2135 walk_type(db, &type_.derived(ty.clone()), cb);
2140 db: &dyn HirDatabase,
2142 bounds: &[QuantifiedWhereClause],
2143 cb: &mut impl FnMut(Type),
2145 for pred in bounds {
2146 match pred.skip_binders() {
2147 WhereClause::Implemented(trait_ref) => {
2149 // skip the self type. it's likely the type we just got the bounds from
2154 .filter_map(|a| a.ty(&Interner))
2156 walk_type(db, &type_.derived(ty.clone()), cb);
2164 fn walk_type(db: &dyn HirDatabase, type_: &Type, cb: &mut impl FnMut(Type)) {
2165 let ty = type_.ty.strip_references();
2166 match ty.kind(&Interner) {
2167 TyKind::Adt(_, substs) => {
2168 cb(type_.derived(ty.clone()));
2169 walk_substs(db, type_, &substs, cb);
2171 TyKind::AssociatedType(_, substs) => {
2172 if let Some(_) = ty.associated_type_parent_trait(db) {
2173 cb(type_.derived(ty.clone()));
2175 walk_substs(db, type_, &substs, cb);
2177 TyKind::OpaqueType(_, subst) => {
2178 if let Some(bounds) = ty.impl_trait_bounds(db) {
2179 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
2182 walk_substs(db, type_, subst, cb);
2184 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
2185 if let Some(bounds) = ty.impl_trait_bounds(db) {
2186 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
2189 walk_substs(db, type_, &opaque_ty.substitution, cb);
2191 TyKind::Placeholder(_) => {
2192 if let Some(bounds) = ty.impl_trait_bounds(db) {
2193 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
2196 TyKind::Dyn(bounds) => {
2199 &type_.derived(ty.clone()),
2200 bounds.bounds.skip_binders().interned(),
2205 TyKind::Ref(_, _, ty)
2206 | TyKind::Raw(_, ty)
2207 | TyKind::Array(ty, _)
2208 | TyKind::Slice(ty) => {
2209 walk_type(db, &type_.derived(ty.clone()), cb);
2212 TyKind::FnDef(_, substs)
2213 | TyKind::Tuple(_, substs)
2214 | TyKind::Closure(.., substs) => {
2215 walk_substs(db, type_, &substs, cb);
2217 TyKind::Function(hir_ty::FnPointer { substitution, .. }) => {
2218 walk_substs(db, type_, &substitution.0, cb);
2225 walk_type(db, self, &mut cb);
2228 pub fn could_unify_with(&self, db: &dyn HirDatabase, other: &Type) -> bool {
2229 let tys = hir_ty::replace_errors_with_variables(&(self.ty.clone(), other.ty.clone()));
2230 could_unify(db, self.env.clone(), &tys)
2236 pub struct Callable {
2239 def: Option<CallableDefId>,
2240 pub(crate) is_bound_method: bool,
2243 pub enum CallableKind {
2245 TupleStruct(Struct),
2246 TupleEnumVariant(Variant),
2251 pub fn kind(&self) -> CallableKind {
2253 Some(CallableDefId::FunctionId(it)) => CallableKind::Function(it.into()),
2254 Some(CallableDefId::StructId(it)) => CallableKind::TupleStruct(it.into()),
2255 Some(CallableDefId::EnumVariantId(it)) => CallableKind::TupleEnumVariant(it.into()),
2256 None => CallableKind::Closure,
2259 pub fn receiver_param(&self, db: &dyn HirDatabase) -> Option<ast::SelfParam> {
2260 let func = match self.def {
2261 Some(CallableDefId::FunctionId(it)) if self.is_bound_method => it,
2264 let src = func.lookup(db.upcast()).source(db.upcast());
2265 let param_list = src.value.param_list()?;
2266 param_list.self_param()
2268 pub fn n_params(&self) -> usize {
2269 self.sig.params().len() - if self.is_bound_method { 1 } else { 0 }
2273 db: &dyn HirDatabase,
2274 ) -> Vec<(Option<Either<ast::SelfParam, ast::Pat>>, Type)> {
2279 .skip(if self.is_bound_method { 1 } else { 0 })
2280 .map(|ty| self.ty.derived(ty.clone()));
2281 let patterns = match self.def {
2282 Some(CallableDefId::FunctionId(func)) => {
2283 let src = func.lookup(db.upcast()).source(db.upcast());
2284 src.value.param_list().map(|param_list| {
2287 .map(|it| Some(Either::Left(it)))
2288 .filter(|_| !self.is_bound_method)
2290 .chain(param_list.params().map(|it| it.pat().map(Either::Right)))
2295 patterns.into_iter().flatten().chain(iter::repeat(None)).zip(types).collect()
2297 pub fn return_type(&self) -> Type {
2298 self.ty.derived(self.sig.ret().clone())
2303 #[derive(Debug, PartialEq, Eq, Hash)]
2305 ModuleDef(ModuleDef),
2307 GenericParam(GenericParam),
2316 pub fn all_items(def: PerNs) -> ArrayVec<Self, 3> {
2317 let mut items = ArrayVec::new();
2319 match (def.take_types(), def.take_values()) {
2320 (Some(m1), None) => items.push(ScopeDef::ModuleDef(m1.into())),
2321 (None, Some(m2)) => items.push(ScopeDef::ModuleDef(m2.into())),
2322 (Some(m1), Some(m2)) => {
2323 // Some items, like unit structs and enum variants, are
2324 // returned as both a type and a value. Here we want
2325 // to de-duplicate them.
2327 items.push(ScopeDef::ModuleDef(m1.into()));
2328 items.push(ScopeDef::ModuleDef(m2.into()));
2330 items.push(ScopeDef::ModuleDef(m1.into()));
2336 if let Some(macro_def_id) = def.take_macros() {
2337 items.push(ScopeDef::MacroDef(macro_def_id.into()));
2340 if items.is_empty() {
2341 items.push(ScopeDef::Unknown);
2348 impl From<ItemInNs> for ScopeDef {
2349 fn from(item: ItemInNs) -> Self {
2351 ItemInNs::Types(id) => ScopeDef::ModuleDef(id.into()),
2352 ItemInNs::Values(id) => ScopeDef::ModuleDef(id.into()),
2353 ItemInNs::Macros(id) => ScopeDef::MacroDef(id.into()),
2358 pub trait HasVisibility {
2359 fn visibility(&self, db: &dyn HirDatabase) -> Visibility;
2360 fn is_visible_from(&self, db: &dyn HirDatabase, module: Module) -> bool {
2361 let vis = self.visibility(db);
2362 vis.is_visible_from(db.upcast(), module.id)