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},
47 AdtId, AssocContainerId, AssocItemId, AssocItemLoc, AttrDefId, ConstId, ConstParamId,
48 DefWithBodyId, EnumId, FunctionId, GenericDefId, HasModule, ImplId, LifetimeParamId,
49 LocalEnumVariantId, LocalFieldId, Lookup, ModuleId, StaticId, StructId, TraitId, TypeAliasId,
52 use hir_expand::{diagnostics::DiagnosticSink, name::name, MacroDefKind};
55 method_resolution::{self, TyFingerprint},
58 traits::{FnTrait, Solution, SolutionVariables},
59 AliasEq, AliasTy, BoundVar, CallableDefId, CallableSig, Canonical, CanonicalVarKinds, Cast,
60 DebruijnIndex, InEnvironment, Interner, ProjectionTy, QuantifiedWhereClause, Scalar,
61 Substitution, TraitEnvironment, Ty, TyDefId, TyKind, TyVariableKind, WhereClause,
63 use itertools::Itertools;
64 use rustc_hash::FxHashSet;
65 use stdx::{format_to, impl_from};
67 ast::{self, AttrsOwner, NameOwner},
70 use tt::{Ident, Leaf, Literal, TokenTree};
72 use crate::db::{DefDatabase, HirDatabase};
75 attrs::{HasAttrs, Namespace},
76 has_source::HasSource,
77 semantics::{PathResolution, Semantics, SemanticsScope},
80 // Be careful with these re-exports.
82 // `hir` is the boundary between the compiler and the IDE. It should try hard to
83 // isolate the compiler from the ide, to allow the two to be refactored
84 // independently. Re-exporting something from the compiler is the sure way to
85 // breach the boundary.
87 // Generally, a refactoring which *removes* a name from this list is a good
92 attr::{Attr, Attrs, AttrsWithOwner, Documentation},
93 body::scope::ExprScopes,
94 find_path::PrefixKind,
97 nameres::ModuleSource,
98 path::{ModPath, PathKind},
99 type_ref::{Mutability, TypeRef},
100 visibility::Visibility,
104 ExpandResult, HirFileId, InFile, MacroCallId, MacroCallLoc, /* FIXME */ MacroDefId,
107 hir_ty::display::HirDisplay,
110 // These are negative re-exports: pub using these names is forbidden, they
111 // should remain private to hir internals.
115 hir_expand::{hygiene::Hygiene, name::AsName},
118 /// hir::Crate describes a single crate. It's the main interface with which
119 /// a crate's dependencies interact. Mostly, it should be just a proxy for the
121 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
123 pub(crate) id: CrateId,
127 pub struct CrateDependency {
133 pub fn dependencies(self, db: &dyn HirDatabase) -> Vec<CrateDependency> {
134 db.crate_graph()[self.id]
138 let krate = Crate { id: dep.crate_id };
139 let name = dep.as_name();
140 CrateDependency { krate, name }
145 pub fn reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
146 let crate_graph = db.crate_graph();
150 crate_graph[krate].dependencies.iter().any(|it| it.crate_id == self.id)
152 .map(|id| Crate { id })
156 pub fn transitive_reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
158 .transitive_reverse_dependencies(self.id)
160 .map(|id| Crate { id })
164 pub fn root_module(self, db: &dyn HirDatabase) -> Module {
165 let def_map = db.crate_def_map(self.id);
166 Module { id: def_map.module_id(def_map.root()) }
169 pub fn root_file(self, db: &dyn HirDatabase) -> FileId {
170 db.crate_graph()[self.id].root_file_id
173 pub fn edition(self, db: &dyn HirDatabase) -> Edition {
174 db.crate_graph()[self.id].edition
177 pub fn display_name(self, db: &dyn HirDatabase) -> Option<CrateDisplayName> {
178 db.crate_graph()[self.id].display_name.clone()
181 pub fn query_external_importables(
183 db: &dyn DefDatabase,
184 query: import_map::Query,
185 ) -> impl Iterator<Item = Either<ModuleDef, MacroDef>> {
186 import_map::search_dependencies(db, self.into(), query).into_iter().map(|item| match item {
187 ItemInNs::Types(mod_id) | ItemInNs::Values(mod_id) => Either::Left(mod_id.into()),
188 ItemInNs::Macros(mac_id) => Either::Right(mac_id.into()),
192 pub fn all(db: &dyn HirDatabase) -> Vec<Crate> {
193 db.crate_graph().iter().map(|id| Crate { id }).collect()
196 /// Try to get the root URL of the documentation of a crate.
197 pub fn get_html_root_url(self: &Crate, db: &dyn HirDatabase) -> Option<String> {
198 // Look for #![doc(html_root_url = "...")]
199 let attrs = db.attrs(AttrDefId::ModuleId(self.root_module(db).into()));
200 let doc_attr_q = attrs.by_key("doc");
202 if !doc_attr_q.exists() {
206 let doc_url = doc_attr_q.tt_values().map(|tt| {
207 let name = tt.token_trees.iter()
208 .skip_while(|tt| !matches!(tt, TokenTree::Leaf(Leaf::Ident(Ident{text: ref ident, ..})) if ident == "html_root_url"))
213 Some(TokenTree::Leaf(Leaf::Literal(Literal{ref text, ..}))) => Some(text),
218 doc_url.map(|s| s.trim_matches('"').trim_end_matches('/').to_owned() + "/")
222 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
224 pub(crate) id: ModuleId,
227 /// The defs which can be visible in the module.
228 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
233 // Can't be directly declared, but can be imported.
238 TypeAlias(TypeAlias),
239 BuiltinType(BuiltinType),
244 Adt(Struct, Enum, Union),
254 impl From<VariantDef> for ModuleDef {
255 fn from(var: VariantDef) -> Self {
257 VariantDef::Struct(t) => Adt::from(t).into(),
258 VariantDef::Union(t) => Adt::from(t).into(),
259 VariantDef::Variant(t) => t.into(),
265 pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
267 ModuleDef::Module(it) => it.parent(db),
268 ModuleDef::Function(it) => Some(it.module(db)),
269 ModuleDef::Adt(it) => Some(it.module(db)),
270 ModuleDef::Variant(it) => Some(it.module(db)),
271 ModuleDef::Const(it) => Some(it.module(db)),
272 ModuleDef::Static(it) => Some(it.module(db)),
273 ModuleDef::Trait(it) => Some(it.module(db)),
274 ModuleDef::TypeAlias(it) => Some(it.module(db)),
275 ModuleDef::BuiltinType(_) => None,
279 pub fn canonical_path(&self, db: &dyn HirDatabase) -> Option<String> {
280 let mut segments = vec![self.name(db)?.to_string()];
281 for m in self.module(db)?.path_to_root(db) {
282 segments.extend(m.name(db).map(|it| it.to_string()))
285 Some(segments.join("::"))
288 pub fn definition_visibility(&self, db: &dyn HirDatabase) -> Option<Visibility> {
289 let module = match self {
290 ModuleDef::Module(it) => it.parent(db)?,
291 ModuleDef::Function(it) => return Some(it.visibility(db)),
292 ModuleDef::Adt(it) => it.module(db),
293 ModuleDef::Variant(it) => {
294 let parent = it.parent_enum(db);
295 let module = it.module(db);
296 return module.visibility_of(db, &ModuleDef::Adt(Adt::Enum(parent)));
298 ModuleDef::Const(it) => return Some(it.visibility(db)),
299 ModuleDef::Static(it) => it.module(db),
300 ModuleDef::Trait(it) => it.module(db),
301 ModuleDef::TypeAlias(it) => return Some(it.visibility(db)),
302 ModuleDef::BuiltinType(_) => return None,
305 module.visibility_of(db, self)
308 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
310 ModuleDef::Adt(it) => Some(it.name(db)),
311 ModuleDef::Trait(it) => Some(it.name(db)),
312 ModuleDef::Function(it) => Some(it.name(db)),
313 ModuleDef::Variant(it) => Some(it.name(db)),
314 ModuleDef::TypeAlias(it) => Some(it.name(db)),
315 ModuleDef::Module(it) => it.name(db),
316 ModuleDef::Const(it) => it.name(db),
317 ModuleDef::Static(it) => it.name(db),
318 ModuleDef::BuiltinType(it) => Some(it.name()),
322 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
323 let id = match self {
324 ModuleDef::Adt(it) => match it {
325 Adt::Struct(it) => it.id.into(),
326 Adt::Enum(it) => it.id.into(),
327 Adt::Union(it) => it.id.into(),
329 ModuleDef::Trait(it) => it.id.into(),
330 ModuleDef::Function(it) => it.id.into(),
331 ModuleDef::TypeAlias(it) => it.id.into(),
332 ModuleDef::Module(it) => it.id.into(),
333 ModuleDef::Const(it) => it.id.into(),
334 ModuleDef::Static(it) => it.id.into(),
338 let module = match self.module(db) {
343 hir_ty::diagnostics::validate_module_item(db, module.id.krate(), id, sink)
348 /// Name of this module.
349 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
350 let def_map = self.id.def_map(db.upcast());
351 let parent = def_map[self.id.local_id].parent?;
352 def_map[parent].children.iter().find_map(|(name, module_id)| {
353 if *module_id == self.id.local_id {
361 /// Returns the crate this module is part of.
362 pub fn krate(self) -> Crate {
363 Crate { id: self.id.krate() }
366 /// Topmost parent of this module. Every module has a `crate_root`, but some
367 /// might be missing `krate`. This can happen if a module's file is not included
368 /// in the module tree of any target in `Cargo.toml`.
369 pub fn crate_root(self, db: &dyn HirDatabase) -> Module {
370 let def_map = db.crate_def_map(self.id.krate());
371 Module { id: def_map.module_id(def_map.root()) }
374 /// Iterates over all child modules.
375 pub fn children(self, db: &dyn HirDatabase) -> impl Iterator<Item = Module> {
376 let def_map = self.id.def_map(db.upcast());
377 let children = def_map[self.id.local_id]
380 .map(|(_, module_id)| Module { id: def_map.module_id(*module_id) })
381 .collect::<Vec<_>>();
385 /// Finds a parent module.
386 pub fn parent(self, db: &dyn HirDatabase) -> Option<Module> {
387 // FIXME: handle block expressions as modules (their parent is in a different DefMap)
388 let def_map = self.id.def_map(db.upcast());
389 let parent_id = def_map[self.id.local_id].parent?;
390 Some(Module { id: def_map.module_id(parent_id) })
393 pub fn path_to_root(self, db: &dyn HirDatabase) -> Vec<Module> {
394 let mut res = vec![self];
396 while let Some(next) = curr.parent(db) {
403 /// Returns a `ModuleScope`: a set of items, visible in this module.
406 db: &dyn HirDatabase,
407 visible_from: Option<Module>,
408 ) -> Vec<(Name, ScopeDef)> {
409 self.id.def_map(db.upcast())[self.id.local_id]
412 .filter_map(|(name, def)| {
413 if let Some(m) = visible_from {
415 def.filter_visibility(|vis| vis.is_visible_from(db.upcast(), m.id));
416 if filtered.is_none() && !def.is_none() {
419 Some((name, filtered))
425 .flat_map(|(name, def)| {
426 ScopeDef::all_items(def).into_iter().map(move |item| (name.clone(), item))
431 pub fn visibility_of(self, db: &dyn HirDatabase, def: &ModuleDef) -> Option<Visibility> {
432 self.id.def_map(db.upcast())[self.id.local_id].scope.visibility_of(def.clone().into())
435 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
436 let _p = profile::span("Module::diagnostics").detail(|| {
437 format!("{:?}", self.name(db).map_or("<unknown>".into(), |name| name.to_string()))
439 let def_map = self.id.def_map(db.upcast());
440 def_map.add_diagnostics(db.upcast(), self.id.local_id, sink);
441 for decl in self.declarations(db) {
443 crate::ModuleDef::Function(f) => f.diagnostics(db, sink),
444 crate::ModuleDef::Module(m) => {
445 // Only add diagnostics from inline modules
446 if def_map[m.id.local_id].origin.is_inline() {
447 m.diagnostics(db, sink)
451 decl.diagnostics(db, sink);
456 for impl_def in self.impl_defs(db) {
457 for item in impl_def.items(db) {
458 if let AssocItem::Function(f) = item {
459 f.diagnostics(db, sink);
465 pub fn declarations(self, db: &dyn HirDatabase) -> Vec<ModuleDef> {
466 let def_map = self.id.def_map(db.upcast());
467 def_map[self.id.local_id].scope.declarations().map(ModuleDef::from).collect()
470 pub fn impl_defs(self, db: &dyn HirDatabase) -> Vec<Impl> {
471 let def_map = self.id.def_map(db.upcast());
472 def_map[self.id.local_id].scope.impls().map(Impl::from).collect()
475 /// Finds a path that can be used to refer to the given item from within
476 /// this module, if possible.
477 pub fn find_use_path(self, db: &dyn DefDatabase, item: impl Into<ItemInNs>) -> Option<ModPath> {
478 hir_def::find_path::find_path(db, item.into(), self.into())
481 /// Finds a path that can be used to refer to the given item from within
482 /// this module, if possible. This is used for returning import paths for use-statements.
483 pub fn find_use_path_prefixed(
485 db: &dyn DefDatabase,
486 item: impl Into<ItemInNs>,
487 prefix_kind: PrefixKind,
488 ) -> Option<ModPath> {
489 hir_def::find_path::find_path_prefixed(db, item.into(), self.into(), prefix_kind)
493 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
495 pub(crate) parent: VariantDef,
496 pub(crate) id: LocalFieldId,
499 #[derive(Debug, PartialEq, Eq)]
500 pub enum FieldSource {
501 Named(ast::RecordField),
502 Pos(ast::TupleField),
506 pub fn name(&self, db: &dyn HirDatabase) -> Name {
507 self.parent.variant_data(db).fields()[self.id].name.clone()
510 /// Returns the type as in the signature of the struct (i.e., with
511 /// placeholder types for type parameters). This is good for showing
512 /// signature help, but not so good to actually get the type of the field
513 /// when you actually have a variable of the struct.
514 pub fn signature_ty(&self, db: &dyn HirDatabase) -> Type {
515 let var_id = self.parent.into();
516 let generic_def_id: GenericDefId = match self.parent {
517 VariantDef::Struct(it) => it.id.into(),
518 VariantDef::Union(it) => it.id.into(),
519 VariantDef::Variant(it) => it.parent.id.into(),
521 let substs = Substitution::type_params(db, generic_def_id);
522 let ty = db.field_types(var_id)[self.id].clone().subst(&substs);
523 Type::new(db, self.parent.module(db).id.krate(), var_id, ty)
526 pub fn parent_def(&self, _db: &dyn HirDatabase) -> VariantDef {
531 impl HasVisibility for Field {
532 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
533 let variant_data = self.parent.variant_data(db);
534 let visibility = &variant_data.fields()[self.id].visibility;
535 let parent_id: hir_def::VariantId = self.parent.into();
536 visibility.resolve(db.upcast(), &parent_id.resolver(db.upcast()))
540 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
542 pub(crate) id: StructId,
546 pub fn module(self, db: &dyn HirDatabase) -> Module {
547 Module { id: self.id.lookup(db.upcast()).container }
550 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
551 Some(self.module(db).krate())
554 pub fn name(self, db: &dyn HirDatabase) -> Name {
555 db.struct_data(self.id).name.clone()
558 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
559 db.struct_data(self.id)
563 .map(|(id, _)| Field { parent: self.into(), id })
567 pub fn ty(self, db: &dyn HirDatabase) -> Type {
568 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
571 pub fn repr(self, db: &dyn HirDatabase) -> Option<ReprKind> {
572 db.struct_data(self.id).repr.clone()
575 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
576 self.variant_data(db).kind()
579 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
580 db.struct_data(self.id).variant_data.clone()
584 impl HasVisibility for Struct {
585 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
586 db.struct_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
590 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
592 pub(crate) id: UnionId,
596 pub fn name(self, db: &dyn HirDatabase) -> Name {
597 db.union_data(self.id).name.clone()
600 pub fn module(self, db: &dyn HirDatabase) -> Module {
601 Module { id: self.id.lookup(db.upcast()).container }
604 pub fn ty(self, db: &dyn HirDatabase) -> Type {
605 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
608 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
609 db.union_data(self.id)
613 .map(|(id, _)| Field { parent: self.into(), id })
617 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
618 db.union_data(self.id).variant_data.clone()
622 impl HasVisibility for Union {
623 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
624 db.union_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
628 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
630 pub(crate) id: EnumId,
634 pub fn module(self, db: &dyn HirDatabase) -> Module {
635 Module { id: self.id.lookup(db.upcast()).container }
638 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
639 Some(self.module(db).krate())
642 pub fn name(self, db: &dyn HirDatabase) -> Name {
643 db.enum_data(self.id).name.clone()
646 pub fn variants(self, db: &dyn HirDatabase) -> Vec<Variant> {
647 db.enum_data(self.id).variants.iter().map(|(id, _)| Variant { parent: self, id }).collect()
650 pub fn ty(self, db: &dyn HirDatabase) -> Type {
651 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
655 impl HasVisibility for Enum {
656 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
657 db.enum_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
661 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
663 pub(crate) parent: Enum,
664 pub(crate) id: LocalEnumVariantId,
668 pub fn module(self, db: &dyn HirDatabase) -> Module {
669 self.parent.module(db)
671 pub fn parent_enum(self, _db: &dyn HirDatabase) -> Enum {
675 pub fn name(self, db: &dyn HirDatabase) -> Name {
676 db.enum_data(self.parent.id).variants[self.id].name.clone()
679 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
680 self.variant_data(db)
683 .map(|(id, _)| Field { parent: self.into(), id })
687 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
688 self.variant_data(db).kind()
691 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
692 db.enum_data(self.parent.id).variants[self.id].variant_data.clone()
697 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
703 impl_from!(Struct, Union, Enum for Adt);
706 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
707 let subst = db.generic_defaults(self.into());
708 subst.iter().any(|ty| ty.value.is_unknown())
711 /// Turns this ADT into a type. Any type parameters of the ADT will be
712 /// turned into unknown types, which is good for e.g. finding the most
713 /// general set of completions, but will not look very nice when printed.
714 pub fn ty(self, db: &dyn HirDatabase) -> Type {
715 let id = AdtId::from(self);
716 Type::from_def(db, id.module(db.upcast()).krate(), id)
719 pub fn module(self, db: &dyn HirDatabase) -> Module {
721 Adt::Struct(s) => s.module(db),
722 Adt::Union(s) => s.module(db),
723 Adt::Enum(e) => e.module(db),
727 pub fn krate(self, db: &dyn HirDatabase) -> Crate {
728 self.module(db).krate()
731 pub fn name(self, db: &dyn HirDatabase) -> Name {
733 Adt::Struct(s) => s.name(db),
734 Adt::Union(u) => u.name(db),
735 Adt::Enum(e) => e.name(db),
740 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
741 pub enum VariantDef {
746 impl_from!(Struct, Union, Variant for VariantDef);
749 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
751 VariantDef::Struct(it) => it.fields(db),
752 VariantDef::Union(it) => it.fields(db),
753 VariantDef::Variant(it) => it.fields(db),
757 pub fn module(self, db: &dyn HirDatabase) -> Module {
759 VariantDef::Struct(it) => it.module(db),
760 VariantDef::Union(it) => it.module(db),
761 VariantDef::Variant(it) => it.module(db),
765 pub fn name(&self, db: &dyn HirDatabase) -> Name {
767 VariantDef::Struct(s) => s.name(db),
768 VariantDef::Union(u) => u.name(db),
769 VariantDef::Variant(e) => e.name(db),
773 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
775 VariantDef::Struct(it) => it.variant_data(db),
776 VariantDef::Union(it) => it.variant_data(db),
777 VariantDef::Variant(it) => it.variant_data(db),
782 /// The defs which have a body.
783 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
784 pub enum DefWithBody {
789 impl_from!(Function, Const, Static for DefWithBody);
792 pub fn module(self, db: &dyn HirDatabase) -> Module {
794 DefWithBody::Const(c) => c.module(db),
795 DefWithBody::Function(f) => f.module(db),
796 DefWithBody::Static(s) => s.module(db),
800 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
802 DefWithBody::Function(f) => Some(f.name(db)),
803 DefWithBody::Static(s) => s.name(db),
804 DefWithBody::Const(c) => c.name(db),
809 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
810 pub struct Function {
811 pub(crate) id: FunctionId,
815 pub fn module(self, db: &dyn HirDatabase) -> Module {
816 self.id.lookup(db.upcast()).module(db.upcast()).into()
819 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
820 Some(self.module(db).krate())
823 pub fn name(self, db: &dyn HirDatabase) -> Name {
824 db.function_data(self.id).name.clone()
827 /// Get this function's return type
828 pub fn ret_type(self, db: &dyn HirDatabase) -> Type {
829 let resolver = self.id.resolver(db.upcast());
830 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
831 let ret_type = &db.function_data(self.id).ret_type;
832 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
833 let ty = ctx.lower_ty(ret_type);
834 Type::new_with_resolver_inner(db, krate, &resolver, ty)
837 pub fn self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
838 if !db.function_data(self.id).has_self_param {
841 Some(SelfParam { func: self.id })
844 pub fn assoc_fn_params(self, db: &dyn HirDatabase) -> Vec<Param> {
845 let resolver = self.id.resolver(db.upcast());
846 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
847 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
848 let environment = db.trait_environment(self.id.into());
849 db.function_data(self.id)
853 .map(|(idx, type_ref)| {
854 let ty = Type { krate, env: environment.clone(), ty: ctx.lower_ty(type_ref) };
855 Param { func: self, ty, idx }
859 pub fn method_params(self, db: &dyn HirDatabase) -> Option<Vec<Param>> {
860 if self.self_param(db).is_none() {
863 let mut res = self.assoc_fn_params(db);
868 pub fn is_unsafe(self, db: &dyn HirDatabase) -> bool {
869 db.function_data(self.id).qualifier.is_unsafe
872 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
873 let krate = self.module(db).id.krate();
874 hir_def::diagnostics::validate_body(db.upcast(), self.id.into(), sink);
875 hir_ty::diagnostics::validate_module_item(db, krate, self.id.into(), sink);
876 hir_ty::diagnostics::validate_body(db, self.id.into(), sink);
879 /// Whether this function declaration has a definition.
881 /// This is false in the case of required (not provided) trait methods.
882 pub fn has_body(self, db: &dyn HirDatabase) -> bool {
883 db.function_data(self.id).has_body
886 /// A textual representation of the HIR of this function for debugging purposes.
887 pub fn debug_hir(self, db: &dyn HirDatabase) -> String {
888 let body = db.body(self.id.into());
890 let mut result = String::new();
891 format_to!(result, "HIR expressions in the body of `{}`:\n", self.name(db));
892 for (id, expr) in body.exprs.iter() {
893 format_to!(result, "{:?}: {:?}\n", id, expr);
900 // Note: logically, this belongs to `hir_ty`, but we are not using it there yet.
907 impl From<hir_ty::Mutability> for Access {
908 fn from(mutability: hir_ty::Mutability) -> Access {
910 hir_ty::Mutability::Not => Access::Shared,
911 hir_ty::Mutability::Mut => Access::Exclusive,
919 /// The index in parameter list, including self parameter.
925 pub fn ty(&self) -> &Type {
929 pub fn pattern_source(&self, db: &dyn HirDatabase) -> Option<ast::Pat> {
930 let params = self.func.source(db)?.value.param_list()?;
931 if params.self_param().is_some() {
932 params.params().nth(self.idx.checked_sub(1)?)?.pat()
934 params.params().nth(self.idx)?.pat()
939 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
940 pub struct SelfParam {
945 pub fn access(self, db: &dyn HirDatabase) -> Access {
946 let func_data = db.function_data(self.func);
950 .map(|param| match *param {
951 TypeRef::Reference(.., mutability) => match mutability {
952 hir_def::type_ref::Mutability::Shared => Access::Shared,
953 hir_def::type_ref::Mutability::Mut => Access::Exclusive,
957 .unwrap_or(Access::Owned)
960 pub fn display(self, db: &dyn HirDatabase) -> &'static str {
961 match self.access(db) {
962 Access::Shared => "&self",
963 Access::Exclusive => "&mut self",
964 Access::Owned => "self",
969 impl HasVisibility for Function {
970 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
971 let function_data = db.function_data(self.id);
972 let visibility = &function_data.visibility;
973 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
977 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
979 pub(crate) id: ConstId,
983 pub fn module(self, db: &dyn HirDatabase) -> Module {
984 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
987 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
988 Some(self.module(db).krate())
991 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
992 db.const_data(self.id).name.clone()
995 pub fn type_ref(self, db: &dyn HirDatabase) -> TypeRef {
996 db.const_data(self.id).type_ref.clone()
1000 impl HasVisibility for Const {
1001 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1002 let function_data = db.const_data(self.id);
1003 let visibility = &function_data.visibility;
1004 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1008 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1010 pub(crate) id: StaticId,
1014 pub fn module(self, db: &dyn HirDatabase) -> Module {
1015 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1018 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
1019 Some(self.module(db).krate())
1022 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1023 db.static_data(self.id).name.clone()
1026 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
1027 db.static_data(self.id).mutable
1031 impl HasVisibility for Static {
1032 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1033 db.static_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1037 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1039 pub(crate) id: TraitId,
1043 pub fn module(self, db: &dyn HirDatabase) -> Module {
1044 Module { id: self.id.lookup(db.upcast()).container }
1047 pub fn name(self, db: &dyn HirDatabase) -> Name {
1048 db.trait_data(self.id).name.clone()
1051 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
1052 db.trait_data(self.id).items.iter().map(|(_name, it)| (*it).into()).collect()
1055 pub fn is_auto(self, db: &dyn HirDatabase) -> bool {
1056 db.trait_data(self.id).is_auto
1060 impl HasVisibility for Trait {
1061 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1062 db.trait_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1066 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1067 pub struct TypeAlias {
1068 pub(crate) id: TypeAliasId,
1072 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
1073 let subst = db.generic_defaults(self.id.into());
1074 subst.iter().any(|ty| ty.value.is_unknown())
1077 pub fn module(self, db: &dyn HirDatabase) -> Module {
1078 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1081 pub fn krate(self, db: &dyn HirDatabase) -> Crate {
1082 self.module(db).krate()
1085 pub fn type_ref(self, db: &dyn HirDatabase) -> Option<TypeRef> {
1086 db.type_alias_data(self.id).type_ref.clone()
1089 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1090 Type::from_def(db, self.id.lookup(db.upcast()).module(db.upcast()).krate(), self.id)
1093 pub fn name(self, db: &dyn HirDatabase) -> Name {
1094 db.type_alias_data(self.id).name.clone()
1098 impl HasVisibility for TypeAlias {
1099 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1100 let function_data = db.type_alias_data(self.id);
1101 let visibility = &function_data.visibility;
1102 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1106 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1107 pub struct BuiltinType {
1108 pub(crate) inner: hir_def::builtin_type::BuiltinType,
1112 pub fn ty(self, db: &dyn HirDatabase, module: Module) -> Type {
1113 let resolver = module.id.resolver(db.upcast());
1114 Type::new_with_resolver(db, &resolver, Ty::builtin(self.inner))
1115 .expect("crate not present in resolver")
1118 pub fn name(self) -> Name {
1119 self.inner.as_name()
1123 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1124 pub struct MacroDef {
1125 pub(crate) id: MacroDefId,
1129 /// FIXME: right now, this just returns the root module of the crate that
1130 /// defines this macro. The reasons for this is that macros are expanded
1131 /// early, in `hir_expand`, where modules simply do not exist yet.
1132 pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
1133 let krate = self.id.krate;
1134 let def_map = db.crate_def_map(krate);
1135 let module_id = def_map.root();
1136 Some(Module { id: def_map.module_id(module_id) })
1139 /// XXX: this parses the file
1140 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1141 match self.source(db)?.value {
1142 Either::Left(it) => it.name().map(|it| it.as_name()),
1143 Either::Right(it) => it.name().map(|it| it.as_name()),
1147 /// Indicate it is a proc-macro
1148 pub fn is_proc_macro(&self) -> bool {
1149 matches!(self.id.kind, MacroDefKind::ProcMacro(..))
1152 /// Indicate it is a derive macro
1153 pub fn is_derive_macro(&self) -> bool {
1154 // FIXME: wrong for `ProcMacro`
1155 matches!(self.id.kind, MacroDefKind::ProcMacro(..) | MacroDefKind::BuiltInDerive(..))
1159 /// Invariant: `inner.as_assoc_item(db).is_some()`
1160 /// We do not actively enforce this invariant.
1161 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1162 pub enum AssocItem {
1165 TypeAlias(TypeAlias),
1168 pub enum AssocItemContainer {
1172 pub trait AsAssocItem {
1173 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem>;
1176 impl AsAssocItem for Function {
1177 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1178 as_assoc_item(db, AssocItem::Function, self.id)
1181 impl AsAssocItem for Const {
1182 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1183 as_assoc_item(db, AssocItem::Const, self.id)
1186 impl AsAssocItem for TypeAlias {
1187 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1188 as_assoc_item(db, AssocItem::TypeAlias, self.id)
1191 impl AsAssocItem for ModuleDef {
1192 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1194 ModuleDef::Function(it) => it.as_assoc_item(db),
1195 ModuleDef::Const(it) => it.as_assoc_item(db),
1196 ModuleDef::TypeAlias(it) => it.as_assoc_item(db),
1201 fn as_assoc_item<ID, DEF, CTOR, AST>(db: &dyn HirDatabase, ctor: CTOR, id: ID) -> Option<AssocItem>
1203 ID: Lookup<Data = AssocItemLoc<AST>>,
1205 CTOR: FnOnce(DEF) -> AssocItem,
1208 match id.lookup(db.upcast()).container {
1209 AssocContainerId::TraitId(_) | AssocContainerId::ImplId(_) => Some(ctor(DEF::from(id))),
1210 AssocContainerId::ModuleId(_) => None,
1215 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1217 AssocItem::Function(it) => Some(it.name(db)),
1218 AssocItem::Const(it) => it.name(db),
1219 AssocItem::TypeAlias(it) => Some(it.name(db)),
1222 pub fn module(self, db: &dyn HirDatabase) -> Module {
1224 AssocItem::Function(f) => f.module(db),
1225 AssocItem::Const(c) => c.module(db),
1226 AssocItem::TypeAlias(t) => t.module(db),
1229 pub fn container(self, db: &dyn HirDatabase) -> AssocItemContainer {
1230 let container = match self {
1231 AssocItem::Function(it) => it.id.lookup(db.upcast()).container,
1232 AssocItem::Const(it) => it.id.lookup(db.upcast()).container,
1233 AssocItem::TypeAlias(it) => it.id.lookup(db.upcast()).container,
1236 AssocContainerId::TraitId(id) => AssocItemContainer::Trait(id.into()),
1237 AssocContainerId::ImplId(id) => AssocItemContainer::Impl(id.into()),
1238 AssocContainerId::ModuleId(_) => panic!("invalid AssocItem"),
1242 pub fn containing_trait(self, db: &dyn HirDatabase) -> Option<Trait> {
1243 match self.container(db) {
1244 AssocItemContainer::Trait(t) => Some(t),
1250 impl HasVisibility for AssocItem {
1251 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1253 AssocItem::Function(f) => f.visibility(db),
1254 AssocItem::Const(c) => c.visibility(db),
1255 AssocItem::TypeAlias(t) => t.visibility(db),
1260 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
1261 pub enum GenericDef {
1265 TypeAlias(TypeAlias),
1267 // enum variants cannot have generics themselves, but their parent enums
1268 // can, and this makes some code easier to write
1270 // consts can have type parameters from their parents (i.e. associated consts of traits)
1275 Adt(Struct, Enum, Union),
1285 pub fn params(self, db: &dyn HirDatabase) -> Vec<GenericParam> {
1286 let generics = db.generic_params(self.into());
1287 let ty_params = generics
1290 .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
1291 .map(GenericParam::TypeParam);
1292 let lt_params = generics
1295 .map(|(local_id, _)| LifetimeParam {
1296 id: LifetimeParamId { parent: self.into(), local_id },
1298 .map(GenericParam::LifetimeParam);
1299 let const_params = generics
1302 .map(|(local_id, _)| ConstParam { id: ConstParamId { parent: self.into(), local_id } })
1303 .map(GenericParam::ConstParam);
1304 ty_params.chain(lt_params).chain(const_params).collect()
1307 pub fn type_params(self, db: &dyn HirDatabase) -> Vec<TypeParam> {
1308 let generics = db.generic_params(self.into());
1312 .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
1317 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1319 pub(crate) parent: DefWithBodyId,
1320 pub(crate) pat_id: PatId,
1324 pub fn is_param(self, db: &dyn HirDatabase) -> bool {
1325 let src = self.source(db);
1327 Either::Left(bind_pat) => {
1328 bind_pat.syntax().ancestors().any(|it| ast::Param::can_cast(it.kind()))
1330 Either::Right(_self_param) => true,
1334 // FIXME: why is this an option? It shouldn't be?
1335 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1336 let body = db.body(self.parent);
1337 match &body[self.pat_id] {
1338 Pat::Bind { name, .. } => Some(name.clone()),
1343 pub fn is_self(self, db: &dyn HirDatabase) -> bool {
1344 self.name(db) == Some(name![self])
1347 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
1348 let body = db.body(self.parent);
1349 matches!(&body[self.pat_id], Pat::Bind { mode: BindingAnnotation::Mutable, .. })
1352 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
1356 pub fn module(self, db: &dyn HirDatabase) -> Module {
1357 self.parent(db).module(db)
1360 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1361 let def = self.parent;
1362 let infer = db.infer(def);
1363 let ty = infer[self.pat_id].clone();
1364 let krate = def.module(db.upcast()).krate();
1365 Type::new(db, krate, def, ty)
1368 pub fn source(self, db: &dyn HirDatabase) -> InFile<Either<ast::IdentPat, ast::SelfParam>> {
1369 let (_body, source_map) = db.body_with_source_map(self.parent);
1370 let src = source_map.pat_syntax(self.pat_id).unwrap(); // Hmm...
1371 let root = src.file_syntax(db.upcast());
1373 ast.map_left(|it| it.cast().unwrap().to_node(&root)).map_right(|it| it.to_node(&root))
1378 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1380 pub(crate) parent: DefWithBodyId,
1381 pub(crate) label_id: LabelId,
1385 pub fn module(self, db: &dyn HirDatabase) -> Module {
1386 self.parent(db).module(db)
1389 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
1393 pub fn name(self, db: &dyn HirDatabase) -> Name {
1394 let body = db.body(self.parent);
1395 body[self.label_id].name.clone()
1398 pub fn source(self, db: &dyn HirDatabase) -> InFile<ast::Label> {
1399 let (_body, source_map) = db.body_with_source_map(self.parent);
1400 let src = source_map.label_syntax(self.label_id);
1401 let root = src.file_syntax(db.upcast());
1402 src.map(|ast| ast.to_node(&root))
1406 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1407 pub enum GenericParam {
1408 TypeParam(TypeParam),
1409 LifetimeParam(LifetimeParam),
1410 ConstParam(ConstParam),
1412 impl_from!(TypeParam, LifetimeParam, ConstParam for GenericParam);
1415 pub fn module(self, db: &dyn HirDatabase) -> Module {
1417 GenericParam::TypeParam(it) => it.module(db),
1418 GenericParam::LifetimeParam(it) => it.module(db),
1419 GenericParam::ConstParam(it) => it.module(db),
1423 pub fn name(self, db: &dyn HirDatabase) -> Name {
1425 GenericParam::TypeParam(it) => it.name(db),
1426 GenericParam::LifetimeParam(it) => it.name(db),
1427 GenericParam::ConstParam(it) => it.name(db),
1432 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1433 pub struct TypeParam {
1434 pub(crate) id: TypeParamId,
1438 pub fn name(self, db: &dyn HirDatabase) -> Name {
1439 let params = db.generic_params(self.id.parent);
1440 params.types[self.id.local_id].name.clone().unwrap_or_else(Name::missing)
1443 pub fn module(self, db: &dyn HirDatabase) -> Module {
1444 self.id.parent.module(db.upcast()).into()
1447 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1448 let resolver = self.id.parent.resolver(db.upcast());
1449 let krate = self.id.parent.module(db.upcast()).krate();
1450 let ty = TyKind::Placeholder(hir_ty::to_placeholder_idx(db, self.id)).intern(&Interner);
1451 Type::new_with_resolver_inner(db, krate, &resolver, ty)
1454 pub fn trait_bounds(self, db: &dyn HirDatabase) -> Vec<Trait> {
1455 db.generic_predicates_for_param(self.id)
1457 .filter_map(|pred| match &pred.skip_binders().skip_binders() {
1458 hir_ty::WhereClause::Implemented(trait_ref) => {
1459 Some(Trait::from(trait_ref.hir_trait_id()))
1466 pub fn default(self, db: &dyn HirDatabase) -> Option<Type> {
1467 let params = db.generic_defaults(self.id.parent);
1468 let local_idx = hir_ty::param_idx(db, self.id)?;
1469 let resolver = self.id.parent.resolver(db.upcast());
1470 let krate = self.id.parent.module(db.upcast()).krate();
1471 let ty = params.get(local_idx)?.clone();
1472 let subst = Substitution::type_params(db, self.id.parent);
1473 let ty = ty.subst(&subst.prefix(local_idx));
1474 Some(Type::new_with_resolver_inner(db, krate, &resolver, ty))
1478 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1479 pub struct LifetimeParam {
1480 pub(crate) id: LifetimeParamId,
1483 impl LifetimeParam {
1484 pub fn name(self, db: &dyn HirDatabase) -> Name {
1485 let params = db.generic_params(self.id.parent);
1486 params.lifetimes[self.id.local_id].name.clone()
1489 pub fn module(self, db: &dyn HirDatabase) -> Module {
1490 self.id.parent.module(db.upcast()).into()
1493 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
1494 self.id.parent.into()
1498 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1499 pub struct ConstParam {
1500 pub(crate) id: ConstParamId,
1504 pub fn name(self, db: &dyn HirDatabase) -> Name {
1505 let params = db.generic_params(self.id.parent);
1506 params.consts[self.id.local_id].name.clone()
1509 pub fn module(self, db: &dyn HirDatabase) -> Module {
1510 self.id.parent.module(db.upcast()).into()
1513 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
1514 self.id.parent.into()
1517 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1518 let def = self.id.parent;
1519 let krate = def.module(db.upcast()).krate();
1520 Type::new(db, krate, def, db.const_param_ty(self.id))
1524 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1526 pub(crate) id: ImplId,
1530 pub fn all_in_crate(db: &dyn HirDatabase, krate: Crate) -> Vec<Impl> {
1531 let inherent = db.inherent_impls_in_crate(krate.id);
1532 let trait_ = db.trait_impls_in_crate(krate.id);
1534 inherent.all_impls().chain(trait_.all_impls()).map(Self::from).collect()
1537 pub fn all_for_type(db: &dyn HirDatabase, Type { krate, ty, .. }: Type) -> Vec<Impl> {
1538 let def_crates = match ty.def_crates(db, krate) {
1539 Some(def_crates) => def_crates,
1540 None => return Vec::new(),
1543 let filter = |impl_def: &Impl| {
1544 let target_ty = impl_def.target_ty(db);
1545 let rref = target_ty.remove_ref();
1546 ty.equals_ctor(rref.as_ref().map_or(&target_ty.ty, |it| &it.ty))
1549 let mut all = Vec::new();
1550 def_crates.iter().for_each(|&id| {
1551 all.extend(db.inherent_impls_in_crate(id).all_impls().map(Self::from).filter(filter))
1553 let fp = TyFingerprint::for_impl(&ty);
1554 for id in def_crates
1556 .flat_map(|&id| Crate { id }.transitive_reverse_dependencies(db))
1557 .map(|Crate { id }| id)
1558 .chain(def_crates.iter().copied())
1562 Some(fp) => all.extend(
1563 db.trait_impls_in_crate(id).for_self_ty(fp).map(Self::from).filter(filter),
1566 .extend(db.trait_impls_in_crate(id).all_impls().map(Self::from).filter(filter)),
1572 pub fn all_for_trait(db: &dyn HirDatabase, trait_: Trait) -> Vec<Impl> {
1573 let krate = trait_.module(db).krate();
1574 let mut all = Vec::new();
1575 for Crate { id } in krate.transitive_reverse_dependencies(db).into_iter().chain(Some(krate))
1577 let impls = db.trait_impls_in_crate(id);
1578 all.extend(impls.for_trait(trait_.id).map(Self::from))
1583 // FIXME: the return type is wrong. This should be a hir version of
1584 // `TraitRef` (ie, resolved `TypeRef`).
1585 pub fn target_trait(self, db: &dyn HirDatabase) -> Option<TypeRef> {
1586 db.impl_data(self.id).target_trait.clone()
1589 pub fn target_ty(self, db: &dyn HirDatabase) -> Type {
1590 let impl_data = db.impl_data(self.id);
1591 let resolver = self.id.resolver(db.upcast());
1592 let krate = self.id.lookup(db.upcast()).container.krate();
1593 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1594 let ty = ctx.lower_ty(&impl_data.target_type);
1595 Type::new_with_resolver_inner(db, krate, &resolver, ty)
1598 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
1599 db.impl_data(self.id).items.iter().map(|it| (*it).into()).collect()
1602 pub fn is_negative(self, db: &dyn HirDatabase) -> bool {
1603 db.impl_data(self.id).is_negative
1606 pub fn module(self, db: &dyn HirDatabase) -> Module {
1607 self.id.lookup(db.upcast()).container.into()
1610 pub fn krate(self, db: &dyn HirDatabase) -> Crate {
1611 Crate { id: self.module(db).id.krate() }
1614 pub fn is_builtin_derive(self, db: &dyn HirDatabase) -> Option<InFile<ast::Attr>> {
1615 let src = self.source(db)?;
1616 let item = src.file_id.is_builtin_derive(db.upcast())?;
1617 let hygenic = hir_expand::hygiene::Hygiene::new(db.upcast(), item.file_id);
1619 // FIXME: handle `cfg_attr`
1624 let path = ModPath::from_src(it.path()?, &hygenic)?;
1625 if path.as_ident()?.to_string() == "derive" {
1633 Some(item.with_value(attr))
1637 #[derive(Clone, PartialEq, Eq, Debug)]
1640 env: Arc<TraitEnvironment>,
1645 pub(crate) fn new_with_resolver(
1646 db: &dyn HirDatabase,
1647 resolver: &Resolver,
1650 let krate = resolver.krate()?;
1651 Some(Type::new_with_resolver_inner(db, krate, resolver, ty))
1653 pub(crate) fn new_with_resolver_inner(
1654 db: &dyn HirDatabase,
1656 resolver: &Resolver,
1660 resolver.generic_def().map_or_else(Default::default, |d| db.trait_environment(d));
1661 Type { krate, env: environment, ty }
1664 fn new(db: &dyn HirDatabase, krate: CrateId, lexical_env: impl HasResolver, ty: Ty) -> Type {
1665 let resolver = lexical_env.resolver(db.upcast());
1667 resolver.generic_def().map_or_else(Default::default, |d| db.trait_environment(d));
1668 Type { krate, env: environment, ty }
1672 db: &dyn HirDatabase,
1674 def: impl HasResolver + Into<TyDefId> + Into<GenericDefId>,
1676 let substs = Substitution::build_for_def(db, def).fill_with_unknown().build();
1677 let ty = db.ty(def.into()).subst(&substs);
1678 Type::new(db, krate, def, ty)
1681 pub fn is_unit(&self) -> bool {
1682 matches!(self.ty.interned(&Interner), TyKind::Tuple(0, ..))
1684 pub fn is_bool(&self) -> bool {
1685 matches!(self.ty.interned(&Interner), TyKind::Scalar(Scalar::Bool))
1688 pub fn is_mutable_reference(&self) -> bool {
1689 matches!(self.ty.interned(&Interner), TyKind::Ref(hir_ty::Mutability::Mut, ..))
1692 pub fn is_usize(&self) -> bool {
1693 matches!(self.ty.interned(&Interner), TyKind::Scalar(Scalar::Uint(UintTy::Usize)))
1696 pub fn remove_ref(&self) -> Option<Type> {
1697 match &self.ty.interned(&Interner) {
1698 TyKind::Ref(.., ty) => Some(self.derived(ty.clone())),
1703 pub fn is_unknown(&self) -> bool {
1704 self.ty.is_unknown()
1707 /// Checks that particular type `ty` implements `std::future::Future`.
1708 /// This function is used in `.await` syntax completion.
1709 pub fn impls_future(&self, db: &dyn HirDatabase) -> bool {
1710 // No special case for the type of async block, since Chalk can figure it out.
1712 let krate = self.krate;
1714 let std_future_trait =
1715 db.lang_item(krate, "future_trait".into()).and_then(|it| it.as_trait());
1716 let std_future_trait = match std_future_trait {
1718 None => return false,
1722 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(&Interner) };
1723 method_resolution::implements_trait(
1732 /// Checks that particular type `ty` implements `std::ops::FnOnce`.
1734 /// This function can be used to check if a particular type is callable, since FnOnce is a
1735 /// supertrait of Fn and FnMut, so all callable types implements at least FnOnce.
1736 pub fn impls_fnonce(&self, db: &dyn HirDatabase) -> bool {
1737 let krate = self.krate;
1739 let fnonce_trait = match FnTrait::FnOnce.get_id(db, krate) {
1741 None => return false,
1745 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(&Interner) };
1746 method_resolution::implements_trait_unique(
1755 pub fn impls_trait(&self, db: &dyn HirDatabase, trait_: Trait, args: &[Type]) -> bool {
1756 let trait_ref = hir_ty::TraitRef {
1757 trait_id: hir_ty::to_chalk_trait_id(trait_.id),
1758 substitution: Substitution::build_for_def(db, trait_.id)
1759 .push(self.ty.clone())
1760 .fill(args.iter().map(|t| t.ty.clone()))
1764 let goal = Canonical {
1765 value: hir_ty::InEnvironment::new(self.env.env.clone(), trait_ref.cast(&Interner)),
1766 binders: CanonicalVarKinds::empty(&Interner),
1769 db.trait_solve(self.krate, goal).is_some()
1772 pub fn normalize_trait_assoc_type(
1774 db: &dyn HirDatabase,
1779 let subst = Substitution::build_for_def(db, trait_.id)
1780 .push(self.ty.clone())
1781 .fill(args.iter().map(|t| t.ty.clone()))
1783 let goal = Canonical::new(
1785 self.env.env.clone(),
1787 alias: AliasTy::Projection(ProjectionTy {
1788 associated_ty_id: to_assoc_type_id(alias.id),
1789 substitution: subst,
1791 ty: TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0))
1796 [TyVariableKind::General].iter().copied(),
1799 match db.trait_solve(self.krate, goal)? {
1800 Solution::Unique(SolutionVariables(subst)) => {
1801 subst.value.first().map(|ty| self.derived(ty.clone()))
1803 Solution::Ambig(_) => None,
1807 pub fn is_copy(&self, db: &dyn HirDatabase) -> bool {
1808 let lang_item = db.lang_item(self.krate, SmolStr::new("copy"));
1809 let copy_trait = match lang_item {
1810 Some(LangItemTarget::TraitId(it)) => it,
1813 self.impls_trait(db, copy_trait.into(), &[])
1816 pub fn as_callable(&self, db: &dyn HirDatabase) -> Option<Callable> {
1817 let def = self.ty.callable_def(db);
1819 let sig = self.ty.callable_sig(db)?;
1820 Some(Callable { ty: self.clone(), sig, def, is_bound_method: false })
1823 pub fn is_closure(&self) -> bool {
1824 matches!(&self.ty.interned(&Interner), TyKind::Closure { .. })
1827 pub fn is_fn(&self) -> bool {
1828 matches!(&self.ty.interned(&Interner), TyKind::FnDef(..) | TyKind::Function { .. })
1831 pub fn is_packed(&self, db: &dyn HirDatabase) -> bool {
1832 let adt_id = match self.ty.interned(&Interner) {
1833 &TyKind::Adt(hir_ty::AdtId(adt_id), ..) => adt_id,
1837 let adt = adt_id.into();
1839 Adt::Struct(s) => matches!(s.repr(db), Some(ReprKind::Packed)),
1844 pub fn is_raw_ptr(&self) -> bool {
1845 matches!(&self.ty.interned(&Interner), TyKind::Raw(..))
1848 pub fn contains_unknown(&self) -> bool {
1849 return go(&self.ty);
1851 fn go(ty: &Ty) -> bool {
1852 match ty.interned(&Interner) {
1853 TyKind::Unknown => true,
1855 TyKind::Adt(_, substs)
1856 | TyKind::AssociatedType(_, substs)
1857 | TyKind::Tuple(_, substs)
1858 | TyKind::OpaqueType(_, substs)
1859 | TyKind::FnDef(_, substs)
1860 | TyKind::Closure(_, substs) => substs.iter().any(go),
1862 TyKind::Array(ty) | TyKind::Slice(ty) | TyKind::Raw(_, ty) | TyKind::Ref(_, ty) => {
1869 | TyKind::Placeholder(_)
1870 | TyKind::BoundVar(_)
1871 | TyKind::InferenceVar(_, _)
1873 | TyKind::Function(_)
1875 | TyKind::ForeignType(_) => false,
1880 pub fn fields(&self, db: &dyn HirDatabase) -> Vec<(Field, Type)> {
1881 let (variant_id, substs) = match self.ty.interned(&Interner) {
1882 &TyKind::Adt(hir_ty::AdtId(AdtId::StructId(s)), ref substs) => (s.into(), substs),
1883 &TyKind::Adt(hir_ty::AdtId(AdtId::UnionId(u)), ref substs) => (u.into(), substs),
1884 _ => return Vec::new(),
1887 db.field_types(variant_id)
1889 .map(|(local_id, ty)| {
1890 let def = Field { parent: variant_id.into(), id: local_id };
1891 let ty = ty.clone().subst(substs);
1892 (def, self.derived(ty))
1897 pub fn tuple_fields(&self, _db: &dyn HirDatabase) -> Vec<Type> {
1898 if let TyKind::Tuple(_, substs) = &self.ty.interned(&Interner) {
1899 substs.iter().map(|ty| self.derived(ty.clone())).collect()
1905 pub fn autoderef<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Type> + 'a {
1906 // There should be no inference vars in types passed here
1907 // FIXME check that?
1909 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(&Interner) };
1910 let environment = self.env.env.clone();
1911 let ty = InEnvironment { goal: canonical, environment };
1912 autoderef(db, Some(self.krate), ty)
1913 .map(|canonical| canonical.value)
1914 .map(move |ty| self.derived(ty))
1917 // This would be nicer if it just returned an iterator, but that runs into
1918 // lifetime problems, because we need to borrow temp `CrateImplDefs`.
1919 pub fn iterate_assoc_items<T>(
1921 db: &dyn HirDatabase,
1923 mut callback: impl FnMut(AssocItem) -> Option<T>,
1925 for krate in self.ty.def_crates(db, krate.id)? {
1926 let impls = db.inherent_impls_in_crate(krate);
1928 for impl_def in impls.for_self_ty(&self.ty) {
1929 for &item in db.impl_data(*impl_def).items.iter() {
1930 if let Some(result) = callback(item.into()) {
1931 return Some(result);
1939 pub fn type_parameters(&self) -> impl Iterator<Item = Type> + '_ {
1944 .flat_map(|substs| substs.iter())
1945 .map(move |ty| self.derived(ty.clone()))
1948 pub fn iterate_method_candidates<T>(
1950 db: &dyn HirDatabase,
1952 traits_in_scope: &FxHashSet<TraitId>,
1953 name: Option<&Name>,
1954 mut callback: impl FnMut(&Ty, Function) -> Option<T>,
1956 // There should be no inference vars in types passed here
1957 // FIXME check that?
1958 // FIXME replace Unknown by bound vars here
1960 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(&Interner) };
1962 let env = self.env.clone();
1963 let krate = krate.id;
1965 method_resolution::iterate_method_candidates(
1972 method_resolution::LookupMode::MethodCall,
1974 AssocItemId::FunctionId(f) => callback(ty, f.into()),
1980 pub fn iterate_path_candidates<T>(
1982 db: &dyn HirDatabase,
1984 traits_in_scope: &FxHashSet<TraitId>,
1985 name: Option<&Name>,
1986 mut callback: impl FnMut(&Ty, AssocItem) -> 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(
2004 method_resolution::LookupMode::Path,
2005 |ty, it| callback(ty, it.into()),
2009 pub fn as_adt(&self) -> Option<Adt> {
2010 let (adt, _subst) = self.ty.as_adt()?;
2014 pub fn as_dyn_trait(&self) -> Option<Trait> {
2015 self.ty.dyn_trait().map(Into::into)
2018 pub fn as_impl_traits(&self, db: &dyn HirDatabase) -> Option<Vec<Trait>> {
2019 self.ty.impl_trait_bounds(db).map(|it| {
2021 .filter_map(|pred| match pred.skip_binders() {
2022 hir_ty::WhereClause::Implemented(trait_ref) => {
2023 Some(Trait::from(trait_ref.hir_trait_id()))
2031 pub fn as_associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<Trait> {
2032 self.ty.associated_type_parent_trait(db).map(Into::into)
2035 fn derived(&self, ty: Ty) -> Type {
2036 Type { krate: self.krate, env: self.env.clone(), ty }
2039 pub fn walk(&self, db: &dyn HirDatabase, mut cb: impl FnMut(Type)) {
2040 // TypeWalk::walk for a Ty at first visits parameters and only after that the Ty itself.
2041 // We need a different order here.
2044 db: &dyn HirDatabase,
2046 substs: &Substitution,
2047 cb: &mut impl FnMut(Type),
2049 for ty in substs.iter() {
2050 walk_type(db, &type_.derived(ty.clone()), cb);
2055 db: &dyn HirDatabase,
2057 bounds: &[QuantifiedWhereClause],
2058 cb: &mut impl FnMut(Type),
2060 for pred in bounds {
2061 match pred.skip_binders() {
2062 WhereClause::Implemented(trait_ref) => {
2064 // skip the self type. it's likely the type we just got the bounds from
2065 for ty in trait_ref.substitution.iter().skip(1) {
2066 walk_type(db, &type_.derived(ty.clone()), cb);
2074 fn walk_type(db: &dyn HirDatabase, type_: &Type, cb: &mut impl FnMut(Type)) {
2075 let ty = type_.ty.strip_references();
2076 match ty.interned(&Interner) {
2077 TyKind::Adt(..) => {
2078 cb(type_.derived(ty.clone()));
2080 TyKind::AssociatedType(..) => {
2081 if let Some(_) = ty.associated_type_parent_trait(db) {
2082 cb(type_.derived(ty.clone()));
2085 TyKind::OpaqueType(..) => {
2086 if let Some(bounds) = ty.impl_trait_bounds(db) {
2087 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
2090 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
2091 if let Some(bounds) = ty.impl_trait_bounds(db) {
2092 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
2095 walk_substs(db, type_, &opaque_ty.substitution, cb);
2097 TyKind::Placeholder(_) => {
2098 if let Some(bounds) = ty.impl_trait_bounds(db) {
2099 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
2102 TyKind::Dyn(bounds) => {
2105 &type_.derived(ty.clone()),
2106 bounds.bounds.skip_binders().interned(),
2111 TyKind::Ref(_, ty) | TyKind::Raw(_, ty) | TyKind::Array(ty) | TyKind::Slice(ty) => {
2112 walk_type(db, &type_.derived(ty.clone()), cb);
2117 if let Some(substs) = ty.substs() {
2118 walk_substs(db, type_, &substs, cb);
2122 walk_type(db, self, &mut cb);
2128 pub struct Callable {
2131 def: Option<CallableDefId>,
2132 pub(crate) is_bound_method: bool,
2135 pub enum CallableKind {
2137 TupleStruct(Struct),
2138 TupleEnumVariant(Variant),
2143 pub fn kind(&self) -> CallableKind {
2145 Some(CallableDefId::FunctionId(it)) => CallableKind::Function(it.into()),
2146 Some(CallableDefId::StructId(it)) => CallableKind::TupleStruct(it.into()),
2147 Some(CallableDefId::EnumVariantId(it)) => CallableKind::TupleEnumVariant(it.into()),
2148 None => CallableKind::Closure,
2151 pub fn receiver_param(&self, db: &dyn HirDatabase) -> Option<ast::SelfParam> {
2152 let func = match self.def {
2153 Some(CallableDefId::FunctionId(it)) if self.is_bound_method => it,
2156 let src = func.lookup(db.upcast()).source(db.upcast());
2157 let param_list = src.value.param_list()?;
2158 param_list.self_param()
2160 pub fn n_params(&self) -> usize {
2161 self.sig.params().len() - if self.is_bound_method { 1 } else { 0 }
2165 db: &dyn HirDatabase,
2166 ) -> Vec<(Option<Either<ast::SelfParam, ast::Pat>>, Type)> {
2171 .skip(if self.is_bound_method { 1 } else { 0 })
2172 .map(|ty| self.ty.derived(ty.clone()));
2173 let patterns = match self.def {
2174 Some(CallableDefId::FunctionId(func)) => {
2175 let src = func.lookup(db.upcast()).source(db.upcast());
2176 src.value.param_list().map(|param_list| {
2179 .map(|it| Some(Either::Left(it)))
2180 .filter(|_| !self.is_bound_method)
2182 .chain(param_list.params().map(|it| it.pat().map(Either::Right)))
2187 patterns.into_iter().flatten().chain(iter::repeat(None)).zip(types).collect()
2189 pub fn return_type(&self) -> Type {
2190 self.ty.derived(self.sig.ret().clone())
2195 #[derive(Debug, PartialEq, Eq, Hash)]
2197 ModuleDef(ModuleDef),
2199 GenericParam(GenericParam),
2208 pub fn all_items(def: PerNs) -> ArrayVec<[Self; 3]> {
2209 let mut items = ArrayVec::new();
2211 match (def.take_types(), def.take_values()) {
2212 (Some(m1), None) => items.push(ScopeDef::ModuleDef(m1.into())),
2213 (None, Some(m2)) => items.push(ScopeDef::ModuleDef(m2.into())),
2214 (Some(m1), Some(m2)) => {
2215 // Some items, like unit structs and enum variants, are
2216 // returned as both a type and a value. Here we want
2217 // to de-duplicate them.
2219 items.push(ScopeDef::ModuleDef(m1.into()));
2220 items.push(ScopeDef::ModuleDef(m2.into()));
2222 items.push(ScopeDef::ModuleDef(m1.into()));
2228 if let Some(macro_def_id) = def.take_macros() {
2229 items.push(ScopeDef::MacroDef(macro_def_id.into()));
2232 if items.is_empty() {
2233 items.push(ScopeDef::Unknown);
2240 impl From<ItemInNs> for ScopeDef {
2241 fn from(item: ItemInNs) -> Self {
2243 ItemInNs::Types(id) => ScopeDef::ModuleDef(id.into()),
2244 ItemInNs::Values(id) => ScopeDef::ModuleDef(id.into()),
2245 ItemInNs::Macros(id) => ScopeDef::MacroDef(id.into()),
2250 pub trait HasVisibility {
2251 fn visibility(&self, db: &dyn HirDatabase) -> Visibility;
2252 fn is_visible_from(&self, db: &dyn HirDatabase, module: Module) -> bool {
2253 let vis = self.visibility(db);
2254 vis.is_visible_from(db.upcast(), module.id)