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};
55 autoderef, could_unify,
56 method_resolution::{self, TyFingerprint},
59 AliasEq, AliasTy, BoundVar, CallableDefId, CallableSig, Canonical, CanonicalVarKinds, Cast,
60 DebruijnIndex, InEnvironment, Interner, QuantifiedWhereClause, Scalar, Solution,
61 SolutionVariables, Substitution, TraitEnvironment, Ty, TyBuilder, TyDefId, TyKind,
62 TyVariableKind, WhereClause,
64 use itertools::Itertools;
65 use rustc_hash::FxHashSet;
66 use stdx::{format_to, impl_from};
68 ast::{self, AttrsOwner, NameOwner},
71 use tt::{Ident, Leaf, Literal, TokenTree};
73 use crate::db::{DefDatabase, HirDatabase};
76 attrs::{HasAttrs, Namespace},
77 has_source::HasSource,
78 semantics::{PathResolution, Semantics, SemanticsScope},
81 // Be careful with these re-exports.
83 // `hir` is the boundary between the compiler and the IDE. It should try hard to
84 // isolate the compiler from the ide, to allow the two to be refactored
85 // independently. Re-exporting something from the compiler is the sure way to
86 // breach the boundary.
88 // Generally, a refactoring which *removes* a name from this list is a good
93 attr::{Attr, Attrs, AttrsWithOwner, Documentation},
94 body::scope::ExprScopes,
95 find_path::PrefixKind,
98 nameres::ModuleSource,
99 path::{ModPath, PathKind},
100 type_ref::{Mutability, TypeRef},
101 visibility::Visibility,
105 ExpandResult, HirFileId, InFile, MacroCallId, MacroCallLoc, /* FIXME */ MacroDefId,
108 hir_ty::display::HirDisplay,
111 // These are negative re-exports: pub using these names is forbidden, they
112 // should remain private to hir internals.
116 hir_expand::{hygiene::Hygiene, name::AsName},
119 /// hir::Crate describes a single crate. It's the main interface with which
120 /// a crate's dependencies interact. Mostly, it should be just a proxy for the
122 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
124 pub(crate) id: CrateId,
128 pub struct CrateDependency {
134 pub fn dependencies(self, db: &dyn HirDatabase) -> Vec<CrateDependency> {
135 db.crate_graph()[self.id]
139 let krate = Crate { id: dep.crate_id };
140 let name = dep.as_name();
141 CrateDependency { krate, name }
146 pub fn reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
147 let crate_graph = db.crate_graph();
151 crate_graph[krate].dependencies.iter().any(|it| it.crate_id == self.id)
153 .map(|id| Crate { id })
157 pub fn transitive_reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
158 db.crate_graph().transitive_rev_deps(self.id).into_iter().map(|id| Crate { id }).collect()
161 pub fn root_module(self, db: &dyn HirDatabase) -> Module {
162 let def_map = db.crate_def_map(self.id);
163 Module { id: def_map.module_id(def_map.root()) }
166 pub fn root_file(self, db: &dyn HirDatabase) -> FileId {
167 db.crate_graph()[self.id].root_file_id
170 pub fn edition(self, db: &dyn HirDatabase) -> Edition {
171 db.crate_graph()[self.id].edition
174 pub fn display_name(self, db: &dyn HirDatabase) -> Option<CrateDisplayName> {
175 db.crate_graph()[self.id].display_name.clone()
178 pub fn query_external_importables(
180 db: &dyn DefDatabase,
181 query: import_map::Query,
182 ) -> impl Iterator<Item = Either<ModuleDef, MacroDef>> {
183 import_map::search_dependencies(db, self.into(), query).into_iter().map(|item| match item {
184 ItemInNs::Types(mod_id) | ItemInNs::Values(mod_id) => Either::Left(mod_id.into()),
185 ItemInNs::Macros(mac_id) => Either::Right(mac_id.into()),
189 pub fn all(db: &dyn HirDatabase) -> Vec<Crate> {
190 db.crate_graph().iter().map(|id| Crate { id }).collect()
193 /// Try to get the root URL of the documentation of a crate.
194 pub fn get_html_root_url(self: &Crate, db: &dyn HirDatabase) -> Option<String> {
195 // Look for #![doc(html_root_url = "...")]
196 let attrs = db.attrs(AttrDefId::ModuleId(self.root_module(db).into()));
197 let doc_attr_q = attrs.by_key("doc");
199 if !doc_attr_q.exists() {
203 let doc_url = doc_attr_q.tt_values().map(|tt| {
204 let name = tt.token_trees.iter()
205 .skip_while(|tt| !matches!(tt, TokenTree::Leaf(Leaf::Ident(Ident{text: ref ident, ..})) if ident == "html_root_url"))
210 Some(TokenTree::Leaf(Leaf::Literal(Literal{ref text, ..}))) => Some(text),
215 doc_url.map(|s| s.trim_matches('"').trim_end_matches('/').to_owned() + "/")
219 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
221 pub(crate) id: ModuleId,
224 /// The defs which can be visible in the module.
225 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
230 // Can't be directly declared, but can be imported.
235 TypeAlias(TypeAlias),
236 BuiltinType(BuiltinType),
241 Adt(Struct, Enum, Union),
251 impl From<VariantDef> for ModuleDef {
252 fn from(var: VariantDef) -> Self {
254 VariantDef::Struct(t) => Adt::from(t).into(),
255 VariantDef::Union(t) => Adt::from(t).into(),
256 VariantDef::Variant(t) => t.into(),
262 pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
264 ModuleDef::Module(it) => it.parent(db),
265 ModuleDef::Function(it) => Some(it.module(db)),
266 ModuleDef::Adt(it) => Some(it.module(db)),
267 ModuleDef::Variant(it) => Some(it.module(db)),
268 ModuleDef::Const(it) => Some(it.module(db)),
269 ModuleDef::Static(it) => Some(it.module(db)),
270 ModuleDef::Trait(it) => Some(it.module(db)),
271 ModuleDef::TypeAlias(it) => Some(it.module(db)),
272 ModuleDef::BuiltinType(_) => None,
276 pub fn canonical_path(&self, db: &dyn HirDatabase) -> Option<String> {
277 let mut segments = vec![self.name(db)?.to_string()];
278 for m in self.module(db)?.path_to_root(db) {
279 segments.extend(m.name(db).map(|it| it.to_string()))
282 Some(segments.join("::"))
285 pub fn definition_visibility(&self, db: &dyn HirDatabase) -> Option<Visibility> {
286 let module = match self {
287 ModuleDef::Module(it) => it.parent(db)?,
288 ModuleDef::Function(it) => return Some(it.visibility(db)),
289 ModuleDef::Adt(it) => it.module(db),
290 ModuleDef::Variant(it) => {
291 let parent = it.parent_enum(db);
292 let module = it.module(db);
293 return module.visibility_of(db, &ModuleDef::Adt(Adt::Enum(parent)));
295 ModuleDef::Const(it) => return Some(it.visibility(db)),
296 ModuleDef::Static(it) => it.module(db),
297 ModuleDef::Trait(it) => it.module(db),
298 ModuleDef::TypeAlias(it) => return Some(it.visibility(db)),
299 ModuleDef::BuiltinType(_) => return None,
302 module.visibility_of(db, self)
305 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
307 ModuleDef::Adt(it) => Some(it.name(db)),
308 ModuleDef::Trait(it) => Some(it.name(db)),
309 ModuleDef::Function(it) => Some(it.name(db)),
310 ModuleDef::Variant(it) => Some(it.name(db)),
311 ModuleDef::TypeAlias(it) => Some(it.name(db)),
312 ModuleDef::Module(it) => it.name(db),
313 ModuleDef::Const(it) => it.name(db),
314 ModuleDef::Static(it) => it.name(db),
315 ModuleDef::BuiltinType(it) => Some(it.name()),
319 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
320 let id = match self {
321 ModuleDef::Adt(it) => match it {
322 Adt::Struct(it) => it.id.into(),
323 Adt::Enum(it) => it.id.into(),
324 Adt::Union(it) => it.id.into(),
326 ModuleDef::Trait(it) => it.id.into(),
327 ModuleDef::Function(it) => it.id.into(),
328 ModuleDef::TypeAlias(it) => it.id.into(),
329 ModuleDef::Module(it) => it.id.into(),
330 ModuleDef::Const(it) => it.id.into(),
331 ModuleDef::Static(it) => it.id.into(),
335 let module = match self.module(db) {
340 hir_ty::diagnostics::validate_module_item(db, module.id.krate(), id, sink)
345 /// Name of this module.
346 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
347 let def_map = self.id.def_map(db.upcast());
348 let parent = def_map[self.id.local_id].parent?;
349 def_map[parent].children.iter().find_map(|(name, module_id)| {
350 if *module_id == self.id.local_id {
358 /// Returns the crate this module is part of.
359 pub fn krate(self) -> Crate {
360 Crate { id: self.id.krate() }
363 /// Topmost parent of this module. Every module has a `crate_root`, but some
364 /// might be missing `krate`. This can happen if a module's file is not included
365 /// in the module tree of any target in `Cargo.toml`.
366 pub fn crate_root(self, db: &dyn HirDatabase) -> Module {
367 let def_map = db.crate_def_map(self.id.krate());
368 Module { id: def_map.module_id(def_map.root()) }
371 /// Iterates over all child modules.
372 pub fn children(self, db: &dyn HirDatabase) -> impl Iterator<Item = Module> {
373 let def_map = self.id.def_map(db.upcast());
374 let children = def_map[self.id.local_id]
377 .map(|(_, module_id)| Module { id: def_map.module_id(*module_id) })
378 .collect::<Vec<_>>();
382 /// Finds a parent module.
383 pub fn parent(self, db: &dyn HirDatabase) -> Option<Module> {
384 // FIXME: handle block expressions as modules (their parent is in a different DefMap)
385 let def_map = self.id.def_map(db.upcast());
386 let parent_id = def_map[self.id.local_id].parent?;
387 Some(Module { id: def_map.module_id(parent_id) })
390 pub fn path_to_root(self, db: &dyn HirDatabase) -> Vec<Module> {
391 let mut res = vec![self];
393 while let Some(next) = curr.parent(db) {
400 /// Returns a `ModuleScope`: a set of items, visible in this module.
403 db: &dyn HirDatabase,
404 visible_from: Option<Module>,
405 ) -> Vec<(Name, ScopeDef)> {
406 self.id.def_map(db.upcast())[self.id.local_id]
409 .filter_map(|(name, def)| {
410 if let Some(m) = visible_from {
412 def.filter_visibility(|vis| vis.is_visible_from(db.upcast(), m.id));
413 if filtered.is_none() && !def.is_none() {
416 Some((name, filtered))
422 .flat_map(|(name, def)| {
423 ScopeDef::all_items(def).into_iter().map(move |item| (name.clone(), item))
428 pub fn visibility_of(self, db: &dyn HirDatabase, def: &ModuleDef) -> Option<Visibility> {
429 self.id.def_map(db.upcast())[self.id.local_id].scope.visibility_of(def.clone().into())
432 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
433 let _p = profile::span("Module::diagnostics").detail(|| {
434 format!("{:?}", self.name(db).map_or("<unknown>".into(), |name| name.to_string()))
436 let def_map = self.id.def_map(db.upcast());
437 def_map.add_diagnostics(db.upcast(), self.id.local_id, sink);
438 for decl in self.declarations(db) {
440 crate::ModuleDef::Function(f) => f.diagnostics(db, sink),
441 crate::ModuleDef::Module(m) => {
442 // Only add diagnostics from inline modules
443 if def_map[m.id.local_id].origin.is_inline() {
444 m.diagnostics(db, sink)
448 decl.diagnostics(db, sink);
453 for impl_def in self.impl_defs(db) {
454 for item in impl_def.items(db) {
455 if let AssocItem::Function(f) = item {
456 f.diagnostics(db, sink);
462 pub fn declarations(self, db: &dyn HirDatabase) -> Vec<ModuleDef> {
463 let def_map = self.id.def_map(db.upcast());
464 def_map[self.id.local_id].scope.declarations().map(ModuleDef::from).collect()
467 pub fn impl_defs(self, db: &dyn HirDatabase) -> Vec<Impl> {
468 let def_map = self.id.def_map(db.upcast());
469 def_map[self.id.local_id].scope.impls().map(Impl::from).collect()
472 /// Finds a path that can be used to refer to the given item from within
473 /// this module, if possible.
474 pub fn find_use_path(self, db: &dyn DefDatabase, item: impl Into<ItemInNs>) -> Option<ModPath> {
475 hir_def::find_path::find_path(db, item.into(), self.into())
478 /// Finds a path that can be used to refer to the given item from within
479 /// this module, if possible. This is used for returning import paths for use-statements.
480 pub fn find_use_path_prefixed(
482 db: &dyn DefDatabase,
483 item: impl Into<ItemInNs>,
484 prefix_kind: PrefixKind,
485 ) -> Option<ModPath> {
486 hir_def::find_path::find_path_prefixed(db, item.into(), self.into(), prefix_kind)
490 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
492 pub(crate) parent: VariantDef,
493 pub(crate) id: LocalFieldId,
496 #[derive(Debug, PartialEq, Eq)]
497 pub enum FieldSource {
498 Named(ast::RecordField),
499 Pos(ast::TupleField),
503 pub fn name(&self, db: &dyn HirDatabase) -> Name {
504 self.parent.variant_data(db).fields()[self.id].name.clone()
507 /// Returns the type as in the signature of the struct (i.e., with
508 /// placeholder types for type parameters). This is good for showing
509 /// signature help, but not so good to actually get the type of the field
510 /// when you actually have a variable of the struct.
511 pub fn signature_ty(&self, db: &dyn HirDatabase) -> Type {
512 let var_id = self.parent.into();
513 let generic_def_id: GenericDefId = match self.parent {
514 VariantDef::Struct(it) => it.id.into(),
515 VariantDef::Union(it) => it.id.into(),
516 VariantDef::Variant(it) => it.parent.id.into(),
518 let substs = TyBuilder::type_params_subst(db, generic_def_id);
519 let ty = db.field_types(var_id)[self.id].clone().subst(&substs);
520 Type::new(db, self.parent.module(db).id.krate(), var_id, ty)
523 pub fn parent_def(&self, _db: &dyn HirDatabase) -> VariantDef {
528 impl HasVisibility for Field {
529 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
530 let variant_data = self.parent.variant_data(db);
531 let visibility = &variant_data.fields()[self.id].visibility;
532 let parent_id: hir_def::VariantId = self.parent.into();
533 visibility.resolve(db.upcast(), &parent_id.resolver(db.upcast()))
537 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
539 pub(crate) id: StructId,
543 pub fn module(self, db: &dyn HirDatabase) -> Module {
544 Module { id: self.id.lookup(db.upcast()).container }
547 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
548 Some(self.module(db).krate())
551 pub fn name(self, db: &dyn HirDatabase) -> Name {
552 db.struct_data(self.id).name.clone()
555 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
556 db.struct_data(self.id)
560 .map(|(id, _)| Field { parent: self.into(), id })
564 pub fn ty(self, db: &dyn HirDatabase) -> Type {
565 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
568 pub fn repr(self, db: &dyn HirDatabase) -> Option<ReprKind> {
569 db.struct_data(self.id).repr.clone()
572 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
573 self.variant_data(db).kind()
576 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
577 db.struct_data(self.id).variant_data.clone()
581 impl HasVisibility for Struct {
582 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
583 db.struct_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
587 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
589 pub(crate) id: UnionId,
593 pub fn name(self, db: &dyn HirDatabase) -> Name {
594 db.union_data(self.id).name.clone()
597 pub fn module(self, db: &dyn HirDatabase) -> Module {
598 Module { id: self.id.lookup(db.upcast()).container }
601 pub fn ty(self, db: &dyn HirDatabase) -> Type {
602 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
605 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
606 db.union_data(self.id)
610 .map(|(id, _)| Field { parent: self.into(), id })
614 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
615 db.union_data(self.id).variant_data.clone()
619 impl HasVisibility for Union {
620 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
621 db.union_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
625 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
627 pub(crate) id: EnumId,
631 pub fn module(self, db: &dyn HirDatabase) -> Module {
632 Module { id: self.id.lookup(db.upcast()).container }
635 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
636 Some(self.module(db).krate())
639 pub fn name(self, db: &dyn HirDatabase) -> Name {
640 db.enum_data(self.id).name.clone()
643 pub fn variants(self, db: &dyn HirDatabase) -> Vec<Variant> {
644 db.enum_data(self.id).variants.iter().map(|(id, _)| Variant { parent: self, id }).collect()
647 pub fn ty(self, db: &dyn HirDatabase) -> Type {
648 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
652 impl HasVisibility for Enum {
653 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
654 db.enum_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
658 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
660 pub(crate) parent: Enum,
661 pub(crate) id: LocalEnumVariantId,
665 pub fn module(self, db: &dyn HirDatabase) -> Module {
666 self.parent.module(db)
668 pub fn parent_enum(self, _db: &dyn HirDatabase) -> Enum {
672 pub fn name(self, db: &dyn HirDatabase) -> Name {
673 db.enum_data(self.parent.id).variants[self.id].name.clone()
676 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
677 self.variant_data(db)
680 .map(|(id, _)| Field { parent: self.into(), id })
684 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
685 self.variant_data(db).kind()
688 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
689 db.enum_data(self.parent.id).variants[self.id].variant_data.clone()
694 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
700 impl_from!(Struct, Union, Enum for Adt);
703 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
704 let subst = db.generic_defaults(self.into());
705 subst.iter().any(|ty| ty.value.is_unknown())
708 /// Turns this ADT into a type. Any type parameters of the ADT will be
709 /// turned into unknown types, which is good for e.g. finding the most
710 /// general set of completions, but will not look very nice when printed.
711 pub fn ty(self, db: &dyn HirDatabase) -> Type {
712 let id = AdtId::from(self);
713 Type::from_def(db, id.module(db.upcast()).krate(), id)
716 pub fn module(self, db: &dyn HirDatabase) -> Module {
718 Adt::Struct(s) => s.module(db),
719 Adt::Union(s) => s.module(db),
720 Adt::Enum(e) => e.module(db),
724 pub fn krate(self, db: &dyn HirDatabase) -> Crate {
725 self.module(db).krate()
728 pub fn name(self, db: &dyn HirDatabase) -> Name {
730 Adt::Struct(s) => s.name(db),
731 Adt::Union(u) => u.name(db),
732 Adt::Enum(e) => e.name(db),
737 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
738 pub enum VariantDef {
743 impl_from!(Struct, Union, Variant for VariantDef);
746 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
748 VariantDef::Struct(it) => it.fields(db),
749 VariantDef::Union(it) => it.fields(db),
750 VariantDef::Variant(it) => it.fields(db),
754 pub fn module(self, db: &dyn HirDatabase) -> Module {
756 VariantDef::Struct(it) => it.module(db),
757 VariantDef::Union(it) => it.module(db),
758 VariantDef::Variant(it) => it.module(db),
762 pub fn name(&self, db: &dyn HirDatabase) -> Name {
764 VariantDef::Struct(s) => s.name(db),
765 VariantDef::Union(u) => u.name(db),
766 VariantDef::Variant(e) => e.name(db),
770 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
772 VariantDef::Struct(it) => it.variant_data(db),
773 VariantDef::Union(it) => it.variant_data(db),
774 VariantDef::Variant(it) => it.variant_data(db),
779 /// The defs which have a body.
780 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
781 pub enum DefWithBody {
786 impl_from!(Function, Const, Static for DefWithBody);
789 pub fn module(self, db: &dyn HirDatabase) -> Module {
791 DefWithBody::Const(c) => c.module(db),
792 DefWithBody::Function(f) => f.module(db),
793 DefWithBody::Static(s) => s.module(db),
797 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
799 DefWithBody::Function(f) => Some(f.name(db)),
800 DefWithBody::Static(s) => s.name(db),
801 DefWithBody::Const(c) => c.name(db),
806 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
807 pub struct Function {
808 pub(crate) id: FunctionId,
812 pub fn module(self, db: &dyn HirDatabase) -> Module {
813 self.id.lookup(db.upcast()).module(db.upcast()).into()
816 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
817 Some(self.module(db).krate())
820 pub fn name(self, db: &dyn HirDatabase) -> Name {
821 db.function_data(self.id).name.clone()
824 /// Get this function's return type
825 pub fn ret_type(self, db: &dyn HirDatabase) -> Type {
826 let resolver = self.id.resolver(db.upcast());
827 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
828 let ret_type = &db.function_data(self.id).ret_type;
829 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
830 let ty = ctx.lower_ty(ret_type);
831 Type::new_with_resolver_inner(db, krate, &resolver, ty)
834 pub fn self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
835 if !db.function_data(self.id).has_self_param() {
838 Some(SelfParam { func: self.id })
841 pub fn assoc_fn_params(self, db: &dyn HirDatabase) -> Vec<Param> {
842 let resolver = self.id.resolver(db.upcast());
843 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
844 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
845 let environment = db.trait_environment(self.id.into());
846 db.function_data(self.id)
850 .map(|(idx, type_ref)| {
851 let ty = Type { krate, env: environment.clone(), ty: ctx.lower_ty(type_ref) };
852 Param { func: self, ty, idx }
857 pub fn method_params(self, db: &dyn HirDatabase) -> Option<Vec<Param>> {
858 if self.self_param(db).is_none() {
861 let mut res = self.assoc_fn_params(db);
866 pub fn is_unsafe(self, db: &dyn HirDatabase) -> bool {
867 db.function_data(self.id).is_unsafe()
870 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
871 let krate = self.module(db).id.krate();
872 hir_def::diagnostics::validate_body(db.upcast(), self.id.into(), sink);
873 hir_ty::diagnostics::validate_module_item(db, krate, self.id.into(), sink);
874 hir_ty::diagnostics::validate_body(db, self.id.into(), sink);
877 /// Whether this function declaration has a definition.
879 /// This is false in the case of required (not provided) trait methods.
880 pub fn has_body(self, db: &dyn HirDatabase) -> bool {
881 db.function_data(self.id).has_body()
884 /// A textual representation of the HIR of this function for debugging purposes.
885 pub fn debug_hir(self, db: &dyn HirDatabase) -> String {
886 let body = db.body(self.id.into());
888 let mut result = String::new();
889 format_to!(result, "HIR expressions in the body of `{}`:\n", self.name(db));
890 for (id, expr) in body.exprs.iter() {
891 format_to!(result, "{:?}: {:?}\n", id, expr);
898 // Note: logically, this belongs to `hir_ty`, but we are not using it there yet.
905 impl From<hir_ty::Mutability> for Access {
906 fn from(mutability: hir_ty::Mutability) -> Access {
908 hir_ty::Mutability::Not => Access::Shared,
909 hir_ty::Mutability::Mut => Access::Exclusive,
914 #[derive(Clone, Debug)]
917 /// The index in parameter list, including self parameter.
923 pub fn ty(&self) -> &Type {
927 pub fn as_local(&self, db: &dyn HirDatabase) -> Local {
928 let parent = DefWithBodyId::FunctionId(self.func.into());
929 let body = db.body(parent);
930 Local { parent, pat_id: body.params[self.idx] }
933 pub fn pattern_source(&self, db: &dyn HirDatabase) -> Option<ast::Pat> {
934 self.source(db).and_then(|p| p.value.pat())
937 pub fn source(&self, db: &dyn HirDatabase) -> Option<InFile<ast::Param>> {
938 let InFile { file_id, value } = self.func.source(db)?;
939 let params = value.param_list()?;
940 if params.self_param().is_some() {
941 params.params().nth(self.idx.checked_sub(1)?)
943 params.params().nth(self.idx)
945 .map(|value| InFile { file_id, value })
949 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
950 pub struct SelfParam {
955 pub fn access(self, db: &dyn HirDatabase) -> Access {
956 let func_data = db.function_data(self.func);
960 .map(|param| match &**param {
961 TypeRef::Reference(.., mutability) => match mutability {
962 hir_def::type_ref::Mutability::Shared => Access::Shared,
963 hir_def::type_ref::Mutability::Mut => Access::Exclusive,
967 .unwrap_or(Access::Owned)
970 pub fn display(self, db: &dyn HirDatabase) -> &'static str {
971 match self.access(db) {
972 Access::Shared => "&self",
973 Access::Exclusive => "&mut self",
974 Access::Owned => "self",
978 pub fn source(&self, db: &dyn HirDatabase) -> Option<InFile<ast::SelfParam>> {
979 let InFile { file_id, value } = Function::from(self.func).source(db)?;
982 .and_then(|params| params.self_param())
983 .map(|value| InFile { file_id, value })
987 impl HasVisibility for Function {
988 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
989 let function_data = db.function_data(self.id);
990 let visibility = &function_data.visibility;
991 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
995 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
997 pub(crate) id: ConstId,
1001 pub fn module(self, db: &dyn HirDatabase) -> Module {
1002 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1005 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
1006 Some(self.module(db).krate())
1009 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1010 db.const_data(self.id).name.clone()
1013 pub fn type_ref(self, db: &dyn HirDatabase) -> TypeRef {
1014 db.const_data(self.id).type_ref.as_ref().clone()
1018 impl HasVisibility for Const {
1019 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1020 let function_data = db.const_data(self.id);
1021 let visibility = &function_data.visibility;
1022 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1026 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1028 pub(crate) id: StaticId,
1032 pub fn module(self, db: &dyn HirDatabase) -> Module {
1033 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1036 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
1037 Some(self.module(db).krate())
1040 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1041 db.static_data(self.id).name.clone()
1044 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
1045 db.static_data(self.id).mutable
1049 impl HasVisibility for Static {
1050 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1051 db.static_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1055 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1057 pub(crate) id: TraitId,
1061 pub fn module(self, db: &dyn HirDatabase) -> Module {
1062 Module { id: self.id.lookup(db.upcast()).container }
1065 pub fn name(self, db: &dyn HirDatabase) -> Name {
1066 db.trait_data(self.id).name.clone()
1069 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
1070 db.trait_data(self.id).items.iter().map(|(_name, it)| (*it).into()).collect()
1073 pub fn is_auto(self, db: &dyn HirDatabase) -> bool {
1074 db.trait_data(self.id).is_auto
1078 impl HasVisibility for Trait {
1079 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1080 db.trait_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1084 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1085 pub struct TypeAlias {
1086 pub(crate) id: TypeAliasId,
1090 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
1091 let subst = db.generic_defaults(self.id.into());
1092 subst.iter().any(|ty| ty.value.is_unknown())
1095 pub fn module(self, db: &dyn HirDatabase) -> Module {
1096 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1099 pub fn krate(self, db: &dyn HirDatabase) -> Crate {
1100 self.module(db).krate()
1103 pub fn type_ref(self, db: &dyn HirDatabase) -> Option<TypeRef> {
1104 db.type_alias_data(self.id).type_ref.as_deref().cloned()
1107 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1108 Type::from_def(db, self.id.lookup(db.upcast()).module(db.upcast()).krate(), self.id)
1111 pub fn name(self, db: &dyn HirDatabase) -> Name {
1112 db.type_alias_data(self.id).name.clone()
1116 impl HasVisibility for TypeAlias {
1117 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1118 let function_data = db.type_alias_data(self.id);
1119 let visibility = &function_data.visibility;
1120 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1124 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1125 pub struct BuiltinType {
1126 pub(crate) inner: hir_def::builtin_type::BuiltinType,
1130 pub fn ty(self, db: &dyn HirDatabase, module: Module) -> Type {
1131 let resolver = module.id.resolver(db.upcast());
1132 Type::new_with_resolver(db, &resolver, TyBuilder::builtin(self.inner))
1133 .expect("crate not present in resolver")
1136 pub fn name(self) -> Name {
1137 self.inner.as_name()
1141 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1142 pub enum MacroKind {
1149 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1150 pub struct MacroDef {
1151 pub(crate) id: MacroDefId,
1155 /// FIXME: right now, this just returns the root module of the crate that
1156 /// defines this macro. The reasons for this is that macros are expanded
1157 /// early, in `hir_expand`, where modules simply do not exist yet.
1158 pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
1159 let krate = self.id.krate;
1160 let def_map = db.crate_def_map(krate);
1161 let module_id = def_map.root();
1162 Some(Module { id: def_map.module_id(module_id) })
1165 /// XXX: this parses the file
1166 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1167 match self.source(db)?.value {
1168 Either::Left(it) => it.name().map(|it| it.as_name()),
1169 Either::Right(it) => it.name().map(|it| it.as_name()),
1173 pub fn kind(&self) -> MacroKind {
1174 match self.id.kind {
1175 MacroDefKind::Declarative(_) => MacroKind::Declarative,
1176 MacroDefKind::BuiltIn(_, _) => MacroKind::BuiltIn,
1177 MacroDefKind::BuiltInDerive(_, _) => MacroKind::Derive,
1178 MacroDefKind::BuiltInEager(_, _) => MacroKind::BuiltIn,
1179 // FIXME might be a derive
1180 MacroDefKind::ProcMacro(_, _) => MacroKind::ProcMacro,
1185 /// Invariant: `inner.as_assoc_item(db).is_some()`
1186 /// We do not actively enforce this invariant.
1187 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1188 pub enum AssocItem {
1191 TypeAlias(TypeAlias),
1194 pub enum AssocItemContainer {
1198 pub trait AsAssocItem {
1199 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem>;
1202 impl AsAssocItem for Function {
1203 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1204 as_assoc_item(db, AssocItem::Function, self.id)
1207 impl AsAssocItem for Const {
1208 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1209 as_assoc_item(db, AssocItem::Const, self.id)
1212 impl AsAssocItem for TypeAlias {
1213 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1214 as_assoc_item(db, AssocItem::TypeAlias, self.id)
1217 impl AsAssocItem for ModuleDef {
1218 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1220 ModuleDef::Function(it) => it.as_assoc_item(db),
1221 ModuleDef::Const(it) => it.as_assoc_item(db),
1222 ModuleDef::TypeAlias(it) => it.as_assoc_item(db),
1227 fn as_assoc_item<ID, DEF, CTOR, AST>(db: &dyn HirDatabase, ctor: CTOR, id: ID) -> Option<AssocItem>
1229 ID: Lookup<Data = AssocItemLoc<AST>>,
1231 CTOR: FnOnce(DEF) -> AssocItem,
1234 match id.lookup(db.upcast()).container {
1235 AssocContainerId::TraitId(_) | AssocContainerId::ImplId(_) => Some(ctor(DEF::from(id))),
1236 AssocContainerId::ModuleId(_) => None,
1241 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1243 AssocItem::Function(it) => Some(it.name(db)),
1244 AssocItem::Const(it) => it.name(db),
1245 AssocItem::TypeAlias(it) => Some(it.name(db)),
1248 pub fn module(self, db: &dyn HirDatabase) -> Module {
1250 AssocItem::Function(f) => f.module(db),
1251 AssocItem::Const(c) => c.module(db),
1252 AssocItem::TypeAlias(t) => t.module(db),
1255 pub fn container(self, db: &dyn HirDatabase) -> AssocItemContainer {
1256 let container = match self {
1257 AssocItem::Function(it) => it.id.lookup(db.upcast()).container,
1258 AssocItem::Const(it) => it.id.lookup(db.upcast()).container,
1259 AssocItem::TypeAlias(it) => it.id.lookup(db.upcast()).container,
1262 AssocContainerId::TraitId(id) => AssocItemContainer::Trait(id.into()),
1263 AssocContainerId::ImplId(id) => AssocItemContainer::Impl(id.into()),
1264 AssocContainerId::ModuleId(_) => panic!("invalid AssocItem"),
1268 pub fn containing_trait(self, db: &dyn HirDatabase) -> Option<Trait> {
1269 match self.container(db) {
1270 AssocItemContainer::Trait(t) => Some(t),
1276 impl HasVisibility for AssocItem {
1277 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1279 AssocItem::Function(f) => f.visibility(db),
1280 AssocItem::Const(c) => c.visibility(db),
1281 AssocItem::TypeAlias(t) => t.visibility(db),
1286 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
1287 pub enum GenericDef {
1291 TypeAlias(TypeAlias),
1293 // enum variants cannot have generics themselves, but their parent enums
1294 // can, and this makes some code easier to write
1296 // consts can have type parameters from their parents (i.e. associated consts of traits)
1301 Adt(Struct, Enum, Union),
1311 pub fn params(self, db: &dyn HirDatabase) -> Vec<GenericParam> {
1312 let generics = db.generic_params(self.into());
1313 let ty_params = generics
1316 .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
1317 .map(GenericParam::TypeParam);
1318 let lt_params = generics
1321 .map(|(local_id, _)| LifetimeParam {
1322 id: LifetimeParamId { parent: self.into(), local_id },
1324 .map(GenericParam::LifetimeParam);
1325 let const_params = generics
1328 .map(|(local_id, _)| ConstParam { id: ConstParamId { parent: self.into(), local_id } })
1329 .map(GenericParam::ConstParam);
1330 ty_params.chain(lt_params).chain(const_params).collect()
1333 pub fn type_params(self, db: &dyn HirDatabase) -> Vec<TypeParam> {
1334 let generics = db.generic_params(self.into());
1338 .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
1343 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1345 pub(crate) parent: DefWithBodyId,
1346 pub(crate) pat_id: PatId,
1350 pub fn is_param(self, db: &dyn HirDatabase) -> bool {
1351 let src = self.source(db);
1353 Either::Left(bind_pat) => {
1354 bind_pat.syntax().ancestors().any(|it| ast::Param::can_cast(it.kind()))
1356 Either::Right(_self_param) => true,
1360 pub fn as_self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
1362 DefWithBodyId::FunctionId(func) if self.is_self(db) => Some(SelfParam { func }),
1367 // FIXME: why is this an option? It shouldn't be?
1368 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1369 let body = db.body(self.parent);
1370 match &body[self.pat_id] {
1371 Pat::Bind { name, .. } => Some(name.clone()),
1376 pub fn is_self(self, db: &dyn HirDatabase) -> bool {
1377 self.name(db) == Some(name![self])
1380 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
1381 let body = db.body(self.parent);
1382 matches!(&body[self.pat_id], Pat::Bind { mode: BindingAnnotation::Mutable, .. })
1385 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
1389 pub fn module(self, db: &dyn HirDatabase) -> Module {
1390 self.parent(db).module(db)
1393 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1394 let def = self.parent;
1395 let infer = db.infer(def);
1396 let ty = infer[self.pat_id].clone();
1397 let krate = def.module(db.upcast()).krate();
1398 Type::new(db, krate, def, ty)
1401 pub fn source(self, db: &dyn HirDatabase) -> InFile<Either<ast::IdentPat, ast::SelfParam>> {
1402 let (_body, source_map) = db.body_with_source_map(self.parent);
1403 let src = source_map.pat_syntax(self.pat_id).unwrap(); // Hmm...
1404 let root = src.file_syntax(db.upcast());
1406 ast.map_left(|it| it.cast().unwrap().to_node(&root)).map_right(|it| it.to_node(&root))
1411 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1413 pub(crate) parent: DefWithBodyId,
1414 pub(crate) label_id: LabelId,
1418 pub fn module(self, db: &dyn HirDatabase) -> Module {
1419 self.parent(db).module(db)
1422 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
1426 pub fn name(self, db: &dyn HirDatabase) -> Name {
1427 let body = db.body(self.parent);
1428 body[self.label_id].name.clone()
1431 pub fn source(self, db: &dyn HirDatabase) -> InFile<ast::Label> {
1432 let (_body, source_map) = db.body_with_source_map(self.parent);
1433 let src = source_map.label_syntax(self.label_id);
1434 let root = src.file_syntax(db.upcast());
1435 src.map(|ast| ast.to_node(&root))
1439 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1440 pub enum GenericParam {
1441 TypeParam(TypeParam),
1442 LifetimeParam(LifetimeParam),
1443 ConstParam(ConstParam),
1445 impl_from!(TypeParam, LifetimeParam, ConstParam for GenericParam);
1448 pub fn module(self, db: &dyn HirDatabase) -> Module {
1450 GenericParam::TypeParam(it) => it.module(db),
1451 GenericParam::LifetimeParam(it) => it.module(db),
1452 GenericParam::ConstParam(it) => it.module(db),
1456 pub fn name(self, db: &dyn HirDatabase) -> Name {
1458 GenericParam::TypeParam(it) => it.name(db),
1459 GenericParam::LifetimeParam(it) => it.name(db),
1460 GenericParam::ConstParam(it) => it.name(db),
1465 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1466 pub struct TypeParam {
1467 pub(crate) id: TypeParamId,
1471 pub fn name(self, db: &dyn HirDatabase) -> Name {
1472 let params = db.generic_params(self.id.parent);
1473 params.types[self.id.local_id].name.clone().unwrap_or_else(Name::missing)
1476 pub fn module(self, db: &dyn HirDatabase) -> Module {
1477 self.id.parent.module(db.upcast()).into()
1480 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1481 let resolver = self.id.parent.resolver(db.upcast());
1482 let krate = self.id.parent.module(db.upcast()).krate();
1483 let ty = TyKind::Placeholder(hir_ty::to_placeholder_idx(db, self.id)).intern(&Interner);
1484 Type::new_with_resolver_inner(db, krate, &resolver, ty)
1487 pub fn trait_bounds(self, db: &dyn HirDatabase) -> Vec<Trait> {
1488 db.generic_predicates_for_param(self.id)
1490 .filter_map(|pred| match &pred.skip_binders().skip_binders() {
1491 hir_ty::WhereClause::Implemented(trait_ref) => {
1492 Some(Trait::from(trait_ref.hir_trait_id()))
1499 pub fn default(self, db: &dyn HirDatabase) -> Option<Type> {
1500 let params = db.generic_defaults(self.id.parent);
1501 let local_idx = hir_ty::param_idx(db, self.id)?;
1502 let resolver = self.id.parent.resolver(db.upcast());
1503 let krate = self.id.parent.module(db.upcast()).krate();
1504 let ty = params.get(local_idx)?.clone();
1505 let subst = TyBuilder::type_params_subst(db, self.id.parent);
1506 let ty = ty.subst(&subst.prefix(local_idx));
1507 Some(Type::new_with_resolver_inner(db, krate, &resolver, ty))
1511 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1512 pub struct LifetimeParam {
1513 pub(crate) id: LifetimeParamId,
1516 impl LifetimeParam {
1517 pub fn name(self, db: &dyn HirDatabase) -> Name {
1518 let params = db.generic_params(self.id.parent);
1519 params.lifetimes[self.id.local_id].name.clone()
1522 pub fn module(self, db: &dyn HirDatabase) -> Module {
1523 self.id.parent.module(db.upcast()).into()
1526 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
1527 self.id.parent.into()
1531 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1532 pub struct ConstParam {
1533 pub(crate) id: ConstParamId,
1537 pub fn name(self, db: &dyn HirDatabase) -> Name {
1538 let params = db.generic_params(self.id.parent);
1539 params.consts[self.id.local_id].name.clone()
1542 pub fn module(self, db: &dyn HirDatabase) -> Module {
1543 self.id.parent.module(db.upcast()).into()
1546 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
1547 self.id.parent.into()
1550 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1551 let def = self.id.parent;
1552 let krate = def.module(db.upcast()).krate();
1553 Type::new(db, krate, def, db.const_param_ty(self.id))
1557 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1559 pub(crate) id: ImplId,
1563 pub fn all_in_crate(db: &dyn HirDatabase, krate: Crate) -> Vec<Impl> {
1564 let inherent = db.inherent_impls_in_crate(krate.id);
1565 let trait_ = db.trait_impls_in_crate(krate.id);
1567 inherent.all_impls().chain(trait_.all_impls()).map(Self::from).collect()
1570 pub fn all_for_type(db: &dyn HirDatabase, Type { krate, ty, .. }: Type) -> Vec<Impl> {
1571 let def_crates = match ty.def_crates(db, krate) {
1572 Some(def_crates) => def_crates,
1573 None => return Vec::new(),
1576 let filter = |impl_def: &Impl| {
1577 let self_ty = impl_def.self_ty(db);
1578 let rref = self_ty.remove_ref();
1579 ty.equals_ctor(rref.as_ref().map_or(&self_ty.ty, |it| &it.ty))
1582 let mut all = Vec::new();
1583 def_crates.iter().for_each(|&id| {
1584 all.extend(db.inherent_impls_in_crate(id).all_impls().map(Self::from).filter(filter))
1586 let fp = TyFingerprint::for_impl(&ty);
1587 for id in def_crates
1589 .flat_map(|&id| Crate { id }.transitive_reverse_dependencies(db))
1590 .map(|Crate { id }| id)
1591 .chain(def_crates.iter().copied())
1595 Some(fp) => all.extend(
1596 db.trait_impls_in_crate(id).for_self_ty(fp).map(Self::from).filter(filter),
1599 .extend(db.trait_impls_in_crate(id).all_impls().map(Self::from).filter(filter)),
1605 pub fn all_for_trait(db: &dyn HirDatabase, trait_: Trait) -> Vec<Impl> {
1606 let krate = trait_.module(db).krate();
1607 let mut all = Vec::new();
1608 for Crate { id } in krate.transitive_reverse_dependencies(db).into_iter() {
1609 let impls = db.trait_impls_in_crate(id);
1610 all.extend(impls.for_trait(trait_.id).map(Self::from))
1615 // FIXME: the return type is wrong. This should be a hir version of
1616 // `TraitRef` (ie, resolved `TypeRef`).
1617 pub fn trait_(self, db: &dyn HirDatabase) -> Option<TraitRef> {
1618 db.impl_data(self.id).target_trait.as_deref().cloned()
1621 pub fn self_ty(self, db: &dyn HirDatabase) -> Type {
1622 let impl_data = db.impl_data(self.id);
1623 let resolver = self.id.resolver(db.upcast());
1624 let krate = self.id.lookup(db.upcast()).container.krate();
1625 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1626 let ty = ctx.lower_ty(&impl_data.self_ty);
1627 Type::new_with_resolver_inner(db, krate, &resolver, ty)
1630 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
1631 db.impl_data(self.id).items.iter().map(|it| (*it).into()).collect()
1634 pub fn is_negative(self, db: &dyn HirDatabase) -> bool {
1635 db.impl_data(self.id).is_negative
1638 pub fn module(self, db: &dyn HirDatabase) -> Module {
1639 self.id.lookup(db.upcast()).container.into()
1642 pub fn krate(self, db: &dyn HirDatabase) -> Crate {
1643 Crate { id: self.module(db).id.krate() }
1646 pub fn is_builtin_derive(self, db: &dyn HirDatabase) -> Option<InFile<ast::Attr>> {
1647 let src = self.source(db)?;
1648 let item = src.file_id.is_builtin_derive(db.upcast())?;
1649 let hygenic = hir_expand::hygiene::Hygiene::new(db.upcast(), item.file_id);
1651 // FIXME: handle `cfg_attr`
1656 let path = ModPath::from_src(it.path()?, &hygenic)?;
1657 if path.as_ident()?.to_string() == "derive" {
1665 Some(item.with_value(attr))
1669 #[derive(Clone, PartialEq, Eq, Debug)]
1672 env: Arc<TraitEnvironment>,
1677 pub(crate) fn new_with_resolver(
1678 db: &dyn HirDatabase,
1679 resolver: &Resolver,
1682 let krate = resolver.krate()?;
1683 Some(Type::new_with_resolver_inner(db, krate, resolver, ty))
1685 pub(crate) fn new_with_resolver_inner(
1686 db: &dyn HirDatabase,
1688 resolver: &Resolver,
1692 resolver.generic_def().map_or_else(Default::default, |d| db.trait_environment(d));
1693 Type { krate, env: environment, ty }
1696 fn new(db: &dyn HirDatabase, krate: CrateId, lexical_env: impl HasResolver, ty: Ty) -> Type {
1697 let resolver = lexical_env.resolver(db.upcast());
1699 resolver.generic_def().map_or_else(Default::default, |d| db.trait_environment(d));
1700 Type { krate, env: environment, ty }
1704 db: &dyn HirDatabase,
1706 def: impl HasResolver + Into<TyDefId>,
1708 let ty = TyBuilder::def_ty(db, def.into()).fill_with_unknown().build();
1709 Type::new(db, krate, def, ty)
1712 pub fn is_unit(&self) -> bool {
1713 matches!(self.ty.kind(&Interner), TyKind::Tuple(0, ..))
1715 pub fn is_bool(&self) -> bool {
1716 matches!(self.ty.kind(&Interner), TyKind::Scalar(Scalar::Bool))
1719 pub fn is_mutable_reference(&self) -> bool {
1720 matches!(self.ty.kind(&Interner), TyKind::Ref(hir_ty::Mutability::Mut, ..))
1723 pub fn is_usize(&self) -> bool {
1724 matches!(self.ty.kind(&Interner), TyKind::Scalar(Scalar::Uint(UintTy::Usize)))
1727 pub fn remove_ref(&self) -> Option<Type> {
1728 match &self.ty.kind(&Interner) {
1729 TyKind::Ref(.., ty) => Some(self.derived(ty.clone())),
1734 pub fn is_unknown(&self) -> bool {
1735 self.ty.is_unknown()
1738 /// Checks that particular type `ty` implements `std::future::Future`.
1739 /// This function is used in `.await` syntax completion.
1740 pub fn impls_future(&self, db: &dyn HirDatabase) -> bool {
1741 // No special case for the type of async block, since Chalk can figure it out.
1743 let krate = self.krate;
1745 let std_future_trait =
1746 db.lang_item(krate, "future_trait".into()).and_then(|it| it.as_trait());
1747 let std_future_trait = match std_future_trait {
1749 None => return false,
1753 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(&Interner) };
1754 method_resolution::implements_trait(
1763 /// Checks that particular type `ty` implements `std::ops::FnOnce`.
1765 /// This function can be used to check if a particular type is callable, since FnOnce is a
1766 /// supertrait of Fn and FnMut, so all callable types implements at least FnOnce.
1767 pub fn impls_fnonce(&self, db: &dyn HirDatabase) -> bool {
1768 let krate = self.krate;
1770 let fnonce_trait = match FnTrait::FnOnce.get_id(db, krate) {
1772 None => return false,
1776 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(&Interner) };
1777 method_resolution::implements_trait_unique(
1786 pub fn impls_trait(&self, db: &dyn HirDatabase, trait_: Trait, args: &[Type]) -> bool {
1787 let trait_ref = TyBuilder::trait_ref(db, trait_.id)
1788 .push(self.ty.clone())
1789 .fill(args.iter().map(|t| t.ty.clone()))
1792 let goal = Canonical {
1793 value: hir_ty::InEnvironment::new(self.env.env.clone(), trait_ref.cast(&Interner)),
1794 binders: CanonicalVarKinds::empty(&Interner),
1797 db.trait_solve(self.krate, goal).is_some()
1800 pub fn normalize_trait_assoc_type(
1802 db: &dyn HirDatabase,
1806 let projection = TyBuilder::assoc_type_projection(db, alias.id)
1807 .push(self.ty.clone())
1808 .fill(args.iter().map(|t| t.ty.clone()))
1810 let goal = Canonical::new(
1812 self.env.env.clone(),
1814 alias: AliasTy::Projection(projection),
1815 ty: TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0))
1820 [TyVariableKind::General].iter().copied(),
1823 match db.trait_solve(self.krate, goal)? {
1824 Solution::Unique(SolutionVariables(subst)) => subst
1828 .map(|ty| self.derived(ty.assert_ty_ref(&Interner).clone())),
1829 Solution::Ambig(_) => None,
1833 pub fn is_copy(&self, db: &dyn HirDatabase) -> bool {
1834 let lang_item = db.lang_item(self.krate, SmolStr::new("copy"));
1835 let copy_trait = match lang_item {
1836 Some(LangItemTarget::TraitId(it)) => it,
1839 self.impls_trait(db, copy_trait.into(), &[])
1842 pub fn as_callable(&self, db: &dyn HirDatabase) -> Option<Callable> {
1843 let def = self.ty.callable_def(db);
1845 let sig = self.ty.callable_sig(db)?;
1846 Some(Callable { ty: self.clone(), sig, def, is_bound_method: false })
1849 pub fn is_closure(&self) -> bool {
1850 matches!(&self.ty.kind(&Interner), TyKind::Closure { .. })
1853 pub fn is_fn(&self) -> bool {
1854 matches!(&self.ty.kind(&Interner), TyKind::FnDef(..) | TyKind::Function { .. })
1857 pub fn is_packed(&self, db: &dyn HirDatabase) -> bool {
1858 let adt_id = match self.ty.kind(&Interner) {
1859 &TyKind::Adt(hir_ty::AdtId(adt_id), ..) => adt_id,
1863 let adt = adt_id.into();
1865 Adt::Struct(s) => matches!(s.repr(db), Some(ReprKind::Packed)),
1870 pub fn is_raw_ptr(&self) -> bool {
1871 matches!(&self.ty.kind(&Interner), TyKind::Raw(..))
1874 pub fn contains_unknown(&self) -> bool {
1875 return go(&self.ty);
1877 fn go(ty: &Ty) -> bool {
1878 match ty.kind(&Interner) {
1879 TyKind::Error => true,
1881 TyKind::Adt(_, substs)
1882 | TyKind::AssociatedType(_, substs)
1883 | TyKind::Tuple(_, substs)
1884 | TyKind::OpaqueType(_, substs)
1885 | TyKind::FnDef(_, substs)
1886 | TyKind::Closure(_, substs) => {
1887 substs.iter(&Interner).filter_map(|a| a.ty(&Interner)).any(go)
1890 TyKind::Array(ty) | TyKind::Slice(ty) | TyKind::Raw(_, ty) | TyKind::Ref(_, ty) => {
1897 | TyKind::Placeholder(_)
1898 | TyKind::BoundVar(_)
1899 | TyKind::InferenceVar(_, _)
1901 | TyKind::Function(_)
1903 | TyKind::ForeignType(_) => false,
1908 pub fn fields(&self, db: &dyn HirDatabase) -> Vec<(Field, Type)> {
1909 let (variant_id, substs) = match self.ty.kind(&Interner) {
1910 &TyKind::Adt(hir_ty::AdtId(AdtId::StructId(s)), ref substs) => (s.into(), substs),
1911 &TyKind::Adt(hir_ty::AdtId(AdtId::UnionId(u)), ref substs) => (u.into(), substs),
1912 _ => return Vec::new(),
1915 db.field_types(variant_id)
1917 .map(|(local_id, ty)| {
1918 let def = Field { parent: variant_id.into(), id: local_id };
1919 let ty = ty.clone().subst(substs);
1920 (def, self.derived(ty))
1925 pub fn tuple_fields(&self, _db: &dyn HirDatabase) -> Vec<Type> {
1926 if let TyKind::Tuple(_, substs) = &self.ty.kind(&Interner) {
1929 .map(|ty| self.derived(ty.assert_ty_ref(&Interner).clone()))
1936 pub fn autoderef<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Type> + 'a {
1937 // There should be no inference vars in types passed here
1938 // FIXME check that?
1940 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(&Interner) };
1941 let environment = self.env.env.clone();
1942 let ty = InEnvironment { goal: canonical, environment };
1943 autoderef(db, Some(self.krate), ty)
1944 .map(|canonical| canonical.value)
1945 .map(move |ty| self.derived(ty))
1948 // This would be nicer if it just returned an iterator, but that runs into
1949 // lifetime problems, because we need to borrow temp `CrateImplDefs`.
1950 pub fn iterate_assoc_items<T>(
1952 db: &dyn HirDatabase,
1954 mut callback: impl FnMut(AssocItem) -> Option<T>,
1956 for krate in self.ty.def_crates(db, krate.id)? {
1957 let impls = db.inherent_impls_in_crate(krate);
1959 for impl_def in impls.for_self_ty(&self.ty) {
1960 for &item in db.impl_data(*impl_def).items.iter() {
1961 if let Some(result) = callback(item.into()) {
1962 return Some(result);
1970 pub fn type_parameters(&self) -> impl Iterator<Item = Type> + '_ {
1975 .flat_map(|substs| substs.iter(&Interner))
1976 .filter_map(|arg| arg.ty(&Interner).cloned())
1977 .map(move |ty| self.derived(ty))
1980 pub fn iterate_method_candidates<T>(
1982 db: &dyn HirDatabase,
1984 traits_in_scope: &FxHashSet<TraitId>,
1985 name: Option<&Name>,
1986 mut callback: impl FnMut(&Ty, Function) -> Option<T>,
1988 // There should be no inference vars in types passed here
1989 // FIXME check that?
1990 // FIXME replace Unknown by bound vars here
1992 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(&Interner) };
1994 let env = self.env.clone();
1995 let krate = krate.id;
1997 method_resolution::iterate_method_candidates(
2005 method_resolution::LookupMode::MethodCall,
2007 AssocItemId::FunctionId(f) => callback(ty, f.into()),
2013 pub fn iterate_path_candidates<T>(
2015 db: &dyn HirDatabase,
2017 traits_in_scope: &FxHashSet<TraitId>,
2018 name: Option<&Name>,
2019 mut callback: impl FnMut(&Ty, AssocItem) -> Option<T>,
2021 // There should be no inference vars in types passed here
2022 // FIXME check that?
2023 // FIXME replace Unknown by bound vars here
2025 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(&Interner) };
2027 let env = self.env.clone();
2028 let krate = krate.id;
2030 method_resolution::iterate_method_candidates(
2038 method_resolution::LookupMode::Path,
2039 |ty, it| callback(ty, it.into()),
2043 pub fn as_adt(&self) -> Option<Adt> {
2044 let (adt, _subst) = self.ty.as_adt()?;
2048 pub fn as_dyn_trait(&self) -> Option<Trait> {
2049 self.ty.dyn_trait().map(Into::into)
2052 pub fn as_impl_traits(&self, db: &dyn HirDatabase) -> Option<Vec<Trait>> {
2053 self.ty.impl_trait_bounds(db).map(|it| {
2055 .filter_map(|pred| match pred.skip_binders() {
2056 hir_ty::WhereClause::Implemented(trait_ref) => {
2057 Some(Trait::from(trait_ref.hir_trait_id()))
2065 pub fn as_associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<Trait> {
2066 self.ty.associated_type_parent_trait(db).map(Into::into)
2069 fn derived(&self, ty: Ty) -> Type {
2070 Type { krate: self.krate, env: self.env.clone(), ty }
2073 pub fn walk(&self, db: &dyn HirDatabase, mut cb: impl FnMut(Type)) {
2074 // TypeWalk::walk for a Ty at first visits parameters and only after that the Ty itself.
2075 // We need a different order here.
2078 db: &dyn HirDatabase,
2080 substs: &Substitution,
2081 cb: &mut impl FnMut(Type),
2083 for ty in substs.iter(&Interner).filter_map(|a| a.ty(&Interner)) {
2084 walk_type(db, &type_.derived(ty.clone()), cb);
2089 db: &dyn HirDatabase,
2091 bounds: &[QuantifiedWhereClause],
2092 cb: &mut impl FnMut(Type),
2094 for pred in bounds {
2095 match pred.skip_binders() {
2096 WhereClause::Implemented(trait_ref) => {
2098 // skip the self type. it's likely the type we just got the bounds from
2103 .filter_map(|a| a.ty(&Interner))
2105 walk_type(db, &type_.derived(ty.clone()), cb);
2113 fn walk_type(db: &dyn HirDatabase, type_: &Type, cb: &mut impl FnMut(Type)) {
2114 let ty = type_.ty.strip_references();
2115 match ty.kind(&Interner) {
2116 TyKind::Adt(..) => {
2117 cb(type_.derived(ty.clone()));
2119 TyKind::AssociatedType(..) => {
2120 if let Some(_) = ty.associated_type_parent_trait(db) {
2121 cb(type_.derived(ty.clone()));
2124 TyKind::OpaqueType(..) => {
2125 if let Some(bounds) = ty.impl_trait_bounds(db) {
2126 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
2129 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
2130 if let Some(bounds) = ty.impl_trait_bounds(db) {
2131 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
2134 walk_substs(db, type_, &opaque_ty.substitution, cb);
2136 TyKind::Placeholder(_) => {
2137 if let Some(bounds) = ty.impl_trait_bounds(db) {
2138 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
2141 TyKind::Dyn(bounds) => {
2144 &type_.derived(ty.clone()),
2145 bounds.bounds.skip_binders().interned(),
2150 TyKind::Ref(_, ty) | TyKind::Raw(_, ty) | TyKind::Array(ty) | TyKind::Slice(ty) => {
2151 walk_type(db, &type_.derived(ty.clone()), cb);
2156 if let Some(substs) = ty.substs() {
2157 walk_substs(db, type_, &substs, cb);
2161 walk_type(db, self, &mut cb);
2164 pub fn could_unify_with(&self, other: &Type) -> bool {
2165 could_unify(&self.ty, &other.ty)
2171 pub struct Callable {
2174 def: Option<CallableDefId>,
2175 pub(crate) is_bound_method: bool,
2178 pub enum CallableKind {
2180 TupleStruct(Struct),
2181 TupleEnumVariant(Variant),
2186 pub fn kind(&self) -> CallableKind {
2188 Some(CallableDefId::FunctionId(it)) => CallableKind::Function(it.into()),
2189 Some(CallableDefId::StructId(it)) => CallableKind::TupleStruct(it.into()),
2190 Some(CallableDefId::EnumVariantId(it)) => CallableKind::TupleEnumVariant(it.into()),
2191 None => CallableKind::Closure,
2194 pub fn receiver_param(&self, db: &dyn HirDatabase) -> Option<ast::SelfParam> {
2195 let func = match self.def {
2196 Some(CallableDefId::FunctionId(it)) if self.is_bound_method => it,
2199 let src = func.lookup(db.upcast()).source(db.upcast());
2200 let param_list = src.value.param_list()?;
2201 param_list.self_param()
2203 pub fn n_params(&self) -> usize {
2204 self.sig.params().len() - if self.is_bound_method { 1 } else { 0 }
2208 db: &dyn HirDatabase,
2209 ) -> Vec<(Option<Either<ast::SelfParam, ast::Pat>>, Type)> {
2214 .skip(if self.is_bound_method { 1 } else { 0 })
2215 .map(|ty| self.ty.derived(ty.clone()));
2216 let patterns = match self.def {
2217 Some(CallableDefId::FunctionId(func)) => {
2218 let src = func.lookup(db.upcast()).source(db.upcast());
2219 src.value.param_list().map(|param_list| {
2222 .map(|it| Some(Either::Left(it)))
2223 .filter(|_| !self.is_bound_method)
2225 .chain(param_list.params().map(|it| it.pat().map(Either::Right)))
2230 patterns.into_iter().flatten().chain(iter::repeat(None)).zip(types).collect()
2232 pub fn return_type(&self) -> Type {
2233 self.ty.derived(self.sig.ret().clone())
2238 #[derive(Debug, PartialEq, Eq, Hash)]
2240 ModuleDef(ModuleDef),
2242 GenericParam(GenericParam),
2251 pub fn all_items(def: PerNs) -> ArrayVec<Self, 3> {
2252 let mut items = ArrayVec::new();
2254 match (def.take_types(), def.take_values()) {
2255 (Some(m1), None) => items.push(ScopeDef::ModuleDef(m1.into())),
2256 (None, Some(m2)) => items.push(ScopeDef::ModuleDef(m2.into())),
2257 (Some(m1), Some(m2)) => {
2258 // Some items, like unit structs and enum variants, are
2259 // returned as both a type and a value. Here we want
2260 // to de-duplicate them.
2262 items.push(ScopeDef::ModuleDef(m1.into()));
2263 items.push(ScopeDef::ModuleDef(m2.into()));
2265 items.push(ScopeDef::ModuleDef(m1.into()));
2271 if let Some(macro_def_id) = def.take_macros() {
2272 items.push(ScopeDef::MacroDef(macro_def_id.into()));
2275 if items.is_empty() {
2276 items.push(ScopeDef::Unknown);
2283 impl From<ItemInNs> for ScopeDef {
2284 fn from(item: ItemInNs) -> Self {
2286 ItemInNs::Types(id) => ScopeDef::ModuleDef(id.into()),
2287 ItemInNs::Values(id) => ScopeDef::ModuleDef(id.into()),
2288 ItemInNs::Macros(id) => ScopeDef::MacroDef(id.into()),
2293 pub trait HasVisibility {
2294 fn visibility(&self, db: &dyn HirDatabase) -> Visibility;
2295 fn is_visible_from(&self, db: &dyn HirDatabase, module: Module) -> bool {
2296 let vis = self.visibility(db);
2297 vis.is_visible_from(db.upcast(), module.id)