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, def_crates, TyFingerprint},
60 AliasEq, AliasTy, BoundVar, CallableDefId, CallableSig, Canonical, CanonicalVarKinds, Cast,
61 DebruijnIndex, InEnvironment, Interner, QuantifiedWhereClause, Scalar, Solution, Substitution,
62 TraitEnvironment, TraitRefExt, Ty, TyBuilder, TyDefId, TyExt, TyKind, TyVariableKind,
65 use itertools::Itertools;
66 use rustc_hash::FxHashSet;
67 use stdx::{format_to, impl_from};
69 ast::{self, AttrsOwner, NameOwner},
72 use tt::{Ident, Leaf, Literal, TokenTree};
74 use crate::db::{DefDatabase, HirDatabase};
77 attrs::{HasAttrs, Namespace},
78 has_source::HasSource,
79 semantics::{PathResolution, Semantics, SemanticsScope},
82 // Be careful with these re-exports.
84 // `hir` is the boundary between the compiler and the IDE. It should try hard to
85 // isolate the compiler from the ide, to allow the two to be refactored
86 // independently. Re-exporting something from the compiler is the sure way to
87 // breach the boundary.
89 // Generally, a refactoring which *removes* a name from this list is a good
92 cfg::{CfgAtom, CfgExpr, CfgOptions},
95 attr::{Attr, Attrs, AttrsWithOwner, Documentation},
96 body::scope::ExprScopes,
97 find_path::PrefixKind,
100 nameres::ModuleSource,
101 path::{ModPath, PathKind},
102 type_ref::{Mutability, TypeRef},
103 visibility::Visibility,
107 ExpandResult, HirFileId, InFile, MacroCallId, MacroCallLoc, /* FIXME */ MacroDefId,
110 hir_ty::display::HirDisplay,
113 // These are negative re-exports: pub using these names is forbidden, they
114 // should remain private to hir internals.
118 hir_expand::{hygiene::Hygiene, name::AsName},
121 /// hir::Crate describes a single crate. It's the main interface with which
122 /// a crate's dependencies interact. Mostly, it should be just a proxy for the
124 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
126 pub(crate) id: CrateId,
130 pub struct CrateDependency {
136 pub fn dependencies(self, db: &dyn HirDatabase) -> Vec<CrateDependency> {
137 db.crate_graph()[self.id]
141 let krate = Crate { id: dep.crate_id };
142 let name = dep.as_name();
143 CrateDependency { krate, name }
148 pub fn reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
149 let crate_graph = db.crate_graph();
153 crate_graph[krate].dependencies.iter().any(|it| it.crate_id == self.id)
155 .map(|id| Crate { id })
159 pub fn transitive_reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
160 db.crate_graph().transitive_rev_deps(self.id).into_iter().map(|id| Crate { id }).collect()
163 pub fn root_module(self, db: &dyn HirDatabase) -> Module {
164 let def_map = db.crate_def_map(self.id);
165 Module { id: def_map.module_id(def_map.root()) }
168 pub fn root_file(self, db: &dyn HirDatabase) -> FileId {
169 db.crate_graph()[self.id].root_file_id
172 pub fn edition(self, db: &dyn HirDatabase) -> Edition {
173 db.crate_graph()[self.id].edition
176 pub fn display_name(self, db: &dyn HirDatabase) -> Option<CrateDisplayName> {
177 db.crate_graph()[self.id].display_name.clone()
180 pub fn query_external_importables(
182 db: &dyn DefDatabase,
183 query: import_map::Query,
184 ) -> impl Iterator<Item = Either<ModuleDef, MacroDef>> {
185 import_map::search_dependencies(db, self.into(), query).into_iter().map(|item| match item {
186 ItemInNs::Types(mod_id) | ItemInNs::Values(mod_id) => Either::Left(mod_id.into()),
187 ItemInNs::Macros(mac_id) => Either::Right(mac_id.into()),
191 pub fn all(db: &dyn HirDatabase) -> Vec<Crate> {
192 db.crate_graph().iter().map(|id| Crate { id }).collect()
195 /// Try to get the root URL of the documentation of a crate.
196 pub fn get_html_root_url(self: &Crate, db: &dyn HirDatabase) -> Option<String> {
197 // Look for #![doc(html_root_url = "...")]
198 let attrs = db.attrs(AttrDefId::ModuleId(self.root_module(db).into()));
199 let doc_attr_q = attrs.by_key("doc");
201 if !doc_attr_q.exists() {
205 let doc_url = doc_attr_q.tt_values().map(|tt| {
206 let name = tt.token_trees.iter()
207 .skip_while(|tt| !matches!(tt, TokenTree::Leaf(Leaf::Ident(Ident{text: ref ident, ..})) if ident == "html_root_url"))
212 Some(TokenTree::Leaf(Leaf::Literal(Literal{ref text, ..}))) => Some(text),
217 doc_url.map(|s| s.trim_matches('"').trim_end_matches('/').to_owned() + "/")
220 pub fn cfg(&self, db: &dyn HirDatabase) -> CfgOptions {
221 db.crate_graph()[self.id].cfg_options.clone()
225 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
227 pub(crate) id: ModuleId,
230 /// The defs which can be visible in the module.
231 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
236 // Can't be directly declared, but can be imported.
241 TypeAlias(TypeAlias),
242 BuiltinType(BuiltinType),
247 Adt(Struct, Enum, Union),
257 impl From<VariantDef> for ModuleDef {
258 fn from(var: VariantDef) -> Self {
260 VariantDef::Struct(t) => Adt::from(t).into(),
261 VariantDef::Union(t) => Adt::from(t).into(),
262 VariantDef::Variant(t) => t.into(),
268 pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
270 ModuleDef::Module(it) => it.parent(db),
271 ModuleDef::Function(it) => Some(it.module(db)),
272 ModuleDef::Adt(it) => Some(it.module(db)),
273 ModuleDef::Variant(it) => Some(it.module(db)),
274 ModuleDef::Const(it) => Some(it.module(db)),
275 ModuleDef::Static(it) => Some(it.module(db)),
276 ModuleDef::Trait(it) => Some(it.module(db)),
277 ModuleDef::TypeAlias(it) => Some(it.module(db)),
278 ModuleDef::BuiltinType(_) => None,
282 pub fn canonical_path(&self, db: &dyn HirDatabase) -> Option<String> {
283 let mut segments = vec![self.name(db)?.to_string()];
284 for m in self.module(db)?.path_to_root(db) {
285 segments.extend(m.name(db).map(|it| it.to_string()))
288 Some(segments.join("::"))
291 pub fn definition_visibility(&self, db: &dyn HirDatabase) -> Option<Visibility> {
292 let module = match self {
293 ModuleDef::Module(it) => it.parent(db)?,
294 ModuleDef::Function(it) => return Some(it.visibility(db)),
295 ModuleDef::Adt(it) => it.module(db),
296 ModuleDef::Variant(it) => {
297 let parent = it.parent_enum(db);
298 let module = it.module(db);
299 return module.visibility_of(db, &ModuleDef::Adt(Adt::Enum(parent)));
301 ModuleDef::Const(it) => return Some(it.visibility(db)),
302 ModuleDef::Static(it) => it.module(db),
303 ModuleDef::Trait(it) => it.module(db),
304 ModuleDef::TypeAlias(it) => return Some(it.visibility(db)),
305 ModuleDef::BuiltinType(_) => return None,
308 module.visibility_of(db, self)
311 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
313 ModuleDef::Adt(it) => Some(it.name(db)),
314 ModuleDef::Trait(it) => Some(it.name(db)),
315 ModuleDef::Function(it) => Some(it.name(db)),
316 ModuleDef::Variant(it) => Some(it.name(db)),
317 ModuleDef::TypeAlias(it) => Some(it.name(db)),
318 ModuleDef::Module(it) => it.name(db),
319 ModuleDef::Const(it) => it.name(db),
320 ModuleDef::Static(it) => it.name(db),
321 ModuleDef::BuiltinType(it) => Some(it.name()),
325 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
326 let id = match self {
327 ModuleDef::Adt(it) => match it {
328 Adt::Struct(it) => it.id.into(),
329 Adt::Enum(it) => it.id.into(),
330 Adt::Union(it) => it.id.into(),
332 ModuleDef::Trait(it) => it.id.into(),
333 ModuleDef::Function(it) => it.id.into(),
334 ModuleDef::TypeAlias(it) => it.id.into(),
335 ModuleDef::Module(it) => it.id.into(),
336 ModuleDef::Const(it) => it.id.into(),
337 ModuleDef::Static(it) => it.id.into(),
341 let module = match self.module(db) {
346 hir_ty::diagnostics::validate_module_item(db, module.id.krate(), id, sink)
351 /// Name of this module.
352 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
353 let def_map = self.id.def_map(db.upcast());
354 let parent = def_map[self.id.local_id].parent?;
355 def_map[parent].children.iter().find_map(|(name, module_id)| {
356 if *module_id == self.id.local_id {
364 /// Returns the crate this module is part of.
365 pub fn krate(self) -> Crate {
366 Crate { id: self.id.krate() }
369 /// Topmost parent of this module. Every module has a `crate_root`, but some
370 /// might be missing `krate`. This can happen if a module's file is not included
371 /// in the module tree of any target in `Cargo.toml`.
372 pub fn crate_root(self, db: &dyn HirDatabase) -> Module {
373 let def_map = db.crate_def_map(self.id.krate());
374 Module { id: def_map.module_id(def_map.root()) }
377 /// Iterates over all child modules.
378 pub fn children(self, db: &dyn HirDatabase) -> impl Iterator<Item = Module> {
379 let def_map = self.id.def_map(db.upcast());
380 let children = def_map[self.id.local_id]
383 .map(|(_, module_id)| Module { id: def_map.module_id(*module_id) })
384 .collect::<Vec<_>>();
388 /// Finds a parent module.
389 pub fn parent(self, db: &dyn HirDatabase) -> Option<Module> {
390 // FIXME: handle block expressions as modules (their parent is in a different DefMap)
391 let def_map = self.id.def_map(db.upcast());
392 let parent_id = def_map[self.id.local_id].parent?;
393 Some(Module { id: def_map.module_id(parent_id) })
396 pub fn path_to_root(self, db: &dyn HirDatabase) -> Vec<Module> {
397 let mut res = vec![self];
399 while let Some(next) = curr.parent(db) {
406 /// Returns a `ModuleScope`: a set of items, visible in this module.
409 db: &dyn HirDatabase,
410 visible_from: Option<Module>,
411 ) -> Vec<(Name, ScopeDef)> {
412 self.id.def_map(db.upcast())[self.id.local_id]
415 .filter_map(|(name, def)| {
416 if let Some(m) = visible_from {
418 def.filter_visibility(|vis| vis.is_visible_from(db.upcast(), m.id));
419 if filtered.is_none() && !def.is_none() {
422 Some((name, filtered))
428 .flat_map(|(name, def)| {
429 ScopeDef::all_items(def).into_iter().map(move |item| (name.clone(), item))
434 pub fn visibility_of(self, db: &dyn HirDatabase, def: &ModuleDef) -> Option<Visibility> {
435 self.id.def_map(db.upcast())[self.id.local_id].scope.visibility_of(def.clone().into())
438 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
439 let _p = profile::span("Module::diagnostics").detail(|| {
440 format!("{:?}", self.name(db).map_or("<unknown>".into(), |name| name.to_string()))
442 let def_map = self.id.def_map(db.upcast());
443 def_map.add_diagnostics(db.upcast(), self.id.local_id, sink);
444 for decl in self.declarations(db) {
446 crate::ModuleDef::Function(f) => f.diagnostics(db, sink),
447 crate::ModuleDef::Module(m) => {
448 // Only add diagnostics from inline modules
449 if def_map[m.id.local_id].origin.is_inline() {
450 m.diagnostics(db, sink)
454 decl.diagnostics(db, sink);
459 for impl_def in self.impl_defs(db) {
460 for item in impl_def.items(db) {
461 if let AssocItem::Function(f) = item {
462 f.diagnostics(db, sink);
468 pub fn declarations(self, db: &dyn HirDatabase) -> Vec<ModuleDef> {
469 let def_map = self.id.def_map(db.upcast());
470 def_map[self.id.local_id].scope.declarations().map(ModuleDef::from).collect()
473 pub fn impl_defs(self, db: &dyn HirDatabase) -> Vec<Impl> {
474 let def_map = self.id.def_map(db.upcast());
475 def_map[self.id.local_id].scope.impls().map(Impl::from).collect()
478 /// Finds a path that can be used to refer to the given item from within
479 /// this module, if possible.
480 pub fn find_use_path(self, db: &dyn DefDatabase, item: impl Into<ItemInNs>) -> Option<ModPath> {
481 hir_def::find_path::find_path(db, item.into(), self.into())
484 /// Finds a path that can be used to refer to the given item from within
485 /// this module, if possible. This is used for returning import paths for use-statements.
486 pub fn find_use_path_prefixed(
488 db: &dyn DefDatabase,
489 item: impl Into<ItemInNs>,
490 prefix_kind: PrefixKind,
491 ) -> Option<ModPath> {
492 hir_def::find_path::find_path_prefixed(db, item.into(), self.into(), prefix_kind)
496 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
498 pub(crate) parent: VariantDef,
499 pub(crate) id: LocalFieldId,
502 #[derive(Debug, PartialEq, Eq)]
503 pub enum FieldSource {
504 Named(ast::RecordField),
505 Pos(ast::TupleField),
509 pub fn name(&self, db: &dyn HirDatabase) -> Name {
510 self.parent.variant_data(db).fields()[self.id].name.clone()
513 /// Returns the type as in the signature of the struct (i.e., with
514 /// placeholder types for type parameters). This is good for showing
515 /// signature help, but not so good to actually get the type of the field
516 /// when you actually have a variable of the struct.
517 pub fn ty(&self, db: &dyn HirDatabase) -> Type {
518 let var_id = self.parent.into();
519 let generic_def_id: GenericDefId = match self.parent {
520 VariantDef::Struct(it) => it.id.into(),
521 VariantDef::Union(it) => it.id.into(),
522 VariantDef::Variant(it) => it.parent.id.into(),
524 let substs = TyBuilder::type_params_subst(db, generic_def_id);
525 let ty = db.field_types(var_id)[self.id].clone().substitute(&Interner, &substs);
526 Type::new(db, self.parent.module(db).id.krate(), var_id, ty)
529 pub fn parent_def(&self, _db: &dyn HirDatabase) -> VariantDef {
534 impl HasVisibility for Field {
535 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
536 let variant_data = self.parent.variant_data(db);
537 let visibility = &variant_data.fields()[self.id].visibility;
538 let parent_id: hir_def::VariantId = self.parent.into();
539 visibility.resolve(db.upcast(), &parent_id.resolver(db.upcast()))
543 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
545 pub(crate) id: StructId,
549 pub fn module(self, db: &dyn HirDatabase) -> Module {
550 Module { id: self.id.lookup(db.upcast()).container }
553 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
554 Some(self.module(db).krate())
557 pub fn name(self, db: &dyn HirDatabase) -> Name {
558 db.struct_data(self.id).name.clone()
561 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
562 db.struct_data(self.id)
566 .map(|(id, _)| Field { parent: self.into(), id })
570 pub fn ty(self, db: &dyn HirDatabase) -> Type {
571 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
574 pub fn repr(self, db: &dyn HirDatabase) -> Option<ReprKind> {
575 db.struct_data(self.id).repr.clone()
578 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
579 self.variant_data(db).kind()
582 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
583 db.struct_data(self.id).variant_data.clone()
587 impl HasVisibility for Struct {
588 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
589 db.struct_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
593 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
595 pub(crate) id: UnionId,
599 pub fn name(self, db: &dyn HirDatabase) -> Name {
600 db.union_data(self.id).name.clone()
603 pub fn module(self, db: &dyn HirDatabase) -> Module {
604 Module { id: self.id.lookup(db.upcast()).container }
607 pub fn ty(self, db: &dyn HirDatabase) -> Type {
608 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
611 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
612 db.union_data(self.id)
616 .map(|(id, _)| Field { parent: self.into(), id })
620 fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
621 db.union_data(self.id).variant_data.clone()
625 impl HasVisibility for Union {
626 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
627 db.union_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
631 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
633 pub(crate) id: EnumId,
637 pub fn module(self, db: &dyn HirDatabase) -> Module {
638 Module { id: self.id.lookup(db.upcast()).container }
641 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
642 Some(self.module(db).krate())
645 pub fn name(self, db: &dyn HirDatabase) -> Name {
646 db.enum_data(self.id).name.clone()
649 pub fn variants(self, db: &dyn HirDatabase) -> Vec<Variant> {
650 db.enum_data(self.id).variants.iter().map(|(id, _)| Variant { parent: self, id }).collect()
653 pub fn ty(self, db: &dyn HirDatabase) -> Type {
654 Type::from_def(db, self.id.lookup(db.upcast()).container.krate(), self.id)
658 impl HasVisibility for Enum {
659 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
660 db.enum_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
664 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
666 pub(crate) parent: Enum,
667 pub(crate) id: LocalEnumVariantId,
671 pub fn module(self, db: &dyn HirDatabase) -> Module {
672 self.parent.module(db)
674 pub fn parent_enum(self, _db: &dyn HirDatabase) -> Enum {
678 pub fn name(self, db: &dyn HirDatabase) -> Name {
679 db.enum_data(self.parent.id).variants[self.id].name.clone()
682 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
683 self.variant_data(db)
686 .map(|(id, _)| Field { parent: self.into(), id })
690 pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
691 self.variant_data(db).kind()
694 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
695 db.enum_data(self.parent.id).variants[self.id].variant_data.clone()
700 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
706 impl_from!(Struct, Union, Enum for Adt);
709 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
710 let subst = db.generic_defaults(self.into());
711 subst.iter().any(|ty| ty.skip_binders().is_unknown())
714 /// Turns this ADT into a type. Any type parameters of the ADT will be
715 /// turned into unknown types, which is good for e.g. finding the most
716 /// general set of completions, but will not look very nice when printed.
717 pub fn ty(self, db: &dyn HirDatabase) -> Type {
718 let id = AdtId::from(self);
719 Type::from_def(db, id.module(db.upcast()).krate(), id)
722 pub fn module(self, db: &dyn HirDatabase) -> Module {
724 Adt::Struct(s) => s.module(db),
725 Adt::Union(s) => s.module(db),
726 Adt::Enum(e) => e.module(db),
730 pub fn krate(self, db: &dyn HirDatabase) -> Crate {
731 self.module(db).krate()
734 pub fn name(self, db: &dyn HirDatabase) -> Name {
736 Adt::Struct(s) => s.name(db),
737 Adt::Union(u) => u.name(db),
738 Adt::Enum(e) => e.name(db),
743 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
744 pub enum VariantDef {
749 impl_from!(Struct, Union, Variant for VariantDef);
752 pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
754 VariantDef::Struct(it) => it.fields(db),
755 VariantDef::Union(it) => it.fields(db),
756 VariantDef::Variant(it) => it.fields(db),
760 pub fn module(self, db: &dyn HirDatabase) -> Module {
762 VariantDef::Struct(it) => it.module(db),
763 VariantDef::Union(it) => it.module(db),
764 VariantDef::Variant(it) => it.module(db),
768 pub fn name(&self, db: &dyn HirDatabase) -> Name {
770 VariantDef::Struct(s) => s.name(db),
771 VariantDef::Union(u) => u.name(db),
772 VariantDef::Variant(e) => e.name(db),
776 pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
778 VariantDef::Struct(it) => it.variant_data(db),
779 VariantDef::Union(it) => it.variant_data(db),
780 VariantDef::Variant(it) => it.variant_data(db),
785 /// The defs which have a body.
786 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
787 pub enum DefWithBody {
792 impl_from!(Function, Const, Static for DefWithBody);
795 pub fn module(self, db: &dyn HirDatabase) -> Module {
797 DefWithBody::Const(c) => c.module(db),
798 DefWithBody::Function(f) => f.module(db),
799 DefWithBody::Static(s) => s.module(db),
803 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
805 DefWithBody::Function(f) => Some(f.name(db)),
806 DefWithBody::Static(s) => s.name(db),
807 DefWithBody::Const(c) => c.name(db),
812 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
813 pub struct Function {
814 pub(crate) id: FunctionId,
818 pub fn module(self, db: &dyn HirDatabase) -> Module {
819 self.id.lookup(db.upcast()).module(db.upcast()).into()
822 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
823 Some(self.module(db).krate())
826 pub fn name(self, db: &dyn HirDatabase) -> Name {
827 db.function_data(self.id).name.clone()
830 /// Get this function's return type
831 pub fn ret_type(self, db: &dyn HirDatabase) -> Type {
832 let resolver = self.id.resolver(db.upcast());
833 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
834 let ret_type = &db.function_data(self.id).ret_type;
835 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
836 let ty = ctx.lower_ty(ret_type);
837 Type::new_with_resolver_inner(db, krate, &resolver, ty)
840 pub fn self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
841 if !db.function_data(self.id).has_self_param() {
844 Some(SelfParam { func: self.id })
847 pub fn assoc_fn_params(self, db: &dyn HirDatabase) -> Vec<Param> {
848 let resolver = self.id.resolver(db.upcast());
849 let krate = self.id.lookup(db.upcast()).container.module(db.upcast()).krate();
850 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
851 let environment = db.trait_environment(self.id.into());
852 db.function_data(self.id)
856 .map(|(idx, type_ref)| {
857 let ty = Type { krate, env: environment.clone(), ty: ctx.lower_ty(type_ref) };
858 Param { func: self, ty, idx }
863 pub fn method_params(self, db: &dyn HirDatabase) -> Option<Vec<Param>> {
864 if self.self_param(db).is_none() {
867 let mut res = self.assoc_fn_params(db);
872 pub fn is_unsafe(self, db: &dyn HirDatabase) -> bool {
873 db.function_data(self.id).is_unsafe()
876 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
877 let krate = self.module(db).id.krate();
878 hir_def::diagnostics::validate_body(db.upcast(), self.id.into(), sink);
879 hir_ty::diagnostics::validate_module_item(db, krate, self.id.into(), sink);
880 hir_ty::diagnostics::validate_body(db, self.id.into(), sink);
883 /// Whether this function declaration has a definition.
885 /// This is false in the case of required (not provided) trait methods.
886 pub fn has_body(self, db: &dyn HirDatabase) -> bool {
887 db.function_data(self.id).has_body()
890 /// A textual representation of the HIR of this function for debugging purposes.
891 pub fn debug_hir(self, db: &dyn HirDatabase) -> String {
892 let body = db.body(self.id.into());
894 let mut result = String::new();
895 format_to!(result, "HIR expressions in the body of `{}`:\n", self.name(db));
896 for (id, expr) in body.exprs.iter() {
897 format_to!(result, "{:?}: {:?}\n", id, expr);
904 // Note: logically, this belongs to `hir_ty`, but we are not using it there yet.
911 impl From<hir_ty::Mutability> for Access {
912 fn from(mutability: hir_ty::Mutability) -> Access {
914 hir_ty::Mutability::Not => Access::Shared,
915 hir_ty::Mutability::Mut => Access::Exclusive,
920 #[derive(Clone, Debug)]
923 /// The index in parameter list, including self parameter.
929 pub fn ty(&self) -> &Type {
933 pub fn as_local(&self, db: &dyn HirDatabase) -> Local {
934 let parent = DefWithBodyId::FunctionId(self.func.into());
935 let body = db.body(parent);
936 Local { parent, pat_id: body.params[self.idx] }
939 pub fn pattern_source(&self, db: &dyn HirDatabase) -> Option<ast::Pat> {
940 self.source(db).and_then(|p| p.value.pat())
943 pub fn source(&self, db: &dyn HirDatabase) -> Option<InFile<ast::Param>> {
944 let InFile { file_id, value } = self.func.source(db)?;
945 let params = value.param_list()?;
946 if params.self_param().is_some() {
947 params.params().nth(self.idx.checked_sub(1)?)
949 params.params().nth(self.idx)
951 .map(|value| InFile { file_id, value })
955 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
956 pub struct SelfParam {
961 pub fn access(self, db: &dyn HirDatabase) -> Access {
962 let func_data = db.function_data(self.func);
966 .map(|param| match &**param {
967 TypeRef::Reference(.., mutability) => match mutability {
968 hir_def::type_ref::Mutability::Shared => Access::Shared,
969 hir_def::type_ref::Mutability::Mut => Access::Exclusive,
973 .unwrap_or(Access::Owned)
976 pub fn display(self, db: &dyn HirDatabase) -> &'static str {
977 match self.access(db) {
978 Access::Shared => "&self",
979 Access::Exclusive => "&mut self",
980 Access::Owned => "self",
984 pub fn source(&self, db: &dyn HirDatabase) -> Option<InFile<ast::SelfParam>> {
985 let InFile { file_id, value } = Function::from(self.func).source(db)?;
988 .and_then(|params| params.self_param())
989 .map(|value| InFile { file_id, value })
993 impl HasVisibility for Function {
994 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
995 let function_data = db.function_data(self.id);
996 let visibility = &function_data.visibility;
997 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1001 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1003 pub(crate) id: ConstId,
1007 pub fn module(self, db: &dyn HirDatabase) -> Module {
1008 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1011 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
1012 Some(self.module(db).krate())
1015 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1016 db.const_data(self.id).name.clone()
1019 pub fn type_ref(self, db: &dyn HirDatabase) -> TypeRef {
1020 db.const_data(self.id).type_ref.as_ref().clone()
1024 impl HasVisibility for Const {
1025 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1026 let function_data = db.const_data(self.id);
1027 let visibility = &function_data.visibility;
1028 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1032 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1034 pub(crate) id: StaticId,
1038 pub fn module(self, db: &dyn HirDatabase) -> Module {
1039 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1042 pub fn krate(self, db: &dyn HirDatabase) -> Option<Crate> {
1043 Some(self.module(db).krate())
1046 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1047 db.static_data(self.id).name.clone()
1050 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
1051 db.static_data(self.id).mutable
1055 impl HasVisibility for Static {
1056 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1057 db.static_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1061 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1063 pub(crate) id: TraitId,
1067 pub fn module(self, db: &dyn HirDatabase) -> Module {
1068 Module { id: self.id.lookup(db.upcast()).container }
1071 pub fn name(self, db: &dyn HirDatabase) -> Name {
1072 db.trait_data(self.id).name.clone()
1075 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
1076 db.trait_data(self.id).items.iter().map(|(_name, it)| (*it).into()).collect()
1079 pub fn is_auto(self, db: &dyn HirDatabase) -> bool {
1080 db.trait_data(self.id).is_auto
1084 impl HasVisibility for Trait {
1085 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1086 db.trait_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1090 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1091 pub struct TypeAlias {
1092 pub(crate) id: TypeAliasId,
1096 pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
1097 let subst = db.generic_defaults(self.id.into());
1098 subst.iter().any(|ty| ty.skip_binders().is_unknown())
1101 pub fn module(self, db: &dyn HirDatabase) -> Module {
1102 Module { id: self.id.lookup(db.upcast()).module(db.upcast()) }
1105 pub fn krate(self, db: &dyn HirDatabase) -> Crate {
1106 self.module(db).krate()
1109 pub fn type_ref(self, db: &dyn HirDatabase) -> Option<TypeRef> {
1110 db.type_alias_data(self.id).type_ref.as_deref().cloned()
1113 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1114 Type::from_def(db, self.id.lookup(db.upcast()).module(db.upcast()).krate(), self.id)
1117 pub fn name(self, db: &dyn HirDatabase) -> Name {
1118 db.type_alias_data(self.id).name.clone()
1122 impl HasVisibility for TypeAlias {
1123 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1124 let function_data = db.type_alias_data(self.id);
1125 let visibility = &function_data.visibility;
1126 visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1130 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1131 pub struct BuiltinType {
1132 pub(crate) inner: hir_def::builtin_type::BuiltinType,
1136 pub fn ty(self, db: &dyn HirDatabase, module: Module) -> Type {
1137 let resolver = module.id.resolver(db.upcast());
1138 Type::new_with_resolver(db, &resolver, TyBuilder::builtin(self.inner))
1139 .expect("crate not present in resolver")
1142 pub fn name(self) -> Name {
1143 self.inner.as_name()
1147 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1148 pub enum MacroKind {
1155 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1156 pub struct MacroDef {
1157 pub(crate) id: MacroDefId,
1161 /// FIXME: right now, this just returns the root module of the crate that
1162 /// defines this macro. The reasons for this is that macros are expanded
1163 /// early, in `hir_expand`, where modules simply do not exist yet.
1164 pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
1165 let krate = self.id.krate;
1166 let def_map = db.crate_def_map(krate);
1167 let module_id = def_map.root();
1168 Some(Module { id: def_map.module_id(module_id) })
1171 /// XXX: this parses the file
1172 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1173 match self.source(db)?.value {
1174 Either::Left(it) => it.name().map(|it| it.as_name()),
1175 Either::Right(it) => it.name().map(|it| it.as_name()),
1179 pub fn kind(&self) -> MacroKind {
1180 match self.id.kind {
1181 MacroDefKind::Declarative(_) => MacroKind::Declarative,
1182 MacroDefKind::BuiltIn(_, _) => MacroKind::BuiltIn,
1183 MacroDefKind::BuiltInDerive(_, _) => MacroKind::Derive,
1184 MacroDefKind::BuiltInEager(_, _) => MacroKind::BuiltIn,
1185 // FIXME might be a derive
1186 MacroDefKind::ProcMacro(_, _) => MacroKind::ProcMacro,
1191 /// Invariant: `inner.as_assoc_item(db).is_some()`
1192 /// We do not actively enforce this invariant.
1193 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1194 pub enum AssocItem {
1197 TypeAlias(TypeAlias),
1200 pub enum AssocItemContainer {
1204 pub trait AsAssocItem {
1205 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem>;
1208 impl AsAssocItem for Function {
1209 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1210 as_assoc_item(db, AssocItem::Function, self.id)
1213 impl AsAssocItem for Const {
1214 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1215 as_assoc_item(db, AssocItem::Const, self.id)
1218 impl AsAssocItem for TypeAlias {
1219 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1220 as_assoc_item(db, AssocItem::TypeAlias, self.id)
1223 impl AsAssocItem for ModuleDef {
1224 fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
1226 ModuleDef::Function(it) => it.as_assoc_item(db),
1227 ModuleDef::Const(it) => it.as_assoc_item(db),
1228 ModuleDef::TypeAlias(it) => it.as_assoc_item(db),
1233 fn as_assoc_item<ID, DEF, CTOR, AST>(db: &dyn HirDatabase, ctor: CTOR, id: ID) -> Option<AssocItem>
1235 ID: Lookup<Data = AssocItemLoc<AST>>,
1237 CTOR: FnOnce(DEF) -> AssocItem,
1240 match id.lookup(db.upcast()).container {
1241 AssocContainerId::TraitId(_) | AssocContainerId::ImplId(_) => Some(ctor(DEF::from(id))),
1242 AssocContainerId::ModuleId(_) => None,
1247 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1249 AssocItem::Function(it) => Some(it.name(db)),
1250 AssocItem::Const(it) => it.name(db),
1251 AssocItem::TypeAlias(it) => Some(it.name(db)),
1254 pub fn module(self, db: &dyn HirDatabase) -> Module {
1256 AssocItem::Function(f) => f.module(db),
1257 AssocItem::Const(c) => c.module(db),
1258 AssocItem::TypeAlias(t) => t.module(db),
1261 pub fn container(self, db: &dyn HirDatabase) -> AssocItemContainer {
1262 let container = match self {
1263 AssocItem::Function(it) => it.id.lookup(db.upcast()).container,
1264 AssocItem::Const(it) => it.id.lookup(db.upcast()).container,
1265 AssocItem::TypeAlias(it) => it.id.lookup(db.upcast()).container,
1268 AssocContainerId::TraitId(id) => AssocItemContainer::Trait(id.into()),
1269 AssocContainerId::ImplId(id) => AssocItemContainer::Impl(id.into()),
1270 AssocContainerId::ModuleId(_) => panic!("invalid AssocItem"),
1274 pub fn containing_trait(self, db: &dyn HirDatabase) -> Option<Trait> {
1275 match self.container(db) {
1276 AssocItemContainer::Trait(t) => Some(t),
1282 impl HasVisibility for AssocItem {
1283 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1285 AssocItem::Function(f) => f.visibility(db),
1286 AssocItem::Const(c) => c.visibility(db),
1287 AssocItem::TypeAlias(t) => t.visibility(db),
1292 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
1293 pub enum GenericDef {
1297 TypeAlias(TypeAlias),
1299 // enum variants cannot have generics themselves, but their parent enums
1300 // can, and this makes some code easier to write
1302 // consts can have type parameters from their parents (i.e. associated consts of traits)
1307 Adt(Struct, Enum, Union),
1317 pub fn params(self, db: &dyn HirDatabase) -> Vec<GenericParam> {
1318 let generics = db.generic_params(self.into());
1319 let ty_params = generics
1322 .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
1323 .map(GenericParam::TypeParam);
1324 let lt_params = generics
1327 .map(|(local_id, _)| LifetimeParam {
1328 id: LifetimeParamId { parent: self.into(), local_id },
1330 .map(GenericParam::LifetimeParam);
1331 let const_params = generics
1334 .map(|(local_id, _)| ConstParam { id: ConstParamId { parent: self.into(), local_id } })
1335 .map(GenericParam::ConstParam);
1336 ty_params.chain(lt_params).chain(const_params).collect()
1339 pub fn type_params(self, db: &dyn HirDatabase) -> Vec<TypeParam> {
1340 let generics = db.generic_params(self.into());
1344 .map(|(local_id, _)| TypeParam { id: TypeParamId { parent: self.into(), local_id } })
1349 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1351 pub(crate) parent: DefWithBodyId,
1352 pub(crate) pat_id: PatId,
1356 pub fn is_param(self, db: &dyn HirDatabase) -> bool {
1357 let src = self.source(db);
1359 Either::Left(bind_pat) => {
1360 bind_pat.syntax().ancestors().any(|it| ast::Param::can_cast(it.kind()))
1362 Either::Right(_self_param) => true,
1366 pub fn as_self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
1368 DefWithBodyId::FunctionId(func) if self.is_self(db) => Some(SelfParam { func }),
1373 // FIXME: why is this an option? It shouldn't be?
1374 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1375 let body = db.body(self.parent);
1376 match &body[self.pat_id] {
1377 Pat::Bind { name, .. } => Some(name.clone()),
1382 pub fn is_self(self, db: &dyn HirDatabase) -> bool {
1383 self.name(db) == Some(name![self])
1386 pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
1387 let body = db.body(self.parent);
1388 matches!(&body[self.pat_id], Pat::Bind { mode: BindingAnnotation::Mutable, .. })
1391 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
1395 pub fn module(self, db: &dyn HirDatabase) -> Module {
1396 self.parent(db).module(db)
1399 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1400 let def = self.parent;
1401 let infer = db.infer(def);
1402 let ty = infer[self.pat_id].clone();
1403 let krate = def.module(db.upcast()).krate();
1404 Type::new(db, krate, def, ty)
1407 pub fn source(self, db: &dyn HirDatabase) -> InFile<Either<ast::IdentPat, ast::SelfParam>> {
1408 let (_body, source_map) = db.body_with_source_map(self.parent);
1409 let src = source_map.pat_syntax(self.pat_id).unwrap(); // Hmm...
1410 let root = src.file_syntax(db.upcast());
1412 ast.map_left(|it| it.cast().unwrap().to_node(&root)).map_right(|it| it.to_node(&root))
1417 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1419 pub(crate) parent: DefWithBodyId,
1420 pub(crate) label_id: LabelId,
1424 pub fn module(self, db: &dyn HirDatabase) -> Module {
1425 self.parent(db).module(db)
1428 pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
1432 pub fn name(self, db: &dyn HirDatabase) -> Name {
1433 let body = db.body(self.parent);
1434 body[self.label_id].name.clone()
1437 pub fn source(self, db: &dyn HirDatabase) -> InFile<ast::Label> {
1438 let (_body, source_map) = db.body_with_source_map(self.parent);
1439 let src = source_map.label_syntax(self.label_id);
1440 let root = src.file_syntax(db.upcast());
1441 src.map(|ast| ast.to_node(&root))
1445 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1446 pub enum GenericParam {
1447 TypeParam(TypeParam),
1448 LifetimeParam(LifetimeParam),
1449 ConstParam(ConstParam),
1451 impl_from!(TypeParam, LifetimeParam, ConstParam for GenericParam);
1454 pub fn module(self, db: &dyn HirDatabase) -> Module {
1456 GenericParam::TypeParam(it) => it.module(db),
1457 GenericParam::LifetimeParam(it) => it.module(db),
1458 GenericParam::ConstParam(it) => it.module(db),
1462 pub fn name(self, db: &dyn HirDatabase) -> Name {
1464 GenericParam::TypeParam(it) => it.name(db),
1465 GenericParam::LifetimeParam(it) => it.name(db),
1466 GenericParam::ConstParam(it) => it.name(db),
1471 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1472 pub struct TypeParam {
1473 pub(crate) id: TypeParamId,
1477 pub fn name(self, db: &dyn HirDatabase) -> Name {
1478 let params = db.generic_params(self.id.parent);
1479 params.types[self.id.local_id].name.clone().unwrap_or_else(Name::missing)
1482 pub fn module(self, db: &dyn HirDatabase) -> Module {
1483 self.id.parent.module(db.upcast()).into()
1486 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1487 let resolver = self.id.parent.resolver(db.upcast());
1488 let krate = self.id.parent.module(db.upcast()).krate();
1489 let ty = TyKind::Placeholder(hir_ty::to_placeholder_idx(db, self.id)).intern(&Interner);
1490 Type::new_with_resolver_inner(db, krate, &resolver, ty)
1493 pub fn trait_bounds(self, db: &dyn HirDatabase) -> Vec<Trait> {
1494 db.generic_predicates_for_param(self.id)
1496 .filter_map(|pred| match &pred.skip_binders().skip_binders() {
1497 hir_ty::WhereClause::Implemented(trait_ref) => {
1498 Some(Trait::from(trait_ref.hir_trait_id()))
1505 pub fn default(self, db: &dyn HirDatabase) -> Option<Type> {
1506 let params = db.generic_defaults(self.id.parent);
1507 let local_idx = hir_ty::param_idx(db, self.id)?;
1508 let resolver = self.id.parent.resolver(db.upcast());
1509 let krate = self.id.parent.module(db.upcast()).krate();
1510 let ty = params.get(local_idx)?.clone();
1511 let subst = TyBuilder::type_params_subst(db, self.id.parent);
1512 let ty = ty.substitute(&Interner, &subst_prefix(&subst, local_idx));
1513 Some(Type::new_with_resolver_inner(db, krate, &resolver, ty))
1517 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1518 pub struct LifetimeParam {
1519 pub(crate) id: LifetimeParamId,
1522 impl LifetimeParam {
1523 pub fn name(self, db: &dyn HirDatabase) -> Name {
1524 let params = db.generic_params(self.id.parent);
1525 params.lifetimes[self.id.local_id].name.clone()
1528 pub fn module(self, db: &dyn HirDatabase) -> Module {
1529 self.id.parent.module(db.upcast()).into()
1532 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
1533 self.id.parent.into()
1537 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1538 pub struct ConstParam {
1539 pub(crate) id: ConstParamId,
1543 pub fn name(self, db: &dyn HirDatabase) -> Name {
1544 let params = db.generic_params(self.id.parent);
1545 params.consts[self.id.local_id].name.clone()
1548 pub fn module(self, db: &dyn HirDatabase) -> Module {
1549 self.id.parent.module(db.upcast()).into()
1552 pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
1553 self.id.parent.into()
1556 pub fn ty(self, db: &dyn HirDatabase) -> Type {
1557 let def = self.id.parent;
1558 let krate = def.module(db.upcast()).krate();
1559 Type::new(db, krate, def, db.const_param_ty(self.id))
1563 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1565 pub(crate) id: ImplId,
1569 pub fn all_in_crate(db: &dyn HirDatabase, krate: Crate) -> Vec<Impl> {
1570 let inherent = db.inherent_impls_in_crate(krate.id);
1571 let trait_ = db.trait_impls_in_crate(krate.id);
1573 inherent.all_impls().chain(trait_.all_impls()).map(Self::from).collect()
1576 pub fn all_for_type(db: &dyn HirDatabase, Type { krate, ty, .. }: Type) -> Vec<Impl> {
1577 let def_crates = match def_crates(db, &ty, krate) {
1578 Some(def_crates) => def_crates,
1579 None => return Vec::new(),
1582 let filter = |impl_def: &Impl| {
1583 let self_ty = impl_def.self_ty(db);
1584 let rref = self_ty.remove_ref();
1585 ty.equals_ctor(rref.as_ref().map_or(&self_ty.ty, |it| &it.ty))
1588 let fp = TyFingerprint::for_inherent_impl(&ty);
1589 let fp = if let Some(fp) = fp {
1595 let mut all = Vec::new();
1596 def_crates.iter().for_each(|&id| {
1598 db.inherent_impls_in_crate(id)
1606 for id in def_crates
1608 .flat_map(|&id| Crate { id }.transitive_reverse_dependencies(db))
1609 .map(|Crate { id }| id)
1610 .chain(def_crates.iter().copied())
1614 db.trait_impls_in_crate(id)
1615 .for_self_ty_without_blanket_impls(fp)
1623 pub fn all_for_trait(db: &dyn HirDatabase, trait_: Trait) -> Vec<Impl> {
1624 let krate = trait_.module(db).krate();
1625 let mut all = Vec::new();
1626 for Crate { id } in krate.transitive_reverse_dependencies(db).into_iter() {
1627 let impls = db.trait_impls_in_crate(id);
1628 all.extend(impls.for_trait(trait_.id).map(Self::from))
1633 // FIXME: the return type is wrong. This should be a hir version of
1634 // `TraitRef` (ie, resolved `TypeRef`).
1635 pub fn trait_(self, db: &dyn HirDatabase) -> Option<TraitRef> {
1636 db.impl_data(self.id).target_trait.as_deref().cloned()
1639 pub fn self_ty(self, db: &dyn HirDatabase) -> Type {
1640 let impl_data = db.impl_data(self.id);
1641 let resolver = self.id.resolver(db.upcast());
1642 let krate = self.id.lookup(db.upcast()).container.krate();
1643 let ctx = hir_ty::TyLoweringContext::new(db, &resolver);
1644 let ty = ctx.lower_ty(&impl_data.self_ty);
1645 Type::new_with_resolver_inner(db, krate, &resolver, ty)
1648 pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
1649 db.impl_data(self.id).items.iter().map(|it| (*it).into()).collect()
1652 pub fn is_negative(self, db: &dyn HirDatabase) -> bool {
1653 db.impl_data(self.id).is_negative
1656 pub fn module(self, db: &dyn HirDatabase) -> Module {
1657 self.id.lookup(db.upcast()).container.into()
1660 pub fn krate(self, db: &dyn HirDatabase) -> Crate {
1661 Crate { id: self.module(db).id.krate() }
1664 pub fn is_builtin_derive(self, db: &dyn HirDatabase) -> Option<InFile<ast::Attr>> {
1665 let src = self.source(db)?;
1666 let item = src.file_id.is_builtin_derive(db.upcast())?;
1667 let hygenic = hir_expand::hygiene::Hygiene::new(db.upcast(), item.file_id);
1669 // FIXME: handle `cfg_attr`
1674 let path = ModPath::from_src(db.upcast(), it.path()?, &hygenic)?;
1675 if path.as_ident()?.to_string() == "derive" {
1683 Some(item.with_value(attr))
1687 #[derive(Clone, PartialEq, Eq, Debug)]
1690 env: Arc<TraitEnvironment>,
1695 pub(crate) fn new_with_resolver(
1696 db: &dyn HirDatabase,
1697 resolver: &Resolver,
1700 let krate = resolver.krate()?;
1701 Some(Type::new_with_resolver_inner(db, krate, resolver, ty))
1703 pub(crate) fn new_with_resolver_inner(
1704 db: &dyn HirDatabase,
1706 resolver: &Resolver,
1710 resolver.generic_def().map_or_else(Default::default, |d| db.trait_environment(d));
1711 Type { krate, env: environment, ty }
1714 fn new(db: &dyn HirDatabase, krate: CrateId, lexical_env: impl HasResolver, ty: Ty) -> Type {
1715 let resolver = lexical_env.resolver(db.upcast());
1717 resolver.generic_def().map_or_else(Default::default, |d| db.trait_environment(d));
1718 Type { krate, env: environment, ty }
1722 db: &dyn HirDatabase,
1724 def: impl HasResolver + Into<TyDefId>,
1726 let ty = TyBuilder::def_ty(db, def.into()).fill_with_unknown().build();
1727 Type::new(db, krate, def, ty)
1730 pub fn is_unit(&self) -> bool {
1731 matches!(self.ty.kind(&Interner), TyKind::Tuple(0, ..))
1733 pub fn is_bool(&self) -> bool {
1734 matches!(self.ty.kind(&Interner), TyKind::Scalar(Scalar::Bool))
1737 pub fn is_mutable_reference(&self) -> bool {
1738 matches!(self.ty.kind(&Interner), TyKind::Ref(hir_ty::Mutability::Mut, ..))
1741 pub fn is_usize(&self) -> bool {
1742 matches!(self.ty.kind(&Interner), TyKind::Scalar(Scalar::Uint(UintTy::Usize)))
1745 pub fn remove_ref(&self) -> Option<Type> {
1746 match &self.ty.kind(&Interner) {
1747 TyKind::Ref(.., ty) => Some(self.derived(ty.clone())),
1752 pub fn strip_references(&self) -> Type {
1753 self.derived(self.ty.strip_references().clone())
1756 pub fn is_unknown(&self) -> bool {
1757 self.ty.is_unknown()
1760 /// Checks that particular type `ty` implements `std::future::Future`.
1761 /// This function is used in `.await` syntax completion.
1762 pub fn impls_future(&self, db: &dyn HirDatabase) -> bool {
1763 // No special case for the type of async block, since Chalk can figure it out.
1765 let krate = self.krate;
1767 let std_future_trait =
1768 db.lang_item(krate, "future_trait".into()).and_then(|it| it.as_trait());
1769 let std_future_trait = match std_future_trait {
1771 None => return false,
1775 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(&Interner) };
1776 method_resolution::implements_trait(
1785 /// Checks that particular type `ty` implements `std::ops::FnOnce`.
1787 /// This function can be used to check if a particular type is callable, since FnOnce is a
1788 /// supertrait of Fn and FnMut, so all callable types implements at least FnOnce.
1789 pub fn impls_fnonce(&self, db: &dyn HirDatabase) -> bool {
1790 let krate = self.krate;
1792 let fnonce_trait = match FnTrait::FnOnce.get_id(db, krate) {
1794 None => return false,
1798 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(&Interner) };
1799 method_resolution::implements_trait_unique(
1808 pub fn impls_trait(&self, db: &dyn HirDatabase, trait_: Trait, args: &[Type]) -> bool {
1809 let trait_ref = TyBuilder::trait_ref(db, trait_.id)
1810 .push(self.ty.clone())
1811 .fill(args.iter().map(|t| t.ty.clone()))
1814 let goal = Canonical {
1815 value: hir_ty::InEnvironment::new(&self.env.env, trait_ref.cast(&Interner)),
1816 binders: CanonicalVarKinds::empty(&Interner),
1819 db.trait_solve(self.krate, goal).is_some()
1822 pub fn normalize_trait_assoc_type(
1824 db: &dyn HirDatabase,
1828 let projection = TyBuilder::assoc_type_projection(db, alias.id)
1829 .push(self.ty.clone())
1830 .fill(args.iter().map(|t| t.ty.clone()))
1832 let goal = hir_ty::make_canonical(
1836 alias: AliasTy::Projection(projection),
1837 ty: TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0))
1842 [TyVariableKind::General].iter().copied(),
1845 match db.trait_solve(self.krate, goal)? {
1846 Solution::Unique(s) => s
1849 .as_slice(&Interner)
1851 .map(|ty| self.derived(ty.assert_ty_ref(&Interner).clone())),
1852 Solution::Ambig(_) => None,
1856 pub fn is_copy(&self, db: &dyn HirDatabase) -> bool {
1857 let lang_item = db.lang_item(self.krate, SmolStr::new("copy"));
1858 let copy_trait = match lang_item {
1859 Some(LangItemTarget::TraitId(it)) => it,
1862 self.impls_trait(db, copy_trait.into(), &[])
1865 pub fn as_callable(&self, db: &dyn HirDatabase) -> Option<Callable> {
1866 let def = self.ty.callable_def(db);
1868 let sig = self.ty.callable_sig(db)?;
1869 Some(Callable { ty: self.clone(), sig, def, is_bound_method: false })
1872 pub fn is_closure(&self) -> bool {
1873 matches!(&self.ty.kind(&Interner), TyKind::Closure { .. })
1876 pub fn is_fn(&self) -> bool {
1877 matches!(&self.ty.kind(&Interner), TyKind::FnDef(..) | TyKind::Function { .. })
1880 pub fn is_packed(&self, db: &dyn HirDatabase) -> bool {
1881 let adt_id = match self.ty.kind(&Interner) {
1882 &TyKind::Adt(hir_ty::AdtId(adt_id), ..) => adt_id,
1886 let adt = adt_id.into();
1888 Adt::Struct(s) => matches!(s.repr(db), Some(ReprKind::Packed)),
1893 pub fn is_raw_ptr(&self) -> bool {
1894 matches!(&self.ty.kind(&Interner), TyKind::Raw(..))
1897 pub fn contains_unknown(&self) -> bool {
1898 return go(&self.ty);
1900 fn go(ty: &Ty) -> bool {
1901 match ty.kind(&Interner) {
1902 TyKind::Error => true,
1904 TyKind::Adt(_, substs)
1905 | TyKind::AssociatedType(_, substs)
1906 | TyKind::Tuple(_, substs)
1907 | TyKind::OpaqueType(_, substs)
1908 | TyKind::FnDef(_, substs)
1909 | TyKind::Closure(_, substs) => {
1910 substs.iter(&Interner).filter_map(|a| a.ty(&Interner)).any(go)
1913 TyKind::Array(ty, _)
1915 | TyKind::Raw(_, ty)
1916 | TyKind::Ref(_, _, ty) => go(ty),
1921 | TyKind::Placeholder(_)
1922 | TyKind::BoundVar(_)
1923 | TyKind::InferenceVar(_, _)
1925 | TyKind::Function(_)
1927 | TyKind::Foreign(_)
1928 | TyKind::Generator(..)
1929 | TyKind::GeneratorWitness(..) => false,
1934 pub fn fields(&self, db: &dyn HirDatabase) -> Vec<(Field, Type)> {
1935 let (variant_id, substs) = match self.ty.kind(&Interner) {
1936 &TyKind::Adt(hir_ty::AdtId(AdtId::StructId(s)), ref substs) => (s.into(), substs),
1937 &TyKind::Adt(hir_ty::AdtId(AdtId::UnionId(u)), ref substs) => (u.into(), substs),
1938 _ => return Vec::new(),
1941 db.field_types(variant_id)
1943 .map(|(local_id, ty)| {
1944 let def = Field { parent: variant_id.into(), id: local_id };
1945 let ty = ty.clone().substitute(&Interner, substs);
1946 (def, self.derived(ty))
1951 pub fn tuple_fields(&self, _db: &dyn HirDatabase) -> Vec<Type> {
1952 if let TyKind::Tuple(_, substs) = &self.ty.kind(&Interner) {
1955 .map(|ty| self.derived(ty.assert_ty_ref(&Interner).clone()))
1962 pub fn autoderef<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Type> + 'a {
1963 // There should be no inference vars in types passed here
1964 // FIXME check that?
1966 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(&Interner) };
1967 let environment = self.env.env.clone();
1968 let ty = InEnvironment { goal: canonical, environment };
1969 autoderef(db, Some(self.krate), ty)
1970 .map(|canonical| canonical.value)
1971 .map(move |ty| self.derived(ty))
1974 // This would be nicer if it just returned an iterator, but that runs into
1975 // lifetime problems, because we need to borrow temp `CrateImplDefs`.
1976 pub fn iterate_assoc_items<T>(
1978 db: &dyn HirDatabase,
1980 mut callback: impl FnMut(AssocItem) -> Option<T>,
1982 for krate in def_crates(db, &self.ty, krate.id)? {
1983 let impls = db.inherent_impls_in_crate(krate);
1985 for impl_def in impls.for_self_ty(&self.ty) {
1986 for &item in db.impl_data(*impl_def).items.iter() {
1987 if let Some(result) = callback(item.into()) {
1988 return Some(result);
1996 pub fn type_arguments(&self) -> impl Iterator<Item = Type> + '_ {
2001 .flat_map(|(_, substs)| substs.iter(&Interner))
2002 .filter_map(|arg| arg.ty(&Interner).cloned())
2003 .map(move |ty| self.derived(ty))
2006 pub fn iterate_method_candidates<T>(
2008 db: &dyn HirDatabase,
2010 traits_in_scope: &FxHashSet<TraitId>,
2011 name: Option<&Name>,
2012 mut callback: impl FnMut(&Ty, Function) -> Option<T>,
2014 // There should be no inference vars in types passed here
2015 // FIXME check that?
2016 // FIXME replace Unknown by bound vars here
2018 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(&Interner) };
2020 let env = self.env.clone();
2021 let krate = krate.id;
2023 method_resolution::iterate_method_candidates(
2031 method_resolution::LookupMode::MethodCall,
2033 AssocItemId::FunctionId(f) => callback(ty, f.into()),
2039 pub fn iterate_path_candidates<T>(
2041 db: &dyn HirDatabase,
2043 traits_in_scope: &FxHashSet<TraitId>,
2044 name: Option<&Name>,
2045 mut callback: impl FnMut(&Ty, AssocItem) -> Option<T>,
2047 // There should be no inference vars in types passed here
2048 // FIXME check that?
2049 // FIXME replace Unknown by bound vars here
2051 Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(&Interner) };
2053 let env = self.env.clone();
2054 let krate = krate.id;
2056 method_resolution::iterate_method_candidates(
2064 method_resolution::LookupMode::Path,
2065 |ty, it| callback(ty, it.into()),
2069 pub fn as_adt(&self) -> Option<Adt> {
2070 let (adt, _subst) = self.ty.as_adt()?;
2074 pub fn as_builtin(&self) -> Option<BuiltinType> {
2075 self.ty.as_builtin().map(|inner| BuiltinType { inner })
2078 pub fn as_dyn_trait(&self) -> Option<Trait> {
2079 self.ty.dyn_trait().map(Into::into)
2082 /// If a type can be represented as `dyn Trait`, returns all traits accessible via this type,
2083 /// or an empty iterator otherwise.
2084 pub fn applicable_inherent_traits<'a>(
2086 db: &'a dyn HirDatabase,
2087 ) -> impl Iterator<Item = Trait> + 'a {
2089 .filter_map(|derefed_type| derefed_type.ty.dyn_trait())
2090 .flat_map(move |dyn_trait_id| hir_ty::all_super_traits(db.upcast(), dyn_trait_id))
2094 pub fn as_impl_traits(&self, db: &dyn HirDatabase) -> Option<Vec<Trait>> {
2095 self.ty.impl_trait_bounds(db).map(|it| {
2097 .filter_map(|pred| match pred.skip_binders() {
2098 hir_ty::WhereClause::Implemented(trait_ref) => {
2099 Some(Trait::from(trait_ref.hir_trait_id()))
2107 pub fn as_associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<Trait> {
2108 self.ty.associated_type_parent_trait(db).map(Into::into)
2111 fn derived(&self, ty: Ty) -> Type {
2112 Type { krate: self.krate, env: self.env.clone(), ty }
2115 pub fn walk(&self, db: &dyn HirDatabase, mut cb: impl FnMut(Type)) {
2116 // TypeWalk::walk for a Ty at first visits parameters and only after that the Ty itself.
2117 // We need a different order here.
2120 db: &dyn HirDatabase,
2122 substs: &Substitution,
2123 cb: &mut impl FnMut(Type),
2125 for ty in substs.iter(&Interner).filter_map(|a| a.ty(&Interner)) {
2126 walk_type(db, &type_.derived(ty.clone()), cb);
2131 db: &dyn HirDatabase,
2133 bounds: &[QuantifiedWhereClause],
2134 cb: &mut impl FnMut(Type),
2136 for pred in bounds {
2137 match pred.skip_binders() {
2138 WhereClause::Implemented(trait_ref) => {
2140 // skip the self type. it's likely the type we just got the bounds from
2145 .filter_map(|a| a.ty(&Interner))
2147 walk_type(db, &type_.derived(ty.clone()), cb);
2155 fn walk_type(db: &dyn HirDatabase, type_: &Type, cb: &mut impl FnMut(Type)) {
2156 let ty = type_.ty.strip_references();
2157 match ty.kind(&Interner) {
2158 TyKind::Adt(_, substs) => {
2159 cb(type_.derived(ty.clone()));
2160 walk_substs(db, type_, &substs, cb);
2162 TyKind::AssociatedType(_, substs) => {
2163 if let Some(_) = ty.associated_type_parent_trait(db) {
2164 cb(type_.derived(ty.clone()));
2166 walk_substs(db, type_, &substs, cb);
2168 TyKind::OpaqueType(_, subst) => {
2169 if let Some(bounds) = ty.impl_trait_bounds(db) {
2170 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
2173 walk_substs(db, type_, subst, cb);
2175 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
2176 if let Some(bounds) = ty.impl_trait_bounds(db) {
2177 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
2180 walk_substs(db, type_, &opaque_ty.substitution, cb);
2182 TyKind::Placeholder(_) => {
2183 if let Some(bounds) = ty.impl_trait_bounds(db) {
2184 walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
2187 TyKind::Dyn(bounds) => {
2190 &type_.derived(ty.clone()),
2191 bounds.bounds.skip_binders().interned(),
2196 TyKind::Ref(_, _, ty)
2197 | TyKind::Raw(_, ty)
2198 | TyKind::Array(ty, _)
2199 | TyKind::Slice(ty) => {
2200 walk_type(db, &type_.derived(ty.clone()), cb);
2203 TyKind::FnDef(_, substs)
2204 | TyKind::Tuple(_, substs)
2205 | TyKind::Closure(.., substs) => {
2206 walk_substs(db, type_, &substs, cb);
2208 TyKind::Function(hir_ty::FnPointer { substitution, .. }) => {
2209 walk_substs(db, type_, &substitution.0, cb);
2216 walk_type(db, self, &mut cb);
2219 pub fn could_unify_with(&self, other: &Type) -> bool {
2220 could_unify(&self.ty, &other.ty)
2226 pub struct Callable {
2229 def: Option<CallableDefId>,
2230 pub(crate) is_bound_method: bool,
2233 pub enum CallableKind {
2235 TupleStruct(Struct),
2236 TupleEnumVariant(Variant),
2241 pub fn kind(&self) -> CallableKind {
2243 Some(CallableDefId::FunctionId(it)) => CallableKind::Function(it.into()),
2244 Some(CallableDefId::StructId(it)) => CallableKind::TupleStruct(it.into()),
2245 Some(CallableDefId::EnumVariantId(it)) => CallableKind::TupleEnumVariant(it.into()),
2246 None => CallableKind::Closure,
2249 pub fn receiver_param(&self, db: &dyn HirDatabase) -> Option<ast::SelfParam> {
2250 let func = match self.def {
2251 Some(CallableDefId::FunctionId(it)) if self.is_bound_method => it,
2254 let src = func.lookup(db.upcast()).source(db.upcast());
2255 let param_list = src.value.param_list()?;
2256 param_list.self_param()
2258 pub fn n_params(&self) -> usize {
2259 self.sig.params().len() - if self.is_bound_method { 1 } else { 0 }
2263 db: &dyn HirDatabase,
2264 ) -> Vec<(Option<Either<ast::SelfParam, ast::Pat>>, Type)> {
2269 .skip(if self.is_bound_method { 1 } else { 0 })
2270 .map(|ty| self.ty.derived(ty.clone()));
2271 let patterns = match self.def {
2272 Some(CallableDefId::FunctionId(func)) => {
2273 let src = func.lookup(db.upcast()).source(db.upcast());
2274 src.value.param_list().map(|param_list| {
2277 .map(|it| Some(Either::Left(it)))
2278 .filter(|_| !self.is_bound_method)
2280 .chain(param_list.params().map(|it| it.pat().map(Either::Right)))
2285 patterns.into_iter().flatten().chain(iter::repeat(None)).zip(types).collect()
2287 pub fn return_type(&self) -> Type {
2288 self.ty.derived(self.sig.ret().clone())
2293 #[derive(Debug, PartialEq, Eq, Hash)]
2295 ModuleDef(ModuleDef),
2297 GenericParam(GenericParam),
2306 pub fn all_items(def: PerNs) -> ArrayVec<Self, 3> {
2307 let mut items = ArrayVec::new();
2309 match (def.take_types(), def.take_values()) {
2310 (Some(m1), None) => items.push(ScopeDef::ModuleDef(m1.into())),
2311 (None, Some(m2)) => items.push(ScopeDef::ModuleDef(m2.into())),
2312 (Some(m1), Some(m2)) => {
2313 // Some items, like unit structs and enum variants, are
2314 // returned as both a type and a value. Here we want
2315 // to de-duplicate them.
2317 items.push(ScopeDef::ModuleDef(m1.into()));
2318 items.push(ScopeDef::ModuleDef(m2.into()));
2320 items.push(ScopeDef::ModuleDef(m1.into()));
2326 if let Some(macro_def_id) = def.take_macros() {
2327 items.push(ScopeDef::MacroDef(macro_def_id.into()));
2330 if items.is_empty() {
2331 items.push(ScopeDef::Unknown);
2338 impl From<ItemInNs> for ScopeDef {
2339 fn from(item: ItemInNs) -> Self {
2341 ItemInNs::Types(id) => ScopeDef::ModuleDef(id.into()),
2342 ItemInNs::Values(id) => ScopeDef::ModuleDef(id.into()),
2343 ItemInNs::Macros(id) => ScopeDef::MacroDef(id.into()),
2348 pub trait HasVisibility {
2349 fn visibility(&self, db: &dyn HirDatabase) -> Visibility;
2350 fn is_visible_from(&self, db: &dyn HirDatabase, module: Module) -> bool {
2351 let vis = self.visibility(db);
2352 vis.is_visible_from(db.upcast(), module.id)